basalt-ui 1.0.1 → 1.1.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.
package/dist/surfaces.js CHANGED
@@ -39,13 +39,11 @@ const SURFACES = {
39
39
  shipped: ["**/charts/**"],
40
40
  repo: ["packages/basalt-ui/src/charts/**"]
41
41
  },
42
- replaceBans: true,
43
- // @visx/* MUST NOT inherit from src/** (the re-allow). Full list emitted.
44
- forbiddenImports: [
45
- ...MANTINE_BANS,
46
- v("@visx/tooltip", "Use ChartTooltip + TooltipHeader/Row/Body from {ctx}.")
47
- // LOAD-BEARING ABSENCE: no @visx/* group ban here — charts uniquely permits @visx/*.
48
- ],
42
+ // The @visx/*-only-in-charts boundary is enforced by the `basalt/visx-boundary` oxlint plugin
43
+ // rule, and the Mantine-free boundary by `basalt/token-layer-boundary` (repo-local only — see
44
+ // that rule's file-header comment for why) — both configs/oxlint-plugin.js, not
45
+ // no-restricted-imports.
46
+ forbiddenImports: [],
49
47
  ruleOverrides: [{ rule: "no-underscore-dangle", level: "off", target: "repo" }]
50
48
  },
51
49
  "./tokens": {
@@ -59,11 +57,9 @@ const SURFACES = {
59
57
  shipped: ["**/tokens/**"],
60
58
  repo: ["packages/basalt-ui/src/tokens/**"]
61
59
  },
62
- forbiddenImports: [
63
- ...MANTINE_BANS,
64
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).")
65
- ]
66
- // shipped tokens override is MISSING today → this projection EMITS it (closes D2)
60
+ // Mantine-free boundary enforced by `basalt/token-layer-boundary`, repo-local only (see
61
+ // ./charts above and that rule's file-header comment for why).
62
+ forbiddenImports: []
67
63
  },
68
64
  "./theme-lab": {
69
65
  kind: "tooling",
@@ -85,10 +81,8 @@ const SURFACES = {
85
81
  shipped: [],
86
82
  repo: ["packages/basalt-ui/src/guard/**"]
87
83
  },
88
- forbiddenImports: [
89
- ...MANTINE_BANS,
90
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).")
91
- ]
84
+ // @visx/* ban dropped — `basalt/visx-boundary` now bans it universally outside charts.
85
+ forbiddenImports: [...MANTINE_BANS]
92
86
  },
93
87
  // 6th JS subpath
94
88
  "./query": {
@@ -103,10 +97,8 @@ const SURFACES = {
103
97
  shipped: [],
104
98
  repo: ["packages/basalt-ui/src/query/**"]
105
99
  },
106
- forbiddenImports: [
107
- ...MANTINE_BANS,
108
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).")
109
- ]
100
+ // @visx/* ban dropped — `basalt/visx-boundary` now bans it universally outside charts.
101
+ forbiddenImports: [...MANTINE_BANS]
110
102
  },
111
103
  "./router-tanstack": {
112
104
  kind: "doctrine",
@@ -120,10 +112,8 @@ const SURFACES = {
120
112
  shipped: [],
121
113
  repo: ["packages/basalt-ui/src/router-tanstack/**"]
122
114
  },
123
- forbiddenImports: [
124
- ...MANTINE_BANS,
125
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).")
126
- ]
115
+ // @visx/* ban dropped — `basalt/visx-boundary` now bans it universally outside charts.
116
+ forbiddenImports: [...MANTINE_BANS]
127
117
  },
128
118
  "./forms": {
129
119
  kind: "doctrine",
@@ -197,10 +187,8 @@ const SURFACES = {
197
187
  shipped: [],
198
188
  repo: ["packages/basalt-ui/src/agent/**"]
199
189
  },
200
- forbiddenImports: [
201
- ...MANTINE_BANS,
202
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).")
203
- ]
190
+ // @visx/* ban dropped — `basalt/visx-boundary` now bans it universally outside charts.
191
+ forbiddenImports: [...MANTINE_BANS]
204
192
  },
205
193
  "./content": {
206
194
  kind: "doctrine",
@@ -235,10 +223,8 @@ const SURFACES = {
235
223
  shipped: [],
236
224
  repo: ["packages/basalt-ui/src/state.ts"]
237
225
  },
238
- forbiddenImports: [
239
- ...MANTINE_BANS,
240
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx}).")
241
- ]
226
+ // @visx/* ban dropped — `basalt/visx-boundary` now bans it universally outside charts.
227
+ forbiddenImports: [...MANTINE_BANS]
242
228
  },
