@fabrika/builder 0.9.0-dev.12 → 0.9.0-dev.14

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 (96) hide show
  1. package/BUILD-CONTRACT.md +9 -3
  2. package/README.md +39 -9
  3. package/cli/src/bin.ts +14 -1
  4. package/cli/src/build-review.ts +66 -0
  5. package/cli/src/build-status.ts +41 -3
  6. package/cli/src/catalog.ts +34 -2
  7. package/cli/src/commands/advance.ts +48 -6
  8. package/cli/src/commands/build.ts +152 -15
  9. package/cli/src/commands/design.ts +34 -0
  10. package/cli/src/commands/flows.ts +32 -0
  11. package/cli/src/commands/induce.ts +2 -2
  12. package/cli/src/commands/init.ts +7 -1
  13. package/cli/src/commands/next.ts +9 -2
  14. package/cli/src/context.ts +2 -1
  15. package/cli/src/contrast.ts +301 -0
  16. package/cli/src/daemon-client.ts +29 -3
  17. package/cli/src/design-review.ts +261 -0
  18. package/cli/src/flows.ts +162 -0
  19. package/cli/src/frontmatter.ts +32 -0
  20. package/cli/src/index.ts +10 -1
  21. package/cli/src/induce.ts +61 -3
  22. package/cli/src/issues.ts +15 -29
  23. package/cli/src/layout.ts +5 -2
  24. package/cli/src/packet.ts +36 -3
  25. package/cli/src/phase-state.ts +19 -1
  26. package/cli/src/verify.ts +50 -0
  27. package/daemon/src/handlers.ts +32 -6
  28. package/daemon/src/phases.ts +7 -109
  29. package/daemon/src/platform-source.ts +8 -0
  30. package/decisions/README.md +2 -2
  31. package/decisions/patterns/cf-contract-app.md +57 -0
  32. package/decisions/technologies/bun.md +2 -1
  33. package/decisions/technologies/cf-fabrika-contract.md +45 -0
  34. package/decisions/technologies/cloudflare.md +3 -1
  35. package/decisions/technologies/oblaka.md +1 -1
  36. package/decisions/technologies/opice.md +1 -1
  37. package/decisions/technologies/react.md +1 -1
  38. package/decisions/technologies/tailwind.md +5 -5
  39. package/decisions/technologies/zerops-fabrika-auth.md +1 -1
  40. package/decisions/technologies/zerops-platform.md +1 -1
  41. package/package.json +11 -8
  42. package/shared/approvals.ts +65 -0
  43. package/shared/derive.ts +189 -0
  44. package/shared/gate.ts +20 -0
  45. package/shared/index.ts +6 -1
  46. package/shared/phases.ts +22 -20
  47. package/skill/SKILL.md +25 -16
  48. package/skill/agents/build-orchestrator.md +28 -8
  49. package/skill/agents/flows-author.md +27 -13
  50. package/skill/agents/implementer.md +3 -1
  51. package/skill/agents/opice-skeleton-author.md +8 -7
  52. package/skill/gates/brief.jsx +26 -5
  53. package/skill/gates/review-grid.jsx +3 -8
  54. package/skill/gates/tech.jsx +3 -3
  55. package/stacks/README.md +8 -2
  56. package/stacks/cf-app.md +60 -0
  57. package/stacks/cf-fat.md +1 -0
  58. package/stacks/cf-internal-app.md +2 -2
  59. package/stacks/cf-lightweight.md +3 -2
  60. package/stacks/contember-app.md +1 -0
  61. package/stacks/content-site.md +1 -0
  62. package/stacks/zerops-app.md +1 -0
  63. package/types/cli/src/bin.d.ts +1 -1
  64. package/types/cli/src/build-review.d.ts +13 -0
  65. package/types/cli/src/build-status.d.ts +16 -1
  66. package/types/cli/src/catalog.d.ts +9 -0
  67. package/types/cli/src/commands/design.d.ts +1 -0
  68. package/types/cli/src/commands/flows.d.ts +1 -0
  69. package/types/cli/src/contrast.d.ts +59 -0
  70. package/types/cli/src/daemon-client.d.ts +13 -2
  71. package/types/cli/src/design-review.d.ts +54 -0
  72. package/types/cli/src/flows.d.ts +28 -0
  73. package/types/cli/src/frontmatter.d.ts +8 -0
  74. package/types/cli/src/index.d.ts +1 -1
  75. package/types/cli/src/induce.d.ts +3 -0
  76. package/types/cli/src/issues.d.ts +4 -0
  77. package/types/cli/src/packet.d.ts +9 -1
  78. package/types/cli/src/phase-state.d.ts +1 -1
  79. package/types/cli/src/verify.d.ts +18 -0
  80. package/types/daemon/src/phases.d.ts +4 -16
  81. package/types/daemon/src/platform-remote.d.ts +6 -2
  82. package/types/shared/approvals.d.ts +32 -0
  83. package/types/shared/derive.d.ts +41 -0
  84. package/types/shared/gate.d.ts +11 -0
  85. package/types/shared/index.d.ts +105 -65
  86. package/types/shared/phases.d.ts +7 -1
  87. package/ui/dist/assets/client.css +1 -1
  88. package/ui/dist/assets/client.vn7hykcn.js +120 -0
  89. package/ui/dist/index.html +1 -1
  90. package/cli/src/derive.ts +0 -105
  91. package/skill/gates/build.jsx +0 -20
  92. package/skill/gates/design.jsx +0 -22
  93. package/skill/gates/flows.jsx +0 -14
  94. package/skill/gates/vision.jsx +0 -27
  95. package/types/cli/src/derive.d.ts +0 -17
  96. package/ui/dist/assets/client.8aw2edb7.js +0 -214
