@sssb/tools 0.0.0 → 0.3.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +116 -0
  3. package/package.json +89 -5
  4. package/src/app-port.js +77 -0
  5. package/src/app.js +142 -0
  6. package/src/assembly-checks.d.ts +57 -0
  7. package/src/assembly-checks.js +259 -0
  8. package/src/commands/add-app.js +344 -0
  9. package/src/commands/check-demo-size.js +80 -0
  10. package/src/commands/check-doc-paths.js +48 -0
  11. package/src/commands/check-e2e.js +611 -0
  12. package/src/commands/check-fences.js +51 -0
  13. package/src/commands/check-real-env.js +165 -0
  14. package/src/commands/check-tmpdir-leak.js +78 -0
  15. package/src/commands/ci.js +350 -0
  16. package/src/commands/dev-tick.js +25 -0
  17. package/src/commands/doctor-checks.js +1396 -0
  18. package/src/commands/doctor-settings.js +583 -0
  19. package/src/commands/doctor-vitest.js +262 -0
  20. package/src/commands/doctor.js +1033 -0
  21. package/src/commands/e2e-profile.js +94 -0
  22. package/src/commands/guide.js +108 -0
  23. package/src/commands/launch-json.js +55 -0
  24. package/src/commands/pin.js +411 -0
  25. package/src/commands/port.js +22 -0
  26. package/src/commands/remove-items.js +191 -0
  27. package/src/commands/serve-standalone.js +78 -0
  28. package/src/commands/tick.js +27 -0
  29. package/src/doc-paths.d.ts +106 -0
  30. package/src/doc-paths.js +328 -0
  31. package/src/framework-guard.js +35 -0
  32. package/src/kit.d.ts +49 -0
  33. package/src/kit.js +216 -0
  34. package/src/next.d.ts +16 -0
  35. package/src/next.js +55 -0
  36. package/src/ports.d.ts +72 -0
  37. package/src/ports.js +307 -0
  38. package/src/prune-mantine-css.js +171 -0
  39. package/src/remove-items/code.patch +798 -0
  40. package/src/remove-items/database.patch +218 -0
  41. package/src/remove-items/exact-patch.js +122 -0
  42. package/src/testing/tmp-dir-marker.js +9 -0
  43. package/src/testing/tmp-dir-setup.d.ts +2 -0
  44. package/src/testing/tmp-dir-setup.js +9 -0
  45. package/src/testing/tmp-dir.d.ts +20 -0
  46. package/src/testing/tmp-dir.js +174 -0
  47. package/src/tick/dev-tick.js +128 -0
  48. package/src/tick/tick.js +317 -0
  49. package/src/tick/ticker-marker.d.ts +17 -0
  50. package/src/tick/ticker-marker.js +83 -0
  51. package/src/tick/ticker.d.ts +36 -0
  52. package/src/tick/ticker.js +142 -0
  53. package/src/vite.d.ts +38 -0
  54. package/src/vite.js +64 -0
  55. package/src/vitest.d.ts +38 -0
  56. package/src/vitest.js +82 -0
  57. package/tsconfig.base.json +33 -0
  58. package/README.md +0 -3