243
229
  "./connectivity": {
244
230
  kind: "doctrine",
@@ -279,9 +265,12 @@ const SURFACES = {
279
265
  guardKinds: [],
280
266
  globs: {
281
267
  // Shipped is a catch-all (not just src/**+app/**) so consumer code under components/, lib/,
282
- // features/, etc. is also covered — the narrower re-allow overrides (./tokens, ./charts,
283
- // ./agent) still win for their globs because oxlint overrides are last-writer-wins and
284
- // EMIT_ORDER places #app first (see projectBanList doc comment in gen-oxlint.ts).
268
+ // features/, etc. is also covered. The @visx/*-only-in-charts and Mantine-free charts/tokens
269
+ // boundaries used to live here too and need last-writer-wins EMIT_ORDER games against the
270
+ // narrower ./tokens/./charts overrides — they're now enforced by `basalt/visx-boundary` and
271
+ // `basalt/token-layer-boundary` (plugin rules, immune to that class of clobbering) instead,
272
+ // so the bans left below (antd, framer-motion) are plain global bans with no narrower
273
+ // override to out-order.
285
274
  shipped: ["**/*.{ts,tsx}"],
286
275
  repo: ["packages/basalt-ui/src/**", "apps/playground/src/**"]
287
276
  },
@@ -289,8 +278,6 @@ const SURFACES = {
289
278
  // cli/bin/scripts, repo-local only
290
279
  forbiddenImports: [
291
280
  v("antd", "Use Mantine \u2014 antd is not part of the basalt-ui stack.", { shippedOnly: true }),
292
- v("@visx/tooltip", "Use ChartTooltip + TooltipHeader/Row/Body from {ctx}."),
293
- vg("@visx/*", "Direct @visx/* imports are only allowed inside the charts boundary ({ctx})."),
294
281
  v("framer-motion", "Import from 'motion/react', not the raw framer-motion package.")
295
282
  ]
296
283
  }
@@ -305,8 +292,14 @@ const SKILL_NAMES = [
305
292
  Object.values(SURFACES).filter((s) => s.kind === "doctrine").flatMap((s) => [...s.skill])
306
293
  )
307
294
  ];
295
+ const TOKEN_LAYER_BOUNDARY_SURFACES = /* @__PURE__ */ new Set(["./charts", "./tokens"]);
296
+ function hasTokenLayerBoundaryRegistered(rules) {
297
+ return rules?.["basalt/token-layer-boundary"] === "error";
298
+ }
308
299
  export {
309
300
  RULE_NAMES,
310
301
  SKILL_NAMES,
311
- SURFACES
302
+ SURFACES,
303
+ TOKEN_LAYER_BOUNDARY_SURFACES,
304
+ hasTokenLayerBoundaryRegistered
312
305
  };
package/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # basalt-ui v1.0.1
1
+ # basalt-ui v1.1.0
2
2
  # Opinionated framework for Mantine-based React apps — theme, app shell, visx charts, toolchain presets
3
3
  #
4
4
  # basalt-ui is an opinionated framework for Mantine-based React apps.
@@ -15,7 +15,7 @@
15
15
  # Optional peers are listed per subpath; install only what you use.
16
16
 
17
17
  Package: basalt-ui
18
- Version: 1.0.1
18
+ Version: 1.1.0
19
19
 
20
20
  ## basalt-ui
21
21
  Import: import { ... } from 'basalt-ui'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, visx charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
package/src/cli/index.ts CHANGED
@@ -35,7 +35,7 @@ import { fileURLToPath } from 'node:url'
35
35
  import { checkSource, DEFAULT_GUARD_CONFIG, GUARD_RULES } from '../guard'
36
36
  import type { Finding, GuardConfig, GuardKind } from '../guard'
37
37
  import { evaluateGuardHook } from '../guard/guard-hook'
38
- import { RULE_NAMES, SKILL_NAMES, SURFACES } from '../surfaces'
38
+ import { RULE_NAMES, SKILL_NAMES, SURFACES, TOKEN_LAYER_BOUNDARY_SURFACES } from '../surfaces'
39
39
  import type { DoctrineSpec, SurfaceSpec } from '../surfaces'
40
40
 
41
41
  /** Shape of the optional `"basalt"` key in a consumer's package.json. */
@@ -755,32 +755,105 @@ function unitState(file: ManagedFile, cwd: string, ctx: RenderContext): UnitStat
755
755
  return { current: onDisk, desired }
756
756
  }
