basalt-ui 1.0.1 → 1.0.2

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,219 @@
1
+ /**
2
+ * Regression tests for the `classify()` ledger widening (see `./index.ts`'s `normalizeForLedger` +
3
+ * `writeUnit` + `classify`).
4
+ *
5
+ * `writeUnit` now records a NORMALIZED hash in the manifest (instead of a raw one) for every sync
6
+ * it performs, going forward — that closes the false-positive gap for any consumer whose manifest
7
+ * entry was written by a CLI carrying this fix. But a manifest entry written by an OLDER
8
+ * (pre-1.0.2) CLI holds a RAW hash — `classify`'s legacy path (`sha256(current) === manifestHash`)
9
+ * exists to keep matching that raw entry directly, and it is faithfully exercised below by seeding
10
+ * the manifest with a genuine `sha256(olderBlock)`, not `sha256(normalizeForLedger(olderBlock))`.
11
+ *
12
+ * Two scenarios collide differently against that raw legacy entry:
13
+ * - reformat ONLY (template body unchanged since the entry was written) → the same-version
14
+ * fallback (`normalizeForLedger(current) === normalizeForLedger(desired)`) still catches it,
15
+ * independent of the manifest hash → `unchanged`, healed silently, no `--force` — and the
16
+ * healing sync rewrites the manifest with the NORMALIZED hash, closing the gap for good for
17
+ * that consumer.
18
+ * - reformat AND a cross-version word change (the CLI bin rename baked into the block's own
19
+ * prose) together → NONE of `classify`'s three paths match a raw legacy hash → `drifted`, a
20
+ * real transitional gap that needs one `--force` to heal. See the comment above the legacy-hash
21
+ * path in `classify` (`./index.ts`) for the documented tradeoff.
22
+ *
23
+ * Also proves the two pre-existing same-version guarantees still hold:
24
+ * 2. a real word-level edit at the SAME version → still `drifted` → skipped without `--force`.
25
+ * 3. reformatting + a real edit together → still `drifted`.
26
+ */
27
+ import { afterEach, beforeEach, describe, expect, it } from 'bun:test'
28
+ import { createHash } from 'node:crypto'
29
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
30
+ import { tmpdir } from 'node:os'
31
+ import { join, resolve } from 'node:path'
32
+
33
+ import { init, MANIFEST_PATH, normalizeForLedger, sync } from './index.ts'
34
+
35
+ function sha256(text: string): string {
36
+ return createHash('sha256').update(text, 'utf8').digest('hex')
37
+ }
38
+
39
+ let dir: string
40
+
41
+ function read(relPath: string): string {
42
+ return readFileSync(join(dir, relPath), 'utf8')
43
+ }
44
+
45
+ function write(relPath: string, content: string): void {
46
+ writeFileSync(join(dir, relPath), content, 'utf8')
47
+ }
48
+
49
+ /** Captures both console.log and console.error — sync() reports drift on either depending on flags. */
50
+ function capture(fn: () => number): { code: number; log: string } {
51
+ const originalLog = console.log
52
+ const originalError = console.error
53
+ let log = ''
54
+ console.log = (...args: unknown[]) => {
55
+ log += `${args.join(' ')}\n`
56
+ }
57
+ console.error = (...args: unknown[]) => {
58
+ log += `${args.join(' ')}\n`
59
+ }
60
+ try {
61
+ return { code: fn(), log }
62
+ } finally {
63
+ console.log = originalLog
64
+ console.error = originalError
65
+ }
66
+ }
67
+
68
+ function silenced<T>(fn: () => T): T {
69
+ const originalLog = console.log
70
+ const originalError = console.error
71
+ console.log = () => {}
72
+ console.error = () => {}
73
+ try {
74
+ return fn()
75
+ } finally {
76
+ console.log = originalLog
77
+ console.error = originalError
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The exact argo repro: lefthook's oxfmt inserted an EXTRA blank line after
83
+ * `<!-- basalt:begin … -->` and another before `<!-- basalt:end -->` (a 35-line template rendered
84
+ * as 37 lines post-oxfmt) — a pure formatting delta, zero word changes. Inserted unconditionally
85
+ * (not just when absent) so the fixture reproduces the delta regardless of how many blank lines the
86
+ * live template already ships around its markers.
87
+ */
88
+ function simulateOxfmtReformat(host: string): string {
89
+ const beginLineEnd = host.indexOf('\n', host.indexOf('<!-- basalt:begin')) + 1
90
+ const endMarkerStart = host.indexOf('<!-- basalt:end -->')
91
+ return (
92
+ host.slice(0, beginLineEnd) +
93
+ '\n' +
94
+ host.slice(beginLineEnd, endMarkerStart) +
95
+ '\n' +
96
+ host.slice(endMarkerStart)
97
+ )
98
+ }
99
+
100
+ beforeEach(() => {
101
+ dir = mkdtempSync(resolve(tmpdir(), 'basalt-ledger-'))
102
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'fixture' }))
103
+ silenced(() => init(dir))
104
+ })
105
+
106
+ afterEach(() => {
107
+ rmSync(dir, { recursive: true, force: true })
108
+ })
109
+
110
+ describe('classify ledger: cross-version format-only drift vs a real edit', () => {
111
+ it('a raw legacy manifest hash + reformat + a cross-version word change classifies drifted — the documented transitional gap, healed by one --force', () => {
112
+ const currentBlock = read('CLAUDE.md').trimEnd() // == today's desired (v1.0.1-shaped) block
113
+ expect(currentBlock).toContain('basalt-ui')
114
+
115
+ // Simulate the v1.0.0 body: genuinely different WORDS (the pre-rename bin name), not just an
116
+ // older version token — this is what makes the scenario cross-version, not same-version.
117
+ const olderBlock = currentBlock.replace(/basalt-ui/g, 'basalt')
118
+ expect(olderBlock).not.toBe(currentBlock)
119
+ expect(olderBlock).toContain('bunx basalt sync')
120
+
121
+ // What a PRE-1.0.2 CLI's writeUnit actually recorded at that sync: a RAW hash of the exact
122
+ // bytes it wrote — the fix only normalizes hashes written by a CLI carrying it, so a genuine
123
+ // legacy manifest entry looks like this, not `sha256(normalizeForLedger(olderBlock))`.
124
+ const manifestHash = sha256(olderBlock)
125
+ write(
126
+ MANIFEST_PATH,
127
+ JSON.stringify(
128
+ { version: 1, basaltVersion: '1.0.0', files: { 'CLAUDE.md': manifestHash } },
129
+ null,
130
+ 2,
131
+ ),
132
+ )
133
+
134
+ // What actually sits on disk: the older body, reformatted by the consumer's own lefthook
135
+ // oxfmt AFTER that older sync — the real argo repro shape.
136
+ const onDisk = simulateOxfmtReformat(olderBlock)
137
+ expect(onDisk).not.toBe(olderBlock)
138
+ write('CLAUDE.md', `${onDisk}\n`)
139
+
140
+ const { code, log } = capture(() => sync({}, dir))
141
+ expect(code).toBe(0)
142
+ // NOT healed — none of classify's three paths match a raw legacy hash once the words have
143
+ // also changed cross-version. This is the residual transitional gap documented on `classify`.
144
+ expect(read('CLAUDE.md')).toBe(`${onDisk}\n`)
145
+ expect(log).toContain('locally edited')
146
+
147
+ expect(silenced(() => sync({ check: true }, dir))).toBe(1)
148
+
149
+ // One --force heals it straight to the CURRENT (v1.0.1-shaped) rendering.
150
+ silenced(() => sync({ force: true }, dir))
151
+ expect(read('CLAUDE.md').trimEnd()).toBe(currentBlock)
152
+ })
153
+
154
+ it('a raw legacy manifest hash + reformat only (no word change) still classifies unchanged via the same-version fallback, heals without --force, and the manifest is rewritten with the normalized hash', () => {
155
+ const currentBlock = read('CLAUDE.md').trimEnd() // == today's desired block; body unchanged
156
+
157
+ // What a PRE-1.0.2 CLI's writeUnit recorded for THIS SAME body: a raw hash, not normalized.
158
+ const manifestHash = sha256(currentBlock)
159
+ write(
160
+ MANIFEST_PATH,
161
+ JSON.stringify(
162
+ { version: 1, basaltVersion: '1.0.0', files: { 'CLAUDE.md': manifestHash } },
163
+ null,
164
+ 2,
165
+ ),
166
+ )
167
+
168
+ // What sits on disk: the SAME body, reformatted by the consumer's own lefthook oxfmt — no
169
+ // template-body change since the manifest entry was written.
170
+ const onDisk = simulateOxfmtReformat(currentBlock)
171
+ expect(onDisk).not.toBe(currentBlock)
172
+ write('CLAUDE.md', `${onDisk}\n`)
173
+
174
+ const { code, log } = capture(() => sync({}, dir))
175
+ expect(code).toBe(0)
176
+ // Healed straight to the current rendering, no --force needed: the same-version fallback
177
+ // (`normalizeForLedger(current) === normalizeForLedger(desired)`) matches regardless of what
178
+ // the manifest hash says.
179
+ expect(read('CLAUDE.md').trimEnd()).toBe(currentBlock)
180
+ expect(log).not.toContain('locally edited')
181
+
182
+ // The gap is now closed for good for this consumer: the healing sync rewrote the manifest
183
+ // entry with the NORMALIZED hash (writeUnit's form), not the raw legacy one.
184
+ const manifest = JSON.parse(read(MANIFEST_PATH)) as { files: Record<string, string> }
185
+ expect(manifest.files['CLAUDE.md']).toBe(sha256(normalizeForLedger(currentBlock)))
186
+
187
+ expect(silenced(() => sync({ check: true }, dir))).toBe(0)
188
+ })
189
+
190
+ it('a genuine word-level edit inside the block classifies drifted and is skipped without --force', () => {
191
+ const original = read('CLAUDE.md')
192
+ const edited = original.replace('React 19', 'React 18 (pinned by our team)')
193
+ expect(edited).not.toBe(original)
194
+ write('CLAUDE.md', edited)
195
+
196
+ const { code, log } = capture(() => sync({}, dir))
197
+ expect(code).toBe(0)
198
+ // Untouched — a real edit is never silently overwritten.
199
+ expect(read('CLAUDE.md')).toBe(edited)
200
+ expect(log).toContain('locally edited')
201
+
202
+ expect(silenced(() => sync({ check: true }, dir))).toBe(1)
203
+
204
+ silenced(() => sync({ force: true }, dir))
205
+ expect(read('CLAUDE.md')).toBe(original)
206
+ })
207
+
208
+ it('reformatting AND a real edit together still classifies drifted (whitespace normalization never masks word changes)', () => {
209
+ const original = read('CLAUDE.md')
210
+ const reformattedAndEdited = simulateOxfmtReformat(original).replace(
211
+ 'React 19',
212
+ 'React 18 (pinned by our team)',
213
+ )
214
+ write('CLAUDE.md', reformattedAndEdited)
215
+
216
+ expect(silenced(() => sync({ check: true }, dir))).toBe(1)
217
+ expect(read('CLAUDE.md')).toBe(reformattedAndEdited)
218
+ })
219
+ })
package/src/surfaces.ts CHANGED
@@ -82,13 +82,6 @@ type BaseSurface = {
82
82
  readonly layer: Layer
83
83
  readonly forbiddenImports: readonly ForbiddenImport[]
84
84
  readonly ruleOverrides?: readonly RuleOverride[]
85
- /**
86
- * REPLACE-not-inherit-and-add. When true, this surface's forbiddenImports are the COMPLETE ban
87
- * set for its glob — the generator MUST NOT inherit-and-add the parent (src/**) bans. Charts sets
88
- * this so the @visx/* ban from src/** does NOT leak into the charts override (which would re-ban
89
- * visx). The projection emits the full list.
90
- */
91
- readonly replaceBans?: true
92
85
  /**
93
86
  * Human-readable description of this surface — single source for llms.txt and info output.
94
87
  * Optional on tooling surfaces (they have no llms.txt row).
@@ -159,6 +152,10 @@ const vg = (spec: string, message: string, extra?: Partial<ForbiddenImport>): Fo
159
152
  ...extra,
160
153
  })
161
154
 
155
+ // Mantine-free ban for headless surfaces the `basalt/import-boundary` plugin rule does NOT cover
156
+ // (it only enforces charts/tokens path segments — see oxlint-plugin.js). `./charts` and `./tokens`
157
+ // no longer use this: their Mantine-free + @visx/* boundaries are enforced by that plugin rule
158
+ // instead, so duplicating the ban here would be redundant no-restricted-imports config.
162
159
  const MANTINE_BANS = [
163
160
  v('@mantine/core', '{ctx} must be Mantine-free — no Mantine imports allowed.'),
164
161
  v('@mantine/hooks', '{ctx} must be Mantine-free — no Mantine imports allowed.'),
@@ -201,12 +198,10 @@ export const SURFACES = {
201
198
  shipped: ['**/charts/**'],
202
199
  repo: ['packages/basalt-ui/src/charts/**'],
203
200
  },
204
- replaceBans: true, // @visx/* MUST NOT inherit from src/** (the re-allow). Full list emitted.
205
- forbiddenImports: [
206
- ...MANTINE_BANS,
207
- v('@visx/tooltip', 'Use ChartTooltip + TooltipHeader/Row/Body from {ctx}.'),
208
- // LOAD-BEARING ABSENCE: no @visx/* group ban here — charts uniquely permits @visx/*.
209
- ],
201
+ // The @visx/*-only-in-charts and Mantine-free boundaries are enforced by the
202
+ // `basalt/import-boundary` oxlint plugin rule (configs/oxlint-plugin.js), not
203
+ // no-restricted-imports — see that file's header comment for why.
204
+ forbiddenImports: [],
210
205
  ruleOverrides: [{ rule: 'no-underscore-dangle', level: 'off', target: 'repo' }],
211
206
  },
212
207
  './tokens': {
@@ -221,10 +216,8 @@ export const SURFACES = {
221
216
  shipped: ['**/tokens/**'],
222
217
  repo: ['packages/basalt-ui/src/tokens/**'],
223
218
  },
224
- forbiddenImports: [
225
- ...MANTINE_BANS,
226
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
227
- ], // shipped tokens override is MISSING today → this projection EMITS it (closes D2)
219
+ // Mantine-free + @visx/* boundaries enforced by `basalt/import-boundary` (see ./charts above).
220
+ forbiddenImports: [],
228
221
  },
229
222
  './theme-lab': {
230
223
  kind: 'tooling',
@@ -246,10 +239,8 @@ export const SURFACES = {
246
239
  shipped: [],
247
240
  repo: ['packages/basalt-ui/src/guard/**'],
248
241
  },
249
- forbiddenImports: [
250
- ...MANTINE_BANS,
251
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
252
- ],
242
+ // @visx/* ban dropped — `basalt/import-boundary` now bans it universally outside charts.
243
+ forbiddenImports: [...MANTINE_BANS],
253
244
  }, // 6th JS subpath
254
245
  './query': {
255
246
  kind: 'doctrine',
@@ -263,10 +254,8 @@ export const SURFACES = {
263
254
  shipped: [],
264
255
  repo: ['packages/basalt-ui/src/query/**'],
265
256
  },
266
- forbiddenImports: [
267
- ...MANTINE_BANS,
268
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
269
- ],
257
+ // @visx/* ban dropped — `basalt/import-boundary` now bans it universally outside charts.
258
+ forbiddenImports: [...MANTINE_BANS],
270
259
  },
271
260
  './router-tanstack': {
272
261
  kind: 'doctrine',
@@ -281,10 +270,8 @@ export const SURFACES = {
281
270
  shipped: [],
282
271
  repo: ['packages/basalt-ui/src/router-tanstack/**'],
283
272
  },
284
- forbiddenImports: [
285
- ...MANTINE_BANS,
286
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
287
- ],
273
+ // @visx/* ban dropped — `basalt/import-boundary` now bans it universally outside charts.
274
+ forbiddenImports: [...MANTINE_BANS],
288
275
  },
289
276
  './forms': {
290
277
  kind: 'doctrine',
@@ -365,10 +352,8 @@ export const SURFACES = {
365
352
  shipped: [],
366
353
  repo: ['packages/basalt-ui/src/agent/**'],
367
354
  },
368
- forbiddenImports: [
369
- ...MANTINE_BANS,
370
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
371
- ],
355
+ // @visx/* ban dropped — `basalt/import-boundary` now bans it universally outside charts.
356
+ forbiddenImports: [...MANTINE_BANS],
372
357
  },
373
358
  './content': {
374
359
  kind: 'doctrine',
@@ -405,10 +390,8 @@ export const SURFACES = {
405
390
  shipped: [],
406
391
  repo: ['packages/basalt-ui/src/state.ts'],
407
392
  },
408
- forbiddenImports: [
409
- ...MANTINE_BANS,
410
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
411
- ],
393
+ // @visx/* ban dropped — `basalt/import-boundary` now bans it universally outside charts.
394
+ forbiddenImports: [...MANTINE_BANS],
412
395
  },
413
396
 
414
397
  './connectivity': {
@@ -456,17 +439,17 @@ export const SURFACES = {
456
439
  guardKinds: [],
457
440
  globs: {
458
441
  // Shipped is a catch-all (not just src/**+app/**) so consumer code under components/, lib/,
459
- // features/, etc. is also covered — the narrower re-allow overrides (./tokens, ./charts,
460
- // ./agent) still win for their globs because oxlint overrides are last-writer-wins and
461
- // EMIT_ORDER places #app first (see projectBanList doc comment in gen-oxlint.ts).
442
+ // features/, etc. is also covered. The @visx/*-only-in-charts and Mantine-free charts/tokens
443
+ // boundaries used to live here too and need last-writer-wins EMIT_ORDER games against the
444
+ // narrower ./tokens/./charts overrides — they're now enforced by `basalt/import-boundary`
445
+ // (a plugin rule, immune to that class of clobbering) instead, so the bans left below (antd,
446
+ // framer-motion) are plain global bans with no narrower override to out-order.
462
447
  shipped: ['**/*.{ts,tsx}'],
463
448
  repo: ['packages/basalt-ui/src/**', 'apps/playground/src/**'],
464
449
  },