@@ -0,0 +1,1033 @@
1
+ // @ts-check
2
+ // `sssb doctor [--app <dir>]`: the checks that a workspace's installed SSSB is the one it was built and tested as
3
+ // (ADR-0014 part 5), and that SSSB's conformance suite would actually run (part 3). ONE RUN CHECKS THE WHOLE
4
+ // WORKSPACE: it walks pnpm-workspace.yaml for every importer of @sssb/kit and every APP (in-repo, the apps the
5
+ // workspace's commands fan out over, `sssb.apps` or apps/*; otherwise every importer with a seam of its own,
6
+ // `src/app-config`), and gives each app the per-app checks, the one it runs for (`--app`, or the working directory)
7
+ // among them. WHERE IT STARTS: `--app <dir>`, or the working directory when it resolves @sssb/kit (an app, or an
8
+ // in-repo root), or, at the root of a workspace whose root takes no @sssb/kit (a generated workspace's), the
9
+ // workspace's first app; the walk then also has to reach every app the workspace names, so starting from the first
10
+ // finds what starting from any other would. It fails, naming every problem, on:
11
+ //
12
+ // - FIRST, and alone: a layout pnpm installed with a `nodeLinker` other than `isolated` (`pnp`, `hoisted`), or a
13
+ // `.pnp.cjs` at the root or in doctor's own NODE_OPTIONS, which the checks below are not built for, and under which
14
+ // (Plug'n'Play) Vitest's listing never finishes;
15
+ // - a workspace walk that cannot read pnpm-workspace.yaml, or that does not reach the app doctor runs for (or, when it
16
+ // chose its own start, any app the workspace names);
17
+ // - two copies of a singleton: a peer of @sssb/kit found from the kit's directory and from an app's must be ONE
18
+ // real directory (the `readlink -f` check build-notes tells a dependency PR to run by hand);
19
+ // - an importer of @sssb/kit, anywhere in the workspace, without its own seam: it must declare its
20
+ // `@sssb/app-config` link, and the instance it resolves must have that very seam linked (in-repo mode, where the
21
+ // seam goes through aliases instead, every tsconfig `paths` entry and every Vitest alias that would resolve the
22
+ // seam for an app must send it into that app's own);
23
+ // - an @sssb/* package an app resolves at another version than its @sssb/kit;
24
+ // - an app's port declaration (`"sssb": { "port": … }`) that is not valid, two apps that declare one port slot, or two
25
+ // custom slots with one default port: their dev servers and e2e runs would bind one port (portSlotProblems);
26
+ // - a check of the conformance suite that would not run, unless the app opted out of it by name in its own suite
27
+ // file: the MAIN unit run (the config a bare `vitest` would load for the app: the root's when it runs the app's
28
+ // `src/` tests, else the one Vitest finds walking up from the app, else Vitest's defaults there) must list every
29
+ // unit check from the app's own `src/sssb.conformance.test.ts`; some config that runs its `tests/contract/` files
30
+ // must list every contract check from them;
31
+ // - an app guide copy that is stale against the guide the kit ships (`sssb guide --check`), once the kit ships one;
32
+ // in-repo, only once the repository holds a copy (SSSB's own repo, where the kit's guide is the source).
33
+ //
34
+ // It REPORTS, without failing: every other Vitest config (`vitest*.config.*` at the root or in an app) that runs some of
35
+ // an app's `src/` tests but not its suite, or its `tests/contract/` files without listing every contract check, or that
36
+ // doctor cannot list (any of them CI might run instead); a bare `vitest` from the app's directory, when the root's is
37
+ // the main run, that would not run the app's suite (even one that runs none of its tests); each opt-out with its reason; the flags and file filters the root's and the apps'
38
+ // package.json scripts pass to vitest (doctor proves what each configuration would run, never what a CI step's own
39
+ // command line adds); which script runs each app's contract config (doctor lists the contract checks, it never runs
40
+ // them); `dedupePeerDependents: false` missing from pnpm-workspace.yaml (advice); framework cutover rows the
41
+ // workspace's checklist never mentions; an app, or an app's seam package, that the root's knip JSON config (`knip.json`, `knip.jsonc`, `.knip.json` or
42
+ // `.knip.jsonc`) gives no workspace, and a root `@sssb/create` that knip would call unused; and the commits the workspace pins SSSB's reusable workflow and the plugin's
43
+ // marketplace at (`.github/workflows/*.yml`, `.claude/settings.json`), against the release commit the installed
44
+ // @sssb/kit stamps into its package (`dist/release.json`), naming both commits where they differ; and the adopter's own
45
+ // settings (doctor-settings.js): on the workspace's GitHub repository, read-only through `gh`, whether `sssb /
46
+ // all-checks` is a required check on the default branch, private vulnerability reporting is on, and, for a private
47
+ // repository in an organization, its Actions policy lets it call SSSB's reusable workflow, and whether the plugin
48
+ // `.claude/settings.json` enables is installed on this machine. A `gh` that is missing, signed out, offline or refused
49
+ // reads "not checked", with the reason; none of it runs when `CI` is set.
50
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
51
+ import { createRequire } from 'node:module'
52
+ import path from 'node:path'
53
+ import { readJson, takeAppDir, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
54
+ import { kitDirOf, kitVersionOf, resolveAppsKit } from '../kit.js'
55
+ import {
56
+ aliasProblems,
57
+ areaOf,
58
+ cutoverReport,
59
+ discoverWorkspace,
60
+ githubRepositoryOf,
61
+ importerSeamProblems,
62
+ kitPeers,
63
+ knipGaps,
64
+ missingTests,
65
+ nodeLinkerProblem,
66
+ ownTests,
67
+ packageDirFrom,
68
+ parseWorkspaceYaml,
69
+ pinReport,
70
+ portSlotProblems,
71
+ PROBE,
72
+ realish,
73
+ singletonProblems,
74
+ sssbPackagesOf,
75
+ versionProblems,
76
+ vitestInvocations,
77
+ } from './doctor-checks.js'
78
+ import { settingsReports } from './doctor-settings.js'
79
+ import {
80
+ projectsRunning,
81
+ runKey,
82
+ seamAliases,
83
+ vitestDefaultConfig,
84
+ vitestList,
85
+ vitestRunsFor,
86
+ } from './doctor-vitest.js'
87
+
88
+ const SEAM = '@sssb/app-config'
89
+ const RUNNERS = /** @type {const} */ (['unit', 'contract'])
90
+
91
+ /** @typedef {{ status: 'ok' | 'FAIL' | 'report' | 'advice', title: string, lines?: string[] }} Result */
92
+ /** @typedef {ReturnType<typeof discoverWorkspace>} Workspace */
93
+ /** @typedef {import('./doctor-vitest.js').VitestRun} VitestRun */
94
+ /** @typedef {import('./doctor-checks.js').SeamRoute} SeamRoute */
95
+ /** @typedef {Map<string, ReturnType<typeof vitestList>>} VitestCache each `vitest list`, by cwd, config and selection */
96
+ /** @typedef {{ run: VitestRun, projects: string[] }} Selected a Vitest run, and the projects in it to list (none: all) */
97
+ /**
98
+ * @typedef {object} Plan which runs hold an app to which checks (planFor)
99
+ * @property {Selected | null} main the MAIN unit run: the first run a bare `vitest` would make for the app that runs
100
+ * any of its `src/` test files
101
+ * @property {VitestRun[]} tried the bare runs tried for it, in order
102
+ * @property {string[]} mainErrors a bare run doctor could not list before it found the main one
103
+ * @property {{ run: VitestRun, files: number, bare: boolean }[]} partial other configs that run some of the app's
104
+ * `src/` test files and not its `src/sssb.conformance.test.ts`, and the bare runs past the main one (`bare`) that do
105
+ * not run it, even running none of those files
106
+ * @property {Selected[]} contract every config that runs any of the app's `tests/contract/` files
107
+ * @property {{ run: VitestRun, error: string }[]} unlisted other configs doctor could not list
108
+ * @property {string[]} nested the workspace packages inside the app, whose files are not the app's
109
+ */
110
+
111
+ /**
112
+ * The app doctor runs for, and whether it was chosen for the person. Doctor checks the whole workspace from any of its
113
+ * apps, so the short form has to work where people type it, the root: with no `--app`, a working directory that
114
+ * resolves `@sssb/kit` is the app (as before), and a workspace root that does not (a generated workspace's root takes
115
+ * no framework) starts from the workspace's first app.
116
+ * @param {string[]} args
117
+ * @param {string} [cwd]
118
+ * @returns {{ dir: string, defaulted: boolean, named: string[] }} `named`: when doctor chose the app, every app the
119
+ * workspace names (absolute), which the walk must all reach: the person did not name one to hold it to
120
+ */
121
+ export function doctorApp(args, cwd = process.cwd()) {
122
+ if (args.includes('--app')) return { dir: takeAppDir(args, cwd), defaulted: false, named: [] }
123
+ const here = path.resolve(cwd)
124
+ if (existsSync(path.join(here, 'package.json')) && packageDirFrom(here, '@sssb/kit') !== null) {
125
+ return { dir: here, defaulted: false, named: [] }
126
+ }
127
+ if (existsSync(path.join(here, 'pnpm-workspace.yaml')) && existsSync(path.join(here, 'package.json'))) {
128
+ const apps = workspaceApps(here)
129
+ if (apps.length === 0) {
130
+ throw new UsageError(
131
+ `sssb doctor: ${here} is a workspace root that takes no @sssb/kit and has no apps (\`sssb.apps\` in its ` +
132
+ 'package.json, or apps/<name>): pass --app <dir>',
133
+ )
134
+ }
135
+ return { dir: path.resolve(here, apps[0]), defaulted: true, named: apps.map((a) => path.resolve(here, a)) }
136
+ }
137
+ // Neither: the usual refusal, which says to run from an app or pass --app.
138
+ return { dir: takeAppDir(args, cwd), defaulted: false, named: [] }
139
+ }
140
+
141
+ /** @param {string[]} args */
142
+ export async function run(args) {
143
+ const chosen = doctorApp(args)
144
+ const appDir = realpathSync(chosen.dir)
145
+ if (args.length > 0) throw new UsageError(`sssb doctor: unknown argument ${args[0]} (usage: doctor [--app <dir>])`)
146
+ const root = realpathSync(workspaceRootOf(appDir))
147
+ const rel = relativeTo(root)
148
+ // Said before anything can fail on the app it chose, so a failure there is read with the reason it was picked.
149
+ if (chosen.defaulted) {
150
+ console.log(
151
+ `sssb doctor: no --app, and the working directory (${root}) takes no @sssb/kit: starting from ${rel(appDir)}. One run checks every app of the workspace.`,
152
+ )
153
+ }
154
+ // First: under another layout nothing below holds, and under Plug'n'Play (`.pnp.cjs` in NODE_OPTIONS) Vitest's
155
+ // listing never finishes until the limit stops it.
156
+ const layout = nodeLinkerProblem(root)
157
+ if (layout !== null) {
158
+ console.log(`sssb doctor: ${rel(appDir)}`)
159
+ return print([{ status: 'FAIL', title: `installed layout: ${layout}. Nothing else is checked until it is` }])
160
+ }
161
+ const kitDir = kitDirOf(appDir)
162
+ const version = kitVersionOf(appDir)
163
+ const heading = `sssb doctor: ${rel(appDir)}, @sssb/kit ${version} at ${rel(kitDir)}`
164
+
165
+ /** @type {Workspace} */
166
+ let workspace
167
+ try {
168
+ workspace = discoverWorkspace(root, kitDir)
169
+ } catch (error) {
170
+ if (!(error instanceof UsageError)) throw error
171
+ console.log(heading)
172
+ return print([
173
+ {
174
+ status: 'FAIL',
175
+ title: `workspace walk: ${error.message.replace(/^sssb: /, '')}. Nothing else is checked until doctor can walk the workspace`,
176
+ },
177
+ ])
178
+ }
179
+ const { inRepo, apps } = workspace
180
+ console.log(
181
+ heading +
182
+ (inRepo
183
+ ? ' (in-repo mode: the kit is a package of this workspace, so the seam goes through aliases, not a link)'
184
+ : ''),
185
+ )
186
+
187
+ /** @type {VitestCache} */
188
+ const cache = new Map()
189
+ /** @type {Map<string, Plan>} */
190
+ const plans = new Map()
191
+ for (const app of apps) plans.set(app, planFor(root, app, nestedIn(workspace.packages, app), cache))
192
+ const targets = [...new Set([appDir, ...apps])]
193
+
194
+ /** @type {Result[]} */
195
+ const results = [
196
+ walk(
197
+ root,
198
+ appDir,
199
+ workspace,
200
+ chosen.named.map((dir) => realpathSync(dir)),
201
+ ),
202
+ ...targets.map((target) => singletons(root, target)),
203
+ inRepo ? await inRepoAliases(root, workspace, plans) : importers(root, workspace),
204
+ ...targets.map((target) => versions(root, target)),
205
+ portSlots(root, apps),
206
+ ...apps.flatMap((app) => RUNNERS.flatMap((runner) => conformance(root, app, runner, plans, cache))),
207
+ ...commandLines(root, appDir, apps, plans),
208
+ ...(await guides(root, apps, inRepo)),
209
+ pins(root, kitDir, version, inRepo),
210
+ dedupeAdvice(root, inRepo),
211
+ cutover(root, appDir),
212
+ ...knip(root, apps, workspace.packages),
213
+ ...settings(root, kitDir),
214
+ ]
215
+ return print(results)
216
+ }
217
+
218
+ /** @param {string} root */
219
+ const relativeTo = (root) => (/** @type {string} */ dir) => path.relative(root, dir) || '(the workspace root)'
220
+
221
+ /**
222
+ * @param {Result[]} results
223
+ * @returns {number} the exit code
224
+ */
225
+ function print(results) {
226
+ let problems = 0
227
+ for (const { status, title, lines = [] } of results) {
228
+ console.log(`${status.padEnd(7)} ${title}`)
229
+ for (const line of lines) console.log(` ${status === 'FAIL' ? '- ' : ''}${line}`)
230
+ if (status === 'FAIL') problems += Math.max(lines.length, 1)
231
+ }
232
+ console.log(problems === 0 ? 'sssb doctor: ok' : `sssb doctor: ${problems} problem(s)`)
233
+ return problems === 0 ? 0 : 1
234
+ }
235
+
236
+ /**
237
+ * @param {string} title
238
+ * @param {string[]} problems
239
+ * @param {string[]} [notes]
240
+ * @returns {Result}
241
+ */
242
+ const verdict = (title, problems, notes = []) =>
243
+ problems.length > 0 ? { status: 'FAIL', title, lines: problems } : { status: 'ok', title, lines: notes }
244
+
245
+ /**
246
+ * The workspace packages strictly inside `app` (a root-level app's apps/*), real paths. The app's own seam,
247
+ * `src/app-config`, is a workspace package too (so pnpm keeps it linked), but its files, tests included, are the app's.
248
+ * @param {readonly string[]} packages
249
+ * @param {string} app
250
+ */
251
+ const nestedIn = (packages, app) =>
252
+ packages
253
+ .map((dir) => realpathSync(dir))
254
+ .filter((dir) => dir !== app && dir.startsWith(app + path.sep) && dir !== path.join(app, 'src', 'app-config'))
255
+
256
+ /**
257
+ * PORT SLOTS: each app of the workspace binds a port of its own (see portSlotProblems).
258
+ * @param {string} root
259
+ * @param {readonly string[]} apps
260
+ * @returns {Result}
261
+ */
262
+ function portSlots(root, apps) {
263
+ const { problems, slots } = portSlotProblems(root, apps)
264
+ return verdict('port slots: no two apps bind one port', problems, slots)
265
+ }
266
+
267
+ /**
268
+ * THE WALK REACHES THE APP: what every workspace-wide check below covers is what the walk found, so an app it missed
269
+ * (a pnpm-workspace.yaml glob that does not cover it, a manifest that does not declare @sssb/kit) would pass every
270
+ * one of them unexamined. Doctor's own app must be among the importers, and, when it has a seam, among the apps.
271
+ * @param {string} root
272
+ * @param {string} appDir
273
+ * @param {Workspace} workspace
274
+ * @param {string[]} [named] the apps the workspace names, when doctor chose its own start: each must be reached too,
275
+ * or the bare form would pass a workspace whose walk drops an app that `--app <it>` would fail
276
+ * @returns {Result}
277
+ */
278
+ function walk(root, appDir, workspace, named = []) {
279
+ const rel = relativeTo(root)
280
+ const importerDirs = workspace.importers.map(({ dir }) => dir)
281
+ const importers = importerDirs.map(rel).join(', ') || 'none'
282
+ const apps = workspace.apps.map(rel).join(', ') || 'none'
283
+ /** @type {string[]} */
284
+ const problems = []
285
+ if (!importerDirs.includes(appDir))
286
+ problems.push(
287
+ `${rel(appDir)} is not among the importers of @sssb/kit the walk found (${importers}): check pnpm-workspace.yaml's ` +
288
+ `packages globs, and that ${rel(appDir)}'s package.json declares @sssb/kit`,
289
+ )
290
+ if (existsSync(path.join(appDir, 'src', 'app-config')) && !workspace.apps.includes(appDir))
291
+ problems.push(
292
+ `${rel(appDir)} has a seam (src/app-config) but is not among the apps the walk found (${apps})` +
293
+ (workspace.inRepo ? ": in-repo, the apps are the root package.json's sssb.apps, or apps/*" : ''),
294
+ )
295
+ /** @type {string[]} */
296
+ const unreached = []
297
+ for (const dir of named) {
298
+ if (dir === appDir) continue
299
+ if (!importerDirs.includes(dir) || !workspace.apps.includes(dir)) {
300
+ unreached.push(
301
+ `${rel(dir)} is named by the workspace (\`sssb.apps\`, or apps/*) but the walk does not reach it as an app that ` +
302
+ `takes @sssb/kit (importers: ${importers}; apps: ${apps}): check pnpm-workspace.yaml's packages globs, and that ` +
303
+ `${rel(dir)}'s package.json declares @sssb/kit`,
304
+ )
305
+ }
306
+ }
307
+ if (problems.length === 0 && unreached.length > 0) {
308
+ return {
309
+ status: 'FAIL',
310
+ title: 'workspace walk: it does not reach every app the workspace names, so the checks below do not cover them',
311
+ lines: unreached,
312
+ }
313
+ }
314
+ return problems.length > 0
315
+ ? {
316
+ status: 'FAIL',
317
+ title: `workspace walk: it does not reach ${rel(appDir)}, the app doctor runs for, so the checks below do not cover it`,
318
+ lines: [...problems, ...unreached],
319
+ }
320
+ : {
321
+ status: 'ok',
322
+ title: `workspace walk: ${workspace.packages.length} package(s) from pnpm-workspace.yaml; importers of @sssb/kit: ${importers}; apps: ${apps}`,
323
+ }
324
+ }
325
+
326
+ /**
327
+ * @param {string} root
328
+ * @param {string} target
329
+ * @returns {Result}
330
+ */
331
+ function singletons(root, target) {
332
+ const name = relativeTo(root)(target)
333
+ let kitDir
334
+ try {
335
+ kitDir = kitDirOf(target)
336
+ } catch (error) {
337
+ return { status: 'FAIL', title: `${name}: one copy of each singleton`, lines: [messageOf(error)] }
338
+ }
339
+ const { peers, optional } = kitPeers(kitDir)
340
+ const { problems, notes, same } = singletonProblems({
341
+ peers,
342
+ optional,
343
+ fromKit: (peer) => packageDirFrom(/** @type {string} */ (kitDir), peer),
344
+ fromApp: (peer) => packageDirFrom(target, peer),
345
+ })
346
+ return verdict(
347
+ problems.length > 0
348
+ ? `${name}: one copy of each singleton: it and its @sssb/kit do not share every peer`
349
+ : `${name}: one copy of each singleton: ${same.join(', ') || 'no peer'}`,
350
+ problems,
351
+ notes,
352
+ )
353
+ }
354
+
355
+ /** @param {unknown} error */
356
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error))
357
+
358
+ /**
359
+ * @param {string} root
360
+ * @param {Workspace} workspace
361
+ * @returns {Result}
362
+ */
363
+ function importers(root, workspace) {
364
+ const { problems, importers: found } = importerSeamProblems(root, kitDirOf, workspace.importers, workspace.packages)
365
+ return verdict(
366
+ problems.length > 0
367
+ ? 'one SSSB per importer, with its own seam: an importer of @sssb/kit runs on a seam not its own'
368
+ : `one SSSB per importer, with its own seam: ${found.join(', ') || 'no importer'}`,
369
+ problems,
370
+ )
371
+ }
372
+
373
+ /**
374
+ * In-repo mode's check, over every app of the workspace: every tsconfig `paths` entry, and every alias of every Vitest
375
+ * project that holds the app to checks (its main unit run's, and every contract config's), that would resolve the seam
376
+ * sends it into the app's own.
377
+ * @param {string} root
378
+ * @param {Workspace} workspace
379
+ * @param {Map<string, Plan>} plans
380
+ * @returns {Promise<Result>}
381
+ */
382
+ async function inRepoAliases(root, workspace, plans) {
383
+ /** Paths shown relative to the workspace root (so equal real paths stay equal); a bare specifier as it is. */
384
+ const shown = (/** @type {string} */ file) => (path.isAbsolute(file) ? path.relative(root, file) || '.' : file)
385
+ const show = (/** @type {SeamRoute} */ route) => ({
386
+ find: route.find,
387
+ to: shown(route.to),
388
+ resolved: route.resolved.map(shown),
389
+ })
390
+ /** @type {Parameters<typeof aliasProblems>[0]} */
391
+ const apps = []
392
+ for (const appDir of workspace.apps) {
393
+ const plan = /** @type {Plan} */ (plans.get(appDir))
394
+ const own = realish(path.join(appDir, 'src', 'app-config'))
395
+ /** @type {Parameters<typeof aliasProblems>[0][number]['projects']} */
396
+ const projects = []
397
+ const seen = new Set()
398
+ for (const { run, projects: names } of [...(plan.main ? [plan.main] : []), ...plan.contract]) {
399
+ const key = `${run.cwd}\0${run.config ?? ''}\0${names.join('\0')}`
400
+ if (seen.has(key)) continue
401
+ seen.add(key)
402
+ const config = configName(root, run)
403
+ for (const [project, routes] of await seamAliases(run, names, own))
404
+ projects.push({ config, project, routes: routes.map(show) })
405
+ }
406
+ apps.push({
407
+ app: relativeTo(root)(appDir),
408
+ own: shown(own),
409
+ tsconfig: tsconfigRoutes(appDir).map(show),
410
+ projects,
411
+ })
412
+ }
413
+ const problems = aliasProblems(apps)
414
+ // The other importers have no seam of their own to alias: in-repo, each is compiled within a program that names one
415
+ // (the root's is the framework's own, on its test fixture; the showcase's seed is compiled within the showcase).
416
+ const others = workspace.importers
417
+ .map(({ dir }) => dir)
418
+ .filter((dir) => !workspace.apps.includes(dir))
419
+ .map(relativeTo(root))
420
+ return verdict(
421
+ problems.length > 0
422
+ ? "in-repo mode: an app's aliases send @sssb/app-config somewhere other than its own src/app-config"
423
+ : `in-repo mode: each app's tsconfig and Vitest projects alias @sssb/app-config to its own src/app-config: ${apps
424
+ .map((a) => `${a.app} (${a.projects.map((p) => `${p.config}:${p.project}`).join(', ')})`)
425
+ .join('; ')}`,
426
+ problems,
427
+ others.length
428
+ ? [
429
+ `not apps, so not alias-checked: ${others.join(', ')} (no seam of their own; each compiles within a program that names one)`,
430
+ ]
431
+ : [],
432
+ )
433
+ }
434
+
435
+ /**
436
+ * Every place the app's tsconfig sends the seam, as TypeScript itself reads the file (its `extends` and `baseUrl`
437
+ * honoured), through the compiler the app installs: each target of each `paths` key that is or starts with
438
+ * `@sssb/app-config`, with where a subpath lands through it (a `*` filled in with a probe name). Empty when it maps no
439
+ * such path.
440
+ * @param {string} appDir
441
+ * @returns {SeamRoute[]}
442
+ */
443
+ function tsconfigRoutes(appDir) {
444
+ const file = path.join(appDir, 'tsconfig.json')
445
+ if (!existsSync(file)) return []
446
+ /** @type {typeof import('typescript')} */
447
+ let ts
448
+ try {
449
+ ts = createRequire(path.join(appDir, 'package.json'))('typescript')
450
+ } catch (error) {
451
+ throw new UsageError(`sssb doctor: ${appDir} does not resolve \`typescript\`, which reads its tsconfig`, {
452
+ cause: error,
453
+ })
454
+ }
455
+ const parsed = ts.getParsedCommandLineOfConfigFile(
456
+ file,
457
+ {},
458
+ {
459
+ ...ts.sys,
460
+ onUnRecoverableConfigFileDiagnostic: () => {},
461
+ },
462
+ )
463
+ if (!parsed) return []
464
+ const options = /** @type {{ baseUrl?: string, pathsBasePath?: string }} */ (parsed.options)
465
+ const base = options.baseUrl ?? options.pathsBasePath ?? appDir
466
+ /** @type {SeamRoute[]} */
467
+ const routes = []
468
+ for (const [key, targets] of Object.entries(parsed.options.paths ?? {})) {
469
+ if (!key.startsWith(SEAM)) continue
470
+ for (const target of targets) {
471
+ const to = path.resolve(base, target)
472
+ // The FIRST `*` in the target takes the matched text and any later one stays literal, exactly as
473
+ // TypeScript's resolver substitutes it (`replaceFirstStar`). TypeScript rejects a second `*` only when it
474
+ // builds a program (TS5062), so the parsed config doctor reads still carries such a target, and doctor must
475
+ // follow it where TypeScript would.
476
+ const star = to.indexOf('*')
477
+ const probed = key.includes('*') && star >= 0 ? `${to.slice(0, star)}${PROBE}${to.slice(star + 1)}` : to
478
+ routes.push({ find: key, to, resolved: [realish(probed)] })
479
+ }
480
+ }
481
+ return routes
482
+ }
483
+
484
+ /**
485
+ * @param {string} root
486
+ * @param {string} target
487
+ * @returns {Result}
488
+ */
489
+ function versions(root, target) {
490
+ const name = relativeTo(root)(target)
491
+ const packages = sssbPackagesOf(target)
492
+ const problems = versionProblems(packages)
493
+ return verdict(
494
+ problems.length > 0
495
+ ? `${name}: versions in step: an @sssb package is not the version of @sssb/kit`
496
+ : `${name}: versions in step: ${[...packages].map(([pkg, v]) => `${pkg} ${v}`).join(', ')}`,
497
+ problems,
498
+ )
499
+ }
500
+
501
+ /**
502
+ * How a run is named in doctor's output.
503
+ * @param {string} root
504
+ * @param {VitestRun} run
505
+ */
506
+ const configName = (root, run) =>
507
+ run.config
508
+ ? path.relative(root, run.config) +
509
+ (path.dirname(run.config) === run.cwd ? '' : ` from ${relativeTo(root)(run.cwd)}`)
510
+ : `Vitest's defaults from ${relativeTo(root)(run.cwd)}`
511
+
512
+ /**
513
+ * How a `vitest list` is named in doctor's output: where it runs, the config, the projects selected.
514
+ * @param {string} root
515
+ * @param {Selected} selected
516
+ */
517
+ const listName = (root, { run, projects }) =>
518
+ `vitest list from ${run.cwd === root ? 'the workspace root' : path.relative(root, run.cwd)}` +
519
+ (run.config ? ` --config ${path.relative(run.cwd, run.config)}` : ", Vitest's defaults") +
520
+ (projects.length ? `, project ${projects.join(', ')}` : '')
521
+
522
+ /**
523
+ * A `vitest list`, once per run and selection.
524
+ * @param {VitestRun} run
525
+ * @param {{ filesOnly?: boolean, projects?: readonly string[] }} options
526
+ * @param {VitestCache} cache
527
+ */
528
+ function listOnce(run, options, cache) {
529
+ const key = [run.cwd, run.config ?? '', options.filesOnly ? 'files' : 'tests', ...(options.projects ?? [])].join(
530
+ '\0',
531
+ )
532
+ // After one listing ran out of time, the rest are not waited on: each would likely hang the same way, and the
533
+ // limit is per listing, so one app's configs could each spend it.
534
+ const listed = cache.get(key) ?? cache.get(STOPPED) ?? vitestList(run, options)
535
+ cache.set(key, listed)
536
+ if (!listed.ok && listed.timedOut && !cache.has(STOPPED)) {
537
+ cache.set(STOPPED, {
538
+ ok: false,
539
+ timedOut: true,
540
+ error: `not listed, since an earlier listing ran out of time (${listed.error})`,
541
+ })
542
+ }
543
+ return listed
544
+ }
545
+
546
+ /** The cache key of the error every listing after one that ran out of time returns. */
547
+ const STOPPED = '\0stopped'
548
+
549
+ /**
550
+ * WHICH RUNS HOLD AN APP TO WHICH CHECKS, found with `vitest list --filesOnly` alone (it loads each config and globs
551
+ * its files; it runs no globalSetup and collects no test file):
552
+ *
553
+ * - the MAIN unit run: the first of the runs a bare `vitest` would make for the app (vitestRunsFor's `bare`) that
554
+ * runs any of its `src/` test files, with the projects that run them selected. It must list every unit check. A
555
+ * bare run doctor cannot list stops the search (doctor cannot tell whether that one is the main run);
556
+ * - every OTHER config (root's and app's) that runs some of its `src/` test files but not its
557
+ * `src/sssb.conformance.test.ts`, and every bare run past the main one (the app directory's, when the root's is
558
+ * main) that does not run that file, even one that runs none of them: reported, since CI might run it instead of
559
+ * the main one;
560
+ * - every config (the main run's too) that runs any of its `tests/contract/` files: one of them must list every
561
+ * contract check (Vitest's defaults are no contract config);
562
+ * - every other config doctor cannot list: reported.
563
+ *
564
+ * Only the main run and the contract configs are then listed in full (conformance), which loads their globalSetup.
565
+ * @param {string} root
566
+ * @param {string} app
567
+ * @param {string[]} nested the workspace packages inside the app, whose files are not the app's
568
+ * @param {VitestCache} cache
569
+ * @returns {Plan}
570
+ */
571
+ function planFor(root, app, nested, cache) {
572
+ /** @type {Plan} */
573
+ const plan = { main: null, tried: [], mainErrors: [], partial: [], contract: [], unlisted: [], nested }
574
+ const { bare, configs } = vitestRunsFor(root, app)
575
+ const filesOf = (/** @type {VitestRun} */ run) => listOnce(run, { filesOnly: true }, cache)
576
+ /** @param {import('./doctor-vitest.js').ListedFile[]} listed @param {'unit' | 'contract'} area */
577
+ const inArea = (listed, area) => listed.filter((entry) => areaOf(entry.file, app, nested) === area)
578
+ /** @param {import('./doctor-vitest.js').ListedFile[]} listed */
579
+ const select = (listed) => {
580
+ const projects = projectsRunning(listed, app)
581
+ return projects.includes('') ? [] : projects
582
+ }
583
+
584
+ for (const run of bare) {
585
+ plan.tried.push(run)
586
+ const files = filesOf(run)
587
+ if (!files.ok) {
588
+ plan.mainErrors.push(`${configName(root, run)}: ${files.error}`)
589
+ break
590
+ }
591
+ const unit = inArea(files.listed, 'unit')
592
+ if (unit.length > 0) {
593
+ plan.main = { run, projects: select(unit) }
594
+ break
595
+ }
596
+ }
597
+
598
+ const main = plan.main?.run
599
+ const tried = new Set(plan.tried.map(runKey))
600
+ // The bare runs past the main one (the root's was main: a bare `vitest` from the app's directory, as the app's own
601
+ // scripts and a `pnpm -r` run it). Each is held to the unit area like any other config, and reported even when it
602
+ // runs NONE of the app's src/ files: a config whose globs reach the app only from the root finds nothing there,
603
+ // and passes when it sets `passWithNoTests`. One that is not also a config file run from its own directory (the
604
+ // root's config, run from the app) is only reported: it never joins the contract configs, which are listed in full.
605
+ const untried = new Set(bare.filter((run) => !tried.has(runKey(run))).map(runKey))
606
+ const isConfig = (/** @type {VitestRun} */ run) => configs.some((r) => runKey(r) === runKey(run))
607
+ const suite = path.join(app, 'src', 'sssb.conformance.test.ts')
608
+ const runs = [
609
+ ...configs,
610
+ ...(main?.config && !isConfig(main) ? [main] : []),
611
+ ...bare.filter((run) => untried.has(runKey(run)) && !isConfig(run)),
612
+ ]
613
+ for (const run of runs) {
614
+ const isMain = main !== undefined && runKey(run) === runKey(main)
615
+ const isBare = untried.has(runKey(run))
616
+ const reportOnly = isBare && !isConfig(run)
617
+ const files = filesOf(run)
618
+ if (!files.ok) {
619
+ // A bare run tried for the main one already failed the unit check; any other is reported.
620
+ if (!tried.has(runKey(run))) plan.unlisted.push({ run, error: files.error })
621
+ continue
622
+ }
623
+ const unit = inArea(files.listed, 'unit')
624
+ if (!isMain && (unit.length > 0 || isBare) && !unit.some((entry) => path.resolve(entry.file) === suite))
625
+ plan.partial.push({ run, files: new Set(unit.map((entry) => path.resolve(entry.file))).size, bare: isBare })
626
+ const contract = reportOnly ? [] : inArea(files.listed, 'contract')
627
+ if (contract.length > 0) plan.contract.push({ run, projects: select(contract) })
628
+ }
629
+ return plan
630
+ }
631
+
632
+ /**
633
+ * THE CONFORMANCE SUITE WOULD RUN (the unit runner): the main unit run (planFor) must list every test of every unit
634
+ * check, from the app's own `src/sssb.conformance.test.ts` (ownTests), less the checks the app opted out of by name
635
+ * there; no main run, or one doctor cannot list, fails. Every other config that runs some of the app's `src/` tests but
636
+ * not the suite, and every other config doctor cannot list, is reported: doctor cannot see which config CI runs.
637
+ *
638
+ * THE CONTRACT RUNNER'S CHECKS WOULD RUN: some config that runs the app's `tests/contract/` files must list every
639
+ * contract check; when one does, each other that runs them and does not is reported, and when none does, each fails.
640
+ * Each opt-out is reported with its reason.
641
+ * @param {string} root
642
+ * @param {string} app
643
+ * @param {'unit' | 'contract'} runner
644
+ * @param {Map<string, Plan>} plans
645
+ * @param {VitestCache} cache
646
+ * @returns {Result[]}
647
+ */
648
+ function conformance(root, app, runner, plans, cache) {
649
+ const rel = relativeTo(root)
650
+ const label = `${rel(app)}: ${runner === 'unit' ? 'the conformance suite would run' : "the contract runner's checks would run"}`
651
+ const plan = /** @type {Plan} */ (plans.get(app))
652
+ let registry
653
+ try {
654
+ registry = readJson(resolveAppsKit(app, 'testing/checks.json'))
655
+ } catch (error) {
656
+ return [{ status: 'FAIL', title: label, lines: [messageOf(error)] }]
657
+ }
658
+ /** @type {Result[]} */
659
+ const results = []
660
+ /** @type {Map<string, string>} */
661
+ const opted = new Map()
662
+ /** @param {Selected} selected */
663
+ const check = (selected) => {
664
+ const result = listOnce(selected.run, { projects: selected.projects }, cache)
665
+ const listed = result.ok ? ownTests(result.listed, app, runner, plan.nested) : []
666
+ const outcome = missingTests(listed, registry, runner)
667
+ if (result.ok) for (const { id, reason } of outcome.optedOut) opted.set(id, reason)
668
+ return {
669
+ ...outcome,
670
+ selected,
671
+ where: listName(root, selected),
672
+ error: result.ok ? null : result.error,
673
+ passes: result.ok && outcome.missing.length === 0,
674
+ }
675
+ }
676
+ /** @param {ReturnType<typeof check>} c @returns {Result} */
677
+ const failed = (c) => ({
678
+ status: 'FAIL',
679
+ title: `${label}: ${c.missing.length} of its ${c.expected} tests would not run (${c.where})`,
680
+ lines: [...(c.error === null ? [] : [`${c.where}: ${c.error}`]), ...c.missing.map((n) => `not listed: ${n}`)],
681
+ })
682
+ /** @param {ReturnType<typeof check>} c */
683
+ const passed = (c) =>
684
+ /** @type {Result} */ ({ status: 'ok', title: `${label}: all ${c.expected} tests listed (${c.where})` })
685
+
686
+ if (runner === 'unit') {
687
+ const mainName = plan.main ? configName(root, plan.main.run) : 'the config a bare `vitest` loads'
688
+ if (plan.mainErrors.length > 0)
689
+ results.push({
690
+ status: 'FAIL',
691
+ title: `${label}: doctor cannot list the config a bare \`vitest\` would load for ${rel(app)}, so it cannot tell whether that config runs its tests`,
692
+ lines: plan.mainErrors,
693
+ })
694
+ else if (plan.main === null)
695
+ results.push({
696
+ status: 'FAIL',
697
+ title:
698
+ `${label}: no config a bare \`vitest\` would load for ${rel(app)} runs a test file of its src/ ` +
699
+ `(tried ${plan.tried.map((run) => configName(root, run)).join(', ')}), so nothing holds it to the unit checks`,
700
+ })
701
+ else {
702
+ const c = check(plan.main)
703
+ results.push(c.passes ? passed(c) : failed(c))
704
+ }
705
+ for (const { run, files, bare } of plan.partial) {
706
+ const runs =
707
+ files === 0
708
+ ? 'runs none of its src/ test files, so not src/sssb.conformance.test.ts'
709
+ : `runs ${files} of its src/ test files but not src/sssb.conformance.test.ts`
710
+ results.push({
711
+ status: 'report',
712
+ title: bare
713
+ ? `${rel(app)}: a bare \`vitest\` from ${rel(run.cwd)} loads ` +
714
+ `${run.config ? path.relative(root, run.config) : "no config (Vitest's defaults)"} and ${runs}: ` +
715
+ `if CI runs it there (the app's own scripts, \`pnpm -r\`) instead of ${mainName} from the root, ` +
716
+ 'the conformance checks do not run'
717
+ : `${rel(app)}: ${configName(root, run)} ${runs}: if CI runs it instead of ${mainName}, the ` +
718
+ 'conformance checks do not run',
719
+ })
720
+ }
721
+ for (const { run, error } of plan.unlisted)
722
+ results.push({
723
+ status: 'report',
724
+ title:
725
+ `${rel(app)}: doctor cannot list ${configName(root, run)}, so it cannot tell what that config runs; ` +
726
+ `it is not the config a bare \`vitest\` loads, so this is no failure, but if CI runs it, doctor has not checked it`,
727
+ lines: [error],
728
+ })
729
+ } else if (plan.contract.length === 0) {
730
+ results.push({
731
+ status: 'FAIL',
732
+ title:
733
+ `${label}: no Vitest config at the workspace root or in ${rel(app)} runs a test file of its ` +
734
+ 'tests/contract/, so nothing runs its contract checks',
735
+ })
736
+ } else {
737
+ const checked = plan.contract.map(check)
738
+ const passing = checked.filter((c) => c.passes)
739
+ if (passing.length === 0) results.push(...checked.map(failed))
740
+ else {
741
+ const names = passing.map((c) => configName(root, c.selected.run)).join(', ')
742
+ for (const c of checked)
743
+ results.push(
744
+ c.passes
745
+ ? passed(c)
746
+ : {
747
+ status: 'report',
748
+ title:
749
+ `${rel(app)}: ${configName(root, c.selected.run)} runs its tests/contract/ files but ` +
750
+ (c.error === null
751
+ ? `${c.missing.length} of its ${c.expected} contract tests would not run: ` +
752
+ `if CI runs it instead of ${names}, those checks do not run`
753
+ : `doctor cannot list its tests (${c.error}): if CI runs it instead of ` +
754
+ `${names}, doctor has not checked that the contract checks run`),
755
+ },
756
+ )
757
+ }
758
+ }
759
+ for (const [id, reason] of opted)
760
+ results.push({ status: 'report', title: `${rel(app)}: opted out of ${id}: ${reason || '(no reason given)'}` })
761
+ return results
762
+ }
763
+
764
+ /**
765
+ * WHAT DOCTOR CANNOT SEE: the command line a CI step runs Vitest with. Doctor proves what each configuration would
766
+ * run; a flag or a file filter on the command (`-t`, `--project`, `--shard`, a path...) can run fewer. It reads the
767
+ * root's and the apps' package.json scripts and reports every such flag they pass, and, since it lists the contract
768
+ * checks and never runs them, which script runs each app's contract config, or that none does.
769
+ * @param {string} root
770
+ * @param {string} appDir
771
+ * @param {string[]} apps
772
+ * @param {Map<string, Plan>} plans
773
+ * @returns {Result[]}
774
+ */
775
+ function commandLines(root, appDir, apps, plans) {
776
+ const rel = relativeTo(root)
777
+ const dirs = [...new Set([root, appDir, ...apps])]
778
+ const owner = (/** @type {string} */ dir) => (dir === root ? 'root' : rel(dir))
779
+ const invocations = dirs.flatMap((dir) =>
780
+ vitestInvocations(readJson(path.join(dir, 'package.json')).scripts ?? {}).map((call) => ({ ...call, dir })),
781
+ )
782
+ const narrowed = invocations.filter((call) => call.narrowing.length > 0)
783
+ /** @type {Result[]} */
784
+ const results = [
785
+ {
786
+ status: 'report',
787
+ title:
788
+ "CI's command line: doctor proves what each Vitest configuration would run, not what a CI step's own " +
789
+ 'flags make of it; the flags and file filters the package.json scripts pass to vitest:',
790
+ lines:
791
+ narrowed.length > 0
792
+ ? narrowed.map((call) => `${owner(call.dir)} script ${call.script}: ${call.narrowing.join(', ')}`)
793
+ : [
794
+ `none (scripts of ${dirs.map(owner).join(', ')}; a flag a CI step adds itself is not here to see)`,
795
+ ],
796
+ },
797
+ ]
798
+ /** @type {string[]} */
799
+ const lines = []
800
+ for (const app of apps) {
801
+ const plan = /** @type {Plan} */ (plans.get(app))
802
+ const configs = [...new Set(plan.contract.map(({ run }) => run.config).filter((c) => c !== null))]
803
+ for (const config of configs) {
804
+ const callers = invocations.filter(
805
+ (call) =>
806
+ (call.config ? path.resolve(call.dir, call.config) : vitestDefaultConfig(call.dir)) === config,
807
+ )
808
+ const name = path.relative(root, config)
809
+ lines.push(
810
+ callers.length > 0
811
+ ? `${rel(app)}: ${callers.map((call) => `${owner(call.dir)} script ${call.script}`).join(', ')} runs ${name}`
812
+ : `${rel(app)}: no script of the root's or ${rel(app)}'s package.json runs ${name}; CI must run it itself`,
813
+ )
814
+ }
815
+ }
816
+ if (lines.length > 0)
817
+ results.push({
818
+ status: 'report',
819
+ title: "contract checks: doctor lists them and never runs them, so CI must run each app's contract config:",
820
+ lines,
821
+ })
822
+ return results
823
+ }
824
+
825
+ /**
826
+ * The app guide (`sssb guide --check`) of every app, once the framework ships one.
827
+ *
828
+ * IN-REPO, a missing copy is not a failure. There the kit is a package of the workspace and its guide
829
+ * (`packages/kit/src/guide.md`) is the source, checked by the doc gate; a copy is the adopter's mechanism, and SSSB's
830
+ * own `CLAUDE.md` imports the source itself (`@packages/kit/src/guide.md`, ADR-0014 P13), which nothing can make stale:
831
+ * that import is ok, and its absence is reported. Once a copy exists it is checked as an adopter's is. An adopter's
832
+ * workspace is never in-repo, so a missing copy fails there.
833
+ *
834
+ * @param {string} root
835
+ * @param {string[]} apps
836
+ * @param {boolean} inRepo
837
+ * @returns {Promise<Result[]>}
838
+ */
839
+ async function guides(root, apps, inRepo) {
840
+ /** @type {Result[]} */
841
+ const results = []
842
+ /** @param {string} title */
843
+ const reportOnce = (title) => {
844
+ if (!results.some((r) => r.title === title)) results.push({ status: 'report', title })
845
+ }
846
+ for (const app of apps) {
847
+ let source
848
+ try {
849
+ source = resolveAppsKit(app, 'guide.md')
850
+ } catch {
851
+ reportOnce('app guide: not checked: this @sssb/kit ships no guide (it arrives at P7)')
852
+ continue
853
+ }
854
+ if (inRepo && !existsSync(path.join(workspaceRootOf(app), '.claude', 'sssb-guide.md'))) {
855
+ const importLine = `@${path.relative(root, realpathSync(source)).split(path.sep).join('/')}`
856
+ const claudeMd = path.join(root, 'CLAUDE.md')
857
+ const imports =
858
+ existsSync(claudeMd) &&
859
+ readFileSync(claudeMd, 'utf8')
860
+ .split('\n')
861
+ .some((line) => line.trim().split(/\s+/).includes(importLine))
862
+ if (imports && !results.some((r) => r.status === 'ok' && r.title.startsWith('app guide:')))
863
+ results.push({
864
+ status: 'ok',
865
+ title: `app guide: in-repo, CLAUDE.md imports the kit's guide from its source (${importLine}), so no copy can go stale`,
866
+ })
867
+ else if (!imports)
868
+ reportOnce(
869
+ "app guide: not checked: in-repo, the kit's guide is this workspace's own source, and the repository " +
870
+ `neither imports it from CLAUDE.md (${importLine}) nor holds a copy of it (\`.claude/sssb-guide.md\`)`,
871
+ )
872
+ continue
873
+ }
874
+ const name = relativeTo(root)(app)
875
+ const status = await (await import('./guide.js')).run(['--app', app, '--check'])
876
+ results.push(
877
+ status === 0
878
+ ? { status: 'ok', title: `${name}: app guide: the repository's copy matches the kit's` }
879
+ : { status: 'FAIL', title: `${name}: app guide: the repository's copy is not the kit's (see above)` },
880
+ )
881
+ }
882
+ return results
883
+ }
884
+
885
+ /**
886
+ * The workflow and plugin pins against the kit's release stamp (pinReport): read here, judged there. The workflows are
887
+ * the workspace root's `.github/workflows/*.{yml,yaml}`, the settings its `.claude/settings.json` (the shared one; a
888
+ * machine's `settings.local.json` is no pin of the repository's), the stamp the APP's kit's `dist/release.json`.
889
+ * @param {string} root
890
+ * @param {string} kitDir
891
+ * @param {string} version
892
+ * @param {boolean} inRepo
893
+ * @returns {Result}
894
+ */
895
+ function pins(root, kitDir, version, inRepo) {
896
+ const settingsText = readIfThere(path.join(root, '.claude', 'settings.json'))
897
+ return pinReport({
898
+ inRepo,
899
+ version,
900
+ stamp: readIfThere(path.join(kitDir, 'dist', 'release.json')),
901
+ repository: githubRepositoryOf(readJson(path.join(kitDir, 'package.json')).repository),
902
+ workflows: workflowFiles(root),
903
+ settings: settingsText === null ? null : { file: '.claude/settings.json', text: settingsText },
904
+ })
905
+ }
906
+
907
+ /** @param {string} file */
908
+ const readIfThere = (file) => (existsSync(file) ? readFileSync(file, 'utf8') : null)
909
+
910
+ /**
911
+ * The workspace root's `.github/workflows/*.{yml,yaml}`, sorted, with their text.
912
+ * @param {string} root
913
+ */
914
+ function workflowFiles(root) {
915
+ const dir = path.join(root, '.github', 'workflows')
916
+ return existsSync(dir)
917
+ ? readdirSync(dir)
918
+ .filter((name) => /\.ya?ml$/.test(name))
919
+ .sort()
920
+ .map((name) => ({
921
+ file: `.github/workflows/${name}`,
922
+ text: /** @type {string} */ (readIfThere(path.join(dir, name))),
923
+ }))
924
+ : []
925
+ }
926
+
927
+ /**
928
+ * THE ADOPTER'S OWN SETTINGS, REPORTED, never failed and never written (doctor-settings.js): the workspace's GitHub
929
+ * repository (`sssb / all-checks` required, private vulnerability reporting, the Actions policy a private organization
930
+ * repository needs for SSSB's reusable workflow) read through `gh`, and the plugin `.claude/settings.json` enables
931
+ * against what this machine has installed. Skipped in CI, with a line saying so.
932
+ * @param {string} root
933
+ * @param {string} kitDir
934
+ * @returns {Result[]}
935
+ */
936
+ function settings(root, kitDir) {
937
+ return settingsReports({
938
+ root,
939
+ workflows: workflowFiles(root),
940
+ kitRepository: githubRepositoryOf(readJson(path.join(kitDir, 'package.json')).repository),
941
+ })
942
+ }
943
+
944
+ /**
945
+ * @param {string} root
946
+ * @param {boolean} inRepo
947
+ * @returns {Result}
948
+ */
949
+ function dedupeAdvice(root, inRepo) {
950
+ const { dedupePeerDependents } = parseWorkspaceYaml(readFileSync(path.join(root, 'pnpm-workspace.yaml'), 'utf8'))
951
+ if (dedupePeerDependents === false)
952
+ return { status: 'ok', title: 'pnpm-workspace.yaml sets dedupePeerDependents: false' }
953
+ return {
954
+ status: 'advice',
955
+ title:
956
+ 'pnpm-workspace.yaml does not set `dedupePeerDependents: false`: without it, a package that takes @sssb/kit ' +
957
+ "and links no seam silently shares another app's instance and seam (ADR-0014 part 5). Set it, then reinstall " +
958
+ 'from a fresh lockfile, since a lockfile resolved before it keeps the merged layout' +
959
+ (inRepo ? ' (in-repo mode: the seam goes through aliases here, so this is advice for an adopter)' : ''),
960
+ }
961
+ }
962
+
963
+ /**
964
+ * KNIP: each app, and each app's seam package, has a workspace of its own in the root's knip.json (knipGaps).
965
+ * Reported, never failed; nothing per app when the root's knip config has no `workspaces`, and nothing at all when
966
+ * the root has no knip JSON config.
967
+ * @param {string} root
968
+ * @param {readonly string[]} apps
969
+ * @param {readonly string[]} packages
970
+ * @returns {Result[]}
971
+ */
972
+ function knip(root, apps, packages) {
973
+ const gaps = knipGaps(root, apps, packages)
974
+ if (gaps === null) return []
975
+ if ('unread' in gaps)
976
+ return [{ status: 'report', title: `knip: not checked: ${gaps.file} does not parse as JSON (${gaps.unread})` }]
977
+ /** @type {Result[]} */
978
+ const results = []
979
+ if (gaps.missing === null) {
980
+ // One config for every package: nothing per app to look for.
981
+ } else if (gaps.missing.length === 0)
982
+ results.push({
983
+ status: 'ok',
984
+ title: `knip: ${gaps.file} gives every app, and every app's seam package, a workspace`,
985
+ })
986
+ else
987
+ results.push({
988
+ status: 'report',
989
+ title:
990
+ `knip: ${gaps.file} gives ${gaps.missing.length} of the apps' packages no workspace, so knip reads them ` +
991
+ "with its defaults and calls the seam's modules and the presets' dependencies unused: add an entry for " +
992
+ "each, like the first app's",
993
+ lines: gaps.missing,
994
+ })
995
+ if (gaps.generator)
996
+ results.push({
997
+ status: 'report',
998
+ title:
999
+ `knip: the root installs @sssb/create, which nothing imports (\`sssb add-app\` loads it from ` +
1000
+ `node_modules), so knip calls it unused: \`pnpm remove -w @sssb/create\` once your apps are written, or ` +
1001
+ `add it to the root's ignoreDependencies in ${gaps.file}`,
1002
+ })
1003
+ return results
1004
+ }
1005
+
1006
+ /**
1007
+ * @param {string} root
1008
+ * @param {string} appDir
1009
+ * @returns {Result}
1010
+ */
1011
+ function cutover(root, appDir) {
1012
+ let rows
1013
+ try {
1014
+ rows = readJson(resolveAppsKit(appDir, 'cutover/rows.json'))
1015
+ } catch {
1016
+ return { status: 'report', title: 'cutover rows: not checked: this @sssb/kit publishes no cutover/rows.json' }
1017
+ }
1018
+ const file = path.join(root, 'docs', 'cutover-checklist.md')
1019
+ const checklist = existsSync(file) ? readFileSync(file, 'utf8') : null
1020
+ const { unmentioned, sssbOnly } = cutoverReport(rows, checklist)
1021
+ const skipped = sssbOnly.length ? ` (${sssbOnly.join(', ')}: SSSB's own repository only, not looked for)` : ''
1022
+ if (unmentioned.length === 0)
1023
+ return { status: 'ok', title: `cutover rows: docs/cutover-checklist.md records every framework row${skipped}` }
1024
+ return {
1025
+ status: 'report',
1026
+ title:
1027
+ (checklist === null
1028
+ ? `cutover rows: the workspace has no docs/cutover-checklist.md, so none of the framework's rows is recorded`
1029
+ : `cutover rows: docs/cutover-checklist.md never mentions ${unmentioned.length} framework row(s)`) +
1030
+ skipped,
1031
+ lines: [unmentioned.join(', ')],
1032
+ }
1033
+ }