@reddoorla/maintenance 0.94.1 → 0.95.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +31 -0
  2. package/dist/{announce-PGT4SZZB.js → announce-CLQYX5I4.js} +4 -4
  3. package/dist/{blux-NXQLMS4W.js → blux-4KNXUP2K.js} +1 -1
  4. package/dist/{bump-deps-6OR7LL4E.js → bump-deps-C5G2EFBB.js} +6 -6
  5. package/dist/{chunk-LS6QPANO.js → chunk-2LYOAB2E.js} +2 -2
  6. package/dist/{chunk-KQB2BX4V.js → chunk-2ZAZ7ETT.js} +2 -2
  7. package/dist/{chunk-XTK5VIQB.js → chunk-AVEQUR44.js} +48 -1
  8. package/dist/chunk-AVEQUR44.js.map +1 -0
  9. package/dist/{chunk-B6NUZ2ZX.js → chunk-BCKEP5S6.js} +2 -2
  10. package/dist/{chunk-DMPHP7UP.js → chunk-BI2VI6EM.js} +2 -2
  11. package/dist/{chunk-5FCBYK6L.js → chunk-BVEDKMNG.js} +10 -10
  12. package/dist/{chunk-OCNSIBMP.js → chunk-C3IQQKXL.js} +26 -1
  13. package/dist/{chunk-OCNSIBMP.js.map → chunk-C3IQQKXL.js.map} +1 -1
  14. package/dist/{chunk-PPIZHDJL.js → chunk-CJ2RMTT7.js} +2 -2
  15. package/dist/{chunk-7CJ3DVZW.js → chunk-CWXTNPNZ.js} +2 -2
  16. package/dist/{chunk-TGUESYGF.js → chunk-DFKBTBO3.js} +2 -2
  17. package/dist/{chunk-WHWVYL7B.js → chunk-FSGICFXB.js} +7 -32
  18. package/dist/chunk-FSGICFXB.js.map +1 -0
  19. package/dist/{chunk-3HS6LPFX.js → chunk-FUWFLAWQ.js} +4 -4
  20. package/dist/{chunk-4AIYWWKV.js → chunk-KJRVMMM3.js} +2 -2
  21. package/dist/{chunk-TCF6S7AD.js → chunk-LM2NHRCJ.js} +2 -2
  22. package/dist/{chunk-AEUABPAJ.js → chunk-R5IMFAFR.js} +2 -2
  23. package/dist/{chunk-NTLSMJHW.js → chunk-S7RYFUIK.js} +2 -2
  24. package/dist/{chunk-MLT4QY5X.js → chunk-SLFG7Y76.js} +1 -1
  25. package/dist/chunk-SLFG7Y76.js.map +1 -0
  26. package/dist/{chunk-REJCSA4H.js → chunk-TR3HFH6J.js} +4 -3
  27. package/dist/chunk-TR3HFH6J.js.map +1 -0
  28. package/dist/{chunk-22GKJO5F.js → chunk-VSGMCCGQ.js} +2 -2
  29. package/dist/{chunk-4R3YAQNV.js → chunk-WSJ7RO54.js} +2 -2
  30. package/dist/chunk-XPJQXSC4.js +112 -0
  31. package/dist/chunk-XPJQXSC4.js.map +1 -0
  32. package/dist/chunk-ZCL7C5LH.js +2698 -0
  33. package/dist/chunk-ZCL7C5LH.js.map +1 -0
  34. package/dist/{chunk-ZTPPCHDB.js → chunk-ZQV7UQNE.js} +2 -2
  35. package/dist/cli/bin.js +39 -26
  36. package/dist/cli/bin.js.map +1 -1
  37. package/dist/cli/commands/audit.d.ts +1 -1
  38. package/dist/cli/commands/audit.js +8 -8
  39. package/dist/client-G2WGWPCA.js +11 -0
  40. package/dist/configs/eslint.js +27 -1
  41. package/dist/configs/eslint.js.map +1 -1
  42. package/dist/{convert-to-pnpm-3RVGUBBR.js → convert-to-pnpm-YTFREUJK.js} +6 -6
  43. package/dist/{db-FL7ZBF6H.js → db-XKZYDCKM.js} +9 -9
  44. package/dist/{digest-TZ3QQOSF.js → digest-7UBGUBRK.js} +14 -14
  45. package/dist/{digest-collectors-EHFY2OQC.js → digest-collectors-DJFN5ZDK.js} +8 -8
  46. package/dist/{ensure-site-WIDO6LGU.js → ensure-site-OAAE5YE2.js} +2 -2
  47. package/dist/{forms-notify-target-2LWF5C5B.js → forms-notify-target-UC6PF3AE.js} +2 -2
  48. package/dist/{github-signals-GAHNOAHS.js → github-signals-TX5FPYP6.js} +5 -5
  49. package/dist/{header-image-YN3AQRY3.js → header-image-PSPT7CUM.js} +2 -2
  50. package/dist/{health-endpoint-XLNBWVHK.js → health-endpoint-KVCJYWET.js} +6 -6
  51. package/dist/{health-mirror-EB76EERV.js → health-mirror-XJAKA3EY.js} +3 -3
  52. package/dist/index.d.ts +2 -2
  53. package/dist/index.js +31 -29
  54. package/dist/index.js.map +1 -1
  55. package/dist/{init-YCLSGIEP.js → init-FFE4FCO2.js} +13 -13
  56. package/dist/{launch-FSHDTXSM.js → launch-UD36AHUN.js} +221 -7
  57. package/dist/launch-UD36AHUN.js.map +1 -0
  58. package/dist/match-harness-QRG6XZAR.js +70 -0
  59. package/dist/match-harness-QRG6XZAR.js.map +1 -0
  60. package/dist/migrate-Y7R4CESL.js +7 -0
  61. package/dist/{onboard-NKE6GZKL.js → onboard-TM2KESGF.js} +6 -6
  62. package/dist/{orchestrate-MWXENQOS.js → orchestrate-HYVQPRCE.js} +6 -6
  63. package/dist/{pipeline-MATFYQRC.js → pipeline-YROAY6DT.js} +2 -2
  64. package/dist/{preflight-4VQP7JJL.js → preflight-RYIP54NY.js} +7 -7
  65. package/dist/{prismic-ci-DM352L2Q.js → prismic-ci-6GKKZGB5.js} +13 -11
  66. package/dist/prismic-ci-6GKKZGB5.js.map +1 -0
  67. package/dist/{prismic-models-Q32ARSYS.js → prismic-models-P6FWWVRS.js} +5 -5
  68. package/dist/prospect/types.d.ts +1 -1
  69. package/dist/{prospect-audit-MT6RGMOY.js → prospect-audit-PRHU53HS.js} +5 -5
  70. package/dist/{prospect-audits-RVYEA4KH.js → prospect-audits-R3LWF6U7.js} +10 -4
  71. package/dist/recipes/sync-configs.d.ts +1 -1
  72. package/dist/recipes/sync-configs.js +4 -4
  73. package/dist/{render-JE5P26H5.js → render-YGNGTX3W.js} +2 -2
  74. package/dist/render-from-row-IFSBHWDH.js +1 -1
  75. package/dist/{report-6FFHGUUS.js → report-LQS4ECTM.js} +12 -12
  76. package/dist/{report-mirror-IP64R7B3.js → report-mirror-HDTOJE64.js} +3 -3
  77. package/dist/{schema-2V7BGYVT.js → schema-A4WCPIF4.js} +1 -1
  78. package/dist/{schema-2V7BGYVT.js.map → schema-A4WCPIF4.js.map} +1 -1
  79. package/dist/{self-updating-5DVDIEHB.js → self-updating-MWXIZLL7.js} +6 -6
  80. package/dist/{selftest-LJYXBIO5.js → selftest-VXTHRPRN.js} +9 -9
  81. package/dist/{site-mirror-UKHREAD6.js → site-mirror-WON4FTJ2.js} +3 -3
  82. package/dist/{smoke-suite-NUTC7IUK.js → smoke-suite-7DGITCTZ.js} +6 -6
  83. package/dist/{submissions-5GKJPCIH.js → submissions-OVZPVBYG.js} +2 -2
  84. package/dist/{svelte-codemods-U4NIT6CV.js → svelte-codemods-WSV2FGNG.js} +6 -6
  85. package/dist/{sync-configs-S2JYY6QU.js → sync-configs-RRIHNLIJ.js} +7 -7
  86. package/dist/{types-OIQZ5hWN.d.ts → types-D_bpy89i.d.ts} +1 -1
  87. package/dist/{upgrade-YFZCMUPE.js → upgrade-VTD6V4HS.js} +6 -6
  88. package/dist/util/git.d.ts +46 -1
  89. package/dist/util/git.js +7 -1
  90. package/package.json +1 -1
  91. package/dist/chunk-7MKT4I5T.js +0 -62
  92. package/dist/chunk-7MKT4I5T.js.map +0 -1
  93. package/dist/chunk-MLT4QY5X.js.map +0 -1
  94. package/dist/chunk-REJCSA4H.js.map +0 -1
  95. package/dist/chunk-WHWVYL7B.js.map +0 -1
  96. package/dist/chunk-XTK5VIQB.js.map +0 -1
  97. package/dist/client-M2V6FHH5.js +0 -11
  98. package/dist/launch-FSHDTXSM.js.map +0 -1
  99. package/dist/migrate-K4JETR36.js +0 -7
  100. package/dist/prismic-ci-DM352L2Q.js.map +0 -1
  101. /package/dist/{announce-PGT4SZZB.js.map → announce-CLQYX5I4.js.map} +0 -0
  102. /package/dist/{blux-NXQLMS4W.js.map → blux-4KNXUP2K.js.map} +0 -0
  103. /package/dist/{bump-deps-6OR7LL4E.js.map → bump-deps-C5G2EFBB.js.map} +0 -0
  104. /package/dist/{chunk-LS6QPANO.js.map → chunk-2LYOAB2E.js.map} +0 -0
  105. /package/dist/{chunk-KQB2BX4V.js.map → chunk-2ZAZ7ETT.js.map} +0 -0
  106. /package/dist/{chunk-B6NUZ2ZX.js.map → chunk-BCKEP5S6.js.map} +0 -0
  107. /package/dist/{chunk-DMPHP7UP.js.map → chunk-BI2VI6EM.js.map} +0 -0
  108. /package/dist/{chunk-5FCBYK6L.js.map → chunk-BVEDKMNG.js.map} +0 -0
  109. /package/dist/{chunk-PPIZHDJL.js.map → chunk-CJ2RMTT7.js.map} +0 -0
  110. /package/dist/{chunk-7CJ3DVZW.js.map → chunk-CWXTNPNZ.js.map} +0 -0
  111. /package/dist/{chunk-TGUESYGF.js.map → chunk-DFKBTBO3.js.map} +0 -0
  112. /package/dist/{chunk-3HS6LPFX.js.map → chunk-FUWFLAWQ.js.map} +0 -0
  113. /package/dist/{chunk-4AIYWWKV.js.map → chunk-KJRVMMM3.js.map} +0 -0
  114. /package/dist/{chunk-TCF6S7AD.js.map → chunk-LM2NHRCJ.js.map} +0 -0
  115. /package/dist/{chunk-AEUABPAJ.js.map → chunk-R5IMFAFR.js.map} +0 -0
  116. /package/dist/{chunk-NTLSMJHW.js.map → chunk-S7RYFUIK.js.map} +0 -0
  117. /package/dist/{chunk-22GKJO5F.js.map → chunk-VSGMCCGQ.js.map} +0 -0
  118. /package/dist/{chunk-4R3YAQNV.js.map → chunk-WSJ7RO54.js.map} +0 -0
  119. /package/dist/{chunk-ZTPPCHDB.js.map → chunk-ZQV7UQNE.js.map} +0 -0
  120. /package/dist/{client-M2V6FHH5.js.map → client-G2WGWPCA.js.map} +0 -0
  121. /package/dist/{convert-to-pnpm-3RVGUBBR.js.map → convert-to-pnpm-YTFREUJK.js.map} +0 -0
  122. /package/dist/{db-FL7ZBF6H.js.map → db-XKZYDCKM.js.map} +0 -0
  123. /package/dist/{digest-TZ3QQOSF.js.map → digest-7UBGUBRK.js.map} +0 -0
  124. /package/dist/{digest-collectors-EHFY2OQC.js.map → digest-collectors-DJFN5ZDK.js.map} +0 -0
  125. /package/dist/{ensure-site-WIDO6LGU.js.map → ensure-site-OAAE5YE2.js.map} +0 -0
  126. /package/dist/{forms-notify-target-2LWF5C5B.js.map → forms-notify-target-UC6PF3AE.js.map} +0 -0
  127. /package/dist/{github-signals-GAHNOAHS.js.map → github-signals-TX5FPYP6.js.map} +0 -0
  128. /package/dist/{header-image-YN3AQRY3.js.map → header-image-PSPT7CUM.js.map} +0 -0
  129. /package/dist/{health-endpoint-XLNBWVHK.js.map → health-endpoint-KVCJYWET.js.map} +0 -0
  130. /package/dist/{health-mirror-EB76EERV.js.map → health-mirror-XJAKA3EY.js.map} +0 -0
  131. /package/dist/{init-YCLSGIEP.js.map → init-FFE4FCO2.js.map} +0 -0
  132. /package/dist/{migrate-K4JETR36.js.map → migrate-Y7R4CESL.js.map} +0 -0
  133. /package/dist/{onboard-NKE6GZKL.js.map → onboard-TM2KESGF.js.map} +0 -0
  134. /package/dist/{orchestrate-MWXENQOS.js.map → orchestrate-HYVQPRCE.js.map} +0 -0
  135. /package/dist/{pipeline-MATFYQRC.js.map → pipeline-YROAY6DT.js.map} +0 -0
  136. /package/dist/{preflight-4VQP7JJL.js.map → preflight-RYIP54NY.js.map} +0 -0
  137. /package/dist/{prismic-models-Q32ARSYS.js.map → prismic-models-P6FWWVRS.js.map} +0 -0
  138. /package/dist/{prospect-audit-MT6RGMOY.js.map → prospect-audit-PRHU53HS.js.map} +0 -0
  139. /package/dist/{prospect-audits-RVYEA4KH.js.map → prospect-audits-R3LWF6U7.js.map} +0 -0
  140. /package/dist/{render-JE5P26H5.js.map → render-YGNGTX3W.js.map} +0 -0
  141. /package/dist/{report-6FFHGUUS.js.map → report-LQS4ECTM.js.map} +0 -0
  142. /package/dist/{report-mirror-IP64R7B3.js.map → report-mirror-HDTOJE64.js.map} +0 -0
  143. /package/dist/{self-updating-5DVDIEHB.js.map → self-updating-MWXIZLL7.js.map} +0 -0
  144. /package/dist/{selftest-LJYXBIO5.js.map → selftest-VXTHRPRN.js.map} +0 -0
  145. /package/dist/{site-mirror-UKHREAD6.js.map → site-mirror-WON4FTJ2.js.map} +0 -0
  146. /package/dist/{smoke-suite-NUTC7IUK.js.map → smoke-suite-7DGITCTZ.js.map} +0 -0
  147. /package/dist/{submissions-5GKJPCIH.js.map → submissions-OVZPVBYG.js.map} +0 -0
  148. /package/dist/{svelte-codemods-U4NIT6CV.js.map → svelte-codemods-WSV2FGNG.js.map} +0 -0
  149. /package/dist/{sync-configs-S2JYY6QU.js.map → sync-configs-RRIHNLIJ.js.map} +0 -0
  150. /package/dist/{upgrade-YFZCMUPE.js.map → upgrade-VTD6V4HS.js.map} +0 -0