465
450
  ruleOverrides: [{ rule: 'no-console', level: 'off', target: 'repo' }], // cli/bin/scripts, repo-local only
466
451
  forbiddenImports: [
467
452
  v('antd', 'Use Mantine — antd is not part of the basalt-ui stack.', { shippedOnly: true }),
468
- v('@visx/tooltip', 'Use ChartTooltip + TooltipHeader/Row/Body from {ctx}.'),
469
- vg('@visx/*', 'Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).'),
470
453
  v('framer-motion', "Import from 'motion/react', not the raw framer-motion package."),
471
454
  ],
472
455
  },
@@ -506,3 +489,36 @@ export const SKILL_NAMES = [
506
489
  .flatMap((s) => [...s.skill]),
507
490
  ),
508
491
  ] as const satisfies readonly SkillName[]
492
+
493
+ // ── Mantine-free-via-plugin membership ────────────────────────────────────────────────────────────
494
+
495
+ /**
496
+ * Headless SURFACES keys whose Mantine-free guarantee is enforced by the `basalt/import-boundary`
497
+ * oxlint plugin rule (`configs/oxlint-plugin.js`) instead of a `forbiddenImports` no-restricted-
498
+ * imports ban — the rule fires on `charts`/`tokens` path segments only, so ONLY these two surfaces
499
+ * qualify (every other headless surface still carries its Mantine ban in `forbiddenImports`).
500
+ *
501
+ * Membership alone does NOT satisfy the coverage check — `checkCoverage()`'s assertion 7 (and its
502
+ * test mirror) also require `hasImportBoundaryRuleRegistered` to hold, so a future removal of the
503
+ * plugin rule's registration still fails loudly instead of silently passing.
504
+ */
505
+ export const MANTINE_FREE_VIA_IMPORT_BOUNDARY: ReadonlySet<string> = new Set([
506
+ './charts',
507
+ './tokens',
508
+ ])
509
+
510
+ /**
511
+ * True when a parsed oxlint config's `rules` object registers `basalt/import-boundary` as `'error'`
512
+ * — the live signal (not just a hardcoded assumption) that `MANTINE_FREE_VIA_IMPORT_BOUNDARY`
513
+ * surfaces are actually enforced. Pure — callers read + JSON.parse the config file themselves
514
+ * (surfaces.ts stays dependency-free, no fs access here).
515
+ *
516
+ * @example
517
+ * hasImportBoundaryRuleRegistered({ 'basalt/import-boundary': 'error' }) // true
518
+ * hasImportBoundaryRuleRegistered({}) // false
519
+ */
520
+ export function hasImportBoundaryRuleRegistered(
521
+ rules: Record<string, unknown> | undefined,
522
+ ): boolean {
523
+ return rules?.['basalt/import-boundary'] === 'error'
524
+ }