@@ -0,0 +1,301 @@
1
+ // WCAG 2 contrast of the `@fabrika/ui` token pairs the kit's components draw, under an application's override.
2
+
3
+ export type ThemeMode = 'light' | 'dark'
4
+ type Tokens = Record<string, string>
5
+
6
+ interface Declared {
7
+ value: string
8
+ important: boolean
9
+ }
10
+ type Block = Record<string, Declared>
11
+
12
+ export interface ThemeBlocks {
13
+ /** Top-level `:root` declarations of custom properties. */
14
+ light: Block
15
+ /** Top-level `:root[data-theme='dark']` declarations of custom properties. */
16
+ dark: Block
17
+ /** `--fui-*` names also declared in a rule this reader does not cascade: another selector, or inside an at-rule. */
18
+ elsewhere: string[]
19
+ }
20
+
21
+ interface Pair {
22
+ fg: string
23
+ bg: string
24
+ /** 4.5 for text, 3 for a focus indicator (WCAG 1.4.3 and 1.4.11). */
25
+ min: number
26
+ }
27
+
28
+ /** The foreground/background pairs `components.css` draws. */
29
+ const PAIRS: readonly Pair[] = [
30
+ { fg: '--fui-text', bg: '--fui-bg', min: 4.5 },
31
+ { fg: '--fui-text', bg: '--fui-surface', min: 4.5 },
32
+ { fg: '--fui-text', bg: '--fui-surface-muted', min: 4.5 },
33
+ { fg: '--fui-text', bg: '--fui-border', min: 4.5 },
34
+ { fg: '--fui-text', bg: '--fui-accent-soft', min: 4.5 },
35
+ { fg: '--fui-text-muted', bg: '--fui-bg', min: 4.5 },
36
+ { fg: '--fui-text-muted', bg: '--fui-surface', min: 4.5 },
37
+ { fg: '--fui-text-muted', bg: '--fui-surface-muted', min: 4.5 },
38
+ { fg: '--fui-text-subtle', bg: '--fui-bg', min: 4.5 },
39
+ { fg: '--fui-text-subtle', bg: '--fui-surface', min: 4.5 },
40
+ { fg: '--fui-label-color', bg: '--fui-bg', min: 4.5 },
41
+ { fg: '--fui-label-color', bg: '--fui-surface', min: 4.5 },
42
+ { fg: '--fui-table-head-color', bg: '--fui-surface-muted', min: 4.5 },
43
+ { fg: '--fui-accent', bg: '--fui-bg', min: 4.5 },
44
+ { fg: '--fui-accent', bg: '--fui-surface', min: 4.5 },
45
+ { fg: '--fui-accent', bg: '--fui-accent-soft', min: 4.5 },
46
+ { fg: '--fui-accent-contrast', bg: '--fui-accent', min: 4.5 },
47
+ { fg: '--fui-accent-contrast', bg: '--fui-accent-hover', min: 4.5 },
48
+ { fg: '--fui-accent-contrast', bg: '--fui-danger', min: 4.5 },
49
+ { fg: '--fui-accent-contrast', bg: '--fui-danger-text', min: 4.5 },
50
+ { fg: '--fui-danger-text', bg: '--fui-surface', min: 4.5 },
51
+ { fg: '--fui-success-text', bg: '--fui-success-soft', min: 4.5 },
52
+ { fg: '--fui-warning-text', bg: '--fui-warning-soft', min: 4.5 },
53
+ { fg: '--fui-danger-text', bg: '--fui-danger-soft', min: 4.5 },
54
+ { fg: '--fui-info-text', bg: '--fui-info-soft', min: 4.5 },
55
+ { fg: '--fui-focus', bg: '--fui-bg', min: 3 },
56
+ { fg: '--fui-focus', bg: '--fui-surface', min: 3 },
57
+ { fg: '--fui-focus', bg: '--fui-surface-muted', min: 3 },
58
+ ]
59
+
60
+ export interface ContrastResult {
61
+ fg: string
62
+ bg: string
63
+ mode: ThemeMode
64
+ min: number
65
+ /** Null when either colour could not be computed (`note` says why). */
66
+ ratio: number | null
67
+ /** The same pair with the kit's own values; null when it cannot be computed. */
68
+ kitRatio: number | null
69
+ /**
70
+ * `inherited`: below the minimum with the kit's own values too, and the override does not lower it — the kit's
71
+ * defect, not the application's. Only `fail` is the override's.
72
+ */
73
+ status: 'pass' | 'fail' | 'inherited' | 'unchecked'
74
+ note?: string
75
+ }
76
+
77
+ const LIGHT_SELECTOR = ':root'
78
+ // Quotes removed: `[data-theme=dark]` and `[data-theme="dark"]` are the same selector.
79
+ const DARK_SELECTOR = ':root[data-theme=dark]'
80
+ const FUI_DECLARATION = /(--fui-[\w-]+)\s*:/g
81
+
82
+ /**
83
+ * Reads the custom properties of the top-level `:root` and `:root[data-theme='dark']` rules, the two blocks the kit
84
+ * declares its tokens in. A `--fui-*` token declared anywhere else is listed in `elsewhere`, so no pair that reads it
85
+ * passes on values the browser may not use.
86
+ */
87
+ export function readThemeBlocks(css: string): ThemeBlocks {
88
+ const src = css.replace(/\/\*[\s\S]*?\*\//g, '')
89
+ const light: Block = {}
90
+ const dark: Block = {}
91
+ const read = new Map<string, number>()
92
+ let depth = 0
93
+ let start = 0
94
+ let bodyStart = 0
95
+ let selector = ''
96
+ for (let i = 0; i < src.length; i++) {
97
+ const ch = src.charAt(i)
98
+ if (ch === '{') {
99
+ if (depth === 0) {
100
+ selector = src.slice(start, i)
101
+ bodyStart = i + 1
102
+ }
103
+ depth++
104
+ } else if (ch === '}') {
105
+ depth--
106
+ if (depth === 0) {
107
+ const selectors = selector.split(',').map((s) => s.replace(/\s+/g, '').replace(/["']/g, ''))
108
+ const targets = [selectors.includes(LIGHT_SELECTOR) ? light : null, selectors.includes(DARK_SELECTOR) ? dark : null]
109
+ const body = src.slice(bodyStart, i)
110
+ if (targets.some((t) => t !== null) && !body.includes('{')) {
111
+ const declared = declarations(body)
112
+ for (const target of targets) if (target) Object.assign(target, declared)
113
+ for (const name of Object.keys(declared)) read.set(name, (read.get(name) ?? 0) + 1)
114
+ }
115
+ start = i + 1
116
+ }
117
+ if (depth < 0) depth = 0
118
+ } else if (ch === ';' && depth === 0) {
119
+ start = i + 1
120
+ }
121
+ }
122
+ const total = new Map<string, number>()
123
+ for (const m of src.matchAll(FUI_DECLARATION)) total.set(m[1] ?? '', (total.get(m[1] ?? '') ?? 0) + 1)
124
+ const elsewhere = [...total].filter(([name, count]) => count > (read.get(name) ?? 0)).map(([name]) => name)
125
+ return { light, dark, elsewhere }
126
+ }
127
+
128
+ function declarations(body: string): Block {
129
+ const out: Block = {}
130
+ for (const decl of body.split(';')) {
131
+ const colon = decl.indexOf(':')
132
+ if (colon < 0) continue
133
+ const name = decl.slice(0, colon).trim()
134
+ if (!name.startsWith('--')) continue
135
+ const raw = decl.slice(colon + 1).trim()
136
+ const important = /!\s*important$/i.test(raw)
137
+ out[name] = { value: important ? raw.replace(/!\s*important$/i, '').trim() : raw, important }
138
+ }
139
+ return out
140
+ }
141
+
142
+ /**
143
+ * The token values each mode computes to with the application's stylesheet imported after the kit's. The dark rule is
144
+ * more specific than `:root`, so an application's `:root` override reaches dark mode only where the kit's dark rule
145
+ * declares nothing, or with `!important`, which outranks every normal declaration.
146
+ */
147
+ export function cascade(kit: ThemeBlocks, app: ThemeBlocks): Record<ThemeMode, Tokens> {
148
+ const light = [kit.light, app.light]
149
+ const dark = [kit.light, app.light, kit.dark, app.dark]
150
+ return { light: layered(light), dark: layered(dark) }
151
+ }
152
+
153
+ /** Blocks in ascending precedence: normal declarations first, then the important ones in the same order. */
154
+ function layered(blocks: Block[]): Tokens {
155
+ const out: Tokens = {}
156
+ for (const important of [false, true]) {
157
+ for (const block of blocks) {
158
+ for (const [name, d] of Object.entries(block)) if (d.important === important) out[name] = d.value
159
+ }
160
+ }
161
+ return out
162
+ }
163
+
164
+ export function checkContrast(kit: ThemeBlocks, app: ThemeBlocks): ContrastResult[] {
165
+ const themed = cascade(kit, app)
166
+ const baseline = cascade(kit, { light: {}, dark: {}, elsewhere: [] })
167
+ const elsewhere = new Set(app.elsewhere)
168
+ const modes: ThemeMode[] = ['light', 'dark']
169
+ return modes.flatMap((mode) =>
170
+ PAIRS.map((pair): ContrastResult => {
171
+ const kitMeasured = pairRatio(baseline[mode], pair, new Set())
172
+ const kitRatio = typeof kitMeasured === 'number' ? kitMeasured : null
173
+ const base = { fg: pair.fg, bg: pair.bg, mode, min: pair.min, kitRatio }
174
+ const measured = pairRatio(themed[mode], pair, elsewhere)
175
+ if (typeof measured === 'string') return { ...base, ratio: null, status: 'unchecked', note: measured }
176
+ if (measured >= pair.min) return { ...base, ratio: measured, status: 'pass' }
177
+ const inherited = kitRatio !== null && kitRatio < pair.min && measured >= kitRatio
178
+ return { ...base, ratio: measured, status: inherited ? 'inherited' : 'fail' }
179
+ })
180
+ )
181
+ }
182
+
183
+ /** The opaque colour a token computes to in a mode, as `#rrggbb`; null when it cannot be computed or is translucent. */
184
+ export function tokenHex(kit: ThemeBlocks, app: ThemeBlocks, mode: ThemeMode, name: string): string | null {
185
+ const chain: string[] = []
186
+ const value = resolveVar(cascade(kit, app)[mode], name, chain)
187
+ // A token also declared in a rule the check does not cascade has no definite colour, as its pairs are unchecked.
188
+ if (chain.some((n) => app.elsewhere.includes(n))) return null
189
+ const color = value === null ? null : parseColor(value)
190
+ if (!color || color.a < 1) return null
191
+ const byte = (c: number) => Math.round(c * 255).toString(16).padStart(2, '0')
192
+ return `#${byte(color.r)}${byte(color.g)}${byte(color.b)}`
193
+ }
194
+
195
+ /** The ratio, or why it cannot be computed. */
196
+ function pairRatio(tokens: Tokens, pair: Pair, elsewhere: Set<string>): number | string {
197
+ const fg = tokenColor(tokens, pair.fg, elsewhere)
198
+ if (typeof fg === 'string') return fg
199
+ const bg = tokenColor(tokens, pair.bg, elsewhere)
200
+ if (typeof bg === 'string') return bg
201
+ if (bg.a < 1) return `${pair.bg} is translucent`
202
+ return contrastRatio(over(fg, bg), bg)
203
+ }
204
+
205
+ function tokenColor(tokens: Tokens, name: string, elsewhere: Set<string>): Rgba | string {
206
+ const chain: string[] = []
207
+ const value = resolveVar(tokens, name, chain)
208
+ const unread = chain.find((n) => elsewhere.has(n))
209
+ if (unread) return `${unread} is also declared in a rule the check does not read (another selector, or inside an at-rule)`
210
+ if (value === null) return `${name} is not declared, or its var() chain does not resolve`
211
+ const color = parseColor(value)
212
+ return color ?? `${name} is \`${value}\`, a colour the check does not read`
213
+ }
214
+
215
+ /** Follows a `var()` chain; `chain` collects every token name it read. */
216
+ function resolveVar(tokens: Tokens, name: string, chain: string[]): string | null {
217
+ chain.push(name)
218
+ const value = tokens[name]
219
+ if (value === undefined || chain.length > 16) return null
220
+ const ref = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/.exec(value)
221
+ if (!ref) return value
222
+ return resolveVar(tokens, ref[1] ?? '', chain) ?? ref[2]?.trim() ?? null
223
+ }
224
+
225
+ /** Encoded sRGB channels and alpha, each in [0, 1]. */
226
+ interface Rgba {
227
+ r: number
228
+ g: number
229
+ b: number
230
+ a: number
231
+ }
232
+
233
+ /** OKLCH here; every other CSS colour through `Bun.color`, which does not read OKLCH. Null when neither reads it. */
234
+ export function parseColor(value: string): Rgba | null {
235
+ const v = value.trim().toLowerCase()
236
+ const oklch = /^oklch\(([^()]*)\)$/.exec(v)
237
+ if (oklch) return parseOklch(oklch[1] ?? '')
238
+ const rgba = Bun.color(v, '{rgba}')
239
+ return rgba ? { r: rgba.r / 255, g: rgba.g / 255, b: rgba.b / 255, a: rgba.a } : null
240
+ }
241
+
242
+ function parseOklch(args: string): Rgba | null {
243
+ const parts = args.split(/[\s/]+/).filter((p) => p.length > 0)
244
+ if (parts.length !== 3 && parts.length !== 4) return null
245
+ const l = number(parts[0] ?? '', 1)
246
+ // Chroma's 100% is 0.4 (CSS Color 4).
247
+ const c = number(parts[1] ?? '', 0.4)
248
+ const hue = Number((parts[2] ?? '').replace(/deg$/, ''))
249
+ const a = parts[3] === undefined ? 1 : number(parts[3], 1)
250
+ if (l === null || c === null || a === null || !Number.isFinite(hue)) return null
251
+ return { ...oklchToRgb(Math.min(1, Math.max(0, l)), Math.max(0, c), hue), a: Math.min(1, Math.max(0, a)) }
252
+ }
253
+
254
+ /** A plain number, or a percentage of `full`. */
255
+ function number(part: string, full: number): number | null {
256
+ const pct = part.endsWith('%')
257
+ const n = Number(pct ? part.slice(0, -1) : part)
258
+ if (!Number.isFinite(n)) return null
259
+ return pct ? (n / 100) * full : n
260
+ }
261
+
262
+ /** OKLCH to encoded sRGB. An out-of-gamut colour is clipped channel by channel, not chroma-reduced as a browser may. */
263
+ function oklchToRgb(l: number, c: number, h: number): { r: number; g: number; b: number } {
264
+ const rad = (h * Math.PI) / 180
265
+ const a = c * Math.cos(rad)
266
+ const b = c * Math.sin(rad)
267
+ const lp = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3
268
+ const mp = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3
269
+ const sp = (l - 0.0894841775 * a - 1.291485548 * b) ** 3
270
+ const encode = (x: number) => {
271
+ const v = Math.min(1, Math.max(0, x))
272
+ return v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055
273
+ }
274
+ return {
275
+ r: encode(4.0767416621 * lp - 3.3077115913 * mp + 0.2309699292 * sp),
276
+ g: encode(-1.2684380046 * lp + 2.6097574011 * mp - 0.3413193965 * sp),
277
+ b: encode(-0.0041960863 * lp - 0.7034186147 * mp + 1.707614701 * sp),
278
+ }
279
+ }
280
+
281
+ /** A translucent foreground composited over an opaque background, as the browser paints it. */
282
+ function over(fg: Rgba, bg: Rgba): Rgba {
283
+ const mix = (f: number, b: number) => f * fg.a + b * (1 - fg.a)
284
+ return { r: mix(fg.r, bg.r), g: mix(fg.g, bg.g), b: mix(fg.b, bg.b), a: 1 }
285
+ }
286
+
287
+ export function contrastRatio(x: Rgba, y: Rgba): number {
288
+ const lx = luminance(x)
289
+ const ly = luminance(y)
290
+ return (Math.max(lx, ly) + 0.05) / (Math.min(lx, ly) + 0.05)
291
+ }
292
+
293
+ function luminance({ r, g, b }: Rgba): number {
294
+ const lin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
295
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
296
+ }
297
+
298
+ /** Truncated, never rounded up: WCAG does not round, so 4.499 must not read as 4.50. */
299
+ export function formatRatio(ratio: number): string {
300
+ return `${(Math.floor(ratio * 100) / 100).toFixed(2)}:1`
301
+ }
@@ -1,14 +1,16 @@
1
1
  import { waitForEvent } from '@fabrika/daemon-kit'
2
2
  import {
3
3
  consumedFeedbackSchema,
4
+ consumedGateSchema,
4
5
  feedbackMetaSchema,
5
6
  feedbackTextSchema,
6
7
  phaseStateSchema,
7
8
  planResultSchema,
8
9
  submitFeedbackSchema,
9
10
  } from '../../shared'
11
+ import type { PhaseState } from '../../shared/derive'
12
+ import type { GateVerdict } from '../../shared/gate'
10
13
  import { BASE_URL, TIMEOUT_MS, WS_URL } from './config'
11
- import type { PhaseState } from './derive'
12
14
 
13
15
  const HEALTH_TIMEOUT_MS = 1000
14
16
 
@@ -81,14 +83,38 @@ export async function peekFeedback(sessionId: string): Promise<string | null> {
81
83
  }
82
84
  }
83
85
 
84
- export async function consumeFeedback(sessionId: string): Promise<string | null> {
86
+ export interface ConsumedFeedback {
87
+ feedback: string
88
+ verdict: GateVerdict
89
+ }
90
+
91
+ export async function consumeFeedback(sessionId: string): Promise<ConsumedFeedback | null> {
85
92
  try {
86
93
  const res = await fetch(`${BASE_URL}/api/session/${sessionId}/feedback/consume`, {
87
94
  method: 'POST',
88
95
  signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
89
96
  })
90
97
  const result = consumedFeedbackSchema.safeParse(await res.json())
91
- return result.success ? result.data.feedback : null
98
+ return result.success ? { feedback: result.data.feedback, verdict: result.data.verdict } : null
99
+ } catch {
100
+ return null
101
+ }
102
+ }
103
+
104
+ export interface ConsumedGate {
105
+ revision: number
106
+ verdict: GateVerdict
107
+ }
108
+
109
+ /** Consumes a named gate's latest submission; null when the daemon is down or nothing was submitted. */
110
+ export async function consumeGate(sessionId: string, gateName: string): Promise<ConsumedGate | null> {
111
+ try {
112
+ const res = await fetch(`${BASE_URL}/api/session/${encodeURIComponent(sessionId)}/gate/${encodeURIComponent(gateName)}/consume`, {
113
+ method: 'POST',
114
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
115
+ })
116
+ const result = consumedGateSchema.safeParse(await res.json())
117
+ return result.success ? { revision: result.data.revision, verdict: result.data.verdict } : null
92
118
  } catch {
93
119
  return null
94
120
  }
@@ -0,0 +1,261 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'fs'
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path'
3
+ import { GATE_APPROVE, GATE_CHANGES, GATE_VERDICT_ID } from '../../shared/gate'
4
+ import { literal } from './build-review'
5
+ import { checkContrast, contrastRatio, type ContrastResult, formatRatio, parseColor, readThemeBlocks, type ThemeMode, tokenHex } from './contrast'
6
+ import { extractFrontMatter, list, scalar } from './frontmatter'
7
+
8
+ // Not `design`: that label belongs to the removed design phase, whose old reviews must not count here.
9
+ export const DESIGN_GATE = 'design-checkpoint'
10
+ export const DESIGN_PATH = '.fabrika/architecture/design.md'
11
+ export const DESIGN_REVIEW_PATH = '.fabrika/build/design-review.jsx'
12
+
13
+ export type DesignContrast =
14
+ | { kind: 'checked'; stylesheet: string; overrides: string[][]; results: ContrastResult[]; swatches: Swatches }
15
+ /** The stylesheet's directory does not resolve `@fabrika/ui`: a stack without the kit has other tokens. */
16
+ | { kind: 'no-kit'; stylesheet: string }
17
+ | { kind: 'invalid'; problem: string }
18
+
19
+ /** The colour each swatch token computes to, per mode; null when it cannot be computed. */
20
+ type Swatches = Record<ThemeMode, [string, string | null][]>
21
+
22
+ /** The tokens a variant's swatches show: the page, the text, the accent and its text, focus, danger. */
23
+ const SWATCH_TOKENS = [
24
+ '--fui-bg',
25
+ '--fui-surface',
26
+ '--fui-text',
27
+ '--fui-text-muted',
28
+ '--fui-accent',
29
+ '--fui-accent-contrast',
30
+ '--fui-focus',
31
+ '--fui-danger',
32
+ ]
33
+
34
+ export interface ThemeVariant {
35
+ /** The file name without its extension: what the reviewer picks. */
36
+ name: string
37
+ contrast: DesignContrast
38
+ }
39
+
40
+ export interface Design {
41
+ /** The stylesheet the application imports (`stylesheet:`): what `build done` judges. */
42
+ applied: DesignContrast
43
+ /** The alternatives the reviewer compares (`variants:`); empty when design.md lists none. */
44
+ variants: ThemeVariant[]
45
+ /** What is wrong with the variant list; shown in the view and warned, never refused. */
46
+ problems: string[]
47
+ }
48
+
49
+ /** The theme override that `design.md`'s front matter names (`stylesheet:`), checked against the kit it imports. */
50
+ export function readDesignContrast(repoRoot: string): DesignContrast {
51
+ return readDesign(repoRoot).applied
52
+ }
53
+
54
+ export function readDesign(repoRoot: string): Design {
55
+ const designFile = join(repoRoot, DESIGN_PATH)
56
+ if (!existsSync(designFile)) return { applied: { kind: 'invalid', problem: `${DESIGN_PATH} is missing` }, variants: [], problems: [] }
57
+ const front = extractFrontMatter(readFileSync(designFile, 'utf8')).body
58
+ const stylesheet = scalar(front['stylesheet'])
59
+ const applied: DesignContrast = stylesheet
60
+ ? readStylesheet(repoRoot, stylesheet)
61
+ : { kind: 'invalid', problem: `${DESIGN_PATH} names no \`stylesheet:\` in its front matter` }
62
+ const paths = list(front['variants'])
63
+ const variants = paths.map((path) => ({ name: basename(path).replace(/\.[^.]*$/, ''), contrast: readStylesheet(repoRoot, path) }))
64
+ const problems: string[] = []
65
+ if (front['variants'] !== undefined && paths.length === 0) problems.push('write `variants` on one line, as `[a.css, b.css]`')
66
+ if (paths.length === 1 || paths.length > 3) problems.push(`list two or three \`variants:\` to compare, not ${paths.length}`)
67
+ for (const v of variants) if (v.contrast.kind === 'invalid') problems.push(`${v.contrast.problem}; it is not offered as a choice`)
68
+ const names = variants.map((v) => v.name)
69
+ if (new Set(names).size !== names.length) problems.push('two variants share a file name; the reviewer could not tell them apart')
70
+ return { applied, variants, problems }
71
+ }
72
+
73
+ function readStylesheet(repoRoot: string, stylesheet: string): DesignContrast {
74
+ const file = insideRepository(repoRoot, stylesheet)
75
+ if (!file) return { kind: 'invalid', problem: `stylesheet ${stylesheet} is not a file inside the repository` }
76
+ let kitFile: string
77
+ try {
78
+ kitFile = Bun.resolveSync('@fabrika/ui/theme.css', dirname(file))
79
+ } catch {
80
+ return { kind: 'no-kit', stylesheet }
81
+ }
82
+ const app = readThemeBlocks(readFileSync(file, 'utf8'))
83
+ const kit = readThemeBlocks(readFileSync(kitFile, 'utf8'))
84
+ const names = [...new Set([...Object.keys(app.light), ...Object.keys(app.dark)])].sort()
85
+ const shown = (d: { value: string; important: boolean } | undefined) => (d ? `${d.value}${d.important ? ' !important' : ''}` : '')
86
+ const overrides = names.map((name) => [name, shown(app.light[name]), shown(app.dark[name])])
87
+ const swatch = (mode: ThemeMode) => SWATCH_TOKENS.map((t): [string, string | null] => [t, tokenHex(kit, app, mode, t)])
88
+ return { kind: 'checked', stylesheet, overrides, results: checkContrast(kit, app), swatches: { light: swatch('light'), dark: swatch('dark') } }
89
+ }
90
+
91
+ /**
92
+ * The variant whose `--fui-*` overrides the applied stylesheet declares exactly, or null. Only the kit's tokens count:
93
+ * the applied stylesheet also holds the application's own properties. Values compare without case or extra spaces.
94
+ */
95
+ export function appliedVariant(design: Design): string | null {
96
+ const { applied } = design
97
+ if (applied.kind !== 'checked') return null
98
+ const tokens = (overrides: string[][]) =>
99
+ JSON.stringify(overrides.filter(([name]) => name?.startsWith('--fui-')).map((row) => row.map((cell) => cell.toLowerCase().replace(/\s+/g, ' '))))
100
+ const same = design.variants.find((v) => v.contrast.kind === 'checked' && tokens(v.contrast.overrides) === tokens(applied.overrides))
101
+ return same?.name ?? null
102
+ }
103
+
104
+ /** The real path of a repository-relative file, or null when it is missing, not a file, or resolves outside. */
105
+ function insideRepository(repoRoot: string, path: string): string | null {
106
+ const target = resolve(repoRoot, path)
107
+ if (!existsSync(target)) return null
108
+ const real = realpathSync(target)
109
+ const rel = relative(realpathSync(repoRoot), real)
110
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || !statSync(real).isFile()) return null
111
+ return real
112
+ }
113
+
114
+ export function failingPairs(contrast: DesignContrast): ContrastResult[] {
115
+ return contrast.kind === 'checked' ? contrast.results.filter((r) => r.status === 'fail') : []
116
+ }
117
+
118
+ export function describePair(r: ContrastResult): string {
119
+ const ratio = r.ratio === null ? 'not computed' : formatRatio(r.ratio)
120
+ const line = `${r.mode}: ${r.fg} on ${r.bg} is ${ratio}, needs ${r.min}:1`
121
+ // A pair the kit already leaves below AA fails once the override lowers it further: name what to raise.
122
+ if (r.status === 'fail' && r.kitRatio !== null && r.kitRatio < r.min) {
123
+ return `${line}; the kit's own values give ${formatRatio(r.kitRatio)} and the override lowers it, so raise ${r.fg} as well`
124
+ }
125
+ return line
126
+ }
127
+
128
+ /** One line for the build evidence and the console. */
129
+ export function summarizeContrast(contrast: DesignContrast): string {
130
+ if (contrast.kind === 'invalid') return `contrast not checked: ${contrast.problem}`
131
+ if (contrast.kind === 'no-kit') return `contrast not checked: @fabrika/ui does not resolve from ${contrast.stylesheet}`
132
+ const count = (status: ContrastResult['status']) => contrast.results.filter((r) => r.status === status).length
133
+ const parts = [`${count('pass')} pass`, `${count('fail')} below AA`]
134
+ if (count('inherited') > 0) parts.push(`${count('inherited')} below AA in the kit itself`)
135
+ if (count('unchecked') > 0) parts.push(`${count('unchecked')} not checked`)
136
+ return `contrast: ${parts.join(', ')}`
137
+ }
138
+
139
+ export const VARIANT_CHOICE_ID = 'variant'
140
+
141
+ /**
142
+ * The design checkpoint's view: generated, like the build review, so the reviewer sees computed ratios, not claimed ones.
143
+ * With variants, each is shown side by side with a required choice; the preview shows only the applied stylesheet.
144
+ * `withDesign`: `design.md` exists, so the view shows the recorded decisions beside the computed values.
145
+ */
146
+ export function renderDesignReview(design: Design, urls: string[], withDesign: boolean, now: Date): string {
147
+ const { applied, variants } = design
148
+ const lines = [
149
+ `<Section title="Design checkpoint — theme of the running app">`,
150
+ `\t<Note>{${literal(note(applied, now))}}</Note>`,
151
+ ]
152
+ if (withDesign) lines.push(`\t<Markdown file="${DESIGN_PATH}" />`)
153
+ if (applied.kind === 'checked') {
154
+ lines.push(
155
+ `\t<Table headers={${literal(['Token', 'Light', 'Dark'])}} rows={${literal(applied.overrides)}} />`,
156
+ `\t<Table headers={${literal(['Mode', 'Text or indicator', 'On', 'Ratio', 'Needs', 'Result'])}} rows={${
157
+ literal(contrastRows(applied.results))
158
+ }} />`,
159
+ )
160
+ }
161
+ if (variants.length > 0) {
162
+ const current = appliedVariant(design)
163
+ const where = applied.kind === 'checked' ? applied.stylesheet : 'the applied stylesheet'
164
+ lines.push(
165
+ `\t<Note>{${
166
+ literal(
167
+ current
168
+ ? `The preview shows ${where}, which declares the overrides of variant ${current}.`
169
+ : `The preview shows ${where}, which matches none of the variants below.`,
170
+ )
171
+ }}</Note>`,
172
+ )
173
+ variants.forEach((variant, i) => lines.push(...variantItem(variant, i)))
174
+ }
175
+ for (const problem of design.problems) lines.push(`\t<Note>{${literal(`Variants: ${problem}.`)}}</Note>`)
176
+ lines.push(
177
+ `\t<Table headers={${literal(['Route to open in the preview'])}} rows={${
178
+ literal(urls.length ? urls.map((u) => [u]) : [['(no skeleton declares a url)']])
179
+ }} />`,
180
+ `\t<UserInput id="design-note" label="Which screen or token should change?" placeholder="e.g. the price is hard to read on /cart" multiline />`,
181
+ )
182
+ const offered = variants.filter((v) => v.contrast.kind !== 'invalid').map((v) => v.name)
183
+ if (offered.length >= 2) {
184
+ lines.push(
185
+ `\t<Choice id="${VARIANT_CHOICE_ID}" label="Which variant? (the closest one when requesting changes)" required options={${literal(offered)}} />`,
186
+ )
187
+ }
188
+ lines.push(`\t<Choice id="${GATE_VERDICT_ID}" label="Verdict" required options={['${GATE_APPROVE}', '${GATE_CHANGES}']} />`, '</Section>')
189
+ return lines.join('\n') + '\n'
190
+ }
191
+
192
+ function contrastRows(results: ContrastResult[]): string[][] {
193
+ return results.map((r) => [r.mode, r.fg, r.bg, r.ratio === null ? '-' : formatRatio(r.ratio), `${r.min}:1`, result(r)])
194
+ }
195
+
196
+ function variantItem(variant: ThemeVariant, index: number): string[] {
197
+ const { contrast } = variant
198
+ const where = contrast.kind === 'invalid' ? '' : ` — ${contrast.stylesheet}`
199
+ const failing = failingPairs(contrast).length
200
+ const badge = contrast.kind === 'checked' ? (failing > 0 ? `${failing} below AA` : 'AA') : 'not checked'
201
+ const badgeVariant = contrast.kind === 'checked' ? (failing > 0 ? 'warning' : 'success') : 'neutral'
202
+ const lines = [
203
+ `\t<Item id="variant-${index}" label={${literal(`Variant ${variant.name}${where}`)}} badge={${literal(badge)}} badgeVariant="${badgeVariant}">`,
204
+ ]
205
+ if (contrast.kind === 'checked') {
206
+ const notPassing = contrast.results.filter((r) => r.status !== 'pass')
207
+ lines.push(
208
+ `\t\t<Mermaid>{${literal(swatchMermaid(contrast.swatches))}}</Mermaid>`,
209
+ `\t\t<Table headers={${literal(['Token', 'Light', 'Dark'])}} rows={${literal(contrast.overrides)}} />`,
210
+ notPassing.length > 0
211
+ ? `\t\t<Table headers={${literal(['Mode', 'Text or indicator', 'On', 'Ratio', 'Needs', 'Result'])}} rows={${
212
+ literal(contrastRows(notPassing))
213
+ }} />`
214
+ : `\t\t<Note>Every pair meets AA.</Note>`,
215
+ )
216
+ } else {
217
+ lines.push(`\t\t<Note>{${literal(summarizeContrast(contrast))}}</Note>`)
218
+ }
219
+ lines.push('\t</Item>')
220
+ return lines
221
+ }
222
+
223
+ /** Swatches as a Mermaid graph: only token names and colours the check computed reach it, never repository text. */
224
+ function swatchMermaid(swatches: Swatches): string {
225
+ const lines = ['flowchart LR']
226
+ const styles: string[] = []
227
+ for (const mode of ['light', 'dark'] satisfies ThemeMode[]) {
228
+ lines.push(` subgraph ${mode}`)
229
+ swatches[mode].forEach(([token, hex], i) => {
230
+ const id = `${mode}${i}`
231
+ lines.push(` ${id}["${token} ${hex ?? '(not computed)'}"]`)
232
+ if (hex) styles.push(` style ${id} fill:${hex},color:${readableOn(hex)},stroke:#888888`)
233
+ })
234
+ lines.push(' end')
235
+ }
236
+ return [...lines, ...styles].join('\n')
237
+ }
238
+
239
+ /** Black or white, whichever reads better on the colour. */
240
+ function readableOn(hex: string): string {
241
+ const bg = parseColor(hex)
242
+ const black = parseColor('#000000')
243
+ const white = parseColor('#ffffff')
244
+ if (!bg || !black || !white) return '#000000'
245
+ return contrastRatio(black, bg) >= contrastRatio(white, bg) ? '#000000' : '#ffffff'
246
+ }
247
+
248
+ function result(r: ContrastResult): string {
249
+ if (r.status === 'pass') return 'pass'
250
+ if (r.status === 'fail') return 'BELOW AA'
251
+ if (r.status === 'inherited') return 'below AA in the kit itself'
252
+ return `not checked: ${r.note ?? ''}`
253
+ }
254
+
255
+ function note(contrast: DesignContrast, now: Date): string {
256
+ const source = `Generated by \`fabrika builder design review\` at ${now.toISOString()}. Open each route in the preview pane.`
257
+ if (contrast.kind === 'checked') {
258
+ return `${source} The ratios are WCAG 2 contrast, computed from the --fui-* tokens of ${contrast.stylesheet} over the kit's own; \`build done\` refuses a pair below AA unless the reviewer waives it.`
259
+ }
260
+ return `${source} ${summarizeContrast(contrast)}.`
261
+ }