@behavioral-agentic-design-system/core 0.45.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/package.json +17 -3
  2. package/scripts/a11y-lint.cjs +78 -15
  3. package/scripts/bads-sync.mjs +1 -1
  4. package/scripts/build-tokens.cjs +122 -7
  5. package/scripts/check-dark-contrast.mjs +204 -0
  6. package/scripts/check-flush-edges.mjs +245 -0
  7. package/scripts/design-system-advisory/README.md +239 -0
  8. package/scripts/design-system-advisory/check-copy-punctuation.mjs +44 -0
  9. package/scripts/design-system-advisory/check-even-padding.mjs +35 -0
  10. package/scripts/design-system-advisory/check-hand-built-button.mjs +46 -0
  11. package/scripts/design-system-advisory/check-html-nesting.mjs +51 -0
  12. package/scripts/design-system-advisory/check-icon-sizing.mjs +79 -0
  13. package/scripts/design-system-advisory/check-label-case.mjs +92 -0
  14. package/scripts/design-system-advisory/check-native-form-controls.mjs +53 -0
  15. package/scripts/design-system-advisory/check-radius.mjs +56 -0
  16. package/scripts/design-system-advisory/check-raw-values.mjs +61 -0
  17. package/scripts/design-system-advisory/check-small-text.mjs +72 -0
  18. package/scripts/design-system-advisory/check-tap-target.mjs +70 -0
  19. package/scripts/design-system-advisory/defaults.mjs +90 -0
  20. package/scripts/design-system-advisory/fixtures/clean.tsx.fixture +12 -0
  21. package/scripts/design-system-advisory/fixtures/violations.tsx.fixture +19 -0
  22. package/scripts/design-system-advisory/lib.mjs +255 -0
  23. package/scripts/design-system-advisory/run.mjs +189 -0
  24. package/scripts/design-system-advisory/workflow.yml +82 -0
  25. package/scripts/lib/copy-strings.mjs +146 -0
  26. package/scripts/lib/dark-contrast.mjs +120 -0
  27. package/scripts/lib/flush-edges.mjs +294 -0
  28. package/scripts/lib/lab-lint.mjs +62 -0
  29. package/scripts/lib/mount-page.mjs +25 -0
  30. package/scripts/lib/source-scan.mjs +173 -0
  31. package/scripts/lib/tells.mjs +240 -2
  32. package/scripts/lint-arbitrary-tokens.mjs +47 -0
  33. package/scripts/lint-component-token-refs.mjs +63 -0
  34. package/scripts/lint-content-hierarchy.mjs +114 -0
  35. package/scripts/lint-control-baseline.mjs +72 -0
  36. package/scripts/lint-copy-punctuation.mjs +60 -0
  37. package/scripts/lint-even-padding.mjs +58 -0
  38. package/scripts/lint-label-case.mjs +219 -0
  39. package/scripts/lint-microanimation.mjs +2 -2
  40. package/scripts/lint-proximity.mjs +181 -0
  41. package/scripts/lint-slop.mjs +1 -1
  42. package/scripts/lint-spacing-scale.mjs +78 -0
  43. package/scripts/lint-target-size.cjs +132 -0
  44. package/scripts/lint-token-primitives.mjs +307 -0
  45. package/scripts/size-audit.cjs +2 -2
  46. package/scripts/ux-tells.mjs +8 -6
  47. package/scripts/wcag-audit.cjs +25 -4
  48. package/src/api/layers/file.ts +2 -0
  49. package/src/api/site-auth.ts +14 -2
  50. package/src/app/preview/components/page.tsx +183 -14
  51. package/src/app/preview/sticker-sheet/page.tsx +329 -0
  52. package/src/app/preview/sticker-sheet/specimens.tsx +296 -0
  53. package/src/app/shell.tsx +4 -3
  54. package/src/components/Foundations/Colors.stories.tsx +119 -8
  55. package/src/components/home-tab.tsx +6 -1
  56. package/src/components/onboarding-wizard.tsx +1 -1
  57. package/src/components/ui/avatar.tsx +4 -0
  58. package/src/components/ui/chart.tsx +134 -42
  59. package/src/components/ui/checkbox-group.tsx +1 -1
  60. package/src/components/ui/checkbox.tsx +1 -1
  61. package/src/components/ui/combobox.tsx +1 -0
  62. package/src/components/ui/command.tsx +1 -1
  63. package/src/components/ui/date-picker.tsx +2 -0
  64. package/src/components/ui/date-range-picker.tsx +4 -0
  65. package/src/components/ui/file-upload.tsx +21 -2
  66. package/src/components/ui/heatmap.tsx +3 -1
  67. package/src/components/ui/input-group.tsx +5 -2
  68. package/src/components/ui/multi-select.tsx +1 -0
  69. package/src/components/ui/number-field.tsx +390 -0
  70. package/src/components/ui/radio-group.tsx +2 -2
  71. package/src/components/ui/sparkline.tsx +33 -4
  72. package/src/components/ui/spinner.tsx +23 -4
  73. package/src/components/ui/table.tsx +9 -0
  74. package/src/components/ui/week-picker.tsx +0 -12
  75. package/src/data/component-added.json +12 -0
  76. package/src/data/docs-index.ts +22 -1
  77. package/src/data/history.json +162 -162
  78. package/src/data/sticker-sheet.json +9297 -0
  79. package/src/docs-trace-globs.json +1 -0
  80. package/src/lib/chart-motion.ts +41 -0
  81. package/src/lib/get-icon-color.ts +1 -1
  82. package/src/stories/Accordion.stories.tsx +7 -0
  83. package/src/stories/ActionBar.stories.tsx +5 -0
  84. package/src/stories/Affix.stories.tsx +4 -0
  85. package/src/stories/AiBadge.stories.tsx +9 -7
  86. package/src/stories/Alert.stories.tsx +13 -0
  87. package/src/stories/AlertDialog.stories.tsx +4 -0
  88. package/src/stories/Anchor.stories.tsx +5 -0
  89. package/src/stories/AngleSlider.stories.tsx +6 -3
  90. package/src/stories/AspectRatio.stories.tsx +4 -0
  91. package/src/stories/Autocomplete.stories.tsx +6 -0
  92. package/src/stories/Avatar.stories.tsx +10 -0
  93. package/src/stories/Badge.stories.tsx +14 -6
  94. package/src/stories/Blockquote.stories.tsx +6 -0
  95. package/src/stories/BottomNavigation.stories.tsx +4 -0
  96. package/src/stories/Breadcrumb.stories.tsx +3 -0
  97. package/src/stories/Burger.stories.tsx +1 -0
  98. package/src/stories/Button.stories.tsx +24 -0
  99. package/src/stories/ButtonGroup.stories.tsx +9 -0
  100. package/src/stories/Calendar.stories.tsx +3 -0
  101. package/src/stories/Card.stories.tsx +4 -0
  102. package/src/stories/Carousel.stories.tsx +6 -0
  103. package/src/stories/Cascader.stories.tsx +4 -0
  104. package/src/stories/Chart.stories.tsx +46 -1
  105. package/src/stories/ChatBubble.stories.tsx +8 -2
  106. package/src/stories/ChatMarker.stories.tsx +1 -0
  107. package/src/stories/Checkbox.stories.tsx +40 -0
  108. package/src/stories/CheckboxCard.stories.tsx +8 -0
  109. package/src/stories/CheckboxGroup.stories.tsx +20 -0
  110. package/src/stories/Chip.stories.tsx +10 -19
  111. package/src/stories/CircularProgress.stories.tsx +13 -27
  112. package/src/stories/Clipboard.stories.tsx +6 -0
  113. package/src/stories/CloseButton.stories.tsx +6 -4
  114. package/src/stories/Code.stories.tsx +8 -1
  115. package/src/stories/Collapsible.stories.tsx +2 -0
  116. package/src/stories/ColorPicker.stories.tsx +6 -0
  117. package/src/stories/ColorSwatch.stories.tsx +1 -0
  118. package/src/stories/Combobox.stories.tsx +9 -0
  119. package/src/stories/Command.stories.tsx +2 -0
  120. package/src/stories/Container.stories.tsx +8 -0
  121. package/src/stories/ContextMenu.stories.tsx +9 -0
  122. package/src/stories/CopyButton.stories.tsx +12 -36
  123. package/src/stories/DataList.stories.tsx +8 -0
  124. package/src/stories/DataTable.stories.tsx +9 -0
  125. package/src/stories/DateField.stories.tsx +7 -0
  126. package/src/stories/DatePicker.stories.tsx +34 -0
  127. package/src/stories/DateRangePicker.stories.tsx +32 -0
  128. package/src/stories/Dialog.stories.tsx +8 -0
  129. package/src/stories/Drawer.stories.tsx +6 -0
  130. package/src/stories/DropdownMenu.stories.tsx +2 -0
  131. package/src/stories/Editable.stories.tsx +10 -0
  132. package/src/stories/EmptyState.stories.tsx +9 -0
  133. package/src/stories/Field.stories.tsx +7 -0
  134. package/src/stories/Fieldset.stories.tsx +8 -0
  135. package/src/stories/FileButton.stories.tsx +4 -0
  136. package/src/stories/FileUpload.stories.tsx +16 -17
  137. package/src/stories/FloatLabel.stories.tsx +3 -8
  138. package/src/stories/FloatingActionButton.stories.tsx +10 -0
  139. package/src/stories/FloatingIndicator.stories.tsx +4 -0
  140. package/src/stories/FloatingPanel.stories.tsx +6 -0
  141. package/src/stories/FocusTrap.stories.tsx +5 -0
  142. package/src/stories/FormatByte.stories.tsx +6 -0
  143. package/src/stories/FormatDate.stories.tsx +8 -0
  144. package/src/stories/FormatNumber.stories.tsx +9 -0
  145. package/src/stories/Heatmap.stories.tsx +11 -0
  146. package/src/stories/Highlight.stories.tsx +6 -0
  147. package/src/stories/HoverCard.stories.tsx +4 -0
  148. package/src/stories/Image.stories.tsx +9 -0
  149. package/src/stories/Indicator.stories.tsx +19 -0
  150. package/src/stories/Input.stories.tsx +7 -0
  151. package/src/stories/InputClearButton.stories.tsx +3 -0
  152. package/src/stories/InputGroup.stories.tsx +40 -0
  153. package/src/stories/Kbd.stories.tsx +7 -1
  154. package/src/stories/KeyboardShortcut.stories.tsx +2 -0
  155. package/src/stories/Label.stories.tsx +2 -0
  156. package/src/stories/Link.stories.tsx +9 -0
  157. package/src/stories/List.stories.tsx +8 -0
  158. package/src/stories/Listbox.stories.tsx +1 -0
  159. package/src/stories/LoadingDots.stories.tsx +5 -3
  160. package/src/stories/LoadingOverlay.stories.tsx +5 -1
  161. package/src/stories/Mark.stories.tsx +5 -0
  162. package/src/stories/Marquee.stories.tsx +4 -0
  163. package/src/stories/Masonry.stories.tsx +5 -0
  164. package/src/stories/Menubar.stories.tsx +3 -0
  165. package/src/stories/Meter.stories.tsx +11 -17
  166. package/src/stories/MonthPicker.stories.tsx +5 -1
  167. package/src/stories/MotionToggle.stories.tsx +1 -0
  168. package/src/stories/MultiSelect.stories.tsx +9 -0
  169. package/src/stories/NativeSelect.stories.tsx +1 -0
  170. package/src/stories/NavLink.stories.tsx +7 -0
  171. package/src/stories/NavigationMenu.stories.tsx +5 -0
  172. package/src/stories/NavigationRail.stories.tsx +10 -0
  173. package/src/stories/Notification.stories.tsx +13 -34
  174. package/src/stories/NumberField.stories.tsx +214 -0
  175. package/src/stories/NumberInput.stories.tsx +8 -1
  176. package/src/stories/Overlay.stories.tsx +5 -1
  177. package/src/stories/Pagination.stories.tsx +8 -0
  178. package/src/stories/PasswordInput.stories.tsx +2 -0
  179. package/src/stories/PinInput.stories.tsx +9 -2
  180. package/src/stories/Popover.stories.tsx +2 -0
  181. package/src/stories/Progress.stories.tsx +6 -1
  182. package/src/stories/Prose.stories.tsx +8 -0
  183. package/src/stories/QrCode.stories.tsx +2 -0
  184. package/src/stories/Questionnaire.stories.tsx +7 -0
  185. package/src/stories/RadioGroup.stories.tsx +40 -0
  186. package/src/stories/RatingGroup.stories.tsx +8 -4
  187. package/src/stories/Resizable.stories.tsx +4 -2
  188. package/src/stories/Result.stories.tsx +3 -0
  189. package/src/stories/Reveal.stories.tsx +2 -0
  190. package/src/stories/RollingNumber.stories.tsx +5 -0
  191. package/src/stories/ScrollArea.stories.tsx +3 -1
  192. package/src/stories/SearchInput.stories.tsx +8 -6
  193. package/src/stories/SegmentedControl.stories.tsx +11 -0
  194. package/src/stories/Select.stories.tsx +7 -0
  195. package/src/stories/Separator.stories.tsx +6 -0
  196. package/src/stories/Sheet.stories.tsx +5 -0
  197. package/src/stories/Sidebar.stories.tsx +40 -1
  198. package/src/stories/SimpleGrid.stories.tsx +5 -0
  199. package/src/stories/Skeleton.stories.tsx +8 -0
  200. package/src/stories/SkeletonTable.stories.tsx +6 -5
  201. package/src/stories/SkipLink.stories.tsx +3 -0
  202. package/src/stories/Slider.stories.tsx +2 -1
  203. package/src/stories/Sonner.stories.tsx +7 -0
  204. package/src/stories/Sparkline.stories.tsx +14 -1
  205. package/src/stories/Spinner.stories.tsx +20 -10
  206. package/src/stories/Spoiler.stories.tsx +5 -0
  207. package/src/stories/Squircle.stories.tsx +7 -0
  208. package/src/stories/Stack.stories.tsx +7 -0
  209. package/src/stories/StatusBadge.stories.tsx +12 -6
  210. package/src/stories/Stepper.stories.tsx +5 -0
  211. package/src/stories/Switch.stories.tsx +4 -0
  212. package/src/stories/Table.stories.tsx +10 -1
  213. package/src/stories/Tabs.stories.tsx +8 -0
  214. package/src/stories/Tag.stories.tsx +13 -5
  215. package/src/stories/TagsInput.stories.tsx +13 -0
  216. package/src/stories/Text.stories.tsx +12 -0
  217. package/src/stories/Textarea.stories.tsx +9 -0
  218. package/src/stories/ThemeIcon.stories.tsx +6 -3
  219. package/src/stories/TimePicker.stories.tsx +2 -0
  220. package/src/stories/Timeline.stories.tsx +12 -0
  221. package/src/stories/Timer.stories.tsx +4 -0
  222. package/src/stories/Toggle.stories.tsx +7 -5
  223. package/src/stories/ToggleGroup.stories.tsx +5 -0
  224. package/src/stories/ToggleTip.stories.tsx +4 -0
  225. package/src/stories/Toolbar.stories.tsx +6 -0
  226. package/src/stories/Tooltip.stories.tsx +3 -0
  227. package/src/stories/Tour.stories.tsx +3 -0
  228. package/src/stories/TransferList.stories.tsx +3 -0
  229. package/src/stories/TreeSelect.stories.tsx +4 -0
  230. package/src/stories/TreeView.stories.tsx +5 -0
  231. package/src/stories/TypingIndicator.stories.tsx +4 -0
  232. package/src/stories/VisuallyHidden.stories.tsx +3 -0
  233. package/src/stories/Watermark.stories.tsx +6 -0
  234. package/src/stories/WeekPicker.stories.tsx +4 -1
  235. package/src/stories/WordRotate.stories.tsx +5 -0
  236. package/src/stories/YearPicker.stories.tsx +5 -11
  237. package/src/stories/story-groups.json +2 -1
  238. package/src/styles.css +50 -2
  239. package/src/tokens.json +4 -4
  240. package/LICENSE +0 -21
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-target-size — flag a control whose fixed size is under the touch-target floor.
4
+ *
5
+ * WCAG 2.5.5 (AAA) asks for 44 by 44 CSS px on anything a person presses. This reads the opening
6
+ * tag of a `button`, `Button`, `IconButton`, an element with `role="button"`, or any tag with
7
+ * `onClick`, and flags a fixed `h-`, `w-` or `size-` class under the floor. `min-h-11 min-w-11`
8
+ * on the same tag clears it. a11y-lint points here for touch-target sizes.
9
+ *
10
+ * It sees only sizes written as classes: `h-8`, `size-6`, `w-[32px]`. A size that a component
11
+ * prop sets (`size="sm"`) is not read, and neither is a size built at run time.
12
+ *
13
+ * The floor is 44px by default. Change it with `--min-px=48`, or with `"minTargetPx"` in
14
+ * `.bads-lint.json` at the repo root. The flag wins over the file.
15
+ *
16
+ * Mark an intended exception with `tap-target-ok: <why>` on the line or the line above. A marker
17
+ * with no reason does not count.
18
+ *
19
+ * Run:
20
+ * bads-lint-target-size # report, exit 1 on fail
21
+ * bads-lint-target-size --warn # report, exit 0 (advisory)
22
+ * bads-lint-target-size --min-px=48 # a different floor
23
+ * bads-lint-target-size path/to.tsx # one file, or a directory
24
+ */
25
+
26
+ 'use strict';
27
+
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+ const { resolveScanFiles, guardEmptyScan } = require('./lib/scan-roots.cjs');
31
+
32
+ const ROOT = process.cwd();
33
+ const advisory = process.argv.includes('--warn');
34
+ const DEFAULT_MIN_PX = 44;
35
+ const PX_PER_UNIT = 4;
36
+ const LOOK_BACK = 8;
37
+
38
+ function readMinPx() {
39
+ const flag = process.argv.find((a) => a.startsWith('--min-px='));
40
+ if (flag) {
41
+ const n = Number(flag.slice('--min-px='.length));
42
+ if (Number.isFinite(n) && n > 0) return n;
43
+ console.error(`lint-target-size: --min-px needs a positive number, got "${flag}".`);
44
+ process.exit(2);
45
+ }
46
+ try {
47
+ const parsed = JSON.parse(fs.readFileSync(path.join(ROOT, '.bads-lint.json'), 'utf8'));
48
+ if (Number.isFinite(parsed.minTargetPx) && parsed.minTargetPx > 0) return parsed.minTargetPx;
49
+ } catch { /* no config file: the default stands */ }
50
+ return DEFAULT_MIN_PX;
51
+ }
52
+
53
+ const MIN_PX = readMinPx();
54
+ const MIN_UNITS = MIN_PX / PX_PER_UNIT;
55
+
56
+ // `h-8`, `size-6`, `w-[32px]`, `h-[2rem]`. A fraction (`w-1/2`), `h-full` or `h-screen` has no
57
+ // fixed size, so the pattern does not match it.
58
+ const FIXED_SIZE = /(?<![\w-])(?:h|w|size)-(?:(\d+(?:\.\d+)?)|\[(\d+(?:\.\d+)?)(px|rem)\])(?![\w./[-])/g;
59
+ const MIN_SIZE = /(?<![\w-])min-(?:h|w)-(?:(\d+(?:\.\d+)?)|\[(\d+(?:\.\d+)?)(px|rem)\])(?![\w./[-])/g;
60
+ const TAG_START = /<(button|Button|IconButton|[A-Za-z][\w.]*)\b/;
61
+ const MARKER = /tap-target-ok\s*:\s*[^\s*/}]/;
62
+
63
+ const toPx = (units, value, unit) => {
64
+ if (units !== undefined) return Number(units) * PX_PER_UNIT;
65
+ return unit === 'rem' ? Number(value) * 16 : Number(value);
66
+ };
67
+
68
+ function openingTag(lines, index) {
69
+ for (let i = index; i >= Math.max(0, index - LOOK_BACK); i--) {
70
+ const start = lines[i].match(TAG_START);
71
+ if (!start) continue;
72
+ return { name: start[1], text: lines.slice(i, index + 1).join('\n') };
73
+ }
74
+ return null;
75
+ }
76
+
77
+ const isControl = ({ name, text }) =>
78
+ /^(button|Button|IconButton)$/.test(name) || /\bonClick=/.test(text) || /\brole=["']button["']/.test(text);
79
+
80
+ const clearedByMinimum = (text) =>
81
+ [...text.matchAll(MIN_SIZE)].some((m) => toPx(m[1], m[2], m[3]) >= MIN_PX);
82
+
83
+ const scan = resolveScanFiles({ root: ROOT, argv: process.argv.slice(2), allowDirArgs: true, excludeStories: true });
84
+ const issues = [];
85
+
86
+ for (const file of scan.files) {
87
+ let src;
88
+ try {
89
+ src = fs.readFileSync(file, 'utf8');
90
+ } catch {
91
+ continue;
92
+ }
93
+ if (src.startsWith('/* GENERATED')) continue;
94
+ if (file.includes('/e2e/') || /\.(spec|test)\.tsx?$/.test(file)) continue;
95
+ const lines = src.split('\n');
96
+ for (let i = 0; i < lines.length; i++) {
97
+ const line = lines[i];
98
+ if (/^\s*(\/\/|\/\*|\*)/.test(line)) continue;
99
+ const small = [...line.matchAll(FIXED_SIZE)].filter((m) => toPx(m[1], m[2], m[3]) < MIN_PX);
100
+ if (small.length === 0) continue;
101
+ if (MARKER.test(line) || (i > 0 && MARKER.test(lines[i - 1]))) continue;
102
+ const tag = openingTag(lines, i);
103
+ if (!tag || !isControl(tag) || clearedByMinimum(tag.text)) continue;
104
+ const m = small[0];
105
+ issues.push({
106
+ file: path.relative(ROOT, file),
107
+ line: i + 1,
108
+ message: `${m[0]} is ${toPx(m[1], m[2], m[3])}px on a control, under the ${MIN_PX}px touch-target floor. Add min-h-${MIN_UNITS} min-w-${MIN_UNITS}, or grow the hit area with padding. If a person chose a smaller size, add "tap-target-ok: <why>" on this line or the line above.`,
109
+ });
110
+ }
111
+ }
112
+
113
+ if (issues.length === 0) {
114
+ if (guardEmptyScan(scan, 'lint-target-size')) { /* exited */ }
115
+ console.log(
116
+ scan.files.length
117
+ ? `✓ lint-target-size: no control is fixed under ${MIN_PX}px.`
118
+ : '✓ lint-target-size: no control is fixed under the floor (0 files matched under existing scan roots).'
119
+ );
120
+ process.exit(0);
121
+ }
122
+
123
+ const grouped = issues.reduce((acc, it) => {
124
+ (acc[it.file] = acc[it.file] || []).push(it);
125
+ return acc;
126
+ }, {});
127
+ for (const file of Object.keys(grouped).sort()) {
128
+ console.log(`\n${file}`);
129
+ for (const it of grouped[file]) console.log(` L${it.line} [SC 2.5.5 target-size] ${it.message}`);
130
+ }
131
+ console.log(`\n${issues.length} issue${issues.length === 1 ? '' : 's'} across ${Object.keys(grouped).length} file${Object.keys(grouped).length === 1 ? '' : 's'}.`);
132
+ process.exit(advisory ? 0 : 1);
@@ -0,0 +1,307 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-token-primitives — every semantic color token should alias a primitive
4
+ * (a numbered ramp step like `--color-blue-500`, or a named palette literal
5
+ * like `--color-<brand-name>`), not carry its own hardcoded hex/rgb/oklch
6
+ * value. Checked separately for light and dark: a token can alias a primitive
7
+ * in one mode and still carry a raw literal in the other, so both need their
8
+ * own pass. A hardcoded semantic token means changing a color means hunting
9
+ * down every place that value got typed by hand, instead of moving one
10
+ * primitive and letting every alias follow it.
11
+ *
12
+ * SCOPE — read this before pointing it at a repo. This only has something to
13
+ * say about a Tailwind v4 CSS-first theme that has an actual ramp/primitive
14
+ * layer underneath its semantic tokens (numbered steps, or a named palette).
15
+ * BADS's own default scaffold (packages/core/src/styles.css) does NOT use
16
+ * that shape — it declares flat oklch/hex literals directly on
17
+ * semantic-looking names (`--primary`, `--destructive`, ...) with nothing
18
+ * underneath them, so every token there already IS a literal by design, not
19
+ * a drift defect. Run this against that file and it correctly reports "not
20
+ * applicable" rather than a wall of false positives. It is an opt-in check
21
+ * for forks that build (or are migrating toward) a real primitive ramp —
22
+ * not a rule the default scaffold itself follows.
23
+ *
24
+ * No existing BADS lint (lint-token-intent, lint-css-vars, lint-component-
25
+ * source, wcag-audit, ...) walks a color token's own var() alias chain to
26
+ * its termination. See BADS_UPSTREAM_CANDIDATES.md in the fork this shipped
27
+ * from for the incident that found the gap.
28
+ *
29
+ * Goes through the shared counted-lint tail (strict by default; --warn makes
30
+ * it advisory; --init records a baseline; --ratchet checks against it) — see
31
+ * lib/counted-lint.mjs. That machinery already covers "adopting this on an
32
+ * existing codebase with a backlog": run --init once, then --ratchet in CI.
33
+ *
34
+ * Usage:
35
+ * npx bads-lint-token-primitives
36
+ * --theme <path> theme file to check (default: first of
37
+ * src/styles/theme.css, styles/theme.css,
38
+ * app/globals.css, src/app/globals.css,
39
+ * styles/globals.css that exists)
40
+ * --dark-selector <sel> e.g. ".dark-mode", ".dark", '[data-theme="dark"]'
41
+ * (default: try .dark-mode, then .dark, then
42
+ * [data-theme="dark"] — first one actually
43
+ * present in the file wins; none found means no
44
+ * dark-specific declarations to check, which is
45
+ * a legitimate shape, not an error)
46
+ * --families a,b,c extra primitive RAMP family names on top of the
47
+ * built-in stock Tailwind v4 families (red, blue,
48
+ * rose, slate, ...) — e.g. a fork's own status-
49
+ * color ramp
50
+ * --names a,b,c extra single, non-numbered primitive names on
51
+ * top of the built-in white/black/transparent —
52
+ * e.g. a fork's own named brand palette
53
+ * --warn | --init | --ratchet see lib/counted-lint.mjs
54
+ *
55
+ * Escape hatch: `/* allow-literal-color: <reason> *\/` (a real CSS comment —
56
+ * `//` is not valid CSS and a parser would fold it into the declaration's own
57
+ * value) on the line directly above the declaration, in the SAME mode block
58
+ * as the violation it excuses. A light-mode escape hatch does not also excuse
59
+ * a hardcoded dark override of the same token.
60
+ */
61
+ import fs from "node:fs";
62
+ import path from "node:path";
63
+ import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
64
+
65
+ const THEME_CANDIDATES = ["src/styles/theme.css", "styles/theme.css", "app/globals.css", "src/app/globals.css", "styles/globals.css"];
66
+ const DARK_SELECTOR_CANDIDATES = [".dark-mode", ".dark", '[data-theme="dark"]'];
67
+
68
+ const STOCK_TAILWIND_FAMILIES = [
69
+ "slate",
70
+ "gray",
71
+ "zinc",
72
+ "neutral",
73
+ "stone",
74
+ "red",
75
+ "orange",
76
+ "amber",
77
+ "yellow",
78
+ "lime",
79
+ "green",
80
+ "emerald",
81
+ "teal",
82
+ "cyan",
83
+ "sky",
84
+ "blue",
85
+ "indigo",
86
+ "violet",
87
+ "purple",
88
+ "fuchsia",
89
+ "pink",
90
+ "rose",
91
+ // Common extensions, not stock Tailwind, but common enough across forks
92
+ // to ship as defaults rather than making every brand-ramp fork pass --families.
93
+ "brand",
94
+ "alpha",
95
+ ];
96
+ const DEFAULT_NAMED_SINGLETONS = ["white", "black", "transparent"];
97
+
98
+ /** Finds the first `{ ... }` block whose selector matches `selector` as a real
99
+ * CSS rule — the selector text immediately followed (after whitespace/other
100
+ * selector text, never a brace) by `{`. Anchoring on the `{` is what keeps
101
+ * this from matching selector text sitting inside an unrelated at-rule, e.g.
102
+ * `@custom-variant dark (&:is(.dark *));` for a bare ".dark" search — that
103
+ * line has no `{` right after ".dark", so it's correctly skipped. A class
104
+ * selector also requires a non-word/non-hyphen boundary right after its own
105
+ * name, so searching for ".dark" does not match inside ".dark-mode" or
106
+ * ".darker-overlay" when those appear first in the file.
107
+ */
108
+ export function findBlock(source, selector) {
109
+ const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
110
+ const boundary = /^\.[\w-]+$/.test(selector) ? "(?![\\w-])" : "";
111
+ const re = new RegExp(`${escaped}${boundary}[^{};]*\\{`, "m");
112
+ const m = re.exec(source);
113
+ if (!m) return { block: "", braceStart: -1 };
114
+ const braceStart = m.index + m[0].length;
115
+ let depth = 1;
116
+ let i = braceStart;
117
+ while (depth > 0 && i < source.length) {
118
+ if (source[i] === "{") depth++;
119
+ else if (source[i] === "}") depth--;
120
+ i++;
121
+ }
122
+ return { block: source.slice(braceStart, i - 1), braceStart };
123
+ }
124
+
125
+ /** Declarations plus the source line number each one's `--name:` starts on,
126
+ * so a violation points at a real line and the escape-hatch lookup checks
127
+ * the line directly above THAT declaration. */
128
+ export function parseDeclarations(source, block, blockStart) {
129
+ const map = new Map();
130
+ const re = /--([a-zA-Z0-9_-]+)\s*:\s*([^;]+);/g;
131
+ let m;
132
+ while ((m = re.exec(block))) {
133
+ const lineNo = source.slice(0, blockStart + m.index).split("\n").length;
134
+ map.set(m[1], { value: m[2].trim(), line: lineNo });
135
+ }
136
+ return map;
137
+ }
138
+
139
+ export function aliasOf(value) {
140
+ const m = /^var\(\s*--([a-zA-Z0-9_-]+)\s*\)$/.exec(value);
141
+ return m?.[1];
142
+ }
143
+
144
+ /** Builds the primitive-name predicate for one run: a numbered ramp step
145
+ * (`color-<family>-<step>`) in one of the stock-or-extra families, or a
146
+ * single named primitive (`color-<name>`) in the stock-or-extra names list. */
147
+ export function buildIsPrimitiveName(extraFamilies = [], extraNames = []) {
148
+ const families = [...STOCK_TAILWIND_FAMILIES, ...extraFamilies];
149
+ const names = new Set([...DEFAULT_NAMED_SINGLETONS, ...extraNames].map((n) => `color-${n}`));
150
+ const rampRe = new RegExp(`^color-(${families.join("|")})-[a-zA-Z0-9]+$`);
151
+ return (name) => rampRe.test(name) || names.has(name);
152
+ }
153
+
154
+ /** Walks the var() chain from `name` to termination for one mode, returning
155
+ * the classification and the chain of names visited. `lookup(name, mode)`
156
+ * is injected so the dark lookup's "fall back to light when unoverridden"
157
+ * rule (the same rule the real CSS cascade applies) lives with the caller,
158
+ * which owns both tables. Escape-hatch eligibility is decided against the
159
+ * STARTING name's own declaration in this mode, not wherever the chain
160
+ * happens to terminate. */
161
+ export function classify(startName, mode, { light, dark, lookup, isPrimitiveName }) {
162
+ const startDecl = mode === "dark" ? (dark.get(startName) ?? light.get(startName)) : light.get(startName);
163
+ let name = startName;
164
+ const seen = new Set();
165
+ while (true) {
166
+ if (seen.has(name)) return { kind: "cycle", chain: [...seen, name], startDecl };
167
+ seen.add(name);
168
+ const decl = lookup(name, mode);
169
+ if (decl === undefined) return { kind: "dead-end", chain: [...seen], startDecl };
170
+ const alias = aliasOf(decl.value);
171
+ if (!alias) {
172
+ return {
173
+ kind: isPrimitiveName(name) ? "primitive-literal" : "hardcoded-literal",
174
+ chain: [...seen],
175
+ value: decl.value,
176
+ startDecl,
177
+ };
178
+ }
179
+ if (isPrimitiveName(alias)) return { kind: "resolves-to-primitive", chain: [...seen, alias], startDecl };
180
+ name = alias;
181
+ }
182
+ }
183
+
184
+ function run() {
185
+ const ROOT = process.cwd();
186
+ const argv = process.argv.slice(2);
187
+
188
+ const themeArg = flagValue(argv, "theme", null);
189
+ const themePath = themeArg
190
+ ? path.join(ROOT, themeArg)
191
+ : THEME_CANDIDATES.map((p) => path.join(ROOT, p)).find((p) => fs.existsSync(p));
192
+ if (!themePath || !fs.existsSync(themePath)) {
193
+ console.error(
194
+ `bads-lint-token-primitives: no theme file found (looked for ${THEME_CANDIDATES.join(", ")}). Point at one with --theme <path>.`,
195
+ );
196
+ process.exit(1);
197
+ }
198
+ const relThemePath = path.relative(ROOT, themePath);
199
+
200
+ const RAW = fs.readFileSync(themePath, "utf8");
201
+ const RAW_LINES = RAW.split("\n");
202
+ const tailwindThemePath = path.join(ROOT, "node_modules/tailwindcss/theme.css");
203
+ const TW_RAW = fs.existsSync(tailwindThemePath) ? fs.readFileSync(tailwindThemePath, "utf8") : "";
204
+
205
+ const { block: rootBlock, braceStart: rootBraceStart } = findBlock(RAW, ":root");
206
+ const ROOT_DECLS = rootBraceStart === -1 ? new Map() : parseDeclarations(RAW, rootBlock, rootBraceStart);
207
+ const { block: themeBlock, braceStart: themeBraceStart } = findBlock(RAW, "@theme");
208
+ const THEME_DECLS = themeBraceStart === -1 ? new Map() : parseDeclarations(RAW, themeBlock, themeBraceStart);
209
+ // @theme's own declarations win on a name collision — in a split layout
210
+ // that's the Tailwind-exposed alias, which is the one that's actually
211
+ // semantic-shaped and worth checking.
212
+ const LIGHT = new Map([...ROOT_DECLS, ...THEME_DECLS]);
213
+
214
+ const darkSelectorArg = flagValue(argv, "dark-selector", null);
215
+ const darkCandidates = darkSelectorArg ? [darkSelectorArg] : DARK_SELECTOR_CANDIDATES;
216
+ let darkSelectorUsed = null;
217
+ let DARK = new Map();
218
+ for (const sel of darkCandidates) {
219
+ const { block, braceStart } = findBlock(RAW, sel);
220
+ if (braceStart !== -1) {
221
+ DARK = parseDeclarations(RAW, block, braceStart);
222
+ darkSelectorUsed = sel;
223
+ break;
224
+ }
225
+ }
226
+
227
+ const { block: twBlock, braceStart: twBraceStart } = findBlock(TW_RAW, "@theme");
228
+ const TAILWIND_RAW_LINES = TW_RAW.split("\n");
229
+ const TW_LIGHT = twBraceStart === -1 ? new Map() : parseDeclarations(TW_RAW, twBlock, twBraceStart);
230
+
231
+ function lookup(name, mode) {
232
+ if (mode === "dark") return DARK.get(name) ?? LIGHT.get(name) ?? TW_LIGHT.get(name);
233
+ return LIGHT.get(name) ?? TW_LIGHT.get(name);
234
+ }
235
+
236
+ const extraFamilies = (flagValue(argv, "families", "") || "").split(",").map((s) => s.trim()).filter(Boolean);
237
+ const extraNames = (flagValue(argv, "names", "") || "").split(",").map((s) => s.trim()).filter(Boolean);
238
+ const isPrimitiveName = buildIsPrimitiveName(extraFamilies, extraNames);
239
+
240
+ function hasEscapeHatch(decl) {
241
+ if (!decl || decl.line == null) return false;
242
+ const lines = decl.source === "tailwind" ? TAILWIND_RAW_LINES : RAW_LINES;
243
+ return (lines[decl.line - 2] || "").includes("allow-literal-color:");
244
+ }
245
+
246
+ const colorNames = [...LIGHT.keys()].filter((n) => n.startsWith("color-"));
247
+ const primitiveNamesDeclared = colorNames.filter((n) => isPrimitiveName(n));
248
+
249
+ if (primitiveNamesDeclared.length === 0) {
250
+ console.log(
251
+ `bads-lint-token-primitives: not applicable — ${relThemePath} declares no --color-* primitive (no numbered ramp step, no named primitive matching ${[...STOCK_TAILWIND_FAMILIES, ...extraFamilies].length} known families / ${[...DEFAULT_NAMED_SINGLETONS, ...extraNames].length} known names). This check has nothing to say about a theme with no primitive layer underneath its tokens — see this file's SCOPE note. Pass --families/--names to extend the known lists if this fork does have one under different names.`,
252
+ );
253
+ process.exit(0);
254
+ }
255
+
256
+ const semanticNames = colorNames.filter((n) => !isPrimitiveName(n));
257
+
258
+ const violations = [];
259
+ let skipped = 0;
260
+ for (const name of semanticNames) {
261
+ for (const mode of ["light", "dark"]) {
262
+ const result = classify(name, mode, { light: LIGHT, dark: DARK, lookup, isPrimitiveName });
263
+ if (result.kind === "resolves-to-primitive" || result.kind === "primitive-literal") continue;
264
+ if (result.kind === "hardcoded-literal" && hasEscapeHatch(result.startDecl)) {
265
+ skipped++;
266
+ continue;
267
+ }
268
+ violations.push({ name, mode, ...result });
269
+ }
270
+ }
271
+
272
+ // A primitive is a single fixed value, never a light/dark pair — giving it
273
+ // two secretly makes it behave like a semantic token, which is exactly the
274
+ // bug this file exists to catch one layer up. Only checked when a dark
275
+ // block was actually found.
276
+ if (darkSelectorUsed) {
277
+ for (const name of DARK.keys()) {
278
+ if (!name.startsWith("color-") || !isPrimitiveName(name)) continue;
279
+ const decl = DARK.get(name);
280
+ if (hasEscapeHatch(decl)) {
281
+ skipped++;
282
+ continue;
283
+ }
284
+ violations.push({ name, mode: "dark", kind: "primitive-redeclared-in-dark-mode", value: decl.value, chain: [name], startDecl: decl });
285
+ }
286
+ }
287
+
288
+ const findings = violations.map((v) => ({
289
+ file: relThemePath,
290
+ line: v.startDecl?.line,
291
+ text: `--${v.name} [${v.mode}, ${v.kind}] ${v.value ?? ""} (chain: ${v.chain.join(" -> ")})`.trimEnd(),
292
+ }));
293
+
294
+ process.exit(
295
+ finishCountedLint({
296
+ ruleId: "token-primitives",
297
+ bin: "bads-lint-token-primitives",
298
+ findings,
299
+ scanned: [relThemePath],
300
+ fix: "Point the token at the real primitive it should alias (`var(--color-<family>-<step>)` or `var(--color-<name>)`) instead of a hardcoded hex/rgb/oklch value, or add `/* allow-literal-color: <reason> */` on the line above if the literal is deliberate.",
301
+ argv,
302
+ root: ROOT,
303
+ }),
304
+ );
305
+ }
306
+
307
+ if (isMain(import.meta.url)) run();
@@ -63,7 +63,7 @@ const ESCAPE_HATCH = /allow-text-xs-cta/;
63
63
 
64
64
  // ── BADS-2b: a full-width <Button> below the 44px touch-target floor ─────────
65
65
  //
66
- // CLAUDE.md calls 44px non-negotiable (SC 2.5.5) and then documents Button's
66
+ // AGENTS.md calls 44px non-negotiable (SC 2.5.5) and then documents Button's
67
67
  // `default` (h-9, 36px) and `lg` (h-10, 40px) as exceptions reserved for dense
68
68
  // NON-CTA chrome: toolbars, table row actions, dialog footers. Sir's call on
69
69
  // 2026-09-11 was to keep those sizes and enforce the contract instead, because
@@ -72,7 +72,7 @@ const ESCAPE_HATCH = /allow-text-xs-cta/;
72
72
  //
73
73
  // So the question is how to tell a CTA from chrome, statically, without crying
74
74
  // wolf — a false BLOCKER sends someone to fix a correct component and teaches
75
- // people to bypass the gate (CLAUDE.md, "ask what a passing check measured").
75
+ // people to bypass the gate (docs/agent-rules/ask-what-a-passing-check-measured.md).
76
76
  //
77
77
  // `w-full` is the signal with no honest counter-example. Dense chrome is never
78
78
  // full-width: a toolbar button sits in a row of them, a table row action is
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * ux-tells — open a page in a real browser at three widths and fail it on the
3
+ * ux-tells — open a page in a real browser at four widths (320 is WCAG reflow) and fail it on the
4
4
  * signals that make a page read as generated: gradient text, indigo gradients,
5
5
  * stacks of glass panels, glows, the stock three-icon-card row, a pill above the
6
6
  * headline, decorative emoji, pulsing dots, placeholder copy and images, and
7
- * sideways scrolling. It saves a screenshot of each width so someone can look.
7
+ * sideways scrolling, plus four layout tells measured from the rendered boxes (a crowded heading, text
8
+ * cramped in its box, text painted under another element, a wrapped or clipped button label). It saves a screenshot of each width so someone can look.
8
9
  *
9
10
  * It reads computed styles, so it catches what lint-slop's source scan can't:
10
11
  * classes built at runtime and the effect of the cascade. It runs on any URL, so
@@ -12,7 +13,7 @@
12
13
  * Reduced motion is emulated, so a reading doesn't depend on an animation frame.
13
14
  *
14
15
  * Usage:
15
- * bads-ux-tells <url> [--widths 375,768,1280] [--out .ux-tells] [--json] [--warn]
16
+ * bads-ux-tells <url> [--widths 320,375,768,1280] [--out .ux-tells] [--json] [--warn]
16
17
  *
17
18
  * Exit 1 when any banned tell is found (0 with --warn). Warned tells are listed
18
19
  * and need a reason, not a fix. Rules and rationale: lib/tells.mjs.
@@ -22,7 +23,7 @@
22
23
  import fs from "node:fs";
23
24
  import path from "node:path";
24
25
  import { fileURLToPath } from "node:url";
25
- import { WIDTHS, TELLS, probeSource, classify, merge } from "./lib/tells.mjs";
26
+ import { WIDTHS, TELLS, probeSource, probeLayoutSource, classify, merge } from "./lib/tells.mjs";
26
27
 
27
28
  function chromiumExecutable() {
28
29
  if (process.env.PW_CHROMIUM && fs.existsSync(process.env.PW_CHROMIUM)) return process.env.PW_CHROMIUM;
@@ -44,7 +45,8 @@ export async function check(url, { widths = WIDTHS, out = ".ux-tells", chromium
44
45
  const res = await page.goto(url, { waitUntil: "networkidle", timeout: 60000 }).catch(() => null);
45
46
  if (!res || !res.ok()) { await ctx.close(); throw new Error(`could not load ${url} at ${width}px`); }
46
47
  await page.evaluate(() => document.fonts && document.fonts.ready);
47
- perWidth.push(classify(await page.evaluate(probeSource()), width));
48
+ const facts = { ...(await page.evaluate(probeSource())), ...(await page.evaluate(probeLayoutSource())) };
49
+ perWidth.push(classify(facts, width));
48
50
  for (const [kind, full] of [["fold", false], ["page", true]]) {
49
51
  const file = path.join(out, `${width}-${kind}.jpg`);
50
52
  await page.screenshot({ path: file, fullPage: full, type: "jpeg", quality: 80 });
@@ -58,7 +60,7 @@ export async function check(url, { widths = WIDTHS, out = ".ux-tells", chromium
58
60
 
59
61
  async function main(argv) {
60
62
  const url = argv.find((a) => /^https?:\/\/|^file:\/\//.test(a));
61
- if (!url) { console.error("usage: bads-ux-tells <url> [--widths 375,768,1280] [--out .ux-tells] [--json] [--warn]"); return 2; }
63
+ if (!url) { console.error("usage: bads-ux-tells <url> [--widths 320,375,768,1280] [--out .ux-tells] [--json] [--warn]"); return 2; }
62
64
  const arg = (n, d) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : d; };
63
65
  const widths = arg("--widths", WIDTHS.join(",")).split(",").map(Number).filter((n) => n >= 280 && n <= 3000);
64
66
  let result;
@@ -124,7 +124,7 @@ const LARGE_FLOOR = aa ? 3.0 : 4.5;
124
124
  // library is generally built to AA, not AAA, and a red pipeline over a
125
125
  // palette BADS didn't choose is a bad way to open that conversation. See
126
126
  // docs/superpowers/specs/2026-09-10-client-owned-components-design.md →
127
- // "Accessibility floor: flag, do not enforce" and CLAUDE.md → Accessibility
127
+ // "Accessibility floor: flag, do not enforce" and AGENTS.md → Accessibility
128
128
  // Floor. readSourceOfTruth() never throws and defaults to "bads" with no
129
129
  // identity file, so upstream BADS and "bads"-owned forks are unaffected.
130
130
  //
@@ -295,7 +295,7 @@ function resolveValue(value, modeTokens, depth) {
295
295
  // these fail AAA, the audit emits a warning instead of an error: the picker
296
296
  // surfaces the same warning in-product and clients can ship brand colors that
297
297
  // don't meet AAA as long as they accept the documented trade-off (see
298
- // CLAUDE.md → Accessibility Floor).
298
+ // AGENTS.md → Accessibility Floor).
299
299
  const PAIRS = [
300
300
  ['foreground', 'background', 'body text on page'],
301
301
  ['card-foreground', 'card', 'text on card'],
@@ -571,10 +571,31 @@ if (DOWNGRADE_AAA) {
571
571
  }
572
572
  }
573
573
 
574
+ // Every theme token resolved to a hex per mode, so a consumer of --json (the
575
+ // sticker sheet's token table) reads the audit's own resolution instead of
576
+ // re-implementing oklch math. Translucent tokens are flattened over white and
577
+ // carry `alpha`; unresolvable ones (oklch(from ...)) are omitted.
578
+ function resolvedTokens() {
579
+ const out = {};
580
+ for (const mode of ['light', 'dark']) {
581
+ out[mode] = {};
582
+ for (const [key, tok] of Object.entries(tokens.theme[mode])) {
583
+ if (!tok || typeof tok !== 'object' || tok.$type !== 'color') continue;
584
+ const raw = resolveValue(tok.$value, tokens.theme[mode]);
585
+ if (!raw) continue;
586
+ const entry = { hex: toHex(flattenOver(raw, [1, 1, 1])) };
587
+ if (raw.length === 4 && raw[3] < 1) entry.alpha = Number(raw[3].toFixed(3));
588
+ out[mode][key] = entry;
589
+ }
590
+ }
591
+ return out;
592
+ }
593
+
574
594
  if (json) {
575
595
  console.log(JSON.stringify({
576
596
  floor: { normal: NORMAL_FLOOR, large: LARGE_FLOOR },
577
597
  clientOwned: CLIENT_OWNED,
598
+ tokens: resolvedTokens(),
578
599
  results: all,
579
600
  runtimeMutated: brandResults,
580
601
  staleExceptions,
@@ -652,14 +673,14 @@ if (json) {
652
673
  if (warned.length || brandWarnings) {
653
674
  console.log(
654
675
  `\nWarnings are brand-derived pairs below AAA. The brand picker surfaces` +
655
- ` the same warning in-product (see CLAUDE.md → Accessibility Floor). Not blocking.`,
676
+ ` the same warning in-product (see AGENTS.md → Accessibility Floor). Not blocking.`,
656
677
  );
657
678
  }
658
679
  if (clientDowngraded) {
659
680
  console.log(
660
681
  `\n${clientDowngraded} pair${clientDowngraded === 1 ? '' : 's'} below the AAA floor ${clientDowngraded === 1 ? 'is' : 'are'} ` +
661
682
  `${CLIENT_OWNED_NOTE} (sourceOfTruth.components === "client"). Your palette is being held to AA, ` +
662
- `not AAA — see CLAUDE.md → Accessibility Floor. Not blocking.`,
683
+ `not AAA — see AGENTS.md → Accessibility Floor. Not blocking.`,
663
684
  );
664
685
  }
665
686
  if (failed.length) process.exit(1);
@@ -23,6 +23,7 @@ const ALLOWED_ROOT_MD = new Set([
23
23
  "CLAUDE.md",
24
24
  "CAPABILITIES.md",
25
25
  "AGENTS.md",
26
+ "GEMINI.md",
26
27
  "ATOMIC_DESIGN.md",
27
28
  "BADS_SYNC.md",
28
29
  "CHANGELOG.md",
@@ -49,6 +50,7 @@ function isAllowed(rel: string) {
49
50
  if (norm === "packages/core/src/tokens.json") return true;
50
51
  if (/^layer-[\w-]+\//.test(norm) && /\.(md|json)$/.test(norm)) return true;
51
52
  if (/^docs\/[\w.-]+\.md$/.test(norm)) return true;
53
+ if (/^docs\/agent-rules\/[\w.-]+\.(md|json)$/.test(norm)) return true;
52
54
  if (/^disciplines\/[\w./-]+\.(md|json)$/.test(norm)) return true;
53
55
  if (/^prompts\/[\w.-]+\.md$/.test(norm)) return true;
54
56
  if (/^\.claude\/skills\/[\w.-]+\/SKILL\.md$/.test(norm)) return true;
@@ -59,7 +59,19 @@ export async function POST(req: NextRequest) {
59
59
  return redirect;
60
60
  }
61
61
 
62
+ // Only ever send the visitor to a path on this site. Checking the first characters is not enough: browsers
63
+ // read "/\\evil.com" and "/<tab>/evil.com" as "//evil.com". So resolve the value the way a browser would and
64
+ // accept it only if it stays on the same origin.
62
65
  function sanitizeNext(next: string): string {
63
- if (next.startsWith("/") && !next.startsWith("//")) return next;
64
- return "/";
66
+ if (!next.startsWith("/") || /[\\\u0000-\u001f]/.test(next)) return "/";
67
+ const base = "https://site.invalid";
68
+ try {
69
+ const u = new URL(next, base);
70
+ if (u.origin !== base) return "/";
71
+ const out = u.pathname + u.search + u.hash;
72
+ // URL collapses "/.//evil.com" to "//evil.com", which a browser reads as another site.
73
+ return out.startsWith("//") ? "/" : out;
74
+ } catch {
75
+ return "/";
76
+ }
65
77
  }