@behavioral-agentic-design-system/core 0.34.0 → 0.36.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.
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * health-report.mjs — per-component health score (self-healing layer, Phase A).
4
+ *
5
+ * A 0–100 per registry component derived ONLY from data already on disk:
6
+ * ux-test findings, corrections.md recurrences, component-build ledger status,
7
+ * registry completeness (a11yContract / antiPatterns / examples / costModel),
8
+ * story + showcase presence, and costModel.lastReviewedAt staleness. No
9
+ * runtime telemetry (Phase A boundary — see the plan).
10
+ *
11
+ * The score is INFORMATIONAL. It must never gate a merge (Goodhart guard —
12
+ * docs/specs/2026-08-21-self-healing-layer.md records this as MUST NOT).
13
+ *
14
+ * Deterministic given the same inputs and --date (default: today). Output:
15
+ * ledgers/reports/health-<YYYY-MM>.json (read by /preview/health)
16
+ * Flags:
17
+ * --date=YYYY-MM-DD reference date for staleness + filename
18
+ * --drift append score drops >10 vs the previous report to
19
+ * ledgers/drift.jsonl (source: health)
20
+ */
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+
24
+ // Repo-root resolution is cwd-based (not file-relative) so this works both in
25
+ // upstream BADS (scripts/ -> repo root) and after shipping as a package bin
26
+ // into a client fork, invoked as `npx bads-health-report` from the fork's own
27
+ // repo root.
28
+ const ROOT = process.cwd();
29
+ const argv = process.argv.slice(2);
30
+ const DATE = argv.find((a) => a.startsWith("--date="))?.split("=")[1] || new Date().toISOString().slice(0, 10);
31
+ const DRIFT = argv.includes("--drift");
32
+
33
+ const read = (p) => fs.readFileSync(path.join(ROOT, p), "utf8");
34
+ const readJsonl = (p) => {
35
+ const full = path.join(ROOT, p);
36
+ if (!fs.existsSync(full)) return [];
37
+ return read(p).split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
38
+ };
39
+
40
+ const registry = JSON.parse(read("layer-5-component-registry/component-registry.json"));
41
+ const uxRows = readJsonl("ledgers/ux-tests.jsonl");
42
+ const buildRows = readJsonl("ledgers/component-builds.jsonl");
43
+ const corrections = fs.existsSync(path.join(ROOT, "corrections.md")) ? read("corrections.md") : "";
44
+ const showcase = read("packages/core/src/app/preview/components/page.tsx");
45
+ // case-insensitive: the QrCode/QRCode story case-collision fix means registry
46
+ // name casing and story filename casing can legitimately differ
47
+ const storyFiles = new Set(fs.readdirSync(path.join(ROOT, "packages/core/src/stories")).map((f) => f.toLowerCase()));
48
+
49
+ const kebab = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase();
50
+ const daysBetween = (a, b) => Math.round((new Date(a) - new Date(b)) / 86400000);
51
+
52
+ const UX_PENALTY = { BLOCKER: 25, HIGH: 15, MEDIUM: 8, LOW: 3, none: 0 };
53
+
54
+ const components = Object.keys(registry).sort().map((name) => {
55
+ const e = registry[name];
56
+ const penalties = [];
57
+ let dataPoints = 0;
58
+
59
+ // signal: ux-test findings (rows match on the component field)
60
+ for (const r of uxRows.filter((r) => r.component === name)) {
61
+ dataPoints++;
62
+ const p = UX_PENALTY[r.severity] ?? 0;
63
+ if (p) penalties.push({ source: "ux-test", points: p, why: `${r.severity}: ${String(r.finding || "").slice(0, 100)}` });
64
+ }
65
+
66
+ // signal: corrections recurrences (word-boundary name mentions, capped)
67
+ const mentions = (corrections.match(new RegExp(`\\b${name}\\b`, "g")) || []).length;
68
+ if (mentions) {
69
+ dataPoints += mentions;
70
+ penalties.push({ source: "corrections", points: Math.min(mentions * 5, 15), why: `${mentions} mention(s) in corrections.md` });
71
+ }
72
+
73
+ // signal: build-ledger outcome (latest row for this component)
74
+ const builds = buildRows.filter((r) => (r.candidate || "").split(" ")[0] === name);
75
+ if (builds.length) {
76
+ dataPoints += builds.length;
77
+ const last = builds[builds.length - 1];
78
+ if (last.status === "rejected") penalties.push({ source: "build-ledger", points: 10, why: "last build attempt rejected by gates" });
79
+ }
80
+
81
+ // structure: registry completeness (these are hygiene, not incidents)
82
+ if (!e.a11yContract) penalties.push({ source: "registry", points: 10, why: "no a11yContract" });
83
+ if (!e.antiPatterns?.length) penalties.push({ source: "registry", points: 5, why: "no antiPatterns" });
84
+ if (!e.examples?.length) penalties.push({ source: "registry", points: 5, why: "no examples" });
85
+ if (!e.costModel) penalties.push({ source: "registry", points: 5, why: "no costModel" });
86
+ else if (e.costModel.lastReviewedAt && daysBetween(DATE, e.costModel.lastReviewedAt) > 180)
87
+ penalties.push({ source: "registry", points: 5, why: `costModel last reviewed ${e.costModel.lastReviewedAt}` });
88
+
89
+ // structure: story + showcase presence — REQUIRED only for components whose
90
+ // source ships inside @core (the Storybook rule's scope). Repo-root
91
+ // compositions (bucket C) live in feature tabs, not the components page.
92
+ const inCore = fs.existsSync(path.join(ROOT, "packages/core/src/components/ui", `${kebab(name)}.tsx`));
93
+ if (inCore) {
94
+ if (!storyFiles.has(`${name.toLowerCase()}.stories.tsx`)) penalties.push({ source: "stories", points: 10, why: "no story file (STORYBOOK_RULE violation)" });
95
+ if (!showcase.includes(`<${name}`) && !showcase.includes(`${name}Showcase`) && !showcase.includes(`title="${name}"`))
96
+ penalties.push({ source: "showcase", points: 5, why: "not demonstrated in the components showcase" });
97
+ }
98
+
99
+ const score = Math.max(0, 100 - penalties.reduce((s, p) => s + p.points, 0));
100
+ return {
101
+ name,
102
+ score,
103
+ band: score >= 90 ? "healthy" : score >= 70 ? "watch" : "attention",
104
+ insufficientData: dataPoints === 0,
105
+ dataPoints,
106
+ penalties: penalties.sort((a, b) => b.points - a.points),
107
+ };
108
+ });
109
+
110
+ const known = components.filter((c) => !c.insufficientData);
111
+ const summary = {
112
+ components: components.length,
113
+ scored: known.length,
114
+ insufficientData: components.length - known.length,
115
+ avgScore: known.length ? Math.round(known.reduce((s, c) => s + c.score, 0) / known.length) : null,
116
+ bands: {
117
+ healthy: components.filter((c) => c.band === "healthy").length,
118
+ watch: components.filter((c) => c.band === "watch").length,
119
+ attention: components.filter((c) => c.band === "attention").length,
120
+ },
121
+ };
122
+
123
+ const month = DATE.slice(0, 7);
124
+ const outPath = path.join(ROOT, "ledgers", "reports", `health-${month}.json`);
125
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
126
+
127
+ // --drift: compare against the most recent PRIOR report before overwriting
128
+ if (DRIFT) {
129
+ const prior = fs.readdirSync(path.dirname(outPath))
130
+ .filter((f) => /^health-\d{4}-\d{2}\.json$/.test(f) && f < `health-${month}.json`)
131
+ .sort()
132
+ .pop();
133
+ if (prior) {
134
+ const prev = JSON.parse(read(path.join("ledgers", "reports", prior)));
135
+ const prevScores = Object.fromEntries(prev.components.map((c) => [c.name, c.score]));
136
+ const drops = components.filter((c) => prevScores[c.name] != null && prevScores[c.name] - c.score > 10);
137
+ if (drops.length) {
138
+ const rows = drops.map((c) => JSON.stringify({
139
+ schemaVersion: "1", date: DATE, source: "health", rule: "score-drop",
140
+ target: c.name, severity: c.band === "attention" ? "high" : "medium",
141
+ signal: `health ${prevScores[c.name]} → ${c.score} since ${prior.slice(7, 14)}`,
142
+ evidence: c.penalties[0]?.why || "", status: "open",
143
+ }));
144
+ fs.appendFileSync(path.join(ROOT, "ledgers", "drift.jsonl"), rows.join("\n") + "\n");
145
+ console.log(`drift: logged ${rows.length} score drop(s) to ledgers/drift.jsonl`);
146
+ }
147
+ }
148
+ }
149
+
150
+ fs.writeFileSync(outPath, JSON.stringify({ schemaVersion: "1", generatedFor: DATE, summary, components }, null, 2) + "\n");
151
+
152
+ console.log(`✓ health-report: ${summary.scored} scored, ${summary.insufficientData} insufficient-data, avg ${summary.avgScore} → ledgers/reports/health-${month}.json`);
153
+ const worst = known.filter((c) => c.band !== "healthy").slice(0, 8);
154
+ if (worst.length) {
155
+ console.log("\nLowest bands:");
156
+ for (const c of worst.sort((a, b) => a.score - b.score).slice(0, 8))
157
+ console.log(` ${String(c.score).padStart(3)} ${c.band.padEnd(9)} ${c.name} — ${c.penalties[0]?.why || ""}`);
158
+ }
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ // Layer 2 (Ethics & Responsibility) — registry ethicsContract linter.
3
+ //
4
+ // Promotes the ethicsContract from documented-only (deferred v2) to enforced.
5
+ // The contract lives per-component in layer-5-component-registry/component-registry.json.
6
+ //
7
+ // Enforced rule (errors, blocking):
8
+ // A component that declares it collects data (ethicsContract.dataCollected
9
+ // is a non-empty array) MUST also declare:
10
+ // - dataRetention : a non-empty string (how long / by whom)
11
+ // - consentRequired : a boolean (whether explicit consent is needed)
12
+ // Collecting data without saying how long you keep it, or whether consent is
13
+ // required, is the exact "rule lives only in prose and leaks" failure this
14
+ // linter exists to close.
15
+ //
16
+ // Detection rule (errors, blocking — added by the 2026-07 audit): a primitive
17
+ // in packages/core/src/components/ui/ that renders a data-entry surface
18
+ // (<input>, <textarea>, <select>, contentEditable, or a Radix form control)
19
+ // MUST declare an ethicsContract — even one with dataCollected: [] plus a
20
+ // notes field. Before this, absence was treated as "collects nothing" and the
21
+ // lint could never fail: 2 of 75 components declared contracts while
22
+ // PasswordInput, PinInput, and FileUpload shipped undeclared, and the success
23
+ // message claimed full coverage anyway.
24
+ //
25
+ // Convention for everything OUTSIDE the detected set: a component with NO
26
+ // ethicsContract is assumed to collect nothing. A present-but-incomplete
27
+ // contract is never allowed.
28
+ //
29
+ // Informational (warnings, non-blocking): darkPatternRisk outside the enum,
30
+ // aiDisclosure missing on a contract that names AI in dataCollected.
31
+ //
32
+ // Exit 1 on any error so the pre-commit hook / CI can block. Run:
33
+ // node packages/core/scripts/lint-ethics-contract.mjs
34
+
35
+ import fs from "node:fs";
36
+ import path from "node:path";
37
+
38
+ const REPO_ROOT = process.cwd();
39
+ const REGISTRY = path.join(
40
+ REPO_ROOT,
41
+ "layer-5-component-registry/component-registry.json",
42
+ );
43
+ const RISK = new Set(["none", "low", "medium", "high"]);
44
+
45
+ let errors = 0;
46
+ let warnings = 0;
47
+ let withContract = 0;
48
+ let collecting = 0;
49
+
50
+ function err(name, msg) {
51
+ console.log(`❌ ${name}: ${msg}`);
52
+ errors++;
53
+ }
54
+ function warn(name, msg) {
55
+ console.log(`⚠️ ${name}: ${msg}`);
56
+ warnings++;
57
+ }
58
+
59
+ let registry;
60
+ try {
61
+ registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
62
+ } catch (e) {
63
+ console.error(`lint-ethics-contract: cannot read registry — ${e.message}`);
64
+ process.exit(1);
65
+ }
66
+
67
+ // --- detection pass: which ui/ primitives render a data-entry surface? ---
68
+ const UI_DIR = path.join(REPO_ROOT, "packages/core/src/components/ui");
69
+ const INLINE_SIGNAL = /<input[\s/>]|<textarea[\s/>]|<select[\s/>]|contentEditable/;
70
+ const RADIX_FORM_SIGNAL = /@radix-ui\/react-(checkbox|radio-group|switch|slider|select)\b/;
71
+ const pascal = (stem) => stem.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
72
+
73
+ const requiresContract = new Set();
74
+ if (fs.existsSync(UI_DIR)) {
75
+ for (const f of fs.readdirSync(UI_DIR)) {
76
+ if (!f.endsWith(".tsx")) continue;
77
+ const src = fs.readFileSync(path.join(UI_DIR, f), "utf8");
78
+ if (INLINE_SIGNAL.test(src) || RADIX_FORM_SIGNAL.test(src)) {
79
+ requiresContract.add(pascal(f.replace(/\.tsx$/, "")));
80
+ }
81
+ }
82
+ }
83
+
84
+ const names = Object.keys(registry);
85
+ let required = 0;
86
+ for (const name of requiresContract) {
87
+ if (!names.includes(name)) continue; // file without registry entry — registry-drift checks own that
88
+ required++;
89
+ const c = registry[name]?.ethicsContract;
90
+ if (!c || typeof c !== "object") {
91
+ err(name, `renders a data-entry surface but declares no ethicsContract — declare one (dataCollected may be [] with a notes field explaining why)`);
92
+ }
93
+ }
94
+
95
+ for (const name of names) {
96
+ const c = registry[name]?.ethicsContract;
97
+ if (!c || typeof c !== "object") continue; // absent == collects nothing (non-data-entry components)
98
+ withContract++;
99
+
100
+ if (c.darkPatternRisk !== undefined && !RISK.has(c.darkPatternRisk)) {
101
+ warn(name, `darkPatternRisk "${c.darkPatternRisk}" is not one of none|low|medium|high`);
102
+ }
103
+
104
+ const collected = Array.isArray(c.dataCollected) ? c.dataCollected.filter(Boolean) : [];
105
+ if (collected.length > 0) {
106
+ collecting++;
107
+ if (typeof c.dataRetention !== "string" || c.dataRetention.trim().length === 0) {
108
+ err(name, `collects data (${collected.join(", ")}) but declares no dataRetention`);
109
+ }
110
+ if (typeof c.consentRequired !== "boolean") {
111
+ err(name, `collects data but consentRequired is not declared (must be true/false)`);
112
+ }
113
+ if (collected.some((d) => /\bai\b|model|llm|generat/i.test(d)) &&
114
+ (typeof c.aiDisclosure !== "string" || c.aiDisclosure.trim().length === 0)) {
115
+ warn(name, `collects AI-related data but declares no aiDisclosure`);
116
+ }
117
+ }
118
+ }
119
+
120
+ console.log(
121
+ `\nlint-ethics-contract: ${names.length} components · ${required} data-entry primitives detected · ${withContract} declare an ethicsContract · ${collecting} collect data`,
122
+ );
123
+ console.log(
124
+ errors === 0
125
+ ? `✓ ethicsContract OK — every detected data-entry primitive declares a contract, and every data-collecting one declares retention + consent`
126
+ : `\n${errors} error(s), ${warnings} warning(s). Data-entry primitives must declare an ethicsContract; data-collecting ones must declare dataRetention + consentRequired.`,
127
+ );
128
+
129
+ process.exit(errors === 0 ? 0 : 1);
@@ -0,0 +1,220 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-slop — flag the code-level signals of "AI slop" visual tics: the
4
+ * machine-default moves (indigo→purple gradients, gradient text, springy
5
+ * hover pops, huge glows) that make a vibe-coded UI read as generated.
6
+ *
7
+ * Why this exists: BADS already lists anti-defaults in CLAUDE.md, but they
8
+ * were *prose* enforced only by the (subjective, expensive) independent-
9
+ * critique agent. Per docs/intent-driven-context.md, a constraint — a thing
10
+ * that must NOT happen — should be delivered by a lint. This is that lint.
11
+ * Taxonomy seeded from the kill-ai-slop field guide (github.com/yetone/
12
+ * kill-ai-slop), narrowed to the objective, low-false-positive subset and
13
+ * triaged against BADS's OWN intentional registers so it doesn't fight the
14
+ * system's deliberate choices (the "slop vs chosen design" step).
15
+ *
16
+ * BADS ships ZERO of these today (verified 2026-07-10), so the lint passes
17
+ * clean and acts as a ratchet: it can't regress in without a flag.
18
+ *
19
+ * What it deliberately does NOT flag (BADS "chosen design", not slop):
20
+ * - the terminal register (mono UI + one accent) — a named BADS register
21
+ * - editorial serif emphasis — a named BADS register
22
+ * - semantic alert colors (info/success/warn/error) — intentional
23
+ * - eyebrow / kicker labels — sanctioned by the CTA-size contract
24
+ * - backdrop-blur on the shell top bar / sheet overlays — intentional
25
+ * - chart area-fill gradients — legitimate data viz
26
+ * These are why you can't drop in kill-ai-slop's scanner wholesale.
27
+ *
28
+ * Detectors (rule codes):
29
+ * BADS-SLOP-1 gradient-text bg-clip-text + text-transparent / background-clip:text
30
+ * BADS-SLOP-2 indigo-gradient (from|via|to)-(indigo|violet|purple|fuchsia); #6366f1/#a855f7/#8b5cf6
31
+ * BADS-SLOP-3 springy-hover hover:scale-105 / hover:scale-110 (the AI "pop")
32
+ * BADS-SLOP-4 oversized-shadow box-shadow / shadow-[…] blur ≥ 40px (the AI "glow")
33
+ * BADS-SLOP-5 emoji-in-ui decorative emoji (🚀✨⚡🎉🔥💡🎯🌟🚨💪) in rendered UI copy
34
+ * BADS-SLOP-6 fake-stat-cliche invented-metric marketing tokens hardcoded as copy
35
+ * (99.9%/99.99% uptime, 10k+/1M+ vanity counts, ★★★★★)
36
+ *
37
+ * Rule 6 is adapted from Nutlope's Hallmark slop-test gate 46 (invented
38
+ * metrics), matched to BADS's own "fake stat trio" anti-default. Real metrics
39
+ * come from data/props, not string literals, so a hardcoded stat cliché is a
40
+ * fabricated-trust signal — escape-hatch a genuine, sourced claim with a reason.
41
+ * (Hallmark's over-rounded-glass tell was evaluated as BADS-SLOP-7 but dropped:
42
+ * rounded-full + backdrop-blur has legit uses — e.g. the dev-identity badge —
43
+ * so that subjective call stays with the critique agent, not a hard lint.)
44
+ *
45
+ * Escape hatch: `// allow-slop:BADS-SLOP-N <one-sentence reason>` on the line
46
+ * ABOVE the flagged line. The reason is required (a bare allow is itself
47
+ * flagged) — same discipline as size-audit's // allow-text-xs-cta.
48
+ *
49
+ * Scan scope: app/, components/, packages/core/src/components/,
50
+ * packages/core/src/app/ (.tsx). Stories are skipped (a story may
51
+ * deliberately demonstrate an anti-pattern).
52
+ *
53
+ * Run:
54
+ * pnpm lint:slop # report, exit 1 on any finding
55
+ * pnpm lint:slop:warn # report, exit 0 (advisory; used in the a11y umbrella)
56
+ * node packages/core/scripts/lint-slop.mjs path/to.tsx # scan a specific file
57
+ */
58
+
59
+ import fs from "node:fs";
60
+ import path from "node:path";
61
+
62
+ // Repo-root resolution is cwd-based (not file-relative) so this works both in
63
+ // upstream BADS (scripts/ -> repo root) and after shipping as a package bin
64
+ // into a client fork, invoked as `npx bads-lint-slop` from the fork's own
65
+ // repo root.
66
+ const ROOT = process.cwd();
67
+ const advisory = process.argv.includes("--warn");
68
+ const explicitPaths = process.argv.slice(2).filter((a) => !a.startsWith("--"));
69
+
70
+ const SCAN_ROOTS = [
71
+ "app",
72
+ "components",
73
+ "packages/core/src/components",
74
+ "packages/core/src/app",
75
+ ];
76
+
77
+ // Decorative-emoji set — the classic AI-product sprinkle. Excludes ✓/✗/→ and
78
+ // other functional glyphs; excludes the crescent-moon etc. used in Slack briefs
79
+ // (those live in scripts/, out of scan scope).
80
+ const SLOP_EMOJI = /[\u{1F680}\u{2728}\u{26A1}\u{1F389}\u{1F525}\u{1F4A1}\u{1F3AF}\u{1F31F}\u{1F6A8}\u{1F4AA}\u{1F44B}\u{1F984}\u{1F4A5}\u{1F60D}]/u;
81
+
82
+ const RULES = [
83
+ {
84
+ code: "BADS-SLOP-1",
85
+ name: "gradient-text",
86
+ why: "Rainbow gradient headline (bg-clip-text). Carries no information; the classic 'look premium' move. Use a solid foreground token.",
87
+ test: (line) =>
88
+ (/\bbg-clip-text\b/.test(line) && /\btext-transparent\b/.test(line)) ||
89
+ /background-clip:\s*text/.test(line) ||
90
+ /-webkit-background-clip:\s*text/.test(line),
91
+ },
92
+ {
93
+ code: "BADS-SLOP-2",
94
+ name: "indigo-violet-gradient",
95
+ why: "Indigo→purple diagonal blend — the single most recognizable AI-default gradient. Use a flat brand or semantic surface.",
96
+ // Only the Tailwind gradient-direction stops — a bare violet hex (e.g. a
97
+ // ColorPicker swatch value) is a color, not a gradient, and must not flag.
98
+ // A raw slop-hex only counts when it sits in an actual gradient function.
99
+ test: (line) =>
100
+ /\b(from|via|to)-(indigo|violet|purple|fuchsia)-\d/.test(line) ||
101
+ (/(linear|radial|conic)-gradient|bg-gradient-to-/.test(line) &&
102
+ /#6366f1|#a855f7|#8b5cf6|#7c3aed/i.test(line)),
103
+ },
104
+ {
105
+ code: "BADS-SLOP-3",
106
+ name: "springy-hover",
107
+ why: "hover:scale-105/110 — the bouncy 'pop' every AI card gets. BADS uses token-driven color/elevation shifts on hover, not scale jumps.",
108
+ test: (line) => /\bhover:scale-1(05|10)\b/.test(line),
109
+ },
110
+ {
111
+ code: "BADS-SLOP-4",
112
+ name: "oversized-shadow",
113
+ why: "Shadow blur ≥ 40px — the soft 'glow' that bleeds far past the element. BADS uses the --shadow token scale.",
114
+ test: (line) => {
115
+ // arbitrary Tailwind shadow: shadow-[...40px...]
116
+ const arb = line.match(/shadow-\[[^\]]*?\b(\d{2,})px/);
117
+ if (arb && Number(arb[1]) >= 40) return true;
118
+ // inline box-shadow with a blur radius ≥ 40px (3rd length in the list)
119
+ const inline = line.match(/box-?[Ss]hadow[^;"'`]*?\b(\d{2,})px/);
120
+ if (inline && Number(inline[1]) >= 40) return true;
121
+ return false;
122
+ },
123
+ },
124
+ {
125
+ code: "BADS-SLOP-5",
126
+ name: "emoji-in-ui",
127
+ why: "Decorative emoji in rendered UI copy — 🚀/✨/🔥 on headings and buttons. BADS carries meaning in words, not emoji sprinkle.",
128
+ test: (line, { isComment }) => !isComment && SLOP_EMOJI.test(line),
129
+ },
130
+ {
131
+ code: "BADS-SLOP-6",
132
+ name: "fake-stat-cliche",
133
+ why: "Invented-metric marketing cliché hardcoded as copy (99.9% uptime, 10k+/1M+ counts, ★★★★★). Real metrics come from data, not string literals — a hardcoded one manufactures trust. Use real content from the personas pool, or escape-hatch a genuine, sourced claim.",
134
+ test: (line, { isComment }) => {
135
+ if (isComment) return false;
136
+ return (
137
+ /\b99\.9{1,2}\s*%/.test(line) || // 99.9% / 99.99% uptime cliché
138
+ /\b\d{1,3}[kKmMbB]\+/.test(line) || // 10k+ / 100k+ / 1M+ vanity counts
139
+ /★{3,}/.test(line) // ★★★★★ rating-star cliché row (filled-star glyph)
140
+ );
141
+ },
142
+ },
143
+ ];
144
+
145
+ function walk(dir, out = []) {
146
+ if (!fs.existsSync(dir)) return out;
147
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
148
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
149
+ const full = path.join(dir, entry.name);
150
+ if (entry.isDirectory()) walk(full, out);
151
+ else if (/\.tsx?$/.test(entry.name) && !/\.stories\.tsx?$/.test(entry.name))
152
+ out.push(full);
153
+ }
154
+ return out;
155
+ }
156
+
157
+ function fileList() {
158
+ if (explicitPaths.length) return explicitPaths.map((p) => path.resolve(ROOT, p));
159
+ return SCAN_ROOTS.flatMap((r) => walk(path.join(ROOT, r)));
160
+ }
161
+
162
+ const findings = [];
163
+
164
+ for (const file of fileList()) {
165
+ let src;
166
+ try {
167
+ src = fs.readFileSync(file, "utf8");
168
+ } catch {
169
+ continue;
170
+ }
171
+ const lines = src.split("\n");
172
+ for (let i = 0; i < lines.length; i++) {
173
+ const line = lines[i];
174
+ const trimmed = line.trimStart();
175
+ const isComment = trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*");
176
+ const prev = i > 0 ? lines[i - 1] : "";
177
+ for (const rule of RULES) {
178
+ if (!rule.test(line, { isComment })) continue;
179
+ // escape hatch on the line above: // allow-slop:CODE <reason>
180
+ const esc = prev.match(/\/\/\s*allow-slop:(BADS-SLOP-\d)\b(.*)$/);
181
+ if (esc && esc[1] === rule.code) {
182
+ if (!esc[2].trim()) {
183
+ findings.push({
184
+ file: path.relative(ROOT, file),
185
+ line: i,
186
+ code: rule.code,
187
+ name: rule.name,
188
+ why: "allow-slop escape hatch requires a one-sentence reason.",
189
+ });
190
+ }
191
+ continue; // escaped with a reason — allowed
192
+ }
193
+ findings.push({
194
+ file: path.relative(ROOT, file),
195
+ line: i + 1,
196
+ code: rule.code,
197
+ name: rule.name,
198
+ why: rule.why,
199
+ });
200
+ }
201
+ }
202
+ }
203
+
204
+ if (findings.length === 0) {
205
+ console.log("✓ lint-slop: no AI-slop signals found.");
206
+ process.exit(0);
207
+ }
208
+
209
+ console.log(`lint-slop: ${findings.length} slop signal${findings.length === 1 ? "" : "s"} found\n`);
210
+ for (const f of findings) {
211
+ console.log(` ${f.file}:${f.line} [${f.code} ${f.name}]`);
212
+ console.log(` ${f.why}`);
213
+ console.log(` escape: // allow-slop:${f.code} <reason> on the line above, if intentional\n`);
214
+ }
215
+
216
+ if (advisory) {
217
+ console.log("(advisory — exit 0)");
218
+ process.exit(0);
219
+ }
220
+ process.exit(1);
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-token-intent.mjs — Token Intent Validator (self-healing layer, Phase A).
4
+ *
5
+ * The orphan lint asks "is this token used at all?". This one asks "is it used
6
+ * for what it MEANS?" — the intent ground truth being tokens.json $description
7
+ * fields and the registry's per-component tokenUsage blocks (e.g. warning =
8
+ * caution/attention, destructive = errors and irreversible actions, success =
9
+ * positive confirmation, muted-foreground = secondary text).
10
+ *
11
+ * v1 is deliberately DETERMINISTIC — no prose matching, two rule families with
12
+ * a measurable false-positive rate:
13
+ *
14
+ * BADS-INTENT-1 status-token/copy mismatch — a status token's className on
15
+ * a line whose visible copy carries the OPPOSITE status
16
+ * vocabulary (warning token + error copy, success token +
17
+ * failure copy, destructive token + success copy).
18
+ * BADS-INTENT-2 muted-on-primary — text-muted-foreground styling a display
19
+ * heading register (text-2xl and up). Muted means secondary;
20
+ * a muted headline is a hierarchy bug, not a style choice.
21
+ * (Semantic <h2> at small sizes is the sanctioned eyebrow
22
+ * pattern and deliberately does NOT fire.)
23
+ *
24
+ * Advisory by default (informational-lint rule); --strict exits 1. Escape
25
+ * hatch: `// allow-token-intent: <one-sentence reason>` on the line above.
26
+ * --log appends confirmed findings to ledgers/drift.jsonl (source:intent-lint).
27
+ *
28
+ * Spec: docs/specs/2026-08-21-self-healing-layer.md. MUST stay informational
29
+ * in CI — never a merge gate (Goodhart guard).
30
+ */
31
+ import fs from "node:fs";
32
+ import path from "node:path";
33
+
34
+ // Repo-root resolution is cwd-based (not file-relative) so this works both in
35
+ // upstream BADS (scripts/ -> repo root) and after shipping as a package bin
36
+ // into a client fork, invoked as `npx bads-lint-token-intent` from the fork's
37
+ // own repo root.
38
+ const ROOT = process.cwd();
39
+ const argv = process.argv.slice(2);
40
+ const STRICT = argv.includes("--strict");
41
+ const LOG = argv.includes("--log");
42
+ const fileArgs = argv.filter((a) => !a.startsWith("--"));
43
+
44
+ const SCAN_DIRS = ["app", "components", "packages/core/src/components", "packages/core/src/app"];
45
+
46
+ const tsxFiles = [];
47
+ const walk = (dir) => {
48
+ if (!fs.existsSync(dir)) return;
49
+ for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
50
+ if (d.name === "node_modules" || d.name.startsWith(".")) continue;
51
+ const p = path.join(dir, d.name);
52
+ if (d.isDirectory()) walk(p);
53
+ else if (/\.tsx$/.test(d.name)) tsxFiles.push(p);
54
+ }
55
+ };
56
+ if (fileArgs.length) tsxFiles.push(...fileArgs.map((f) => path.resolve(f)));
57
+ else SCAN_DIRS.forEach((d) => walk(path.join(ROOT, d)));
58
+
59
+ // status vocabulary that indicates the copy's semantic register
60
+ const VOCAB = {
61
+ error: /\b(error|errors|failed|failure|invalid|problem occurred)\b/i,
62
+ success: /\b(success|successful|saved|completed?|all set|confirmed)\b/i,
63
+ };
64
+ // token family → the register it declares (from tokens.json $description /
65
+ // registry tokenUsage) → the registers it must not carry
66
+ const RULES1 = [
67
+ { tokenRe: /\b(?:text|bg|border)-warning\b/, family: "warning", clashes: ["error"], msg: "warning token carrying error copy — errors are the destructive family's intent" },
68
+ { tokenRe: /\b(?:text|bg|border)-success\b/, family: "success", clashes: ["error"], msg: "success token carrying error/failure copy" },
69
+ { tokenRe: /\b(?:text|bg|border)-destructive\b/, family: "destructive", clashes: ["success"], msg: "destructive token carrying success copy — positive confirmation is the success family's intent" },
70
+ ];
71
+ // Heading register = display sizes only. Semantic <h2> at text-sm is the
72
+ // sanctioned eyebrow/section-label pattern (muted is CORRECT there).
73
+ const HEADING_RE = /\btext-(?:2xl|3xl|4xl|5xl|6xl)\b/;
74
+ // Visible copy only: JSX text nodes and human-facing string props. Testing the
75
+ // raw context caused 4/6 false positives on CVA variant maps (the NEXT
76
+ // variant's key name — "success:" — sat inside the context window).
77
+ const visibleCopy = (ctx) => {
78
+ const out = [];
79
+ for (const m of ctx.matchAll(/>([^<>{}]+)</g)) out.push(m[1]);
80
+ for (const m of ctx.matchAll(/(?:aria-label|title|alt|placeholder)=\{?"([^"]+)"/g)) out.push(m[1]);
81
+ return out.join(" ");
82
+ };
83
+
84
+ const findings = [];
85
+ for (const file of tsxFiles) {
86
+ const lines = fs.readFileSync(file, "utf8").split("\n");
87
+ for (let i = 0; i < lines.length; i++) {
88
+ const line = lines[i];
89
+ const prev = lines[i - 1] || "";
90
+ if (prev.includes("allow-token-intent:")) continue;
91
+ // context = the line plus its visible-copy neighborhood (JSX text often
92
+ // sits on the following line after a className-bearing open tag)
93
+ const context = [line, lines[i + 1] || "", lines[i + 2] || ""].join(" ");
94
+ for (const r of RULES1) {
95
+ if (!r.tokenRe.test(line)) continue;
96
+ const copy = visibleCopy(context);
97
+ for (const clash of r.clashes) {
98
+ if (copy && VOCAB[clash].test(copy)) {
99
+ findings.push({ rule: "BADS-INTENT-1", file, line: i + 1, detail: r.msg, evidence: line.trim().slice(0, 140) });
100
+ }
101
+ }
102
+ }
103
+ if (/\btext-muted-foreground\b/.test(line) && HEADING_RE.test(line)) {
104
+ findings.push({ rule: "BADS-INTENT-2", file, line: i + 1, detail: "muted-foreground on a heading register — muted means secondary text", evidence: line.trim().slice(0, 140) });
105
+ }
106
+ }
107
+ }
108
+
109
+ if (!findings.length) {
110
+ console.log(`✓ token-intent: no intent mismatches across ${tsxFiles.length} files (2 rule families)`);
111
+ process.exit(0);
112
+ }
113
+ console.log(`token-intent: ${findings.length} candidate mismatch(es) across ${tsxFiles.length} files ${STRICT ? "" : "(advisory)"}\n`);
114
+ for (const f of findings) {
115
+ console.log(` [${f.rule}] ${path.relative(ROOT, f.file)}:${f.line}\n ${f.detail}\n ${f.evidence}\n`);
116
+ }
117
+ console.log('Escape hatch: `// allow-token-intent: <reason>` on the line above.');
118
+
119
+ if (LOG) {
120
+ const ledger = path.join(ROOT, "ledgers", "drift.jsonl");
121
+ const date = new Date().toISOString().slice(0, 10);
122
+ const rows = findings.map((f) =>
123
+ JSON.stringify({ schemaVersion: "1", date, source: "intent-lint", rule: f.rule, target: `${path.relative(ROOT, f.file)}:${f.line}`, severity: "medium", signal: f.detail, evidence: f.evidence, status: "open" })
124
+ );
125
+ fs.appendFileSync(ledger, rows.join("\n") + "\n");
126
+ console.log(`\nlogged ${rows.length} row(s) to ledgers/drift.jsonl`);
127
+ }
128
+ process.exit(STRICT ? 1 : 0);