757
757
 
758
- /** Write a managed unit to disk (whole file, or marker-spliced region). Returns the unit's hash. */
758
+ type Classification = 'unchanged' | 'drifted' | 'missing' | 'current'
759
+
760
+ /**
761
+ * Normalize a managed unit's rendered bytes for the ledger comparison below — makes a delta that is
762
+ * PURELY formatting or a version bump invisible to drift detection, while a real prose/content edit
763
+ * stays fully visible:
764
+ *
765
+ * - Blank out the per-release `BASALT_VERSION` token in a marker's begin line
766
+ * (`<!-- basalt:begin 1.0.1 -->` → `<!-- basalt:begin -->`). It changes on every release and is
767
+ * the only per-release variable that lands INSIDE the hashed region (the rest of
768
+ * `CLAUDE-block.md.tpl` has no other `{{…}}` placeholders today), so stripping it is what lets
769
+ * one normalized rendering stand in for every version of a given template body instead of
770
+ * needing one ledger entry per release. If a future marker template interpolates another
771
+ * per-release var inside its region, extend this normalization the same way.
772
+ * - Trim trailing whitespace per line and collapse every run of blank lines to none. This is the
773
+ * fix for the actual argo repro: lefthook's oxfmt reformats a spliced block (or a whole managed
774
+ * file) AFTER `writeUnit` has already exited and the manifest hash was recorded, so the manifest
775
+ * can never account for the reformat up front — normalizing it away here is the only place that
776
+ * can.
777
+ *
778
+ * Deliberately whitespace-only — word content is untouched, so a genuine hand-edit inside the block
779
+ * still changes the normalized text and still classifies `drifted`.
780
+ */
781
+ function normalizeForLedger(text: string): string {
782
+ return text
783
+ .replace(/(<!-- basalt:begin)\s+\S+(\s*-->)/, '$1$2')
784
+ .split('\n')
785
+ .map((line) => line.replace(/[ \t]+$/, ''))
786
+ .join('\n')
787
+ .replace(/\n{2,}/g, '\n')
788
+ .trim()
789
+ }
790
+
791
+ /**
792
+ * Write a managed unit to disk (whole file, or marker-spliced region). Returns the unit's hash —
793
+ * `sha256(normalizeForLedger(desired))`, NOT the raw bytes.
794
+ *
795
+ * This is the ledger: the manifest already records "what basalt shipped last sync", one entry per
796
+ * dest — a stored NORMALIZED hash makes that same single entry survive both a downstream formatter
797
+ * (the consumer's own lefthook oxfmt reformatting the written file/block after this function has
798
+ * already returned) and a version bump that changed the template's own words since the recorded
799
+ * entry — the argo cross-version case: current is v1.0.0's block, post-oxfmt; desired is v1.0.1's
800
+ * (different words, e.g. the CLI bin rename). Recording the raw hash can never reconcile that;
801
+ * recording the normalized hash lets `classify()` normalize `state.current` the same way and
802
+ * compare directly against it, no separate historical-hash storage required.
803
+ */
759
804
  function writeUnit(file: ManagedFile, cwd: string, desired: string): string {
760
805
  const destAbs = resolve(cwd, file.dest)
761
806
  if (file.markers) {
762
807
  const host = readIfExists(destAbs) ?? ''
763
808
  writeFileEnsuringDir(destAbs, applyBlock(host, desired))
764
- return sha256(desired)
809
+ } else {
810
+ writeFileEnsuringDir(destAbs, desired)
765
811
  }
766
- writeFileEnsuringDir(destAbs, desired)
767
- return sha256(desired)
812
+ return sha256(normalizeForLedger(desired))
768
813
  }
769
814
 