@@ -0,0 +1,2698 @@
1
+ import {
2
+ PRETTIER_FLAG_NOTE,
3
+ formatWithPrettier,
4
+ resolveTargetPrettier
5
+ } from "./chunk-R53VL3RI.js";
6
+ import {
7
+ withRecipe
8
+ } from "./chunk-ZQV7UQNE.js";
9
+ import {
10
+ defaultSpawn
11
+ } from "./chunk-LBYOLBW7.js";
12
+ import {
13
+ ignoreRulesFor,
14
+ pathsMissingFromHead
15
+ } from "./chunk-AVEQUR44.js";
16
+
17
+ // src/recipes/match-harness/index.ts
18
+ import { mkdir, readFile, rm, rmdir, writeFile } from "fs/promises";
19
+ import { dirname, join } from "path";
20
+
21
+ // src/recipes/match-harness/template.ts
22
+ var HARNESS_MJS_RELATIVE = "matching/harness.mjs";
23
+ var HARNESS_MJS_TEMPLATE = `// The single source for everything the matching gates need to know about this
24
+ // site. DATA lives in matching/harness.json (site-edited); this file is the
25
+ // READ LAYER \u2014 edit harness.json, not this. (It is installed and upgraded by
26
+ // the \`reddoor-maint match-harness\` recipe, which owns these bytes: a hand
27
+ // edit here is flagged on the next run and never silently overwritten.)
28
+ //
29
+ // It exists because the page table, the two hosts, the matrix, the threshold
30
+ // and the skill path were hand-copied all over matching/. Re-measured
31
+ // 2026-09-09 AFTER the six-probe conversion, over the 216 tracked scripts under
32
+ // matching/ (214 top-level \u2014 212 .mjs + 2 .sh \u2014 plus 2 in states/):
33
+ //
34
+ // \u2022 a hand-typed copy of the page table (three or more gate keys sitting next
35
+ // to their route): 8 files. Exactly ONE of them, probe-chrome-count.mjs,
36
+ // still carries all nine rows; probe-anchors.mjs carries five; the other
37
+ // six are three-row detail triples (team/svc/qa).
38
+ // \u2022 the skill path (~/.claude/skills/matching-a-page): 193 copies
39
+ // \u2022 the viewport matrix (1440/834/390): 51 copies
40
+ // \u2022 REF pointed at a host listed in selfHosts \u2014 i.e. comparing the candidate
41
+ // with itself: 12 scripts, one of which (probe-chrome-count.mjs) is also
42
+ // the last nine-row table carrier
43
+ //
44
+ // The first bullet read "the nine-row page table: 5 copies \u2014 gate.sh,
45
+ // probe-anchor-parity.mjs, sweep-all10.sh, sweep-all16.sh, sweep-final.sh" when
46
+ // it was written here at 922dde3. It was wrong within the hour and wrong on two
47
+ // counts: 4e2cd7b took the table out of gate.sh, and the list never named
48
+ // states/index.mjs or probe-chrome-count.mjs, which were both carrying nine-row
49
+ // copies at the time. A census is a claim about code; it has to be measured
50
+ // against the tree, not recalled.
51
+ //
52
+ // node matching/harness.mjs --env shell-safe KEY='value' lines
53
+ // node matching/harness.mjs --table key<TAB>ref<TAB>cand<TAB>anchors
54
+ // node matching/harness.mjs --check-ref the D11 preflight; exit 2 on failure
55
+ // node matching/harness.mjs --check-run <page> <out-dir> <startedAt-iso>
56
+ // did THIS run leave a countable report?
57
+ // exit 2 when it did not
58
+ import { readFileSync, realpathSync } from "node:fs";
59
+ import { homedir } from "node:os";
60
+ import { join } from "node:path";
61
+ import { fileURLToPath, pathToFileURL } from "node:url";
62
+
63
+ // fileURLToPath, not URL#pathname: pathname is percent-encoded, so a checkout
64
+ // under a directory with a space in it would resolve to a path that does not
65
+ // exist.
66
+ const DIR = fileURLToPath(new URL(".", import.meta.url));
67
+ const CFG = JSON.parse(readFileSync(join(DIR, "harness.json"), "utf8"));
68
+
69
+ // Env overrides exist for one-off probes only. They are NOT how a site is
70
+ // configured \u2014 harness.json is, so that what a gate ran against is committed.
71
+ export const REF = process.env.MATCH_REF ?? CFG.ref;
72
+ export const CAND = process.env.MATCH_CAND ?? process.env.CAND_BASE ?? CFG.cand;
73
+ export const MATRIX = CFG.matrix;
74
+ export const THRESHOLD = CFG.threshold;
75
+ export const MAX_HEIGHT_DELTA = CFG.maxHeightDelta;
76
+ export const REF_MARK = CFG.refMark;
77
+ export const CAND_MARK = CFG.candMark;
78
+ export const SELF_HOSTS = CFG.selfHosts ?? [];
79
+
80
+ /** One record per gated page, in harness.json order. \`key\` is the gate key
81
+ * (out-<TAG>-<key>, the SPEC heading, spec-sections/<key>.md); \`uid\` is the
82
+ * Prismic uid or null where the page has no /dev/match twin. */
83
+ export const PAGES = Object.entries(CFG.pages).map(([key, p]) => ({ key, ...p }));
84
+ export const byKey = Object.fromEntries(PAGES.map((p) => [p.key, p]));
85
+
86
+ /** Can this page's region count be PREDICTED at all? It needs anchors \u2014 see
87
+ * TOTALS below \u2014 AND a matrix to measure them at. Exported beside TOTALS
88
+ * rather than left for each consumer to re-derive, because "remember to ask
89
+ * first" is exactly what failed: checkRun remembered, next.mjs did not, for
90
+ * two releases.
91
+ *
92
+ * \`MATRIX.length > 0\` is not defensive padding. TOTALS is
93
+ * \`(anchors + 1) * MATRIX.length\`, so an ANCHORED page with \`matrix: []\`
94
+ * yields 0 \u2014 truthy-adjacent, arithmetically fatal. Measured on a page with 3
95
+ * anchors, an empty matrix and 8 passing regions: without this clause the
96
+ * scorer printed \`SCORE 8/0 regions passing\` and \`Backlog is empty \u2014 Phases 5
97
+ * and 6 are what is left\`, exit 0. The absurd fraction would be questioned;
98
+ * the sentence would not. \`pass/0\` is also Infinity, so such a page sorts
99
+ * BEST and can never be named \`worst\` \u2014 the same ranking bug this change set
100
+ * removed for unanchored pages, one input along. */
101
+ export const scorable = (key) =>
102
+ (byKey[key]?.anchors?.length ?? 0) > 0 && MATRIX.length > 0;
103
+
104
+ /** WHY a page is not scorable, in the words of the thing that is actually
105
+ * missing. A refusal that states a cause it did not check is the shape
106
+ * CLAUDE.md names: a field must never be named after something it cannot
107
+ * observe. "no anchors" printed for a page carrying three of them sends the
108
+ * operator to edit the one part of harness.json that was already right. */
109
+ export const unscorableWhy = (key) =>
110
+ (byKey[key]?.anchors?.length ?? 0) === 0
111
+ ? "no anchors"
112
+ : MATRIX.length === 0
113
+ ? "matrix is empty"
114
+ : null;
115
+
116
+ // DERIVED, never hand-typed: page-diff cuts one region before the first anchor
117
+ // ("top") plus one per anchor, at every viewport. The old hand-written map went
118
+ // stale the moment an anchor list changed, and a wrong denominator makes the
119
+ // score a lie in the flattering direction.
120
+ //
121
+ // THAT IDENTITY HOLDS ONLY WITH ANCHORS. \`splitRegions\` (page-diff.mjs:103-110)
122
+ // only cuts by anchor when there are anchors to cut by; with none it falls back
123
+ // to the page's own <section> boxes, and with none of those to an even four-row
124
+ // grid (lib/regions.mjs:27-35, gridRows = 4, labels \`grid-<r>-<c>\`). So the
125
+ // count is DATA-DEPENDENT, the two pages need not even agree, and no formula
126
+ // over anchors can predict it.
127
+ //
128
+ // \`checkRun\` below already reaches this conclusion \u2014 its \`if (secs.length)\`
129
+ // guard declines to assert a region count without anchors, and says why. That
130
+ // fix was applied to the VALIDATOR and never carried to the DENOMINATOR, so
131
+ // next.mjs went on dividing a real pass count by an imaginary total. Measured
132
+ // 2026-09-09 on a seed harness (anchors: [], matrix of 3): page-diff produced
133
+ // 12 grid regions, all passing, and next.mjs printed \`SCORE 12/3 regions
134
+ // passing\` followed by "Backlog is empty \u2014 Phases 5 and 6 are what is left",
135
+ // exit 0. On a matrix of 4 the same seed prints \`SCORE 16/4\`. The absurd
136
+ // fraction would have been questioned; the sentence would not.
137
+ //
138
+ // So an unpredictable page gets NO NUMBER \u2014 \`null\`, not a plausible-looking
139
+ // integer. That is a SIGNAL, not a barrier: \`a + null\` is \`a\`, so a consumer
140
+ // that sums TOTALS without asking \`scorable()\` still gets a too-small
141
+ // denominator. The barrier is \`scorable()\` plus next.mjs's exit-2 refusal.
142
+ export const TOTALS = Object.fromEntries(
143
+ PAGES.map((p) => [p.key, scorable(p.key) ? (p.anchors.length + 1) * MATRIX.length : null]),
144
+ );
145
+
146
+ /** The SPEC.md heading predicate, shared by gate.sh's preflight and
147
+ * build-spec.mjs so a section can never build fine and then refuse at the
148
+ * gate. Matches the key followed by any non-key character (\`## team\` matches,
149
+ * \`## teamfoo\` does not, \`## our-team\` cannot match \`team\`). */
150
+ export const specHeadingRe = (key) => new RegExp(\`^##+ +\${key}([^A-Za-z0-9_-]|$)\`, "m");
151
+
152
+ export const SKILL_DIR =
153
+ process.env.MATCHING_SKILL_DIR ?? join(homedir(), ".claude/skills/matching-a-page");
154
+ export const PD = join(SKILL_DIR, "page-diff.mjs");
155
+ export const SC = join(SKILL_DIR, "style-census.mjs");
156
+ export const PLAYWRIGHT = pathToFileURL(join(SKILL_DIR, "node_modules/playwright/index.mjs")).href;
157
+
158
+ /** The report format this site's scripts can read, so gate.sh can compare it
159
+ * with \`page-diff --version\` before spending a run and next.mjs can refuse
160
+ * rather than quietly drop a page whose newest report came from another
161
+ * schema. Both do that now \u2014 gate.sh preflights \`page-diff --version\` against
162
+ * this value before spending a run, and next.mjs counts a foreign-schema
163
+ * report as MISSING rather than skipping it. (This said "neither does that
164
+ * yet" \u2014 true at 922dde3 where it was written, false from 4e2cd7b, which
165
+ * gave gate.sh the preflight and did not come back here.) Checked 2026-09-09
166
+ * against the installed skill: \`page-diff --version\` \u2192 \`page-diff 0.1.0
167
+ * report-schema 1\`. */
168
+ export const REPORT_SCHEMA = 1;
169
+
170
+ /**
171
+ * Fail-closed reference preflight. A 200 is NOT evidence: a host that has been
172
+ * repointed at our own build answers 200, and so does a staging host serving a
173
+ * 404 page. Both have happened on a real site \u2014 see the dated measurement in
174
+ * LEDGER.md. A pass here requires an artefact only the reference produces.
175
+ */
176
+ export async function checkRef() {
177
+ if (!REF_MARK) {
178
+ return {
179
+ ok: false,
180
+ why: "harness.json refMark is empty \u2014 set it to a string only the reference serves (a Webflow site id, a build hash). A 200 is not evidence.",
181
+ };
182
+ }
183
+ const host = new URL(REF).host;
184
+ if (SELF_HOSTS.includes(host)) return { ok: false, why: \`REF host \${host} is in selfHosts\` };
185
+ if (host === new URL(CAND).host) return { ok: false, why: \`REF host \${host} equals CAND's host\` };
186
+ let res;
187
+ try {
188
+ res = await fetch(\`\${REF}/\`, { redirect: "manual" });
189
+ } catch (e) {
190
+ return { ok: false, why: \`GET \${REF}/ failed: \${e.message}\` };
191
+ }
192
+ if (res.status !== 200)
193
+ return { ok: false, why: \`GET \${REF}/ \u2192 HTTP \${res.status}, expected 200\` };
194
+ const loc = res.headers.get("location");
195
+ if (loc) return { ok: false, why: \`GET \${REF}/ \u2192 \${res.status} redirect to \${loc}\` };
196
+ const body = await res.text();
197
+ if (!body.includes(REF_MARK))
198
+ return {
199
+ ok: false,
200
+ why: \`\${REF}/ served 200 but WITHOUT refMark \${JSON.stringify(REF_MARK)} \u2014 that is not the reference\`,
201
+ };
202
+ if (CAND_MARK && body.includes(CAND_MARK))
203
+ return {
204
+ ok: false,
205
+ why: \`\${REF}/ contains candMark \${JSON.stringify(CAND_MARK)} \u2014 REF is serving OUR build\`,
206
+ };
207
+ return { ok: true, why: \`\${REF}/ \u2192 200, no redirect, refMark present, candMark absent\` };
208
+ }
209
+
210
+ /**
211
+ * Would next.mjs COUNT a run with this meta? Returns the reason it would not,
212
+ * as a string, or null when it would.
213
+ *
214
+ * A reason string and not a boolean, because the two callers must tell the
215
+ * cases apart: next.mjs treats "schema" as a page BLANKED (it has its own
216
+ * message and its own exit) and merely skips the rest of the diagnostics,
217
+ * while gate.sh prints whatever this says.
218
+ *
219
+ * It lives HERE rather than inside next.mjs because gate.sh now asks the same
220
+ * question, and a question asked twice drifts: a gate that greens a run
221
+ * next.mjs then drops is the same false green one step along. census.sh's
222
+ * GUARD 2c (census.sh:153-168) records exactly that drift between
223
+ * style-census's printer and census-count.mjs's parser \u2014 a COMPLETE census
224
+ * reported as 0 mismatches because the two had versioned apart.
225
+ */
226
+ export function uncountable(m) {
227
+ // Missing schemaVersion means "written before the field existed" = 0. It is
228
+ // not an error on its own; it is only fatal when it would blank a page,
229
+ // which is next.mjs's call to make, not this predicate's.
230
+ if ((m.schemaVersion ?? 0) !== REPORT_SCHEMA) return "schema";
231
+ // A masked / media-neutralised run is a DIAGNOSTIC, never the state of the
232
+ // page. An --mask-photos probe of yfv made \`top\` @834 read 43.9% while the
233
+ // real gate had it passing at 1.3%.
234
+ if ((m.mask?.length ?? 0) > 0) return \`mask=[\${m.mask.join(", ")}]\`;
235
+ if (m.neutralizeMedia) return "neutralize-media";
236
+ if (m.maskPhotos) return "mask-photos";
237
+ if (m.truncated) return "truncated";
238
+ if (m.threshold !== THRESHOLD) return \`threshold \${m.threshold} != \${THRESHOLD}\`;
239
+ return null;
240
+ }
241
+
242
+ /**
243
+ * Did THIS run of page-diff leave a report the scorer will actually count?
244
+ *
245
+ * gate.sh cannot use page-diff's exit status for this. page-diff exits 1 for a
246
+ * region that legitimately FAILED (page-diff.mjs:227) and node exits 1 for the
247
+ * bare \`throw e\` one line below it, so the status cannot tell a finding from a
248
+ * crash-before-looking \u2014 census.sh:17-32 records the same shape for
249
+ * style-census. Measured on 29 Navy with the reference alive and no dev
250
+ * server: every page-diff died in \`page.goto\`, the gate printed \`home exit=1\`
251
+ * and \`ALL DONE\`, exited 0, and wrote no report at all.
252
+ *
253
+ * So the evidence is the artefact only a completed run leaves: the report
254
+ * next.mjs will read, fresh, over the matrix and anchors the table declares.
255
+ * Cheapest and most specific arm first.
256
+ */
257
+ export function checkRun(page, dir, startedAt) {
258
+ const path = join(dir, "report.json");
259
+ let report;
260
+ try {
261
+ report = JSON.parse(readFileSync(path, "utf8"));
262
+ } catch (e) {
263
+ if (e.code === "ENOENT")
264
+ return { ok: false, why: \`\${path}: no report.json \u2014 the run wrote nothing\` };
265
+ return { ok: false, why: \`\${path}: \${e.message}\` };
266
+ }
267
+ const meta = report.meta ?? {};
268
+
269
+ const uncount = uncountable(meta);
270
+ if (uncount)
271
+ return { ok: false, why: \`\${path}: next.mjs would not count this run (\${uncount})\` };
272
+
273
+ // FRESHNESS. lib/report.mjs:45 is \`mkdirSync(outDir, {recursive:true})\` and
274
+ // nothing ever clears the directory, so a crashed re-run under a tag used
275
+ // before leaves the PREVIOUS round's report exactly where it was \u2014 measured
276
+ // 2026-09-09, sha unchanged across the crash. Requiring report.json without
277
+ // this arm reproduces the green one step along. meta.generatedAt is built
278
+ // after \`finally { await browser.close() }\` (page-diff.mjs:163-176), so it
279
+ // is an artefact of the run that wrote it and not of the file's mtime.
280
+ const since = Date.parse(startedAt);
281
+ // NOT skipped when startedAt is unusable: a fail-open default is the exact
282
+ // shape this guard exists to stop.
283
+ if (!Number.isFinite(since))
284
+ return {
285
+ ok: false,
286
+ why: \`startedAt \${JSON.stringify(startedAt)} is not a timestamp \u2014 cannot tell this run's report from a previous round's\`,
287
+ };
288
+ const at = Date.parse(meta.generatedAt ?? "");
289
+ if (!Number.isFinite(at))
290
+ return {
291
+ ok: false,
292
+ why: \`\${path}: no usable meta.generatedAt \u2014 cannot tell this run's report from a previous round's\`,
293
+ };
294
+ if (at < since)
295
+ return {
296
+ ok: false,
297
+ why: \`\${path}: STALE \u2014 written \${meta.generatedAt}, this run started \${startedAt}. page-diff never cleared the directory.\`,
298
+ };
299
+
300
+ // COVERAGE \u2014 what the run was ASKED for, against the table.
301
+ const vws = meta.viewports ?? [];
302
+ if (vws.join(",") !== MATRIX.join(","))
303
+ return {
304
+ ok: false,
305
+ why: \`\${path}: ran viewports [\${vws.join(",")}], harness.json matrix is [\${MATRIX.join(",")}]\`,
306
+ };
307
+ const secs = meta.sections ?? [];
308
+ const want = byKey[page]?.anchors ?? [];
309
+ if (secs.join("\\0") !== want.join("\\0"))
310
+ return {
311
+ ok: false,
312
+ why: \`\${path}: ran sections [\${secs.join(" | ")}], harness.json anchors are [\${want.join(" | ")}]\`,
313
+ };
314
+
315
+ // ...and what it actually PRODUCED. Every viewport the run says it covered
316
+ // has to appear in the regions. Deliberately compared against the run's own
317
+ // meta.viewports and not against MATRIX: the arm above owns "the run used the
318
+ // wrong matrix", and folding the two together would make either one
319
+ // unfalsifiable on its own.
320
+ if (!Array.isArray(report.regions) || report.regions.length === 0)
321
+ return { ok: false, why: \`\${path}: no regions \u2014 nothing was compared\` };
322
+ const seen = new Set(report.regions.map((r) => r.viewport));
323
+ const missing = vws.filter((v) => !seen.has(v));
324
+ if (missing.length)
325
+ return {
326
+ ok: false,
327
+ why: \`\${path}: no region at viewport(s) [\${missing.join(",")}] \u2014 the run covered [\${[...seen].join(",")}]\`,
328
+ };
329
+
330
+ // With anchors the region count is an exact identity: page-diff cuts one
331
+ // region before the first anchor plus one per anchor, at every viewport
332
+ // (regionsFromAnchors, page-diff.mjs:105-109). Measured over the 298 clean
333
+ // gate-shaped runs in the corpus this harness was cut from, all of them
334
+ // anchored: regions.length === (sections + 1) * viewports holds 298/298,
335
+ // while regions.length === TOTALS[page] holds only 260/298 \u2014 the 38 are
336
+ // legitimately narrower HAND rounds. So the identity is checked against the
337
+ // run's OWN meta and the matrix/anchors are checked against the table above.
338
+ //
339
+ // WITHOUT anchors there is no such identity, and asserting one is a FALSE
340
+ // REFUSAL of the shape every new site starts in. page-diff falls back to each
341
+ // page's own <section> boxes and, with none, an even four-row grid
342
+ // (splitRegions, page-diff.mjs:103-110), so the count is data-dependent and
343
+ // the two pages need not even agree. Measured 2026-09-09 against the real
344
+ // page-diff on a seed harness (anchors: [], matrix of 4): 16 regions labelled
345
+ // grid-0-0 \u2026 grid-3-0, not the 4 this identity predicted. The 298/298 above
346
+ // was measured over anchored runs only and never covered this case.
347
+ if (secs.length) {
348
+ const expected = (secs.length + 1) * vws.length;
349
+ if (report.regions.length !== expected)
350
+ return {
351
+ ok: false,
352
+ why: \`\${path}: \${report.regions.length} region(s), expected \${expected} = (\${secs.length} anchors + 1) x \${vws.length} viewport(s)\`,
353
+ };
354
+ }
355
+
356
+ // A green that STATES what it is made of, so a green over nothing reads
357
+ // differently from a green over the matrix (census.sh:219's habit).
358
+ return {
359
+ ok: true,
360
+ why: \`\${report.regions.length} region(s) over \${vws.length} viewport(s), written \${meta.generatedAt}\`,
361
+ };
362
+ }
363
+
364
+ // CLI. Both sides go through realpathSync. \`import.meta.url\` is ALREADY the
365
+ // resolved real path (node resolves symlinks unless --preserve-symlinks) while
366
+ // process.argv[1] is the path as typed, so a plain pathToFileURL compare goes
367
+ // false the moment any component of the invoked path is a symlink \u2014 and then
368
+ // the CLI prints nothing and exits 0, which every caller reads as success.
369
+ // page-diff.mjs:184-189 records exactly that defect and the same fix: "The
370
+ // pathToFileURL compare that replaced the old template string is still false
371
+ // whenever ANY component of the invoked path is a symlink \u2014 which is how this
372
+ // skill is installed now (~/.claude/skills/matching-a-page -> the claude-skills
373
+ // checkout). isMain() resolves the real path on both sides."
374
+ const isMain = () => {
375
+ if (!process.argv[1]) return false;
376
+ try {
377
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
378
+ } catch {
379
+ return false;
380
+ }
381
+ };
382
+
383
+ if (isMain()) {
384
+ const mode = process.argv[2];
385
+ const q = (v) => \`'\${String(v).replace(/'/g, \`'\\\\''\`)}'\`;
386
+ if (mode === "--env") {
387
+ const pairs = [
388
+ ["REF", REF],
389
+ ["CAND", CAND],
390
+ ["MATRIX", MATRIX.join(",")],
391
+ ["VIEWPORTS_SP", MATRIX.join(" ")],
392
+ ["THRESHOLD", THRESHOLD],
393
+ ["MAX_HEIGHT_DELTA", MAX_HEIGHT_DELTA],
394
+ ["PD", PD],
395
+ ["SC", SC],
396
+ ["REPORT_SCHEMA", REPORT_SCHEMA],
397
+ ];
398
+ for (const [k, v] of pairs) console.log(\`\${k}=\${q(v)}\`);
399
+ } else if (mode === "--table") {
400
+ for (const p of PAGES) console.log([p.key, p.ref, p.cand, p.anchors.join(",")].join("\\t"));
401
+ } else if (mode === "--check-ref") {
402
+ const r = await checkRef();
403
+ console.log(\`\${r.ok ? "REF OK" : "REF REFUSED"} \u2014 \${r.why}\`);
404
+ process.exit(r.ok ? 0 : 2);
405
+ } else if (mode === "--check-run") {
406
+ // startedAt is REQUIRED, never defaulted: an optional one is a fail-open
407
+ // door in the one guard that decides whether a page was measured at all.
408
+ const [page, dir, startedAt] = process.argv.slice(3);
409
+ if (!page || !dir || !startedAt) {
410
+ console.error("usage: harness.mjs --check-run <page> <out-dir> <startedAt-iso>");
411
+ process.exit(2);
412
+ }
413
+ const r = checkRun(page, dir, startedAt);
414
+ console.log(\`\${r.ok ? "RUN OK" : "NO RUN"} \u2014 \${r.why}\`);
415
+ process.exit(r.ok ? 0 : 2);
416
+ } else {
417
+ console.error("usage: harness.mjs --env | --table | --check-ref | --check-run");
418
+ process.exit(2);
419
+ }
420
+ }
421
+ `;
422
+ var GATE_SH_RELATIVE = "matching/gate.sh";
423
+ var GATE_SH_TEMPLATE = `#!/usr/bin/env bash
424
+ # The matching gate. This file is generic \u2014 everything specific to a site lives
425
+ # in matching/harness.json (the data) and matching/LEDGER.md (the why). It is
426
+ # installed and upgraded by the \`reddoor-maint match-harness\` recipe, which
427
+ # owns these bytes: a hand edit here is flagged on the next run, never
428
+ # silently overwritten.
429
+ #
430
+ # bash matching/gate.sh <round-tag> [page ...]
431
+ #
432
+ # Runs page-diff for every page in the table (or just the named ones) at the
433
+ # full breakpoint matrix and writes matching/out-<round-tag>-<page>/.
434
+ #
435
+ # The matrix, the anchor lists, the reference and the candidate are DATA. Why a
436
+ # site chose them \u2014 which live breakpoint band hid what, why an anchor is a
437
+ # heading and not a button label \u2014 belongs in matching/LEDGER.md, which is dated
438
+ # and append-only, because JSON holds no comments.
439
+ #
440
+ # NO MASKS and the threshold from harness.json everywhere: the numbers stay
441
+ # honest and a known floor stays visible as its own region. A media-neutralised
442
+ # secondary read is \`node "$PD" ... --neutralize-media\`; next.mjs ignores such
443
+ # runs on purpose (next.mjs:57-64).
444
+ #
445
+ # PREFLIGHT (see the matching rules in CLAUDE.md): a page with no section in
446
+ # matching/SPEC.md has not had Phase 1 done, and its geometry must not be
447
+ # touched. Skipping the spec is how a reference's root-font ladder and its
448
+ # per-component height ladders get found reactively, after the region has
449
+ # already failed several rounds. This refuses the run instead of trusting anyone
450
+ # to remember.
451
+ set -u
452
+ # Everything configurable lives in matching/harness.json; harness.mjs is the one
453
+ # reader. --env emits shell-safe assignments (REF, CAND, MATRIX, VIEWPORTS_SP,
454
+ # THRESHOLD, MAX_HEIGHT_DELTA, PD, SC, REPORT_SCHEMA).
455
+ eval "$(node "$(dirname "$0")/harness.mjs" --env)"
456
+
457
+ # The skill must be able to write reports this site's scripts can read. Cheap,
458
+ # local, and it fails before any browser starts.
459
+ PD_SCHEMA="$(node "$PD" --version 2>/dev/null | awk '{print $4}')"
460
+ if [ "$PD_SCHEMA" != "$REPORT_SCHEMA" ]; then
461
+ echo "gate.sh: page-diff writes report schema '\${PD_SCHEMA:-none}', this harness reads $REPORT_SCHEMA." >&2
462
+ echo " Update matching/harness.mjs REPORT_SCHEMA or the matching-a-page skill." >&2
463
+ exit 2
464
+ fi
465
+ SPEC="$(dirname "$0")/SPEC.md"
466
+ TAG="\${1:?usage: gate.sh <round-tag> [page ...]}"
467
+ # The tag must not contain a hyphen. Output dirs are "out-<TAG>-<page>", and
468
+ # next.mjs recovers the page with /^out-[^-]+-(.+)$/ \u2014 it splits on the FIRST
469
+ # hyphen, so a tag like "r-forms-2026-08-07" yields the page key
470
+ # "forms-2026-08-07-yfv" and that run is silently never counted. It cannot split
471
+ # on the last hyphen instead, because page keys have hyphens of their own
472
+ # ("our-team", "ask-the-doctor"). Failing here is the cheap end of that: a
473
+ # mis-tagged round otherwise LOOKS green because next.mjs keeps reading an older
474
+ # report for the page you just changed. (Cost this once, 2026-08-07.)
475
+ case "$TAG" in
476
+ *-*)
477
+ echo "gate.sh: round tag must not contain a hyphen (got '$TAG')." >&2
478
+ echo " out-<TAG>-<page> is parsed on the first hyphen, so a" >&2
479
+ echo " hyphenated tag hides the run from next.mjs. Try '\${TAG//-/}'." >&2
480
+ exit 2
481
+ ;;
482
+ esac
483
+ shift || true
484
+ WANT=("$@")
485
+
486
+ # What this round actually measured. These are read by the terminal block far
487
+ # below, and the page loop is \`done < <(...)\` \u2014 process substitution, NOT a
488
+ # pipe \u2014 precisely so they survive it (gate.sh's own note at the loop, and
489
+ # census.sh:193-198, record the same trap). Converting that loop to a pipe
490
+ # would leave every counter here reading 0, which is the green this file now
491
+ # exists to stop.
492
+ MEASURED=0
493
+ ATTEMPTED=0
494
+ UNMEASURED=""
495
+ SEEN=""
496
+
497
+ # Fail closed on the reference before spending a single run. A 200 is NOT
498
+ # evidence: a production host that has cut over to OUR build answers 200, and
499
+ # every region then scores near zero against itself. --check-ref requires an
500
+ # artefact only the reference serves (harness.json refMark) and refuses a
501
+ # redirect, a host listed in selfHosts, and a body carrying candMark. Measured
502
+ # on the site this harness was cut from, 2026-09-09 AFTER the consolidation:
503
+ # 12 of its 214 top-level matching scripts still assign REF a host listed in
504
+ # selfHosts \u2014 i.e. compare the candidate with itself. It was 33 of 229 before.
505
+ # (This comment read "33 of its 230" while sitting in the post-consolidation
506
+ # tree, contradicting harness.mjs's 12 three files away.)
507
+ if ! node "$(dirname "$0")/harness.mjs" --check-ref; then
508
+ echo "gate.sh: refusing to gate against an unverified reference." >&2
509
+ exit 2
510
+ fi
511
+
512
+ # Set SPEC_OPTIONAL=1 only for a read-only baseline sweep of pages you are not
513
+ # about to edit. It is recorded in the round tag so the exemption is visible.
514
+ SPEC_OPTIONAL="\${SPEC_OPTIONAL:-0}"
515
+
516
+ has_spec() { # page
517
+ # NB: the obvious \`( |$|\\b)\` guard is rejected by ugrep as an empty
518
+ # subexpression, and a preflight that errors out fails CLOSED \u2014 it refused all
519
+ # 9 pages while SPEC.md was complete. Match the page key followed by any
520
+ # non-key character (so \`## team\` matches but \`## teamfoo\` does not; \`##
521
+ # our-team\` cannot match \`team\` because the key must follow the spaces).
522
+ [ -f "$SPEC" ] && grep -qE "^##+ +$1([^A-Za-z0-9_-]|$)" "$SPEC"
523
+ }
524
+
525
+ run() { # tag refpath candpath sections
526
+ local page="$1" refpath="$2" candpath="$3" sections="$4"
527
+ # BEFORE the WANT filter, so the known-page list stays complete even when
528
+ # WANT matches nothing and there is a typo to name. Mirrors census.sh:107.
529
+ SEEN="$SEEN $page"
530
+ if [ \${#WANT[@]} -gt 0 ]; then
531
+ local hit=0
532
+ for w in "\${WANT[@]}"; do [ "$w" = "$page" ] && hit=1; done
533
+ [ $hit -eq 1 ] || return 0
534
+ fi
535
+ if ! has_spec "$page"; then
536
+ if [ "$SPEC_OPTIONAL" = "1" ]; then
537
+ echo "########## $page ##########"
538
+ echo "WARNING: no '## $page' section in matching/SPEC.md \u2014 Phase 1 not done."
539
+ echo " Running anyway because SPEC_OPTIONAL=1 (baseline read only)."
540
+ echo " Do NOT apply geometry fixes off this run."
541
+ else
542
+ echo "########## $page ##########"
543
+ echo "REFUSED: no '## $page' section in matching/SPEC.md."
544
+ echo " Phase 1 (section census + per-section spec, read from"
545
+ echo " matching/spec/) comes before geometry."
546
+ echo " See CLAUDE.md rule 2. SPEC_OPTIONAL=1 for a baseline read."
547
+ FAILED_PREFLIGHT=1
548
+ return 0
549
+ fi
550
+ fi
551
+ echo "########## $page ##########"
552
+ # Same clock source and same format as page-diff's own meta.generatedAt, so
553
+ # the freshness comparison below is between two ISO strings from one clock.
554
+ local started
555
+ started="$(node -e 'process.stdout.write(new Date().toISOString())')"
556
+ node "$PD" --ref "$REF$refpath" --cand "$CAND$candpath" \\
557
+ --viewports "$MATRIX" --threshold "$THRESHOLD" \\
558
+ --sections "$sections" --out "matching/out-$TAG-$page" \\
559
+ > "matching/out-$TAG-$page.log" 2>&1
560
+ # IMMEDIATELY after the invocation. Any command in between \u2014 the echo
561
+ # included \u2014 destroys $?.
562
+ local status=$?
563
+ echo "$page exit=$status"
564
+ ATTEMPTED=$((ATTEMPTED + 1))
565
+ # $status may DENY a green; it may never GRANT one, and here it does neither.
566
+ # page-diff exits 1 for a region that legitimately FAILED (page-diff.mjs:227)
567
+ # and node exits 1 for the bare \`throw e\` below it, so the status cannot tell
568
+ # a finding from a crash before it looked \u2014 and a matching round's steady
569
+ # state IS a failing gate, so denying on it would break every normal round.
570
+ # Measured on 29 Navy with the reference alive and no dev server: \`home
571
+ # exit=1\`, \`ALL DONE\`, exit 0, and no matching/out-*-home/ written at all.
572
+ # What only a completed run leaves is the report next.mjs will count.
573
+ # census.sh:17-32 is the same argument for style-census.
574
+ local evidence
575
+ if evidence="$(node "$(dirname "$0")/harness.mjs" --check-run "$page" "matching/out-$TAG-$page" "$started" 2>&1)"; then
576
+ MEASURED=$((MEASURED + 1))
577
+ else
578
+ UNMEASURED="$UNMEASURED $page"
579
+ echo " NOT MEASURED: $evidence"
580
+ fi
581
+ }
582
+
583
+ # The page table is matching/harness.json. Process substitution, NOT a pipe:
584
+ # a pipe would run this loop in a subshell and FAILED_PREFLIGHT would not
585
+ # survive to the check below, so a refused page would exit 0.
586
+ while IFS=$'\\t' read -r key refpath candpath anchors; do
587
+ run "$key" "$refpath" "$candpath" "$anchors"
588
+ done < <(node "$(dirname "$0")/harness.mjs" --table)
589
+
590
+ # BOTH kinds of incompleteness are reported in one run: a page refused before
591
+ # it ran, and a page that ran and left nothing countable. Exiting on the first
592
+ # would hide the second from an operator who then fixes only what was printed.
593
+ INCOMPLETE=0
594
+ if [ -n "$UNMEASURED" ]; then
595
+ echo
596
+ echo "GATE INCOMPLETE ($TAG) \u2014 $((ATTEMPTED - MEASURED)) of $ATTEMPTED page(s) produced no"
597
+ echo "countable report:$UNMEASURED"
598
+ echo "Those pages have NOT been measured. next.mjs drops an unreported page from"
599
+ echo "BOTH sides of the score, so the pages that did report would read as the"
600
+ echo "whole site. Full runs: matching/out-$TAG-<page>.log"
601
+ INCOMPLETE=1
602
+ fi
603
+ if [ "\${FAILED_PREFLIGHT:-0}" = "1" ]; then
604
+ echo
605
+ echo "GATE INCOMPLETE ($TAG) \u2014 one or more pages were refused for a missing"
606
+ echo "SPEC.md section. Those pages have NOT been measured; do not report a"
607
+ echo "score for them."
608
+ INCOMPLETE=1
609
+ fi
610
+ if [ "$INCOMPLETE" = "1" ]; then
611
+ exit 2
612
+ fi
613
+ # A green over ZERO pages is still a green. Measured: \`gate.sh nosuch
614
+ # nosuchpage\` printed ALL DONE and exited 0 having run nothing and printed no
615
+ # page header at all. census.sh:199-209 refuses exactly this shape, and
616
+ # strikes.mjs:147-156 was written because a typo silently greened rule 3 on six
617
+ # of nine pages.
618
+ if [ "$ATTEMPTED" -eq 0 ]; then
619
+ if [ -n "$SEEN" ]; then
620
+ echo "gate.sh: \\"\${WANT[*]:-}\\" matches no page \u2014 refusing to report ALL DONE." >&2
621
+ echo " known pages:$SEEN" >&2
622
+ else
623
+ echo "gate.sh: the page table is empty \u2014 refusing to report ALL DONE." >&2
624
+ echo " node matching/harness.mjs --table printed no rows; check" >&2
625
+ echo " \\"pages\\" in matching/harness.json." >&2
626
+ fi
627
+ exit 2
628
+ fi
629
+ # A green that STATES what it is made of (census.sh:219), so a green over
630
+ # nothing cannot read like a green over the table.
631
+ echo "ALL DONE ($TAG) \u2014 $MEASURED of $ATTEMPTED page(s) measured, each one counted."
632
+ `;
633
+ var CENSUS_SH_RELATIVE = "matching/census.sh";
634
+ var CENSUS_SH_TEMPLATE = `#!/usr/bin/env bash
635
+ # Phase 3 style gate \u2014 the mechanical net for the type spec.
636
+ #
637
+ # bash matching/census.sh # all 9 pages, all 3 viewports
638
+ # bash matching/census.sh home yfv # just these
639
+ #
640
+ # style-census diffs the computed type tuple (family, weight, size,
641
+ # line-height, letter-spacing, transform, colour) of every text snippet present
642
+ # on BOTH pages. It is the only gate that catches the 11px footer line and the
643
+ # cyan-vs-teal link that page-diff is structurally blind to \u2014 a region can be
644
+ # pixel-clean at 0.10 and still be wearing the wrong colour on small text.
645
+ #
646
+ # Prints a per-page/per-viewport mismatch count and leaves the full runs in
647
+ # matching/census-<page>-<vw>.log. Exits 1 while any count is non-zero, and 2
648
+ # when it cannot honestly report a count at all.
649
+ #
650
+ # EVIDENCE \u2014 read before adding a guard here, or removing one. A green here
651
+ # has to be produced by a census that RAN. It was not: with style-census.mjs
652
+ # absent this gate printed "Phase 3 CLEAN \u2014 0 undeclared type mismatches" and
653
+ # exited 0. Every run died on module resolution, census-count.mjs read each
654
+ # crash log as "0 0 0" (it counts \` y=\` rows and a stack trace has none \u2014
655
+ # census-count.mjs:35-56), and no rows was reported as no mismatches. Measured
656
+ # again with style-census.mjs PRESENT and the candidate host down: identical
657
+ # output, because style-census exits 1 both when it finds mismatches
658
+ # (style-census.mjs:187) and when it dies before it looks \u2014 so the exit status
659
+ # cannot tell a finding from a crash and may not grant a green either.
660
+ #
661
+ # The guards below are what next.mjs:83-89 (no parseable gate run \u2014 refusing to
662
+ # report a score), strikes.mjs:87-97 (refusing to report "clear") and
663
+ # gate.sh:37-42 (preflight page-diff before spending a run) already do. Each
664
+ # demands an artefact only a working census produces; none of them can turn a
665
+ # red green.
666
+ set -uo pipefail
667
+ # Resolved BEFORE the cd. $0 is the path as TYPED, so a relatively invoked
668
+ # census.sh that resolved the harness afterwards would look for it under
669
+ # whatever root the cd landed on.
670
+ HARNESS="$(cd "$(dirname "$0")" && pwd)/harness.mjs"
671
+ cd "$(dirname "$0")/.."
672
+
673
+ # Everything configurable lives in matching/harness.json; harness.mjs is the one
674
+ # reader. --env supplies REF, CAND, SC and VIEWPORTS_SP \u2014 this gate held its own
675
+ # copy of all four, and its REF went stale when production cut over to our own
676
+ # build (LEDGER "REFERENCE MOVED", verified 2026-08-10) while gate.sh's was
677
+ # repointed the same day.
678
+ eval "$(node "$HARNESS" --env)"
679
+ NODE="\${NODE:-node}"
680
+
681
+ # The matrix is DATA, read as VIEWPORTS_SP, the way gate.sh reads MATRIX. The
682
+ # old VIEWPORTS override is retired rather than silently ignored: a census run
683
+ # over a matrix harness.json does not name is a column set the pixel gate never
684
+ # measured, and it would look exactly like a clean one.
685
+ if [ -n "\${VIEWPORTS:-}" ]; then
686
+ echo "census.sh: the VIEWPORTS override is retired \u2014 the matrix is data now." >&2
687
+ echo " Edit \\"matrix\\" in matching/harness.json, then unset it." >&2
688
+ exit 2
689
+ fi
690
+
691
+ # GUARD 1 \u2014 the tool is there and it starts. gate.sh compares \`page-diff
692
+ # --version\` with the harness's REPORT_SCHEMA before spending a run
693
+ # (gate.sh:37-42); style-census has no --version to compare (page-diff.mjs
694
+ # defines one at 191-195; nothing in style-census.mjs writes one), so the
695
+ # artefact demanded here is the other one only it produces: the usage banner it
696
+ # prints on exit 2 when --ref/--cand are missing (style-census.mjs:151-157).
697
+ # That banner is not free \u2014 \`import { chromium } from "playwright"\` runs first
698
+ # (style-census.mjs:19) \u2014 so a skill directory with no playwright installed
699
+ # fails HERE, once, instead of writing one crash log per page per viewport that
700
+ # every reader downstream counts as zero.
701
+ if [ ! -f "$SC" ]; then
702
+ echo "census.sh: no style-census at $SC \u2014 refusing to report a count." >&2
703
+ echo " Install the matching-a-page skill, or point MATCHING_SKILL_DIR" >&2
704
+ echo " at a checkout that has style-census.mjs." >&2
705
+ exit 2
706
+ fi
707
+ SC_USAGE="$("$NODE" "$SC" 2>&1)"
708
+ case "$SC_USAGE" in
709
+ *"style-census"*"--ref"*"--cand"*"--vw"*) ;;
710
+ *)
711
+ echo "census.sh: $SC did not answer with a style-census --ref/--cand/--vw usage" >&2
712
+ echo " banner \u2014 refusing to report a count. It printed:" >&2
713
+ echo " \${SC_USAGE:-(nothing at all)}" >&2
714
+ exit 2
715
+ ;;
716
+ esac
717
+
718
+ declare -a WANT=("$@")
719
+
720
+ # page -> "refpath candpath": the same table gate.sh drives, from the same file.
721
+ # cut drops the anchors column, which the style census has no argument for
722
+ # (style-census.mjs: --ref <url> --cand <url> [--vw 1440]).
723
+ pages() { node "$HARNESS" --table | cut -f1-3; }
724
+
725
+ TOTAL=0
726
+ AMB=0
727
+ DECL=0
728
+ ROWS=0
729
+ RUNS=0
730
+ BROKEN=0
731
+ SEEN=""
732
+ # One column per viewport, from the matrix. Flush with the data rows below, at
733
+ # last: the old header hardcoded four fixed fields separated by a literal space,
734
+ # which the rows do not have, so its labels sat 1/2/3 columns right of them.
735
+ printf '%-10s' page
736
+ for vw in $VIEWPORTS_SP; do printf '%8s' "$vw"; done
737
+ printf '\\n'
738
+ while read -r page refpath candpath; do
739
+ [ -z "$page" ] && continue
740
+ SEEN="$SEEN $page"
741
+ if [ \${#WANT[@]} -gt 0 ]; then
742
+ hit=0
743
+ for w in "\${WANT[@]}"; do [ "$w" = "$page" ] && hit=1; done
744
+ [ $hit -eq 1 ] || continue
745
+ fi
746
+ ROWS=$((ROWS + 1))
747
+ line=$(printf '%-10s' "$page")
748
+ for vw in $VIEWPORTS_SP; do
749
+ log="matching/census-$page-$vw.log"
750
+ RUNS=$((RUNS + 1))
751
+ "$NODE" "$SC" --ref "$REF$refpath" --cand "$CAND$candpath" --vw "$vw" >"$log" 2>&1
752
+ # GUARD 2 \u2014 this run produced a census. The header and the counts line are
753
+ # written together at style-census.mjs:166-169 and only after both pages
754
+ # have been walked, so they are the artefact a completed run leaves and a
755
+ # crashed one cannot. The viewport is read back out of the header because a
756
+ # --vw that did not take would otherwise fill three differently named logs
757
+ # with the same 1440 census. \`ref runs\`/\`cand runs\` must be non-zero: two
758
+ # pages that rendered no text at all agree perfectly and mean nothing.
759
+ if ! grep -qE "^=== style census, viewport $vw ===\\$" "$log" ||
760
+ ! grep -qE "^ref runs: [1-9][0-9]* +cand runs: [1-9][0-9]* +mismatches: [0-9]+ +ambiguous: [0-9]+\\$" "$log"; then
761
+ BROKEN=$((BROKEN + 1))
762
+ echo "census.sh: $page @$vw produced no usable census \u2014 see $log" >&2
763
+ line="$line$(printf '%8s' '!!')"
764
+ continue
765
+ fi
766
+ # census-count splits the log three ways: REAL mismatches, AMBIGUOUS
767
+ # same-text collisions (style-census's own split), and DECLARED rows the
768
+ # operator has already ruled on (matching/census-deviations.mjs, the same
769
+ # contract as floors.mjs). Only the first is outstanding work \u2014 without the
770
+ # third, this gate can never reach zero and its number means nothing.
771
+ read -r n a d <<<"$("$NODE" matching/census-count.mjs "$log")"
772
+ # GUARD 2b \u2014 three integers, or the counter did not count. census-count.mjs
773
+ # is the reader that turned a stack trace into "0 0 0"; a run of it that
774
+ # dies (a broken census-deviations.mjs, a bad path) prints nothing at all,
775
+ # and bash reads an empty $n as zero in the arithmetic below.
776
+ counted=1
777
+ for v in "\${n:-}" "\${a:-}" "\${d:-}"; do
778
+ case "$v" in "" | *[!0-9]*) counted=0 ;; esac
779
+ done
780
+ if [ "$counted" -eq 0 ]; then
781
+ BROKEN=$((BROKEN + 1))
782
+ echo "census.sh: census-count.mjs did not return three counts for $log" >&2
783
+ line="$line$(printf '%8s' '!!')"
784
+ continue
785
+ fi
786
+ # GUARD 2c \u2014 the number reported is the number the census MEASURED. GUARD 2
787
+ # matched the counts line for PRESENCE and threw its numbers away, so the
788
+ # count printed below came from census-count's row parse and nothing ever
789
+ # compared the two. Measured 2026-09-09: a COMPLETE census whose counts line
790
+ # said "mismatches: 3", whose \`y=\` rows carried one leading space instead of
791
+ # two (census-count.mjs:39 matches /^ {2}y=/), was reported as 0 and this
792
+ # gate printed "Phase 3 CLEAN \u2014 0 undeclared type mismatches", exit 0. The
793
+ # printer lives in the SKILL (style-census.mjs:171-173) and the parser is
794
+ # copied into every site, so the two version independently and drift needs
795
+ # nobody to touch either repo.
796
+ #
797
+ # The identity is exact for mismatches: style-census prints at most 100 rows
798
+ # and states the remainder on its own line (style-census.mjs:175-177), so
799
+ # parsed + remainder == reported. Ambiguous rows are capped the same way
800
+ # (:184) but the remainder is NOT stated, so only a floor is checkable
801
+ # there \u2014 any is not none, and the parse may never exceed the report.
802
+ counts=$(grep -E "^ref runs: [1-9][0-9]* +cand runs: [1-9][0-9]* +mismatches: [0-9]+ +ambiguous: [0-9]+$" "$log" | tail -1)
803
+ said_m=\${counts##*mismatches: }
804
+ said_m=\${said_m%% *}
805
+ said_a=\${counts##*ambiguous: }
806
+ more=$(sed -n 's/^ *\u2026 and \\([0-9][0-9]*\\) more (truncated print, all counted)$/\\1/p' "$log" | tail -1)
807
+ if [ $((n + d + \${more:-0})) -ne "$said_m" ] ||
808
+ [ "$a" -gt "$said_a" ] ||
809
+ { [ "$said_a" -gt 0 ] && [ "$a" -eq 0 ]; }; then
810
+ BROKEN=$((BROKEN + 1))
811
+ echo "census.sh: $log reports mismatches: $said_m ambiguous: $said_a, but" >&2
812
+ echo " census-count.mjs read $((n + d)) mismatch row(s)\${more:+ (+ $more truncated)} and $a ambiguous." >&2
813
+ echo " The census and its reader disagree; there is no count to report." >&2
814
+ line="$line$(printf '%8s' '!!')"
815
+ continue
816
+ fi
817
+ AMB=$((AMB + a))
818
+ DECL=$((DECL + d))
819
+ TOTAL=$((TOTAL + n))
820
+ line="$line$(printf '%8s' "$n")"
821
+ done
822
+ echo "$line"
823
+ done < <(pages)
824
+
825
+ echo
826
+ # GUARD 3 \u2014 something was actually censused. Process substitution above, NOT a
827
+ # pipe: a pipe runs the loop in a subshell and every counter here would still
828
+ # read 0, which is exactly the green this file exists to stop (gate.sh:123-125
829
+ # records the same trap for FAILED_PREFLIGHT). A page name that matches nothing
830
+ # must not report CLEAN either \u2014 strikes.mjs:147-156 is the same refusal, and
831
+ # it was written because a typo silently greened rule 3 on six of nine pages.
832
+ if [ "$ROWS" -eq 0 ]; then
833
+ if [ -n "$SEEN" ]; then
834
+ echo "census.sh: \\"\${WANT[*]:-}\\" matches no page \u2014 refusing to report CLEAN." >&2
835
+ echo " known pages:$SEEN" >&2
836
+ else
837
+ echo "census.sh: the page table is empty \u2014 refusing to report CLEAN." >&2
838
+ echo " node matching/harness.mjs --table printed no rows; check" >&2
839
+ echo " \\"pages\\" in matching/harness.json." >&2
840
+ fi
841
+ exit 2
842
+ fi
843
+ if [ "$BROKEN" -gt 0 ]; then
844
+ echo "CENSUS INCOMPLETE \u2014 $BROKEN of $RUNS run(s) produced no usable census (marked !!)."
845
+ echo "Those page/viewport pairs have NOT been measured; there is no count to"
846
+ echo "report for them, and the totals below would be a floor, not a score."
847
+ echo "Full runs: matching/census-<page>-<vw>.log"
848
+ exit 2
849
+ fi
850
+ if [ "$TOTAL" -eq 0 ]; then
851
+ echo "Phase 3 CLEAN \u2014 0 undeclared type mismatches ($DECL declared, $AMB ambiguous)."
852
+ echo "($RUNS censused run(s) over $ROWS page(s), each one counted.)"
853
+ [ "$AMB" -gt 0 ] && echo "($AMB ambiguous same-text rows remain: each needs ADJUDICATING," &&
854
+ echo " not fixing \u2014 our element matches, another sharing its text does not.)"
855
+ exit 0
856
+ fi
857
+ echo "$TOTAL type mismatch(es) remain (+ $AMB ambiguous, $DECL declared)."
858
+ echo "Full runs: matching/census-<page>-<vw>.log"
859
+ echo "A mismatch is a defect or a ledgered deviation. An ambiguous row is neither"
860
+ echo "until you look: the census keys on TEXT, so two different elements sharing a"
861
+ echo "string land under one key and only one of them may be wrong."
862
+ exit 1
863
+ `;
864
+ var NEXT_MJS_RELATIVE = "matching/next.mjs";
865
+ var NEXT_MJS_TEMPLATE = `// What is still broken, ranked. Exits 1 while work remains.
866
+ //
867
+ // node matching/next.mjs
868
+ //
869
+ // Round protocol step 0 (repo CLAUDE.md rule 5). A commit is a CHECKPOINT, not
870
+ // a stopping point: after committing, run this. If it exits 1 there is a named
871
+ // next action and the round continues without handing control back.
872
+ //
873
+ // Reads the most recent gate log per page rather than the whole corpus, so it
874
+ // reflects HEAD rather than history (that is strikes.mjs's job).
875
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
876
+ import { join } from "node:path";
877
+
878
+ const DIR = new URL(".", import.meta.url).pathname;
879
+
880
+ // PAUSE SWITCH. While matching/PAUSED exists this hands out no agenda and
881
+ // exits 0. It is deliberately the FIRST thing that runs: no report is read, no
882
+ // score is printed, nothing tempting is put on screen to argue with.
883
+ //
884
+ // Why an exit code and not a note somewhere: rule 5 is a LOOP \u2014 "after
885
+ // committing, run next.mjs; while it exits 1 there is a named next action and
886
+ // the round continues". A pause written as prose loses to that loop, because
887
+ // the loop is mechanical and the prose is not. Exiting 0 satisfies rule 5
888
+ // truthfully rather than suspending it: there is no next action.
889
+ const PAUSE = join(DIR, "PAUSED");
890
+ if (existsSync(PAUSE)) {
891
+ console.log("MATCHING PAUSED \u2014 no agenda, and none is to be inferred.\\n");
892
+ console.log(readFileSync(PAUSE, "utf8").trimEnd());
893
+ process.exit(0);
894
+ }
895
+
896
+ import { FLOORS, ACCEPTED } from "./floors.mjs";
897
+ import {
898
+ TOTALS,
899
+ THRESHOLD,
900
+ MAX_HEIGHT_DELTA,
901
+ REPORT_SCHEMA,
902
+ uncountable,
903
+ scorable,
904
+ unscorableWhy,
905
+ byKey,
906
+ } from "./harness.mjs";
907
+
908
+ // Reports written by a different page-diff, by page key. Kept rather than
909
+ // dropped: silently ignoring them is how a page vanishes from the score.
910
+ const schemaMismatch = new Set();
911
+
912
+ const latest = new Map();
913
+ for (const d of readdirSync(DIR).filter((d) => d.startsWith("out-"))) {
914
+ const m = /^out-[^-]+-(.+)$/.exec(d);
915
+ // Membership in the page table is asked of the TABLE. \`!TOTALS[m[1]]\` was a
916
+ // NUMBER standing in for a fact: it is null for an unanchored page and 0 for
917
+ // an empty matrix, and either dropped the page out of \`latest\` while
918
+ // \`Object.keys(TOTALS)\` still listed it \u2014 so a gate run that had just
919
+ // SUCCEEDED came back as "no countable gate run".
920
+ if (!m || !byKey[m[1]]) continue;
921
+ let report, mtime;
922
+ try {
923
+ const p = join(DIR, d, "report.json");
924
+ report = JSON.parse(readFileSync(p, "utf8"));
925
+ mtime = statSync(p).mtimeMs;
926
+ } catch {
927
+ continue;
928
+ }
929
+ // A masked / media-neutralised run is a DIAGNOSTIC, never the state of the
930
+ // page. Picking one up as "latest" silently reports scores nobody can ship \u2014
931
+ // it happened immediately: an --mask-photos probe of yfv made \`top\` @834 read
932
+ // 43.9% here while the real gate had it passing at 1.3%. Missing
933
+ // schemaVersion means "written before the field existed" = 0; it is not an
934
+ // error on its own, only when it would blank a page.
935
+ //
936
+ // The predicate itself lives in harness.mjs now, because gate.sh asks the
937
+ // same question per run and two copies of one question drift \u2014 a gate that
938
+ // greens a run this file then drops is the same false green one step along.
939
+ const why = uncountable(report.meta ?? {});
940
+ if (why === "schema") {
941
+ schemaMismatch.add(m[1]);
942
+ continue;
943
+ }
944
+ if (why) continue;
945
+ const prev = latest.get(m[1]);
946
+ if (!prev || mtime > prev.mtime) latest.set(m[1], { dir: d, mtime, report });
947
+ }
948
+
949
+ const blanked = [...schemaMismatch].filter((p) => !latest.has(p));
950
+ if (blanked.length) {
951
+ console.error(
952
+ \`next: \${blanked.length} page(s) have no run at report schema \${REPORT_SCHEMA} \u2014 \` +
953
+ \`their newest reports came from a different page-diff (\${blanked.sort().join(", ")}).\\n\` +
954
+ \` Re-run: bash matching/gate.sh <tag> \${blanked.sort().join(" ")}\`,
955
+ );
956
+ process.exit(2);
957
+ }
958
+ if (latest.size === 0) {
959
+ console.error(
960
+ "next: no parseable gate run under matching/ \u2014 refusing to report a score.\\n" +
961
+ " Run bash matching/gate.sh <tag> first.",
962
+ );
963
+ process.exit(2);
964
+ }
965
+
966
+ const rows = [];
967
+ const accepted = [];
968
+ let openTotal = 0;
969
+ let floorTotal = 0;
970
+ for (const [page, { dir, report }] of latest) {
971
+ const fails = report.regions.filter((r) => !r.pass);
972
+ for (const f of fails) {
973
+ const floor = FLOORS.find((fl) => fl.match(f, page));
974
+ if (floor) {
975
+ floorTotal++;
976
+ continue;
977
+ }
978
+ const ack = ACCEPTED.find((a) => a.match(f, page));
979
+ if (ack) {
980
+ accepted.push({ page, vw: f.viewport, label: f.label, why: ack.why });
981
+ continue;
982
+ }
983
+ openTotal++;
984
+ rows.push({
985
+ page,
986
+ vw: f.viewport,
987
+ label: f.label,
988
+ mm: f.mismatchFraction,
989
+ dh: f.heightDeltaFraction ?? 0,
990
+ dir,
991
+ });
992
+ }
993
+ }
994
+
995
+ // Pages that REPORTED but cannot be scored: no anchors, so their regions are
996
+ // whatever page-diff's fallback cut and there is no model for one to be right
997
+ // against. Kept separate from \`scored\` and never ranked with it.
998
+ const unscorable = [...latest.entries()]
999
+ .filter(([p]) => !scorable(p))
1000
+ .map(([p, v]) => ({ p, regions: v.report.regions.length }))
1001
+ .sort((a, b) => a.p.localeCompare(b.p));
1002
+
1003
+ // \`.filter(scorable)\` before \`.map\`, because the sort below divides by \`total\`
1004
+ // and an unanchored page's ratio is NOT BOUNDED BY 1. A passing one scored
1005
+ // 16/4 = 4.0 and sorted LAST, i.e. best, so \`worst\` could never name the one
1006
+ // page whose Phase 1 was not done; a failing one scored 0/4 = 0.0, sorted
1007
+ // FIRST, and put \`grid-0-0\`, \`grid-1-0\` \u2026 on the agenda \u2014 an instruction to fix
1008
+ // geometry against regions page-diff invented.
1009
+ const scored = [...latest.entries()]
1010
+ .filter(([p]) => scorable(p))
1011
+ .map(([p, v]) => ({
1012
+ p,
1013
+ pass: v.report.regions.filter((r) => r.pass).length,
1014
+ total: TOTALS[p],
1015
+ }))
1016
+ .sort((a, b) => a.pass / a.total - b.pass / b.total);
1017
+
1018
+ // The denominator is the DECLARED site, not the pages that happened to report.
1019
+ // Summed over \`scored\` it shrank to match the numerator: 8 of 9 pages reporting
1020
+ // read SCORE 160/160 while the ninth, whose page-diff had crashed, was in
1021
+ // neither the numerator nor the denominator nor the list below. harness.mjs:61-67
1022
+ // already gives the reason \u2014 "a wrong denominator makes the score a lie in the
1023
+ // flattering direction" \u2014 and that fix was applied per REGION (\`total:
1024
+ // TOTALS[p]\`) and never per PAGE.
1025
+ const unmeasured = Object.keys(TOTALS)
1026
+ .filter((p) => !latest.has(p))
1027
+ .sort();
1028
+ const sum = scored.reduce((a, s) => a + s.pass, 0);
1029
+ // Summed EXPLICITLY over the scorable pages rather than over TOTALS' values:
1030
+ // \`a + null\` is silently \`a\`, and a denominator that is right only because of a
1031
+ // coercion is the same lie one refactor away.
1032
+ const pagesAll = Object.keys(TOTALS).length;
1033
+ const pagesScorable = Object.keys(TOTALS).filter((p) => scorable(p)).length;
1034
+ const max = Object.keys(TOTALS).reduce((a, p) => a + (scorable(p) ? TOTALS[p] : 0), 0);
1035
+
1036
+ // A score is printed only if SOMETHING can carry one. \`SCORE 0/0\` is a third
1037
+ // lie and the one that reads best of all, so it is never printed: with nothing
1038
+ // scorable the line says so in words and gives no fraction to quote.
1039
+ console.log(
1040
+ (pagesScorable === 0
1041
+ ? \`NO SCORE \u2014 0 of \${pagesAll} page(s) can carry one.\`
1042
+ : \`SCORE \${sum}/\${max} regions passing over \${pagesScorable} of \${pagesAll} page(s)\` +
1043
+ (unmeasured.length ? \` \u2014 \${unmeasured.length} page(s) NOT MEASURED\` : "")) + "\\n",
1044
+ );
1045
+ console.log(
1046
+ [
1047
+ ...scored.map((s) => \` \${s.p.padEnd(9)} \${String(s.pass).padStart(2)}/\${s.total}\`),
1048
+ // The run's OWN region count, as EVIDENCE FOR THE REFUSAL \u2014 it proves a run
1049
+ // happened and explains why it cannot be scored, so a refusal is not
1050
+ // mistaken for a crash. The pass FRACTION is deliberately withheld: it is
1051
+ // the number with no referent, and the number that gets quoted.
1052
+ ...unscorable.map(
1053
+ (u) =>
1054
+ \` \${u.p.padEnd(9)} \${String(u.regions).padStart(2)} region(s) NOT SCORABLE \u2014 \${unscorableWhy(u.p)}\`,
1055
+ ),
1056
+ // \`?/N\`, never \`0/N\`: an unmeasured page is not a page that scored zero,
1057
+ // and printing zero would be a different lie. \`?/?\` when the page is ALSO
1058
+ // unanchored \u2014 \`?/null\` would name the denominator "null", which is worse
1059
+ // than the number it replaced.
1060
+ ...unmeasured.map((p) => \` \${p.padEnd(9)} ?/\${TOTALS[p] ?? "?"} NOT MEASURED\`),
1061
+ ].join("\\n"),
1062
+ );
1063
+
1064
+ if (accepted.length) {
1065
+ console.log(\`\\nOperator-ACCEPTED failures (left failing on purpose):\`);
1066
+ for (const a of accepted)
1067
+ console.log(\` \${a.page} @\${a.vw} "\${a.label}" \u2014 \${a.why.slice(0, 96)}\u2026\`);
1068
+ }
1069
+
1070
+ // BEFORE the \`!rows.length\` branch, and deliberately so: an unmeasured page
1071
+ // contributes no failing region, so that branch would print "Backlog is empty"
1072
+ // and exit 0 over a page nobody had looked at. Exit 2 matches the two guards
1073
+ // above (\`blanked\`, \`latest.size === 0\`) \u2014 neither "clean" nor "work remains"
1074
+ // but "this cannot be scored", the one answer rule 5's while-it-exits-1 loop
1075
+ // cannot swallow. The score print stays above it so the partial state is still
1076
+ // visible.
1077
+ // A page with no anchors has not finished Phase 1, so a score has no referent
1078
+ // and this refuses to invent one \u2014 the same answer \`refMark: ""\` gets from
1079
+ // checkRef and an absent \`## <page>\` SPEC section gets from gate.sh. All three
1080
+ // are seed sentinels, and this was the one that failed OPEN. Repo CLAUDE.md
1081
+ // rule 1's corollary is the whole argument: a field that can only observe
1082
+ // configuration must never be named after the thing it cannot observe, and
1083
+ // "12 of 12 grid rows passed" observes a screenshot cut into quarters, not a
1084
+ // design anyone specced.
1085
+ //
1086
+ // PRINTED here, EXITED below: \`unmeasured\` and \`unscorable\` are different pages
1087
+ // with different remedies, and exiting inside the first block would hide the
1088
+ // second from an operator who then fixes only what was printed.
1089
+ if (unscorable.length) {
1090
+ console.error(
1091
+ \`\\nnext: \${unscorable.length} page(s) have no anchors, so their regions are page-diff's own\\n\` +
1092
+ \` fallback cut and cannot be scored \u2014 \` +
1093
+ unscorable.map((u) => \`\${u.p} (\${u.regions} region(s))\`).join(", ") +
1094
+ \`.\\n Set "anchors" for them in matching/harness.json to section texts that exist on\\n\` +
1095
+ \` BOTH the reference and the candidate, then re-run: bash matching/gate.sh <tag> \` +
1096
+ unscorable.map((u) => u.p).join(" "),
1097
+ );
1098
+ }
1099
+
1100
+ if (unmeasured.length) {
1101
+ console.error(
1102
+ \`\\nnext: \${unmeasured.length} page(s) have no countable gate run \u2014 \${unmeasured.join(", ")}.\\n\` +
1103
+ \` Re-run: bash matching/gate.sh <tag> \${unmeasured.join(" ")}\`,
1104
+ );
1105
+ process.exit(2);
1106
+ }
1107
+
1108
+ // See above: deliberately a second statement, not an \`else\`.
1109
+ if (unscorable.length) process.exit(2);
1110
+
1111
+ if (!rows.length) {
1112
+ console.log(
1113
+ \`\\nNo open geometry failures. \${floorTotal} declared floor(s) remain.\`,
1114
+ );
1115
+ console.log(
1116
+ "Backlog is empty \u2014 Phases 5 (states) and 6 (adversarial review) are what is left.",
1117
+ );
1118
+ process.exit(0);
1119
+ }
1120
+
1121
+ // Worst page first, then worst region inside it: fix where the model is most wrong.
1122
+ //
1123
+ // INVARIANT, documented rather than guarded because no test could redden a
1124
+ // guard here: \`scored[0]\` is safe because \`scored\` is empty only when every
1125
+ // page in \`latest\` is unanchored \u2014 and that means \`unscorable.length > 0\`, so
1126
+ // the exit above already fired. (\`latest\` being empty is caught further up.)
1127
+ // \`rows\` likewise still contains unanchored pages' failing regions; they are
1128
+ // never printed because that same exit fires first. Both facts depend on the
1129
+ // exit staying ABOVE this line \u2014 a second filter here would be a second place
1130
+ // to keep in sync, which is how checkRun and next.mjs drifted apart to begin
1131
+ // with. If that exit ever moves, this becomes a TypeError.
1132
+ const worst = scored[0].p;
1133
+ rows.sort(
1134
+ (a, b) =>
1135
+ (a.page === worst ? -1 : 0) - (b.page === worst ? -1 : 0) || b.mm - a.mm,
1136
+ );
1137
+
1138
+ console.log(
1139
+ \`\\n\${openTotal} open failure(s) + \${floorTotal} declared floor(s).\`,
1140
+ );
1141
+ console.log(\`\\nNEXT: \${worst} \u2014 worst page. Its open regions:\\n\`);
1142
+ for (const r of rows.filter((r) => r.page === worst)) {
1143
+ const why = [];
1144
+ if (r.mm > THRESHOLD) why.push(\`pixels \${(r.mm * 100).toFixed(1)}%\`);
1145
+ if (Math.abs(r.dh) > MAX_HEIGHT_DELTA)
1146
+ why.push(\`height \${(r.dh * 100).toFixed(1)}%\`);
1147
+ console.log(
1148
+ \` @\${String(r.vw).padEnd(5)} \${r.label.slice(0, 44).padEnd(45)} \${why.join(" + ")}\`,
1149
+ );
1150
+ }
1151
+ console.log(\`\\nBefore treating any of these as geometry:\`);
1152
+ console.log(
1153
+ \` node matching/probe-anchor-parity.mjs \${worst} # is the gate cutting comparably?\`,
1154
+ );
1155
+ console.log(
1156
+ \` node matching/strikes.mjs \${worst} # has it stalled? then change the MODEL\`,
1157
+ );
1158
+ console.log(
1159
+ \`\\nRound continues. Do not hand back control with work outstanding.\`,
1160
+ );
1161
+ process.exit(1);
1162
+ `;
1163
+ var STRIKES_MJS_RELATIVE = "matching/strikes.mjs";
1164
+ var STRIKES_MJS_TEMPLATE = `// The 3-strike rule, made countable.
1165
+ //
1166
+ // node matching/strikes.mjs [page]
1167
+ //
1168
+ // The matching skill says: "A region that has not improved after 3 fix ->
1169
+ // re-run cycles: stop. Present the three attempts. Do not widen the threshold,
1170
+ // mask it, or reclassify it \u2014 a stuck region means your model of it is wrong."
1171
+ //
1172
+ // That rule was blown twice on this project (services \`top\`, yfv \`top\`) purely
1173
+ // because nobody was counting. This reads every matching/out-*/report.json,
1174
+ // reconstructs each region's history in chronological order, and prints the
1175
+ // regions that are OUT OF STRIKES. Exit 1 when any exist, so a round that
1176
+ // starts by running this cannot quietly attempt a fourth cycle.
1177
+ //
1178
+ // WHAT THIS ACTUALLY MEASURES (read before trusting a number): report.json
1179
+ // cannot record INTENT, so a "cycle" here is any completed gate run in which
1180
+ // the region was still failing and did not improve by IMPROVE_PP. Runs aimed at
1181
+ // a different region on the same page therefore count too. That makes this a
1182
+ // STALL detector, not a literal attempt counter \u2014 "this has been failing,
1183
+ // unchanged, across N gate runs while you were working on this page." That is
1184
+ // the more useful discipline number anyway, and it is honest about being an
1185
+ // upper bound. Improvement resets the count: real progress earns a fresh start.
1186
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
1187
+ import { join } from "node:path";
1188
+ import { FLOORS } from "./floors.mjs";
1189
+ import {
1190
+ PAGES,
1191
+ THRESHOLD,
1192
+ MAX_HEIGHT_DELTA,
1193
+ REPORT_SCHEMA,
1194
+ } from "./harness.mjs";
1195
+
1196
+ // PAUSE SWITCH \u2014 see matching/next.mjs for why this is an exit code. Round
1197
+ // protocol step 1 is "run strikes.mjs; the stalled regions are the agenda", so
1198
+ // this is the second door into the backlog and has to be shut too. Exits 0:
1199
+ // there are no strikes to spend when no round is being played.
1200
+ const PAUSED = join(new URL(".", import.meta.url).pathname, "PAUSED");
1201
+ if (existsSync(PAUSED)) {
1202
+ console.log("MATCHING PAUSED \u2014 no agenda, and none is to be inferred.\\n");
1203
+ console.log(readFileSync(PAUSED, "utf8").trimEnd());
1204
+ process.exit(0);
1205
+ }
1206
+
1207
+ const IMPROVE_PP = 0.01; // 1 percentage point = the smallest move worth calling progress
1208
+ const MAX_STRIKES = 3;
1209
+ const ROOT = new URL(".", import.meta.url).pathname;
1210
+ const only = process.argv[2] ?? null;
1211
+
1212
+ // The gate key for a report, from its ref path. Deriving it by string surgery
1213
+ // disagreed with the gate on exactly six of the nine rows \u2014 yfv, contact, atd,
1214
+ // svc, qa and team (measured 2026-09-09 against harness.json); the table knows.
1215
+ // keyOf (below) stays as the fallback for a run whose ref was rewritten.
1216
+ const pageOf = (ref) => {
1217
+ const path = new URL(ref).pathname.replace(/\\/$/, "") || "/";
1218
+ return PAGES.find((p) => p.ref === path)?.key ?? null;
1219
+ };
1220
+
1221
+ const runs = [];
1222
+ const unreadable = [];
1223
+ for (const dir of readdirSync(ROOT).filter((d) => d.startsWith("out-"))) {
1224
+ let report;
1225
+ try {
1226
+ report = JSON.parse(readFileSync(join(ROOT, dir, "report.json"), "utf8"));
1227
+ } catch {
1228
+ continue; // not a completed run dir
1229
+ }
1230
+ if (!report.meta?.ref || !Array.isArray(report.regions)) continue;
1231
+ // A report from another schema is still usable for a STALL count as long as
1232
+ // it carries the two fields this reads. Anything else is counted and named,
1233
+ // never silently dropped \u2014 an under-counted history reads as "clear".
1234
+ const usable = report.regions.every(
1235
+ (r) =>
1236
+ typeof r.mismatchFraction === "number" && typeof r.pass === "boolean",
1237
+ );
1238
+ if (!usable) {
1239
+ unreadable.push(\`\${dir} (schema \${report.meta.schemaVersion ?? 0})\`);
1240
+ continue;
1241
+ }
1242
+ runs.push({
1243
+ dir,
1244
+ at: report.meta.generatedAt,
1245
+ meta: report.meta,
1246
+ regions: report.regions,
1247
+ });
1248
+ }
1249
+
1250
+ // The failure mode of a stall detector is always "clear", which is exactly the
1251
+ // answer that stops nobody. A corpus this could not read is not a clean one.
1252
+ if (runs.length === 0) {
1253
+ console.error(
1254
+ \`strikes: no parseable gate run under matching/ \u2014 refusing to report "clear".\` +
1255
+ (unreadable.length
1256
+ ? \`\\n \${unreadable.length} report(s) unreadable at schema \${REPORT_SCHEMA}: \${unreadable.slice(0, 5).join(", ")}\`
1257
+ : ""),
1258
+ );
1259
+ process.exit(2);
1260
+ }
1261
+ if (unreadable.length) {
1262
+ console.error(
1263
+ \`strikes: ignored \${unreadable.length} unreadable report(s) \u2014 the history below is incomplete.\` +
1264
+ \`\\n \${unreadable.slice(0, 5).join(", ")}\`,
1265
+ );
1266
+ }
1267
+
1268
+ runs.sort((a, b) => a.at.localeCompare(b.at));
1269
+
1270
+ // The gate page KEY, recovered from the run dir the way next.mjs does it
1271
+ // (out-<TAG>-<page>, split on the first hyphen \u2014 the tag is hyphen-free by
1272
+ // gate.sh's own preflight). \`pageOf\` now returns that same key off the table,
1273
+ // so the two vocabularies agree and the round protocol in CLAUDE.md \u2014 "run
1274
+ // \`strikes.mjs <page>\` with the key you just passed to gate.sh", which until
1275
+ // 2026-08-13 silently matched nothing \u2014 works either way. This stays because
1276
+ // a dir key is not always a gate key: 69 of this corpus's 377 run dirs are
1277
+ // hand-named probes (out-band3, out-390masked), and FLOORS matches on it.
1278
+ const keyOf = (dir) => /^out-[^-]+-(.+)$/.exec(dir)?.[1] ?? null;
1279
+
1280
+ // key -> chronological list of {dir, at, mm, pass, masked}
1281
+ const history = new Map();
1282
+ const seenNames = new Set();
1283
+ for (const run of runs) {
1284
+ const page = pageOf(run.meta.ref) ?? keyOf(run.dir) ?? "unknown";
1285
+ const gateKey = keyOf(run.dir);
1286
+ seenNames.add(page);
1287
+ if (gateKey) seenNames.add(gateKey);
1288
+ if (only && page !== only && gateKey !== only) continue;
1289
+ for (const r of run.regions) {
1290
+ // A DECLARED FLOOR is flat by definition \u2014 reporting it as stalled is noise
1291
+ // that hides a real stall. It stays in the LEDGER; it does not belong here.
1292
+ if (FLOORS.some((fl) => fl.match(r, gateKey || page))) continue;
1293
+ const key = \`\${page}|\${r.viewport}|\${r.label}\`;
1294
+ if (!history.has(key)) history.set(key, []);
1295
+ history.get(key).push({
1296
+ dir: run.dir,
1297
+ at: run.at,
1298
+ mm: r.mismatchFraction,
1299
+ dh: r.heightDeltaFraction,
1300
+ pass: r.pass,
1301
+ // a run with masks/neutralised media is not comparable to a clean one
1302
+ dirty:
1303
+ (run.meta.mask?.length ?? 0) > 0 ||
1304
+ run.meta.neutralizeMedia ||
1305
+ run.meta.maskPhotos,
1306
+ });
1307
+ }
1308
+ }
1309
+
1310
+ // A name that matches no run must NOT report "clear". This check exists to stop
1311
+ // work on a stalled region, so failing open is the one thing it may never do \u2014
1312
+ // a typo'd or wrong-vocabulary page silently greened rule 3 for six of the nine
1313
+ // pages. Fail loud instead, and say what the vocabulary is.
1314
+ if (only && history.size === 0) {
1315
+ console.error(
1316
+ \`strikes: "\${only}" matches no gate run \u2014 refusing to report "clear".\\n\` +
1317
+ \` known pages: \${[...seenNames].sort().join(", ")}\`,
1318
+ );
1319
+ process.exit(2);
1320
+ }
1321
+
1322
+ const stuck = [];
1323
+ for (const [key, all] of history) {
1324
+ const h = all.filter((e) => !e.dirty); // compare like with like
1325
+ if (h.length === 0) continue;
1326
+ const last = h[h.length - 1];
1327
+ if (last.pass) continue;
1328
+
1329
+ let best = Infinity;
1330
+ let strikes = 0;
1331
+ let sinceIdx = 0;
1332
+ for (let i = 0; i < h.length; i++) {
1333
+ if (h[i].mm < best - IMPROVE_PP) {
1334
+ best = Math.min(best, h[i].mm);
1335
+ strikes = 0;
1336
+ sinceIdx = i;
1337
+ } else {
1338
+ best = Math.min(best, h[i].mm);
1339
+ strikes++;
1340
+ }
1341
+ }
1342
+ if (strikes >= MAX_STRIKES) stuck.push({ key, strikes, h, sinceIdx, last });
1343
+ }
1344
+
1345
+ // Triage order: the worst-matching region that has never moved is the one whose
1346
+ // model is most wrong. Sorting by strike count instead would put a 0.3% region
1347
+ // that only fails on height above a 76% region that fails on everything.
1348
+ stuck.sort((a, b) => b.last.mm - a.last.mm);
1349
+
1350
+ if (stuck.length === 0) {
1351
+ console.log(
1352
+ \`strikes: clear \u2014 no failing region has stalled for \${MAX_STRIKES}+ gate runs\` +
1353
+ (only ? \` on \${only}\` : "") +
1354
+ ".",
1355
+ );
1356
+ process.exit(0);
1357
+ }
1358
+
1359
+ const why = (e) => {
1360
+ const reasons = [];
1361
+ if (e.mm > THRESHOLD) reasons.push(\`pixels \${(e.mm * 100).toFixed(1)}%\`);
1362
+ if (Math.abs(e.dh ?? 0) > MAX_HEIGHT_DELTA)
1363
+ reasons.push(\`height \${((e.dh ?? 0) * 100).toFixed(1)}%\`);
1364
+ return reasons.join(" + ") || "marginal";
1365
+ };
1366
+
1367
+ console.log(
1368
+ \`STALLED \u2014 \${stuck.length} failing region(s) have not moved in \${MAX_STRIKES}+ gate runs.\\n\` +
1369
+ \`These need a new model or the operator, not another attempt. Worst first:\\n\`,
1370
+ );
1371
+ for (const { key, strikes, h, sinceIdx, last } of stuck.slice(0, 20)) {
1372
+ const [page, vw, label] = key.split("|");
1373
+ console.log(
1374
+ \`\${page} @\${vw} "\${label}" \u2014 \${why(last)}, flat across \${strikes} runs\`,
1375
+ );
1376
+ const window = h.slice(Math.max(0, sinceIdx));
1377
+ const shown = window.length > 4 ? [window[0], ...window.slice(-3)] : window;
1378
+ for (const [i, e] of shown.entries()) {
1379
+ const gap =
1380
+ window.length > 4 && i === 1
1381
+ ? \` ... \${window.length - 4} more ...\\n\`
1382
+ : "";
1383
+ console.log(
1384
+ gap +
1385
+ \` \${(e.mm * 100).toFixed(1).padStart(5)}% \${e.at.slice(0, 16).replace("T", " ")} \${e.dir}\`,
1386
+ );
1387
+ }
1388
+ console.log();
1389
+ }
1390
+ if (stuck.length > 20) console.log(\`... and \${stuck.length - 20} more.\\n\`);
1391
+ console.log(
1392
+ "Per the matching skill: present the attempts to the operator.\\n" +
1393
+ "Do NOT widen the threshold, add a mask, or reclassify them as a floor.",
1394
+ );
1395
+ process.exit(1);
1396
+ `;
1397
+ var BUILD_SPEC_MJS_RELATIVE = "matching/build-spec.mjs";
1398
+ var BUILD_SPEC_MJS_TEMPLATE = `// Assemble matching/SPEC.md from the per-page sections in spec-sections/.
1399
+ //
1400
+ // node matching/build-spec.mjs
1401
+ //
1402
+ // SPEC.md is the Phase 1 deliverable and the thing matching/gate.sh preflights
1403
+ // against, so it is GENERATED rather than hand-maintained: edit the section
1404
+ // file, rebuild. The page list comes from matching/harness.mjs (the same
1405
+ // reader gate.sh's \`--table\` loop uses) and the heading test from its
1406
+ // specHeadingRe, whose pattern is has_spec's grep verbatim \u2014 so a section can
1407
+ // no longer build fine here and then re-block its own page at the gate.
1408
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
1409
+ import { join } from "node:path";
1410
+ import { PAGES, specHeadingRe } from "./harness.mjs";
1411
+
1412
+ const DIR = new URL(".", import.meta.url).pathname;
1413
+ const SECTIONS = join(DIR, "spec-sections");
1414
+
1415
+ // Order = live's nav order, then the detail templates. Both fall out of the
1416
+ // table's own order within each group, so this is not a second list to keep.
1417
+ const KEYS = [
1418
+ ...PAGES.filter((p) => p.group === "nav"),
1419
+ ...PAGES.filter((p) => p.group !== "nav"),
1420
+ ].map((p) => p.spec ?? p.key);
1421
+
1422
+ const parts = [];
1423
+ const missing = [];
1424
+
1425
+ const chrome = join(SECTIONS, "_chrome.md");
1426
+ if (existsSync(chrome)) parts.push(readFileSync(chrome, "utf8").trim());
1427
+ else missing.push("_chrome");
1428
+
1429
+ for (const page of KEYS) {
1430
+ const file = join(SECTIONS, \`\${page}.md\`);
1431
+ if (!existsSync(file)) {
1432
+ missing.push(page);
1433
+ continue;
1434
+ }
1435
+ const body = readFileSync(file, "utf8").trim();
1436
+ // The preflight greps \`^##+ +<page>\`; a section that does not open with its
1437
+ // own key would build fine here and then refuse at the gate, which is the
1438
+ // most confusing possible failure. Catch it now.
1439
+ if (!specHeadingRe(page).test(body)) {
1440
+ console.error(
1441
+ \`WARNING: \${page}.md does not open with a '## \${page}' heading \u2014 gate.sh will still refuse this page.\`,
1442
+ );
1443
+ }
1444
+ parts.push(body);
1445
+ }
1446
+
1447
+ // The header is a spec-section like any other, so a site can say what a
1448
+ // citation looks like there and what its own ladders are. DEFAULT_HEADER is
1449
+ // what a site gets before it writes one: the two paragraphs that are true of
1450
+ // every project, and nothing that is not.
1451
+ const DEFAULT_HEADER = \`# Reference spec
1452
+
1453
+ GENERATED by \\\`node matching/build-spec.mjs\\\` from \\\`matching/spec-sections/\\\`.
1454
+ Edit the section files, not this one.
1455
+
1456
+ This is the Phase 1 deliverable of the \\\`matching-a-page\\\` skill and the
1457
+ precondition \\\`matching/gate.sh\\\` enforces: a page with no section here does not
1458
+ get a geometry round (see the matching rules in CLAUDE.md).
1459
+
1460
+ \`;
1461
+ const headerFile = join(SECTIONS, "_header.md");
1462
+ const header = existsSync(headerFile)
1463
+ ? readFileSync(headerFile, "utf8").trimEnd() + "\\n\\n"
1464
+ : DEFAULT_HEADER;
1465
+
1466
+ writeFileSync(join(DIR, "SPEC.md"), header + parts.join("\\n\\n---\\n\\n") + "\\n");
1467
+
1468
+ const built = KEYS.length - missing.filter((m) => m !== "_chrome").length;
1469
+ console.log(
1470
+ \`SPEC.md built \u2014 \${built}/\${KEYS.length} pages\${missing.length ? \`, MISSING: \${missing.join(", ")}\` : ""}\`,
1471
+ );
1472
+ process.exit(missing.length ? 1 : 0);
1473
+ `;
1474
+ var CENSUS_COUNT_MJS_RELATIVE = "matching/census-count.mjs";
1475
+ var CENSUS_COUNT_MJS_TEMPLATE = `// Count one style-census log, splitting declared deviations out of the total.
1476
+ //
1477
+ // node matching/census-count.mjs matching/census-home-1440.log
1478
+ // -> "<real> <ambiguous> <declared>"
1479
+ //
1480
+ // census.sh calls this per page/viewport. Parsing the log rather than importing
1481
+ // style-census keeps the project's declared-deviation policy out of the shared
1482
+ // skill \u2014 the skill reports what it sees; the project decides what it has
1483
+ // already agreed to.
1484
+ import { readFileSync } from "node:fs";
1485
+ import { DECLARED } from "./census-deviations.mjs";
1486
+
1487
+ const path = process.argv[2];
1488
+ if (!path) {
1489
+ console.error("usage: census-count.mjs <census log>");
1490
+ process.exit(2);
1491
+ }
1492
+
1493
+ // A log that cannot be READ is not a log with nothing IN it. This printed
1494
+ // "0 0 0" and exited 0, and census.sh added that to its total \u2014 the same green
1495
+ // it used to grant for a style-census that never ran. There is no count to
1496
+ // give here; say so and let the caller decide, which is never zero.
1497
+ let text = "";
1498
+ try {
1499
+ text = readFileSync(path, "utf8");
1500
+ } catch (e) {
1501
+ console.error(\`census-count: cannot read \${path} \u2014 \${e.message}\`);
1502
+ console.error(" a missing log is not a census with no findings.");
1503
+ process.exit(2);
1504
+ }
1505
+
1506
+ const [head, tail = ""] = text.split("--- AMBIGUOUS");
1507
+
1508
+ /** Pull \`{label, ref, cand}\` rows out of a census section. */
1509
+ function rows(section) {
1510
+ const out = [];
1511
+ const lines = section.split("\\n");
1512
+ for (let i = 0; i < lines.length; i++) {
1513
+ if (!/^ {2}y=/.test(lines[i])) continue;
1514
+ const label = lines[i].replace(/^\\s*y=\\s*\\d+\\s*/, "").trim();
1515
+ const refs = [];
1516
+ const cands = [];
1517
+ for (
1518
+ let j = i + 1;
1519
+ j < lines.length && /^ {4}(ref|cand):/.test(lines[j]);
1520
+ j++
1521
+ ) {
1522
+ const v = lines[j].replace(/^\\s*(ref|cand):\\s*/, "").trim();
1523
+ (lines[j].trim().startsWith("ref:") ? refs : cands).push(v);
1524
+ }
1525
+ if (refs.length && cands.length)
1526
+ out.push({ label, ref: refs[0], cand: cands[0] });
1527
+ else out.push({ label, ref: refs[0] ?? "", cand: cands[0] ?? "" });
1528
+ }
1529
+ return out;
1530
+ }
1531
+
1532
+ const mism = rows(head);
1533
+ const amb = rows(tail);
1534
+ const declared = mism.filter((r) => DECLARED.some((d) => d.match(r)));
1535
+ console.log(
1536
+ \`\${mism.length - declared.length} \${amb.length} \${declared.length}\`,
1537
+ );
1538
+ `;
1539
+ var HARNESS_JSON_RELATIVE = "matching/harness.json";
1540
+ var HARNESS_JSON_TEMPLATE = `{
1541
+ "ref": "__REF__",
1542
+ "cand": "http://localhost:5173",
1543
+ "matrix": [
1544
+ 1440,
1545
+ 834,
1546
+ 390
1547
+ ],
1548
+ "threshold": 0.1,
1549
+ "maxHeightDelta": 0.05,
1550
+ "refMark": "",
1551
+ "candMark": "_app/immutable",
1552
+ "selfHosts": [],
1553
+ "pages": {
1554
+ "home": {
1555
+ "uid": "home",
1556
+ "ref": "/",
1557
+ "cand": "/dev/match/home",
1558
+ "published": "/",
1559
+ "anchors": [],
1560
+ "spec": "home",
1561
+ "group": "nav"
1562
+ }
1563
+ }
1564
+ }
1565
+ `;
1566
+ var FLOORS_MJS_RELATIVE = "matching/floors.mjs";
1567
+ var FLOORS_MJS_TEMPLATE = `// The failures we have already established are NOT geometry. Shared by
1568
+ // next.mjs (which reports them separately from the backlog) and strikes.mjs
1569
+ // (which must not report them as stalled \u2014 a region that cannot move is flat
1570
+ // by definition, and three strikes on one is noise that hides a real stall).
1571
+ // Every entry needs a matching LEDGER entry to stay honest.
1572
+ //
1573
+ // NOTE the second matcher argument. Region records carry \`label\` and
1574
+ // \`viewport\` but not the page, so an entry keyed on label+viewport alone is
1575
+ // safe only where the label is unique site-wide. "top" is not \u2014 every page has
1576
+ // one \u2014 so such an entry would silently accept the \`top\` failure on EVERY page
1577
+ // and hide every real one. next.mjs and strikes.mjs pass the page key as the
1578
+ // second argument: take \`(r, page)\` unless you have checked the label.
1579
+
1580
+ /** Reference behaviour we cannot reproduce (declared floors). */
1581
+ export const FLOORS = [];
1582
+
1583
+ /** Regions the OPERATOR has looked at and chosen to leave failing. These are
1584
+ * not floors and are not silently dropped: next.mjs prints them under their
1585
+ * own heading with the decision, so the number never quietly improves. */
1586
+ export const ACCEPTED = [];
1587
+ `;
1588
+ var CENSUS_DEVIATIONS_MJS_RELATIVE = "matching/census-deviations.mjs";
1589
+ var CENSUS_DEVIATIONS_MJS_TEMPLATE = `// Style-census rows the OPERATOR has looked at and chosen to keep. Same
1590
+ // contract as matching/floors.mjs: nothing is hidden, everything is counted
1591
+ // under its own heading, and every entry needs a LEDGER entry to stay honest.
1592
+ //
1593
+ // node matching/census-count.mjs <log> -> "<real> <ambiguous> <declared>"
1594
+ //
1595
+ // Without this, \`census.sh\` can never reach zero and an "N remaining" figure
1596
+ // says nothing about how much work is left \u2014 one permanent decision is counted
1597
+ // once per page per viewport, so a single ACK can account for dozens of rows.
1598
+
1599
+ /** A row is \`{ label, ref, cand }\`, each of ref/cand a "fam | wt | size | lh |
1600
+ * ls | transform | colour" tuple string. */
1601
+ export const DECLARED = [];
1602
+ `;
1603
+ var SPEC_CHROME_MD_RELATIVE = "matching/spec-sections/_chrome.md";
1604
+ var SPEC_CHROME_MD_TEMPLATE = `## shared chrome
1605
+
1606
+ Site-wide furniture that renders identically on every page \u2014 header, footer, and
1607
+ anything else the per-page sections would otherwise restate. Phase 1 of the
1608
+ \`matching-a-page\` skill fills this in; until it does, this section is a
1609
+ placeholder and \`matching/SPEC.md\` has no shared-chrome contract to cite.
1610
+ `;
1611
+ var SPEC_HEADER_MD_RELATIVE = "matching/spec-sections/_header.md";
1612
+ var SPEC_HEADER_MD_TEMPLATE = `# Reference spec
1613
+
1614
+ GENERATED by \`node matching/build-spec.mjs\` from \`matching/spec-sections/\`.
1615
+ Edit the section files, not this one.
1616
+
1617
+ This is the Phase 1 deliverable of the \`matching-a-page\` skill and the
1618
+ precondition \`matching/gate.sh\` enforces: a page with no section here does not
1619
+ get a geometry round (see the matching rules in CLAUDE.md).
1620
+ `;
1621
+ var LEDGER_MD_RELATIVE = "matching/LEDGER.md";
1622
+ var LEDGER_MD_TEMPLATE = `# Deviations / masks / floors ledger
1623
+
1624
+ Append-only, and written at the moment a decision is made \u2014 not reconstructed at
1625
+ the end of a round, when the reason has already been lost. An entry is never
1626
+ edited to be right: a later entry corrects an earlier one and says which.
1627
+
1628
+ Every entry in \`matching/floors.mjs\` and \`matching/census-deviations.mjs\`, and
1629
+ every mask in \`matching/harness.json\`, needs a line here. Without one the gate
1630
+ has been quietly widened and nothing records who widened it, or why.
1631
+
1632
+ - [deviation | floor | mask | a11y] \`<region or selector>\` \u2014 what differs, why
1633
+ it is accepted, and the evidence: a spec citation, a census row, a gate run.
1634
+ `;
1635
+ var MATCH_ROUTE_SERVER_RELATIVE = "src/routes/dev/match/[uid]/+page.server.ts";
1636
+ var MATCH_ROUTE_SERVER_TEMPLATE = `import { error } from "@sveltejs/kit";
1637
+ import { dev } from "$app/environment";
1638
+ import { documents } from "$lib/site-pages.js";
1639
+
1640
+ // Local matching surface: renders the EXACT assembly \`reddoor-maint
1641
+ // prismic-seed\` publishes, from the same module, so a fix made to pass a gate
1642
+ // is a fix to what ships. Not prerendered, SSR-on-demand, dev-only.
1643
+ export const prerender = false;
1644
+
1645
+ // The seed resolves images to asset ids; here they only need a URL. Dimensions
1646
+ // are nominal \u2014 slices size their own image boxes in CSS.
1647
+ const devImg = (u: string) => ({
1648
+ url: u,
1649
+ alt: null,
1650
+ copyright: null,
1651
+ dimensions: { width: 1600, height: 1067 },
1652
+ edit: { x: 0, y: 0, zoom: 1, background: "transparent" },
1653
+ id: u,
1654
+ });
1655
+
1656
+ export async function load({ params }) {
1657
+ // FIRST statement: everything below reads fixtures that must not be reachable
1658
+ // from a production build. The launch recipe asserts this route 404s on the
1659
+ // deployed URL, with /dev/a11y-fixtures as the 200 control.
1660
+ if (!dev) error(404, { message: "Not found" });
1661
+
1662
+ const docs = documents(devImg) as Array<{ uid: string; data: { slices?: unknown[] } }>;
1663
+ const doc = docs.find((d) => d.uid === params.uid);
1664
+ if (!doc)
1665
+ error(404, {
1666
+ message: \`no assembly for "\${params.uid}" (have: \${docs.map((d) => d.uid).join(", ") || "none"})\`,
1667
+ });
1668
+
1669
+ return { uid: params.uid, slices: doc.data.slices ?? [] };
1670
+ }
1671
+ `;
1672
+ var MATCH_ROUTE_PAGE_RELATIVE = "src/routes/dev/match/[uid]/+page.svelte";
1673
+ var MATCH_ROUTE_PAGE_TEMPLATE = `<script lang="ts">
1674
+ import { SliceZone } from "@prismicio/svelte";
1675
+ import { components } from "$lib/slices";
1676
+
1677
+ let { data } = $props();
1678
+ </script>
1679
+
1680
+ <SliceZone slices={data.slices as never} {components} />
1681
+ `;
1682
+ var SITE_PAGES_JS_RELATIVE = "src/lib/site-pages.js";
1683
+ var SITE_PAGES_JS_TEMPLATE = `// The page assemblies for this site \u2014 the SINGLE source of truth for both
1684
+ // consumers: \`reddoor-maint prismic-seed\`, which publishes them through the
1685
+ // Migration API, and src/routes/dev/match/[uid], the local matching surface.
1686
+ // Because both read from here, any fix made to pass a gate is a fix to what
1687
+ // ships.
1688
+ //
1689
+ // THE MIGRATION API DROPS SILENTLY. It validates against the slice models
1690
+ // registered in Prismic and discards every field the model does not declare \u2014
1691
+ // HTTP 200, no warning. A fixture field with no model behind it renders here and
1692
+ // vanishes on the published route. src/lib/site-pages.test.ts is the mechanical
1693
+ // check; run it before every seed.
1694
+ //
1695
+ // PURE by contract: no node:*, no fetch, no token, no side effects at import,
1696
+ // so Vite can bundle it into the dev route and node can import it into the seed.
1697
+
1698
+ export const lang = "en-us";
1699
+
1700
+ /**
1701
+ * @param {(url: string) => unknown} img resolves an image URL to whatever the
1702
+ * caller needs \u2014 an asset \`{id}\` for the seed, a \`{url}\` for the dev route.
1703
+ * @returns {Array<{type: string, uid: string, title: string, data: Record<string, unknown>}>}
1704
+ */
1705
+ export function documents(img) {
1706
+ void img;
1707
+ return [];
1708
+ }
1709
+ `;
1710
+ var SITE_PAGES_TEST_RELATIVE = "src/lib/site-pages.test.ts";
1711
+ var SITE_PAGES_TEST_TEMPLATE = `// The page assemblies in src/lib/site-pages.js are the SINGLE source of truth
1712
+ // shared by two consumers: the local matching route (src/routes/dev/match/[uid])
1713
+ // and \`reddoor-maint prismic-seed\`, which publishes them to Prismic.
1714
+ //
1715
+ // Those two consumers do NOT validate the same way. The dev route hands the
1716
+ // object straight to the slice components, so any field a fixture sets is
1717
+ // simply there. The Migration API validates against the slice models registered
1718
+ // in Prismic and SILENTLY DROPS every field the model does not declare \u2014 no
1719
+ // error, no warning, a 200. A page can gate green locally and publish wrong.
1720
+ //
1721
+ // This test is the mechanical check. It fails the moment a fixture carries a
1722
+ // field its slice model does not declare \u2014 before the seed runs, not after the
1723
+ // content is published. Run it before every seed.
1724
+ import { describe, expect, it } from "vitest";
1725
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
1726
+ import { fileURLToPath } from "node:url";
1727
+ import { dirname, join } from "node:path";
1728
+ import { documents } from "./site-pages.js";
1729
+
1730
+ const HERE = dirname(fileURLToPath(import.meta.url));
1731
+ const SLICES = join(HERE, "slices");
1732
+
1733
+ type Variation = { primary: string[]; items: string[] };
1734
+ type Slice = {
1735
+ slice_type: string;
1736
+ variation: string;
1737
+ primary?: Record<string, unknown>;
1738
+ items?: Array<Record<string, unknown>>;
1739
+ };
1740
+
1741
+ /** Every slice model in src/lib/slices, indexed by its Prismic slice id. */
1742
+ function loadModels(): Record<string, Record<string, Variation>> {
1743
+ const out: Record<string, Record<string, Variation>> = {};
1744
+ if (!existsSync(SLICES)) return out;
1745
+ for (const dir of readdirSync(SLICES)) {
1746
+ const file = join(SLICES, dir, "model.json");
1747
+ if (!existsSync(file)) continue;
1748
+ const model = JSON.parse(readFileSync(file, "utf8"));
1749
+ out[model.id] = Object.fromEntries(
1750
+ (model.variations ?? []).map((v: Record<string, unknown>) => [
1751
+ v.id,
1752
+ {
1753
+ primary: Object.keys((v.primary as object) ?? {}),
1754
+ items: Object.keys((v.items as object) ?? {}),
1755
+ },
1756
+ ]),
1757
+ );
1758
+ }
1759
+ return out;
1760
+ }
1761
+
1762
+ /** Image resolver stub \u2014 shape only; this test never reads image values. */
1763
+ const stubImg = () => ({ url: "https://example.test/x.jpg" });
1764
+
1765
+ describe("site-pages documents vs slice models", () => {
1766
+ const models = loadModels();
1767
+ const docs = documents(stubImg) as Array<{ uid: string; data: { slices?: Slice[] } }>;
1768
+ const pages: Array<[string, Slice[]]> = docs.map((d) => [d.uid, d.data.slices ?? []]);
1769
+
1770
+ it("declares every slice type the documents use", () => {
1771
+ const missing = new Set<string>();
1772
+ for (const [, slices] of pages)
1773
+ for (const s of slices) if (!models[s.slice_type]) missing.add(s.slice_type);
1774
+ expect([...missing]).toEqual([]);
1775
+ });
1776
+
1777
+ it("declares every variation the documents use", () => {
1778
+ const missing: string[] = [];
1779
+ for (const [uid, slices] of pages)
1780
+ for (const s of slices) {
1781
+ const model = models[s.slice_type];
1782
+ if (model && !model[s.variation]) missing.push(\`\${uid}: \${s.slice_type}/\${s.variation}\`);
1783
+ }
1784
+ expect(missing).toEqual([]);
1785
+ });
1786
+
1787
+ // The one that catches a silent Migration-API drop.
1788
+ it("declares every field the documents set, so Prismic strips nothing", () => {
1789
+ const stripped: string[] = [];
1790
+ for (const [uid, slices] of pages)
1791
+ for (const s of slices) {
1792
+ const variation = models[s.slice_type]?.[s.variation];
1793
+ if (!variation) continue;
1794
+ for (const key of Object.keys(s.primary ?? {}))
1795
+ if (!variation.primary.includes(key))
1796
+ stripped.push(\`\${uid} \${s.slice_type}/\${s.variation} primary.\${key}\`);
1797
+ const itemKeys = new Set((s.items ?? []).flatMap((i) => Object.keys(i)));
1798
+ for (const key of itemKeys)
1799
+ if (!variation.items.includes(key))
1800
+ stripped.push(\`\${uid} \${s.slice_type}/\${s.variation} items.\${key}\`);
1801
+ }
1802
+ expect(stripped).toEqual([]);
1803
+ });
1804
+ });
1805
+ `;
1806
+ var MATCH_HARNESS_FILES = [
1807
+ { rel: HARNESS_MJS_RELATIVE, template: HARNESS_MJS_TEMPLATE, owner: "recipe" },
1808
+ { rel: GATE_SH_RELATIVE, template: GATE_SH_TEMPLATE, owner: "recipe" },
1809
+ { rel: CENSUS_SH_RELATIVE, template: CENSUS_SH_TEMPLATE, owner: "recipe" },
1810
+ { rel: NEXT_MJS_RELATIVE, template: NEXT_MJS_TEMPLATE, owner: "recipe" },
1811
+ { rel: STRIKES_MJS_RELATIVE, template: STRIKES_MJS_TEMPLATE, owner: "recipe" },
1812
+ { rel: BUILD_SPEC_MJS_RELATIVE, template: BUILD_SPEC_MJS_TEMPLATE, owner: "recipe" },
1813
+ { rel: CENSUS_COUNT_MJS_RELATIVE, template: CENSUS_COUNT_MJS_TEMPLATE, owner: "recipe" },
1814
+ { rel: HARNESS_JSON_RELATIVE, template: HARNESS_JSON_TEMPLATE, owner: "site" },
1815
+ { rel: FLOORS_MJS_RELATIVE, template: FLOORS_MJS_TEMPLATE, owner: "site" },
1816
+ { rel: CENSUS_DEVIATIONS_MJS_RELATIVE, template: CENSUS_DEVIATIONS_MJS_TEMPLATE, owner: "site" },
1817
+ { rel: SPEC_CHROME_MD_RELATIVE, template: SPEC_CHROME_MD_TEMPLATE, owner: "site" },
1818
+ { rel: SPEC_HEADER_MD_RELATIVE, template: SPEC_HEADER_MD_TEMPLATE, owner: "site" },
1819
+ { rel: LEDGER_MD_RELATIVE, template: LEDGER_MD_TEMPLATE, owner: "site" },
1820
+ { rel: MATCH_ROUTE_SERVER_RELATIVE, template: MATCH_ROUTE_SERVER_TEMPLATE, owner: "recipe" },
1821
+ { rel: MATCH_ROUTE_PAGE_RELATIVE, template: MATCH_ROUTE_PAGE_TEMPLATE, owner: "recipe" },
1822
+ { rel: SITE_PAGES_JS_RELATIVE, template: SITE_PAGES_JS_TEMPLATE, owner: "site" },
1823
+ { rel: SITE_PAGES_TEST_RELATIVE, template: SITE_PAGES_TEST_TEMPLATE, owner: "recipe" }
1824
+ ];
1825
+ var HARNESS_MJS_PREV_0_95_0 = `// The single source for everything the matching gates need to know about this
1826
+ // site. DATA lives in matching/harness.json (site-edited); this file is the
1827
+ // READ LAYER \u2014 edit harness.json, not this. (It is installed and upgraded by
1828
+ // the \`reddoor-maint match-harness\` recipe, which owns these bytes: a hand
1829
+ // edit here is flagged on the next run and never silently overwritten.)
1830
+ //
1831
+ // It exists because the page table, the two hosts, the matrix, the threshold
1832
+ // and the skill path were hand-copied all over matching/. Re-measured
1833
+ // 2026-09-09 AFTER the six-probe conversion, over the 216 tracked scripts under
1834
+ // matching/ (214 top-level \u2014 212 .mjs + 2 .sh \u2014 plus 2 in states/):
1835
+ //
1836
+ // \u2022 a hand-typed copy of the page table (three or more gate keys sitting next
1837
+ // to their route): 8 files. Exactly ONE of them, probe-chrome-count.mjs,
1838
+ // still carries all nine rows; probe-anchors.mjs carries five; the other
1839
+ // six are three-row detail triples (team/svc/qa).
1840
+ // \u2022 the skill path (~/.claude/skills/matching-a-page): 193 copies
1841
+ // \u2022 the viewport matrix (1440/834/390): 51 copies
1842
+ // \u2022 REF pointed at a host listed in selfHosts \u2014 i.e. comparing the candidate
1843
+ // with itself: 12 scripts, one of which (probe-chrome-count.mjs) is also
1844
+ // the last nine-row table carrier
1845
+ //
1846
+ // The first bullet read "the nine-row page table: 5 copies \u2014 gate.sh,
1847
+ // probe-anchor-parity.mjs, sweep-all10.sh, sweep-all16.sh, sweep-final.sh" when
1848
+ // it was written here at 922dde3. It was wrong within the hour and wrong on two
1849
+ // counts: 4e2cd7b took the table out of gate.sh, and the list never named
1850
+ // states/index.mjs or probe-chrome-count.mjs, which were both carrying nine-row
1851
+ // copies at the time. A census is a claim about code; it has to be measured
1852
+ // against the tree, not recalled.
1853
+ //
1854
+ // node matching/harness.mjs --env shell-safe KEY='value' lines
1855
+ // node matching/harness.mjs --table key<TAB>ref<TAB>cand<TAB>anchors
1856
+ // node matching/harness.mjs --check-ref the D11 preflight; exit 2 on failure
1857
+ import { readFileSync, realpathSync } from "node:fs";
1858
+ import { homedir } from "node:os";
1859
+ import { join } from "node:path";
1860
+ import { fileURLToPath, pathToFileURL } from "node:url";
1861
+
1862
+ // fileURLToPath, not URL#pathname: pathname is percent-encoded, so a checkout
1863
+ // under a directory with a space in it would resolve to a path that does not
1864
+ // exist.
1865
+ const DIR = fileURLToPath(new URL(".", import.meta.url));
1866
+ const CFG = JSON.parse(readFileSync(join(DIR, "harness.json"), "utf8"));
1867
+
1868
+ // Env overrides exist for one-off probes only. They are NOT how a site is
1869
+ // configured \u2014 harness.json is, so that what a gate ran against is committed.
1870
+ export const REF = process.env.MATCH_REF ?? CFG.ref;
1871
+ export const CAND = process.env.MATCH_CAND ?? process.env.CAND_BASE ?? CFG.cand;
1872
+ export const MATRIX = CFG.matrix;
1873
+ export const THRESHOLD = CFG.threshold;
1874
+ export const MAX_HEIGHT_DELTA = CFG.maxHeightDelta;
1875
+ export const REF_MARK = CFG.refMark;
1876
+ export const CAND_MARK = CFG.candMark;
1877
+ export const SELF_HOSTS = CFG.selfHosts ?? [];
1878
+
1879
+ /** One record per gated page, in harness.json order. \`key\` is the gate key
1880
+ * (out-<TAG>-<key>, the SPEC heading, spec-sections/<key>.md); \`uid\` is the
1881
+ * Prismic uid or null where the page has no /dev/match twin. */
1882
+ export const PAGES = Object.entries(CFG.pages).map(([key, p]) => ({ key, ...p }));
1883
+ export const byKey = Object.fromEntries(PAGES.map((p) => [p.key, p]));
1884
+
1885
+ // DERIVED, never hand-typed: page-diff cuts one region before the first anchor
1886
+ // ("top") plus one per anchor, at every viewport. The old hand-written map went
1887
+ // stale the moment an anchor list changed, and a wrong denominator makes the
1888
+ // score a lie in the flattering direction.
1889
+ export const TOTALS = Object.fromEntries(
1890
+ PAGES.map((p) => [p.key, (p.anchors.length + 1) * MATRIX.length]),
1891
+ );
1892
+
1893
+ /** The SPEC.md heading predicate, shared by gate.sh's preflight and
1894
+ * build-spec.mjs so a section can never build fine and then refuse at the
1895
+ * gate. Matches the key followed by any non-key character (\`## team\` matches,
1896
+ * \`## teamfoo\` does not, \`## our-team\` cannot match \`team\`). */
1897
+ export const specHeadingRe = (key) => new RegExp(\`^##+ +\${key}([^A-Za-z0-9_-]|$)\`, "m");
1898
+
1899
+ export const SKILL_DIR =
1900
+ process.env.MATCHING_SKILL_DIR ?? join(homedir(), ".claude/skills/matching-a-page");
1901
+ export const PD = join(SKILL_DIR, "page-diff.mjs");
1902
+ export const SC = join(SKILL_DIR, "style-census.mjs");
1903
+ export const PLAYWRIGHT = pathToFileURL(join(SKILL_DIR, "node_modules/playwright/index.mjs")).href;
1904
+
1905
+ /** The report format this site's scripts can read, so gate.sh can compare it
1906
+ * with \`page-diff --version\` before spending a run and next.mjs can refuse
1907
+ * rather than quietly drop a page whose newest report came from another
1908
+ * schema. Both do that now \u2014 gate.sh preflights \`page-diff --version\` against
1909
+ * this value before spending a run, and next.mjs counts a foreign-schema
1910
+ * report as MISSING rather than skipping it. (This said "neither does that
1911
+ * yet" \u2014 true at 922dde3 where it was written, false from 4e2cd7b, which
1912
+ * gave gate.sh the preflight and did not come back here.) Checked 2026-09-09
1913
+ * against the installed skill: \`page-diff --version\` \u2192 \`page-diff 0.1.0
1914
+ * report-schema 1\`. */
1915
+ export const REPORT_SCHEMA = 1;
1916
+
1917
+ /**
1918
+ * Fail-closed reference preflight. A 200 is NOT evidence: a host that has been
1919
+ * repointed at our own build answers 200, and so does a staging host serving a
1920
+ * 404 page. Both have happened on a real site \u2014 see the dated measurement in
1921
+ * LEDGER.md. A pass here requires an artefact only the reference produces.
1922
+ */
1923
+ export async function checkRef() {
1924
+ if (!REF_MARK) {
1925
+ return {
1926
+ ok: false,
1927
+ why: "harness.json refMark is empty \u2014 set it to a string only the reference serves (a Webflow site id, a build hash). A 200 is not evidence.",
1928
+ };
1929
+ }
1930
+ const host = new URL(REF).host;
1931
+ if (SELF_HOSTS.includes(host)) return { ok: false, why: \`REF host \${host} is in selfHosts\` };
1932
+ if (host === new URL(CAND).host) return { ok: false, why: \`REF host \${host} equals CAND's host\` };
1933
+ let res;
1934
+ try {
1935
+ res = await fetch(\`\${REF}/\`, { redirect: "manual" });
1936
+ } catch (e) {
1937
+ return { ok: false, why: \`GET \${REF}/ failed: \${e.message}\` };
1938
+ }
1939
+ if (res.status !== 200)
1940
+ return { ok: false, why: \`GET \${REF}/ \u2192 HTTP \${res.status}, expected 200\` };
1941
+ const loc = res.headers.get("location");
1942
+ if (loc) return { ok: false, why: \`GET \${REF}/ \u2192 \${res.status} redirect to \${loc}\` };
1943
+ const body = await res.text();
1944
+ if (!body.includes(REF_MARK))
1945
+ return {
1946
+ ok: false,
1947
+ why: \`\${REF}/ served 200 but WITHOUT refMark \${JSON.stringify(REF_MARK)} \u2014 that is not the reference\`,
1948
+ };
1949
+ if (CAND_MARK && body.includes(CAND_MARK))
1950
+ return {
1951
+ ok: false,
1952
+ why: \`\${REF}/ contains candMark \${JSON.stringify(CAND_MARK)} \u2014 REF is serving OUR build\`,
1953
+ };
1954
+ return { ok: true, why: \`\${REF}/ \u2192 200, no redirect, refMark present, candMark absent\` };
1955
+ }
1956
+
1957
+ // CLI. Both sides go through realpathSync. \`import.meta.url\` is ALREADY the
1958
+ // resolved real path (node resolves symlinks unless --preserve-symlinks) while
1959
+ // process.argv[1] is the path as typed, so a plain pathToFileURL compare goes
1960
+ // false the moment any component of the invoked path is a symlink \u2014 and then
1961
+ // the CLI prints nothing and exits 0, which every caller reads as success.
1962
+ // page-diff.mjs:184-189 records exactly that defect and the same fix: "The
1963
+ // pathToFileURL compare that replaced the old template string is still false
1964
+ // whenever ANY component of the invoked path is a symlink \u2014 which is how this
1965
+ // skill is installed now (~/.claude/skills/matching-a-page -> the claude-skills
1966
+ // checkout). isMain() resolves the real path on both sides."
1967
+ const isMain = () => {
1968
+ if (!process.argv[1]) return false;
1969
+ try {
1970
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
1971
+ } catch {
1972
+ return false;
1973
+ }
1974
+ };
1975
+
1976
+ if (isMain()) {
1977
+ const mode = process.argv[2];
1978
+ const q = (v) => \`'\${String(v).replace(/'/g, \`'\\\\''\`)}'\`;
1979
+ if (mode === "--env") {
1980
+ const pairs = [
1981
+ ["REF", REF],
1982
+ ["CAND", CAND],
1983
+ ["MATRIX", MATRIX.join(",")],
1984
+ ["VIEWPORTS_SP", MATRIX.join(" ")],
1985
+ ["THRESHOLD", THRESHOLD],
1986
+ ["MAX_HEIGHT_DELTA", MAX_HEIGHT_DELTA],
1987
+ ["PD", PD],
1988
+ ["SC", SC],
1989
+ ["REPORT_SCHEMA", REPORT_SCHEMA],
1990
+ ];
1991
+ for (const [k, v] of pairs) console.log(\`\${k}=\${q(v)}\`);
1992
+ } else if (mode === "--table") {
1993
+ for (const p of PAGES) console.log([p.key, p.ref, p.cand, p.anchors.join(",")].join("\\t"));
1994
+ } else if (mode === "--check-ref") {
1995
+ const r = await checkRef();
1996
+ console.log(\`\${r.ok ? "REF OK" : "REF REFUSED"} \u2014 \${r.why}\`);
1997
+ process.exit(r.ok ? 0 : 2);
1998
+ } else {
1999
+ console.error("usage: harness.mjs --env | --table | --check-ref");
2000
+ process.exit(2);
2001
+ }
2002
+ }
2003
+ `;
2004
+ var GATE_SH_PREV_0_95_0 = `#!/usr/bin/env bash
2005
+ # The matching gate. This file is generic \u2014 everything specific to a site lives
2006
+ # in matching/harness.json (the data) and matching/LEDGER.md (the why). It is
2007
+ # installed and upgraded by the \`reddoor-maint match-harness\` recipe, which
2008
+ # owns these bytes: a hand edit here is flagged on the next run, never
2009
+ # silently overwritten.
2010
+ #
2011
+ # bash matching/gate.sh <round-tag> [page ...]
2012
+ #
2013
+ # Runs page-diff for every page in the table (or just the named ones) at the
2014
+ # full breakpoint matrix and writes matching/out-<round-tag>-<page>/.
2015
+ #
2016
+ # The matrix, the anchor lists, the reference and the candidate are DATA. Why a
2017
+ # site chose them \u2014 which live breakpoint band hid what, why an anchor is a
2018
+ # heading and not a button label \u2014 belongs in matching/LEDGER.md, which is dated
2019
+ # and append-only, because JSON holds no comments.
2020
+ #
2021
+ # NO MASKS and the threshold from harness.json everywhere: the numbers stay
2022
+ # honest and a known floor stays visible as its own region. A media-neutralised
2023
+ # secondary read is \`node "$PD" ... --neutralize-media\`; next.mjs ignores such
2024
+ # runs on purpose (next.mjs:57-64).
2025
+ #
2026
+ # PREFLIGHT (see the matching rules in CLAUDE.md): a page with no section in
2027
+ # matching/SPEC.md has not had Phase 1 done, and its geometry must not be
2028
+ # touched. Skipping the spec is how a reference's root-font ladder and its
2029
+ # per-component height ladders get found reactively, after the region has
2030
+ # already failed several rounds. This refuses the run instead of trusting anyone
2031
+ # to remember.
2032
+ set -u
2033
+ # Everything configurable lives in matching/harness.json; harness.mjs is the one
2034
+ # reader. --env emits shell-safe assignments (REF, CAND, MATRIX, VIEWPORTS_SP,
2035
+ # THRESHOLD, MAX_HEIGHT_DELTA, PD, SC, REPORT_SCHEMA).
2036
+ eval "$(node "$(dirname "$0")/harness.mjs" --env)"
2037
+
2038
+ # The skill must be able to write reports this site's scripts can read. Cheap,
2039
+ # local, and it fails before any browser starts.
2040
+ PD_SCHEMA="$(node "$PD" --version 2>/dev/null | awk '{print $4}')"
2041
+ if [ "$PD_SCHEMA" != "$REPORT_SCHEMA" ]; then
2042
+ echo "gate.sh: page-diff writes report schema '\${PD_SCHEMA:-none}', this harness reads $REPORT_SCHEMA." >&2
2043
+ echo " Update matching/harness.mjs REPORT_SCHEMA or the matching-a-page skill." >&2
2044
+ exit 2
2045
+ fi
2046
+ SPEC="$(dirname "$0")/SPEC.md"
2047
+ TAG="\${1:?usage: gate.sh <round-tag> [page ...]}"
2048
+ # The tag must not contain a hyphen. Output dirs are "out-<TAG>-<page>", and
2049
+ # next.mjs recovers the page with /^out-[^-]+-(.+)$/ \u2014 it splits on the FIRST
2050
+ # hyphen, so a tag like "r-forms-2026-08-07" yields the page key
2051
+ # "forms-2026-08-07-yfv" and that run is silently never counted. It cannot split
2052
+ # on the last hyphen instead, because page keys have hyphens of their own
2053
+ # ("our-team", "ask-the-doctor"). Failing here is the cheap end of that: a
2054
+ # mis-tagged round otherwise LOOKS green because next.mjs keeps reading an older
2055
+ # report for the page you just changed. (Cost this once, 2026-08-07.)
2056
+ case "$TAG" in
2057
+ *-*)
2058
+ echo "gate.sh: round tag must not contain a hyphen (got '$TAG')." >&2
2059
+ echo " out-<TAG>-<page> is parsed on the first hyphen, so a" >&2
2060
+ echo " hyphenated tag hides the run from next.mjs. Try '\${TAG//-/}'." >&2
2061
+ exit 2
2062
+ ;;
2063
+ esac
2064
+ shift || true
2065
+ WANT=("$@")
2066
+
2067
+ # Fail closed on the reference before spending a single run. A 200 is NOT
2068
+ # evidence: a production host that has cut over to OUR build answers 200, and
2069
+ # every region then scores near zero against itself. --check-ref requires an
2070
+ # artefact only the reference serves (harness.json refMark) and refuses a
2071
+ # redirect, a host listed in selfHosts, and a body carrying candMark. Measured
2072
+ # on the site this harness was cut from, 2026-09-09 AFTER the consolidation:
2073
+ # 12 of its 214 top-level matching scripts still assign REF a host listed in
2074
+ # selfHosts \u2014 i.e. compare the candidate with itself. It was 33 of 229 before.
2075
+ # (This comment read "33 of its 230" while sitting in the post-consolidation
2076
+ # tree, contradicting harness.mjs's 12 three files away.)
2077
+ if ! node "$(dirname "$0")/harness.mjs" --check-ref; then
2078
+ echo "gate.sh: refusing to gate against an unverified reference." >&2
2079
+ exit 2
2080
+ fi
2081
+
2082
+ # Set SPEC_OPTIONAL=1 only for a read-only baseline sweep of pages you are not
2083
+ # about to edit. It is recorded in the round tag so the exemption is visible.
2084
+ SPEC_OPTIONAL="\${SPEC_OPTIONAL:-0}"
2085
+
2086
+ has_spec() { # page
2087
+ # NB: the obvious \`( |$|\\b)\` guard is rejected by ugrep as an empty
2088
+ # subexpression, and a preflight that errors out fails CLOSED \u2014 it refused all
2089
+ # 9 pages while SPEC.md was complete. Match the page key followed by any
2090
+ # non-key character (so \`## team\` matches but \`## teamfoo\` does not; \`##
2091
+ # our-team\` cannot match \`team\` because the key must follow the spaces).
2092
+ [ -f "$SPEC" ] && grep -qE "^##+ +$1([^A-Za-z0-9_-]|$)" "$SPEC"
2093
+ }
2094
+
2095
+ run() { # tag refpath candpath sections
2096
+ local page="$1" refpath="$2" candpath="$3" sections="$4"
2097
+ if [ \${#WANT[@]} -gt 0 ]; then
2098
+ local hit=0
2099
+ for w in "\${WANT[@]}"; do [ "$w" = "$page" ] && hit=1; done
2100
+ [ $hit -eq 1 ] || return 0
2101
+ fi
2102
+ if ! has_spec "$page"; then
2103
+ if [ "$SPEC_OPTIONAL" = "1" ]; then
2104
+ echo "########## $page ##########"
2105
+ echo "WARNING: no '## $page' section in matching/SPEC.md \u2014 Phase 1 not done."
2106
+ echo " Running anyway because SPEC_OPTIONAL=1 (baseline read only)."
2107
+ echo " Do NOT apply geometry fixes off this run."
2108
+ else
2109
+ echo "########## $page ##########"
2110
+ echo "REFUSED: no '## $page' section in matching/SPEC.md."
2111
+ echo " Phase 1 (section census + per-section spec, read from"
2112
+ echo " matching/spec/) comes before geometry."
2113
+ echo " See CLAUDE.md rule 2. SPEC_OPTIONAL=1 for a baseline read."
2114
+ FAILED_PREFLIGHT=1
2115
+ return 0
2116
+ fi
2117
+ fi
2118
+ echo "########## $page ##########"
2119
+ node "$PD" --ref "$REF$refpath" --cand "$CAND$candpath" \\
2120
+ --viewports "$MATRIX" --threshold "$THRESHOLD" \\
2121
+ --sections "$sections" --out "matching/out-$TAG-$page" \\
2122
+ > "matching/out-$TAG-$page.log" 2>&1
2123
+ echo "$page exit=$?"
2124
+ }
2125
+
2126
+ # The page table is matching/harness.json. Process substitution, NOT a pipe:
2127
+ # a pipe would run this loop in a subshell and FAILED_PREFLIGHT would not
2128
+ # survive to the check below, so a refused page would exit 0.
2129
+ while IFS=$'\\t' read -r key refpath candpath anchors; do
2130
+ run "$key" "$refpath" "$candpath" "$anchors"
2131
+ done < <(node "$(dirname "$0")/harness.mjs" --table)
2132
+
2133
+ if [ "\${FAILED_PREFLIGHT:-0}" = "1" ]; then
2134
+ echo
2135
+ echo "GATE INCOMPLETE ($TAG) \u2014 one or more pages were refused for a missing"
2136
+ echo "SPEC.md section. Those pages have NOT been measured; do not report a"
2137
+ echo "score for them."
2138
+ exit 2
2139
+ fi
2140
+ echo "ALL DONE ($TAG)"
2141
+ `;
2142
+ var NEXT_MJS_PREV_0_95_0 = `// What is still broken, ranked. Exits 1 while work remains.
2143
+ //
2144
+ // node matching/next.mjs
2145
+ //
2146
+ // Round protocol step 0 (repo CLAUDE.md rule 5). A commit is a CHECKPOINT, not
2147
+ // a stopping point: after committing, run this. If it exits 1 there is a named
2148
+ // next action and the round continues without handing control back.
2149
+ //
2150
+ // Reads the most recent gate log per page rather than the whole corpus, so it
2151
+ // reflects HEAD rather than history (that is strikes.mjs's job).
2152
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2153
+ import { join } from "node:path";
2154
+
2155
+ const DIR = new URL(".", import.meta.url).pathname;
2156
+
2157
+ // PAUSE SWITCH. While matching/PAUSED exists this hands out no agenda and
2158
+ // exits 0. It is deliberately the FIRST thing that runs: no report is read, no
2159
+ // score is printed, nothing tempting is put on screen to argue with.
2160
+ //
2161
+ // Why an exit code and not a note somewhere: rule 5 is a LOOP \u2014 "after
2162
+ // committing, run next.mjs; while it exits 1 there is a named next action and
2163
+ // the round continues". A pause written as prose loses to that loop, because
2164
+ // the loop is mechanical and the prose is not. Exiting 0 satisfies rule 5
2165
+ // truthfully rather than suspending it: there is no next action.
2166
+ const PAUSE = join(DIR, "PAUSED");
2167
+ if (existsSync(PAUSE)) {
2168
+ console.log("MATCHING PAUSED \u2014 no agenda, and none is to be inferred.\\n");
2169
+ console.log(readFileSync(PAUSE, "utf8").trimEnd());
2170
+ process.exit(0);
2171
+ }
2172
+
2173
+ import { FLOORS, ACCEPTED } from "./floors.mjs";
2174
+ import { TOTALS, THRESHOLD, MAX_HEIGHT_DELTA, REPORT_SCHEMA } from "./harness.mjs";
2175
+
2176
+ // Reports written by a different page-diff, by page key. Kept rather than
2177
+ // dropped: silently ignoring them is how a page vanishes from the score.
2178
+ const schemaMismatch = new Set();
2179
+
2180
+ const latest = new Map();
2181
+ for (const d of readdirSync(DIR).filter((d) => d.startsWith("out-"))) {
2182
+ const m = /^out-[^-]+-(.+)$/.exec(d);
2183
+ if (!m || !TOTALS[m[1]]) continue;
2184
+ let report, mtime;
2185
+ try {
2186
+ const p = join(DIR, d, "report.json");
2187
+ report = JSON.parse(readFileSync(p, "utf8"));
2188
+ mtime = statSync(p).mtimeMs;
2189
+ } catch {
2190
+ continue;
2191
+ }
2192
+ // A masked / media-neutralised run is a DIAGNOSTIC, never the state of the
2193
+ // page. Picking one up as "latest" silently reports scores nobody can ship \u2014
2194
+ // it happened immediately: an --mask-photos probe of yfv made \`top\` @834 read
2195
+ // 43.9% here while the real gate had it passing at 1.3%.
2196
+ const meta = report.meta ?? {};
2197
+ // Missing schemaVersion means "written before the field existed" = 0. It is
2198
+ // not an error on its own; it is only fatal when it would blank a page.
2199
+ if ((meta.schemaVersion ?? 0) !== REPORT_SCHEMA) {
2200
+ schemaMismatch.add(m[1]);
2201
+ continue;
2202
+ }
2203
+ if (
2204
+ (meta.mask?.length ?? 0) > 0 ||
2205
+ meta.neutralizeMedia ||
2206
+ meta.maskPhotos ||
2207
+ meta.truncated
2208
+ )
2209
+ continue;
2210
+ if (meta.threshold !== THRESHOLD) continue;
2211
+ const prev = latest.get(m[1]);
2212
+ if (!prev || mtime > prev.mtime) latest.set(m[1], { dir: d, mtime, report });
2213
+ }
2214
+
2215
+ const blanked = [...schemaMismatch].filter((p) => !latest.has(p));
2216
+ if (blanked.length) {
2217
+ console.error(
2218
+ \`next: \${blanked.length} page(s) have no run at report schema \${REPORT_SCHEMA} \u2014 \` +
2219
+ \`their newest reports came from a different page-diff (\${blanked.sort().join(", ")}).\\n\` +
2220
+ \` Re-run: bash matching/gate.sh <tag> \${blanked.sort().join(" ")}\`,
2221
+ );
2222
+ process.exit(2);
2223
+ }
2224
+ if (latest.size === 0) {
2225
+ console.error(
2226
+ "next: no parseable gate run under matching/ \u2014 refusing to report a score.\\n" +
2227
+ " Run bash matching/gate.sh <tag> first.",
2228
+ );
2229
+ process.exit(2);
2230
+ }
2231
+
2232
+ const rows = [];
2233
+ const accepted = [];
2234
+ let openTotal = 0;
2235
+ let floorTotal = 0;
2236
+ for (const [page, { dir, report }] of latest) {
2237
+ const fails = report.regions.filter((r) => !r.pass);
2238
+ for (const f of fails) {
2239
+ const floor = FLOORS.find((fl) => fl.match(f, page));
2240
+ if (floor) {
2241
+ floorTotal++;
2242
+ continue;
2243
+ }
2244
+ const ack = ACCEPTED.find((a) => a.match(f, page));
2245
+ if (ack) {
2246
+ accepted.push({ page, vw: f.viewport, label: f.label, why: ack.why });
2247
+ continue;
2248
+ }
2249
+ openTotal++;
2250
+ rows.push({
2251
+ page,
2252
+ vw: f.viewport,
2253
+ label: f.label,
2254
+ mm: f.mismatchFraction,
2255
+ dh: f.heightDeltaFraction ?? 0,
2256
+ dir,
2257
+ });
2258
+ }
2259
+ }
2260
+
2261
+ const scored = [...latest.entries()]
2262
+ .map(([p, v]) => ({
2263
+ p,
2264
+ pass: v.report.regions.filter((r) => r.pass).length,
2265
+ total: TOTALS[p],
2266
+ }))
2267
+ .sort((a, b) => a.pass / a.total - b.pass / b.total);
2268
+
2269
+ const sum = scored.reduce((a, s) => a + s.pass, 0);
2270
+ const max = scored.reduce((a, s) => a + s.total, 0);
2271
+ console.log(\`SCORE \${sum}/\${max} regions passing\\n\`);
2272
+ console.log(
2273
+ scored
2274
+ .map((s) => \` \${s.p.padEnd(9)} \${String(s.pass).padStart(2)}/\${s.total}\`)
2275
+ .join("\\n"),
2276
+ );
2277
+
2278
+ if (accepted.length) {
2279
+ console.log(\`\\nOperator-ACCEPTED failures (left failing on purpose):\`);
2280
+ for (const a of accepted)
2281
+ console.log(\` \${a.page} @\${a.vw} "\${a.label}" \u2014 \${a.why.slice(0, 96)}\u2026\`);
2282
+ }
2283
+
2284
+ if (!rows.length) {
2285
+ console.log(
2286
+ \`\\nNo open geometry failures. \${floorTotal} declared floor(s) remain.\`,
2287
+ );
2288
+ console.log(
2289
+ "Backlog is empty \u2014 Phases 5 (states) and 6 (adversarial review) are what is left.",
2290
+ );
2291
+ process.exit(0);
2292
+ }
2293
+
2294
+ // Worst page first, then worst region inside it: fix where the model is most wrong.
2295
+ const worst = scored[0].p;
2296
+ rows.sort(
2297
+ (a, b) =>
2298
+ (a.page === worst ? -1 : 0) - (b.page === worst ? -1 : 0) || b.mm - a.mm,
2299
+ );
2300
+
2301
+ console.log(
2302
+ \`\\n\${openTotal} open failure(s) + \${floorTotal} declared floor(s).\`,
2303
+ );
2304
+ console.log(\`\\nNEXT: \${worst} \u2014 worst page. Its open regions:\\n\`);
2305
+ for (const r of rows.filter((r) => r.page === worst)) {
2306
+ const why = [];
2307
+ if (r.mm > THRESHOLD) why.push(\`pixels \${(r.mm * 100).toFixed(1)}%\`);
2308
+ if (Math.abs(r.dh) > MAX_HEIGHT_DELTA)
2309
+ why.push(\`height \${(r.dh * 100).toFixed(1)}%\`);
2310
+ console.log(
2311
+ \` @\${String(r.vw).padEnd(5)} \${r.label.slice(0, 44).padEnd(45)} \${why.join(" + ")}\`,
2312
+ );
2313
+ }
2314
+ console.log(\`\\nBefore treating any of these as geometry:\`);
2315
+ console.log(
2316
+ \` node matching/probe-anchor-parity.mjs \${worst} # is the gate cutting comparably?\`,
2317
+ );
2318
+ console.log(
2319
+ \` node matching/strikes.mjs \${worst} # has it stalled? then change the MODEL\`,
2320
+ );
2321
+ console.log(
2322
+ \`\\nRound continues. Do not hand back control with work outstanding.\`,
2323
+ );
2324
+ process.exit(1);
2325
+ `;
2326
+ var MATCH_HARNESS_PREVIOUS = {
2327
+ "matching/harness.mjs": [HARNESS_MJS_PREV_0_95_0],
2328
+ "matching/gate.sh": [GATE_SH_PREV_0_95_0],
2329
+ "matching/next.mjs": [NEXT_MJS_PREV_0_95_0]
2330
+ };
2331
+ var MATCH_HARNESS_COUPLED = [
2332
+ "matching/harness.mjs",
2333
+ "matching/gate.sh",
2334
+ "matching/census.sh",
2335
+ "matching/next.mjs",
2336
+ "matching/strikes.mjs",
2337
+ "matching/build-spec.mjs"
2338
+ ];
2339
+ var GITIGNORE_MARKER = "# reddoor-maint match-harness: scripts + records tracked, workspace ignored";
2340
+ var GITIGNORE_BLOCK = `scratch-diff*/
2341
+ matching/*
2342
+ !matching/*.sh
2343
+ !matching/*.mjs
2344
+ !matching/*.md
2345
+ # The pause switch. Extensionless on purpose (it is a sentinel, not a doc), so
2346
+ # the whitelist above misses it \u2014 and an ignored switch is not a switch: it
2347
+ # would work on one machine and be absent from every fresh clone, CI run and
2348
+ # agent that most needs to see it.
2349
+ !matching/PAUSED
2350
+ !matching/spec-sections/
2351
+ !matching/states/
2352
+ matching/states/*
2353
+ !matching/states/*.mjs
2354
+ # derived artefacts, even where the extensions above would catch them
2355
+ matching/*.log
2356
+ matching/*.json
2357
+ # ...except the page table itself, which is the harness's configuration and the
2358
+ # one thing a fresh clone cannot reconstruct.
2359
+ !matching/harness.json
2360
+ matching/*.png
2361
+ `;
2362
+ var PRETTIERIGNORE_MARKER = "# reddoor-maint match-harness";
2363
+ var PRETTIERIGNORE_BLOCK = `# Matching harness \u2014 every file the \`match-harness\` recipe OWNS. It installs
2364
+ # them byte-for-byte and byte-compares them on the next install, so a site whose
2365
+ # prettier config differs must not reformat them: a reformatted file is
2366
+ # indistinguishable from a hand edit, and the recipe refuses to overwrite a hand
2367
+ # edit. Measured on a \`useTabs\`/\`singleQuote\` site, all three src/ entries
2368
+ # below are rewritten by \`prettier --write .\`, and the next upgrade is refused
2369
+ # for all three.
2370
+ #
2371
+ # The bracketed route segment MUST stay backslash-escaped. This file is
2372
+ # gitignore glob syntax, in which \`[uid]\` is a CHARACTER CLASS matching one of
2373
+ # \`u\`, \`i\`, \`d\` \u2014 an unescaped entry silently ignores nothing at all.
2374
+ #
2375
+ # \`matching/*.mjs\` also catches two SITE-owned records (floors.mjs,
2376
+ # census-deviations.mjs). Accepted, not overlooked: eslint lints .mjs, so those
2377
+ # two keep a style check either way, and naming seven scripts instead of one
2378
+ # glob goes stale on the next script the harness gains.
2379
+ #
2380
+ # harness.json is here because it is a TABLE, not prose: it carries a
2381
+ # hand-chosen row layout that prettier reflows.
2382
+ #
2383
+ # Everything else under matching/ (SPEC.md, LEDGER.md, spec-sections/,
2384
+ # states/*.mjs) stays inside \`prettier --check .\`. That is deliberately narrow:
2385
+ # eslint does not lint Markdown, so for the records prettier is the ONLY style
2386
+ # check there is, and a blanket \`matching/\` entry would leave them with none.
2387
+ matching/*.mjs
2388
+ matching/*.sh
2389
+ matching/harness.json
2390
+ src/routes/dev/match/\\[uid\\]/+page.server.ts
2391
+ src/routes/dev/match/\\[uid\\]/+page.svelte
2392
+ src/lib/site-pages.test.ts
2393
+ `;
2394
+ var CLAUDE_MD_MARKER = "## Matching rules (installed by reddoor-maint match-harness)";
2395
+ var CLAUDE_MD_BLOCK = `
2396
+ The \`matching-a-page\` skill governs a live-reference rebuild. These five rules
2397
+ exist because the skill alone did not hold on the project this harness came
2398
+ from \u2014 each one is a drift that actually happened, with the mechanical check
2399
+ that now catches it. \`matching/harness.json\` is this site's configuration;
2400
+ \`matching/LEDGER.md\` is the dated record of every deviation, floor and mask.
2401
+
2402
+ ### 1. Source prescribes, rects only verify
2403
+
2404
+ Every geometry fix must cite the rule it came from: a line in the captured
2405
+ reference stylesheet under \`matching/spec/\`, or the reference's HTML. "The probe
2406
+ says the gap is 40px" is not a source. If you cannot name the line you are
2407
+ guessing \u2014 go read the stylesheet first.
2408
+
2409
+ **Check:** the commit body must name the file:line for each fix.
2410
+ **Operator's challenge:** _"which line of the reference stylesheet says that?"_
2411
+
2412
+ ### 2. Phase 1 before Phase 4
2413
+
2414
+ A page gets its section census and per-section spec in \`matching/SPEC.md\` BEFORE
2415
+ its geometry is touched. No SPEC section, no geometry round. The census is the
2416
+ coverage denominator; skipping it is how a reference's root-font ladder and its
2417
+ per-component height ladders get discovered reactively, after the region has
2418
+ already failed several rounds.
2419
+
2420
+ **Check:** \`matching/gate.sh\` refuses to run a page with no \`SPEC.md\` section.
2421
+ **Operator's challenge:** _"show me the SPEC section for that region."_
2422
+
2423
+ ### 3. Three strikes, then stop
2424
+
2425
+ A failing region that has not improved across 3+ gate runs does not get a fourth
2426
+ attempt. Present the attempts. Never widen the threshold, add a mask, or
2427
+ reclassify it as a floor to make it go away.
2428
+
2429
+ **Check:** \`node matching/strikes.mjs <page>\` \u2014 exits 1 while any region is
2430
+ stalled, and is the first thing a geometry round runs.
2431
+ **Operator's challenge:** _"how many runs has that region been flat?"_
2432
+
2433
+ ### 4. A gate closes an item, nothing else
2434
+
2435
+ No fix is "done" because the code changed. Paste the gate header \u2014 it is
2436
+ self-describing, so a nonstandard threshold or an undisclosed mask is visible.
2437
+ The threshold and the matrix are whatever \`matching/harness.json\` says, on every
2438
+ page, never a subset.
2439
+
2440
+ **Operator's challenge:** _"paste the gate header."_
2441
+
2442
+ ### 5. A commit is a checkpoint, not a stopping point
2443
+
2444
+ Do not hand control back between rounds. After committing, run
2445
+ \`node matching/next.mjs\`: while it exits 1 there is a named next action, and the
2446
+ round continues. Report when the backlog is empty, when a decision is genuinely
2447
+ the operator's (three strikes, a novel floor, a threshold change), or when
2448
+ asked \u2014 not because a commit felt like a natural place to summarise.
2449
+
2450
+ This exists because the failure was habitual, not deliberate: a turn ends when
2451
+ user-facing prose gets written, and "I just committed something good" is the
2452
+ moment that invites writing it. The gate stops incorrect work; this stops
2453
+ premature stopping.
2454
+
2455
+ **Pausing:** create \`matching/PAUSED\` holding a note that says what the pause
2456
+ means; \`next.mjs\` and \`strikes.mjs\` then exit 0 while it exists. This rule says
2457
+ "do not stop while work is named"; it never said "find work to name". An empty
2458
+ agenda and a paused one end the round the same way. Deleting the switch is the
2459
+ operator's call.
2460
+
2461
+ **Check:** \`node matching/next.mjs\` \u2014 exits 1 while any non-floor region fails.
2462
+ **Operator's challenge:** _"what does next.mjs say?"_
2463
+
2464
+ ### Round protocol
2465
+
2466
+ 1. \`node matching/strikes.mjs <page>\` \u2014 if it exits 1, the stalled regions are
2467
+ the agenda, and stalled ones get escalated rather than re-attempted.
2468
+ 2. Confirm the page has a \`matching/SPEC.md\` section; write
2469
+ \`matching/spec-sections/<page>.md\` and run \`node matching/build-spec.mjs\` if
2470
+ not.
2471
+ 3. Fix, each change citing its source line.
2472
+ 4. \`bash matching/gate.sh <tag> <page>\` \u2014 paste the header.
2473
+ 5. Append to \`matching/LEDGER.md\` at the moment a deviation, floor or mask is
2474
+ decided, not reconstructed at the end.
2475
+ 6. \`pnpm verify\`, then commit and push.
2476
+ `;
2477
+
2478
+ // src/recipes/match-harness/previous.ts
2479
+ var MATCH_HARNESS_BLOCK_PREVIOUS = {};
2480
+
2481
+ // src/recipes/match-harness/index.ts
2482
+ var PRETTIER_TIMEOUT_MS = 6e4;
2483
+ async function readIfExists(path) {
2484
+ try {
2485
+ return await readFile(path, "utf-8");
2486
+ } catch {
2487
+ return null;
2488
+ }
2489
+ }
2490
+ function normalize(s) {
2491
+ return s.replace(/\r\n/g, "\n").replace(/[ \t]+$/gm, "").trim();
2492
+ }
2493
+ function planBlockWrite(existing, marker, endMarker, block, previous) {
2494
+ const region = `${marker}
2495
+ ${block}
2496
+ ${endMarker}`;
2497
+ if (existing === null) return { action: "write", content: `${region}
2498
+ ` };
2499
+ const start = existing.indexOf(marker);
2500
+ if (start === -1) {
2501
+ const base = existing.endsWith("\n") ? existing : `${existing}
2502
+ `;
2503
+ return { action: "write", content: `${base}
2504
+ ${region}
2505
+ ` };
2506
+ }
2507
+ const head = existing.slice(0, start);
2508
+ const bodyStart = start + marker.length + 1;
2509
+ const endAt = existing.indexOf(endMarker, bodyStart);
2510
+ if (endAt !== -1) {
2511
+ const body = existing.slice(bodyStart, endAt);
2512
+ if (normalize(body) === normalize(block)) return { action: "skip" };
2513
+ if (previous.some((p) => normalize(body) === normalize(p)))
2514
+ return {
2515
+ action: "replace",
2516
+ content: head + region + existing.slice(endAt + endMarker.length)
2517
+ };
2518
+ return { action: "flag" };
2519
+ }
2520
+ for (const candidate of [block, ...previous]) {
2521
+ if (!existing.startsWith(candidate, bodyStart)) continue;
2522
+ const content = `${head}${region}
2523
+ ${existing.slice(bodyStart + candidate.length)}`;
2524
+ return candidate === block ? { action: "terminate", content } : { action: "replace", content };
2525
+ }
2526
+ return { action: "flag" };
2527
+ }
2528
+ function planFileWrite(existing, template, owner, previous) {
2529
+ if (existing === null) return "write";
2530
+ if (normalize(existing) === normalize(template)) return "skip";
2531
+ if (owner === "site") return "skip";
2532
+ if (previous.some((p) => normalize(existing) === normalize(p))) return "replace";
2533
+ return "flag";
2534
+ }
2535
+ var GITIGNORE_END_MARKER = "# end reddoor-maint match-harness";
2536
+ var PRETTIERIGNORE_END_MARKER = "# end reddoor-maint match-harness";
2537
+ var CLAUDE_MD_END_MARKER = "<!-- end reddoor-maint match-harness -->";
2538
+ var APPENDED_BLOCKS = [
2539
+ [".gitignore", GITIGNORE_MARKER, GITIGNORE_END_MARKER, GITIGNORE_BLOCK],
2540
+ [".prettierignore", PRETTIERIGNORE_MARKER, PRETTIERIGNORE_END_MARKER, PRETTIERIGNORE_BLOCK],
2541
+ ["CLAUDE.md", CLAUDE_MD_MARKER, CLAUDE_MD_END_MARKER, CLAUDE_MD_BLOCK]
2542
+ ];
2543
+ var MATCH_HARNESS_INSTALLED_PATHS = [
2544
+ ...MATCH_HARNESS_FILES.map((f) => f.rel),
2545
+ ...APPENDED_BLOCKS.map(([rel]) => rel)
2546
+ ];
2547
+ async function matchHarness(site, opts, deps = { spawn: defaultSpawn }) {
2548
+ return withRecipe({
2549
+ name: "match-harness",
2550
+ site,
2551
+ plan: async () => {
2552
+ if (!opts.ref || !/^https?:\/\//.test(opts.ref)) {
2553
+ return {
2554
+ kind: "failed",
2555
+ notes: "--ref <url> is required: the harness gates against a live reference, and a harness with no reference can only ever report an absence of errors"
2556
+ };
2557
+ }
2558
+ return {
2559
+ kind: "apply",
2560
+ plan: {
2561
+ ref: opts.ref.replace(/\/$/, ""),
2562
+ cand: opts.cand ?? "http://localhost:5173",
2563
+ matrix: opts.matrix ?? [1440, 834, 390]
2564
+ }
2565
+ };
2566
+ },
2567
+ apply: async (planned, { commit, cwd }) => {
2568
+ const notes = [];
2569
+ const written = [];
2570
+ const before = /* @__PURE__ */ new Map();
2571
+ const previousAll = deps.previous ?? MATCH_HARNESS_PREVIOUS;
2572
+ const blockPreviousAll = deps.blockPrevious ?? MATCH_HARNESS_BLOCK_PREVIOUS;
2573
+ const plans = [];
2574
+ for (const f of MATCH_HARNESS_FILES) {
2575
+ const target = join(cwd, f.rel);
2576
+ let template = f.template;
2577
+ if (f.rel === HARNESS_JSON_RELATIVE) {
2578
+ const seed = JSON.parse(template);
2579
+ seed.ref = planned.ref;
2580
+ seed.cand = planned.cand;
2581
+ seed.matrix = planned.matrix;
2582
+ template = JSON.stringify(seed, null, 2) + "\n";
2583
+ }
2584
+ const existing = await readIfExists(target);
2585
+ plans.push({
2586
+ f,
2587
+ template,
2588
+ existing,
2589
+ action: planFileWrite(existing, template, f.owner, previousAll[f.rel] ?? [])
2590
+ });
2591
+ }
2592
+ const coupled = new Set(MATCH_HARNESS_COUPLED);
2593
+ const blockedBy = plans.filter((p) => coupled.has(p.f.rel) && p.action === "flag").map((p) => p.f.rel);
2594
+ const demoted = plans.filter(
2595
+ (p) => coupled.has(p.f.rel) && p.action === "replace" && !blockedBy.includes(p.f.rel)
2596
+ );
2597
+ if (blockedBy.length > 0 && demoted.length > 0) {
2598
+ for (const p of demoted) p.action = "flag";
2599
+ notes.push(
2600
+ `${blockedBy.join(", ")} differs from the shipped template, so the whole coupled set was left alone: ${MATCH_HARNESS_COUPLED.join(", ")} upgrade together. matching/gate.sh calls \`harness.mjs --check-run\` and matching/next.mjs imports from harness.mjs, so upgrading one without the others leaves a harness that cannot run.`
2601
+ );
2602
+ }
2603
+ const demotedRels = new Set(demoted.map((p) => p.f.rel));
2604
+ for (const { f, template, existing, action } of plans) {
2605
+ if (action === "flag") {
2606
+ if (demotedRels.has(f.rel)) continue;
2607
+ notes.push(
2608
+ `${f.rel} differs from the shipped template and was left alone (hand-edited?)`
2609
+ );
2610
+ continue;
2611
+ }
2612
+ if (action === "skip") continue;
2613
+ const target = join(cwd, f.rel);
2614
+ await mkdir(dirname(target), { recursive: true });
2615
+ before.set(f.rel, existing);
2616
+ await writeFile(target, template, "utf-8");
2617
+ written.push(f.rel);
2618
+ if (action === "replace") notes.push(`${f.rel} upgraded from a previous version`);
2619
+ }
2620
+ for (const [rel, marker, endMarker, block] of APPENDED_BLOCKS) {
2621
+ const path = join(cwd, rel);
2622
+ const existing = await readIfExists(path);
2623
+ const plan = planBlockWrite(
2624
+ existing,
2625
+ marker,
2626
+ endMarker,
2627
+ block,
2628
+ blockPreviousAll[rel] ?? []
2629
+ );
2630
+ if (plan.action === "skip") continue;
2631
+ if (plan.action === "flag") {
2632
+ notes.push(
2633
+ `${rel} carries a match-harness block that differs from every block this recipe has shipped, and was left alone (hand-edited?)`
2634
+ );
2635
+ continue;
2636
+ }
2637
+ before.set(rel, existing);
2638
+ await writeFile(path, plan.content, "utf-8");
2639
+ written.push(rel);
2640
+ if (plan.action === "replace")
2641
+ notes.push(`${rel}'s match-harness block upgraded from a previous version`);
2642
+ if (plan.action === "terminate")
2643
+ notes.push(
2644
+ `${rel}'s match-harness block region was terminated so a future version can update it`
2645
+ );
2646
+ }
2647
+ const siteOwned = new Set(
2648
+ MATCH_HARNESS_FILES.filter((f) => f.owner === "site").map((f) => f.rel)
2649
+ );
2650
+ const toFormat = written.filter((p) => siteOwned.has(p) || p === "CLAUDE.md");
2651
+ if (toFormat.length > 0) {
2652
+ const bin = await (deps.resolvePrettier ?? resolveTargetPrettier)(cwd);
2653
+ if (bin === null) {
2654
+ notes.push(PRETTIER_FLAG_NOTE);
2655
+ } else if (!await formatWithPrettier(deps.spawn, cwd, toFormat, {
2656
+ bin,
2657
+ timeoutMs: PRETTIER_TIMEOUT_MS
2658
+ })) {
2659
+ notes.push(PRETTIER_FLAG_NOTE);
2660
+ }
2661
+ }
2662
+ await commit(
2663
+ "feat: install the matching harness (/dev/match route + matching/ gate scripts)"
2664
+ );
2665
+ const missing = await pathsMissingFromHead(cwd, MATCH_HARNESS_INSTALLED_PATHS);
2666
+ if (missing.length > 0) {
2667
+ const rules = await ignoreRulesFor(cwd, missing);
2668
+ const sources = [...new Set(rules.map((r) => r.split(" ")[0]))];
2669
+ const explained = new Set(rules.map((r) => r.split(" ")[1] ?? ""));
2670
+ const unexplained = missing.filter((p) => !explained.has(p));
2671
+ const removed = [];
2672
+ for (const rel of written.filter((p) => missing.includes(p))) {
2673
+ const prev = before.get(rel);
2674
+ if (prev === void 0) continue;
2675
+ if (prev === null) {
2676
+ await rm(join(cwd, rel), { force: true });
2677
+ removed.push(rel);
2678
+ } else {
2679
+ await writeFile(join(cwd, rel), prev, "utf-8");
2680
+ }
2681
+ }
2682
+ for (const d of [...new Set(removed.map(dirname))].sort((a, b) => b.length - a.length)) {
2683
+ if (d !== ".") await rmdir(join(cwd, d)).catch(() => void 0);
2684
+ }
2685
+ return {
2686
+ kind: "failed",
2687
+ notes: `the harness was NOT installed: ${missing.length} of ${MATCH_HARNESS_INSTALLED_PATHS.length} paths git refused to track, so a fresh clone, CI and the next agent get a harness that does not exist. Absent from the commit: ${missing.join(", ")}. ` + (sources.length > 0 ? `Excluded by ${sources.join(", ")} \u2014 narrow or remove those rules and re-run. ` : "") + (unexplained.length > 0 ? `No ignore rule matched ${unexplained.join(", ")} \u2014 check .git/info/exclude, core.excludesFile, and whether the directory is a nested repository. ` : "") + "Everything this run wrote to those paths has been put back as it was."
2688
+ };
2689
+ }
2690
+ return notes.length > 0 ? { kind: "ok", notes: notes.join("; ") } : { kind: "ok" };
2691
+ }
2692
+ });
2693
+ }
2694
+
2695
+ export {
2696
+ matchHarness
2697
+ };
2698
+ //# sourceMappingURL=chunk-ZCL7C5LH.js.map