770
- type Classification = 'unchanged' | 'drifted' | 'missing' | 'current'
771
-
772
815
  /**
773
816
  * Classify a managed file against the manifest for a sync run.
774
817
  * - missing : the managed unit is absent on disk → recreate.
775
818
  * - current : on disk == desired → nothing to do.
776
- * - unchanged: on disk == manifest hash (untouched since last sync) but != desired → safe overwrite.
777
- * - drifted : on disk != manifest hash AND != desired (locally edited) → skip unless --force.
819
+ * - unchanged: on disk matches a KNOWN-SHIPPED rendering of this template, checked three ways (any
820
+ * one is sufficient) — but != desired as-is → safe overwrite:
821
+ * 1. `sha256(current) === manifestHash` — legacy raw-hash path. An existing consumer
822
+ * manifest (written before this fix, or by a still-running older CLI) holds the RAW
823
+ * hash of what was written, not the normalized one; keep matching it directly so an
824
+ * upgrade never mass-classifies a pristine tree as drifted.
825
+ * Residual transitional gap: a manifest written by a pre-1.0.2 CLI holds a raw hash
826
+ * of the exact old bytes, so if the on-disk block was ALSO reformatted by a
827
+ * downstream formatter AND the template body changed cross-version in the same
828
+ * upgrade, none of the three paths above match and it classifies `drifted`, needing
829
+ * one `--force`. Once any sync since writes a normalized entry (path 2/3 or a
830
+ * healed write), the gap is closed for good for that file. Deliberately not solved
831
+ * by keeping a historical per-version ledger — that's a real but bounded tradeoff.
832
+ * 2. `sha256(normalizeForLedger(current)) === manifestHash` — the ledger proper.
833
+ * `manifestHash` normally holds `sha256(normalizeForLedger(<bytes written at the
834
+ * last sync>))` (see `writeUnit`); normalizing `current` the same way and comparing
835
+ * survives a downstream formatter reformatting the file AND a version bump that
836
+ * changed the template's own words between the sync that wrote this manifest entry
837
+ * and the version being synced now — the argo cross-version false positive.
838
+ * 3. `normalizeForLedger(current) === normalizeForLedger(desired)` — same-version
839
+ * fallback for when there is no manifest entry to compare against at all (e.g. it
840
+ * was dropped), but the on-disk bytes still match today's rendering modulo
841
+ * formatting noise.
842
+ * - drifted : on disk matches NONE of the above (a real, word-level local edit) → skip unless
843
+ * --force.
778
844
  */
779
845
  function classify(state: UnitState, manifestHash: string | undefined): Classification {
780
846
  if (state.current === null) return 'missing'
781
847
  if (state.desired !== null && state.current === state.desired) return 'current'
782
848
  const currentHash = sha256(state.current)
783
849
  if (currentHash === manifestHash) return 'unchanged'
850
+ if (sha256(normalizeForLedger(state.current)) === manifestHash) return 'unchanged'
851
+ if (
852
+ state.desired !== null &&
853
+ normalizeForLedger(state.current) === normalizeForLedger(state.desired)
854
+ ) {
855
+ return 'unchanged'
856
+ }
784
857
  return 'drifted'
785
858
  }
786
859
 
@@ -821,10 +894,11 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
821
894
  // inserts/updates itself inside its host file.
822
895
  const destExists = existsSync(resolve(cwd, file.dest))
823
896
  if (!file.markers && destExists) {
824
- // Already present — keep the consumer's copy untouched. Record the SHIPPED hash so a later
825
- // sync treats a pre-existing-but-different file as locally drifted (skip unless --force),
826
- // never silently clobbering a file the consumer authored before init.
827
- manifest.files[file.dest] = sha256(state.desired)
897
+ // Already present — keep the consumer's copy untouched. Record the SHIPPED hash (normalized,
898
+ // same ledger form `writeUnit` uses) so a later sync treats a pre-existing-but-different file
899
+ // as locally drifted (skip unless --force), never silently clobbering a file the consumer
900
+ // authored before init.
901
+ manifest.files[file.dest] = sha256(normalizeForLedger(state.desired))
828
902
  skipped++
829
903
  continue
830
904
  }
@@ -921,7 +995,10 @@ export function sync(opts: SyncOptions = {}, cwd: string = process.cwd()): numbe
921
995
  const kind = classify(state, manifest.files[file.dest])
922
996
 
923
997
  if (kind === 'current') {
924
- manifest.files[file.dest] = sha256(state.desired)
998
+ // On-disk bytes already equal `desired` exactly — record the ledger's normalized form
999
+ // (not the raw bytes) so this entry keeps behaving like every other `writeUnit`-recorded
1000
+ // hash for a future classify() call.
1001
+ manifest.files[file.dest] = sha256(normalizeForLedger(state.desired))
925
1002
  continue
926
1003
  }
927
1004
 
@@ -986,7 +1063,12 @@ export function sync(opts: SyncOptions = {}, cwd: string = process.cwd()): numbe
986
1063
  * 4. Every non-#, non-'.' JS-subpath SURFACES key has a package.json exports entry.
987
1064
  * 5. Every real package.json exports key has a SURFACES entry.
988
1065
  * 6. Every surface with non-empty forbiddenImports has a globs field.
989
- * 7. Every headless surface carries all 3 Mantine bans (Mantine-free boundary).
1066
+ * 7. Every headless surface is Mantine-free — via all 3 `forbiddenImports` bans, OR (for
1067
+ * `TOKEN_LAYER_BOUNDARY_SURFACES` members, `./charts`/`./tokens`) exemption, since their
1068
+ * Mantine-free guarantee is covered by the repo-local-only `basalt/token-layer-boundary`
1069
+ * plugin rule instead — this assertion cannot verify that rule's live registration itself (see
1070
+ * the assertion's own comment below for why); basalt's own CI does
1071
+ * (`tests/surfaces-coverage.test.ts`).
990
1072
  * 8. Every doctrine optionalPeers entry exists in peerDependencies AND peerDependenciesMeta.
991
1073
  *
992
1074
  * Tooling surfaces are exempt from assertions 1–3 by the discriminant.
@@ -1079,11 +1161,25 @@ export function checkCoverage(): number {
1079
1161
  }
1080
1162
  }
1081
1163
 
1082
- // ── Assertion 7: every headless surface carries all 3 Mantine bans ───────────
1083
- // Guarantees the Mantine-free boundary — a future headless surface without bans fails here.
1164
+ // ── Assertion 7: every headless surface is Mantine-free ──────────────────────
1165
+ // Guarantees the Mantine-free boundary — a future headless surface without coverage fails here.
1166
+ // Coverage is either all 3 forbiddenImports bans, OR membership in
1167
+ // `TOKEN_LAYER_BOUNDARY_SURFACES` (`./charts`/`./tokens`), whose Mantine-free guarantee comes
1168
+ // from the `basalt/token-layer-boundary` plugin rule instead — protects both layering (tokens
1169
+ // upstream of Mantine) and packaging (those two subpaths resolve with no `@mantine/*` installed,
1170
+ // CI-tested via `scripts/pack-test.sh` + `scripts/check-dist-layering.mjs`; see surfaces.ts's
1171
+ // `TOKEN_LAYER_BOUNDARY_SURFACES` doc comment). This assertion CANNOT also verify
1172
+ // that rule's live registration: `check-coverage` is a shipped CLI subcommand whose assertions
1173
+ // must all read pkgRoot-relative paths so it works from inside a consumer's node_modules — and a
1174
+ // repo-local `.oxlintrc.json` read from an installed package path-resolves to the CONSUMER's own
1175
+ // config, not basalt's. That "fails loudly if enforcement is removed" guarantee lives in
1176
+ // basalt's own CI instead (`tests/surfaces-coverage.test.ts`, via
1177
+ // `hasTokenLayerBoundaryRegistered` against `.oxlintrc.json`).
1084
1178
  const REQUIRED_MANTINE_BANS = ['@mantine/core', '@mantine/hooks', '@mantine/*'] as const
1179
+
1085
1180
  for (const [key, spec] of allSpecs) {
1086
1181
  if (spec.layer !== 'headless') continue
1182
+ if (TOKEN_LAYER_BOUNDARY_SURFACES.has(key)) continue
1087
1183
  for (const required of REQUIRED_MANTINE_BANS) {
1088
1184
  const hasBan = spec.forbiddenImports.some((fi) => fi.spec === required)
1089
1185
  if (!hasBan) {
@@ -1531,5 +1627,7 @@ export function run(argv: string[], cwd: string = process.cwd()): number | Promi
1531
1627
  }
1532
1628
 
1533
1629
  // Re-export the managed-file manifest for testing / introspection (no default export).
1534
- export { managedFiles, MANIFEST_PATH, RULE_NAMES, SKILL_NAMES }
1630
+ // `normalizeForLedger` is exported so tests can compute a fixture's expected ledger hash without
1631
+ // duplicating the normalization algorithm — it stays call-site-internal to writeUnit/classify.
1632
+ export { managedFiles, MANIFEST_PATH, normalizeForLedger, RULE_NAMES, SKILL_NAMES }
1535
1633
  export type { ManagedFile, Manifest, SyncOptions, DoctorResult }
@@ -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
+ })