@syntopica/create-baseline 0.9.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -0
  3. package/baseline-versions.json +16 -0
  4. package/bin/baseline-estate.mjs +85 -0
  5. package/bin/conformance/applyFixes.mjs +101 -0
  6. package/bin/conformance/checkActionPins.mjs +43 -0
  7. package/bin/conformance/checkCiWorkflow.mjs +52 -0
  8. package/bin/conformance/checkCoverageThresholds.mjs +112 -0
  9. package/bin/conformance/checkGateCoverage.mjs +128 -0
  10. package/bin/conformance/checkHooksInstalled.mjs +43 -0
  11. package/bin/conformance/checkLintFlag.mjs +86 -0
  12. package/bin/conformance/checkTsconfigPresets.mjs +58 -0
  13. package/bin/conformance/checkTsconfigProjects.mjs +47 -0
  14. package/bin/conformance/checkVersionRanges.mjs +51 -0
  15. package/bin/conformance/ciEntrypoints.mjs +37 -0
  16. package/bin/conformance/expandScripts.mjs +76 -0
  17. package/bin/conformance/formatFindings.mjs +36 -0
  18. package/bin/conformance/loadContext.mjs +175 -0
  19. package/bin/conformance/loadExceptions.mjs +73 -0
  20. package/bin/conformance/rangeFloor.mjs +23 -0
  21. package/bin/conformance/readWorkflows.mjs +29 -0
  22. package/bin/conformance/runConformance.mjs +57 -0
  23. package/bin/create-baseline.mjs +432 -0
  24. package/bin/estate/findConsumers.mjs +46 -0
  25. package/bin/estate/findPythonConsumers.mjs +58 -0
  26. package/bin/estate/formatEstate.mjs +67 -0
  27. package/bin/estate/formatPythonEstate.mjs +37 -0
  28. package/bin/python/checkGateWorkflow.mjs +33 -0
  29. package/bin/python/checkLockPin.mjs +36 -0
  30. package/bin/python/checkQualityGroup.mjs +33 -0
  31. package/bin/python/loadPythonContext.mjs +32 -0
  32. package/bin/python/repositoryRoot.mjs +24 -0
  33. package/bin/python/runPythonConformance.mjs +25 -0
  34. package/bin/scaffold/actionPins.mjs +34 -0
  35. package/bin/scaffold/baselineScripts.mjs +44 -0
  36. package/bin/scaffold/checkPeers.mjs +87 -0
  37. package/bin/scaffold/ciWorkflow.mjs +144 -0
  38. package/bin/scaffold/collectDeps.mjs +10 -0
  39. package/bin/scaffold/composedSubpaths.mjs +41 -0
  40. package/bin/scaffold/depCruiserConfig.mjs +30 -0
  41. package/bin/scaffold/detectFramework.mjs +18 -0
  42. package/bin/scaffold/eslintSubpathPeers.mjs +60 -0
  43. package/bin/scaffold/knipConfig.mjs +9 -0
  44. package/bin/scaffold/lefthookConfig.mjs +33 -0
  45. package/bin/scaffold/oxlintConfig.mjs +19 -0
  46. package/bin/scaffold/readManifest.mjs +17 -0
  47. package/bin/scaffold/renovateConfig.mjs +11 -0
  48. package/bin/scaffold/workspaceRoots.mjs +89 -0
  49. package/bin/scaffold/writeCiWorkflow.mjs +54 -0
  50. package/bin/scaffold/writeMissing.mjs +116 -0
  51. package/package.json +59 -0
  52. package/python-versions.json +3 -0
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A committed `lefthook.yml` is not an installed hook.
3
+ *
4
+ * lefthook only writes into `.git/hooks` when `lefthook install` runs, which
5
+ * is why `prepare` exists. Three repositories in a row adopted the gates with
6
+ * the file in place and no hook installed, and one common cause is silent:
7
+ * pnpm blocks a dependency's install scripts unless `allowBuilds` names it, so
8
+ * `lefthook` never gets to install itself and the only sign is an
9
+ * `ERR_PNPM_IGNORED_BUILDS` line scrolled past during install.
10
+ *
11
+ * A missing hook is a warning, not an error - CI is what makes a gate
12
+ * mandatory, and a hook that fires only on the author's machine was never the
13
+ * enforcement mechanism. It is still worth naming: it is the difference
14
+ * between catching a violation before the commit and catching it after the
15
+ * push.
16
+ */
17
+ export function checkHooksInstalled({ hooks, deps }) {
18
+ if (hooks.installed) return []
19
+
20
+ if (!deps.lefthook) {
21
+ return [
22
+ {
23
+ id: 'hooks',
24
+ level: 'warn',
25
+ message: 'lefthook is not installed',
26
+ detail: 'No pre-commit lint or pre-push secret scan on this machine.',
27
+ },
28
+ ]
29
+ }
30
+
31
+ return [
32
+ {
33
+ id: 'hooks',
34
+ level: 'warn',
35
+ message: 'lefthook.yml is present but .git/hooks is not wired',
36
+ detail:
37
+ 'Run `pnpm run prepare`. If pnpm reports ERR_PNPM_IGNORED_BUILDS for ' +
38
+ 'lefthook, add `lefthook: true` under `allowBuilds:` in ' +
39
+ 'pnpm-workspace.yaml first - otherwise the hooks never reach ' +
40
+ '.git/hooks however many times you run it.',
41
+ },
42
+ ]
43
+ }
@@ -0,0 +1,86 @@
1
+ const NUMERIC_BUDGET = /--max-warnings[=\s]+([1-9]\d*)/
2
+ const ZERO_BUDGET = /--max-warnings[=\s]+0(?!\d)/
3
+
4
+ /**
5
+ * `lint` must fail on warnings.
6
+ *
7
+ * `docs/standards/quality-gates.md` states the invariant: "zero. There is no
8
+ * warning budget." Without the flag, `complexity`, `max-depth`, `max-params`,
9
+ * `max-lines-per-function` and `sonarjs/no-duplicate-string` are advisory and
10
+ * never fail a build - which is the same as not having configured them.
11
+ *
12
+ * A numeric budget is reported separately and more loudly than a missing flag,
13
+ * because it is not an oversight: it is a ratchet frozen at the day's warning
14
+ * count that can only ever be raised. The fix for real debt is
15
+ * `pnpm lint:suppress`, which every baseline project already has - it writes
16
+ * the violations to `eslint-suppressions.json`, where `lint:prune` can shrink
17
+ * them and review can see them.
18
+ */
19
+ export function checkLintFlag({ scripts }) {
20
+ const lint = scripts.lint
21
+ if (!lint) {
22
+ return [
23
+ {
24
+ id: 'lint-script',
25
+ level: 'error',
26
+ message: 'no `lint` script',
27
+ detail: 'Nothing runs ESLint, so no rule in the baseline applies.',
28
+ },
29
+ ]
30
+ }
31
+
32
+ // A delegating script (`turbo run lint`, `pnpm -r lint`) carries the flag in
33
+ // the packages it fans out to, not here. Reporting it against the root would
34
+ // be a false positive on every monorepo.
35
+ if (/\b(?:turbo|nx|lerna)\b|--recursive|\s-r\b/.test(lint)) {
36
+ return [
37
+ {
38
+ id: 'lint-flag',
39
+ level: 'info',
40
+ message: '`lint` delegates to workspaces',
41
+ detail:
42
+ 'Each workspace carries its own flag; this check cannot see them ' +
43
+ 'from the root. Run the conformance check inside each workspace.',
44
+ },
45
+ ]
46
+ }
47
+
48
+ const budget = NUMERIC_BUDGET.exec(lint)
49
+ if (budget) {
50
+ return [
51
+ {
52
+ id: 'lint-flag',
53
+ level: 'error',
54
+ message: `\`lint\` allows ${budget[1]} warnings`,
55
+ detail:
56
+ "A warning budget is a ratchet frozen at today's debt. Replace it " +
57
+ 'with `--max-warnings 0` and run `pnpm lint:suppress` once: the ' +
58
+ 'debt moves into eslint-suppressions.json, where `lint:prune` ' +
59
+ 'shrinks it and review can see it.',
60
+ fix: {
61
+ kind: 'set-script',
62
+ name: 'lint',
63
+ value: lint.replace(NUMERIC_BUDGET, '--max-warnings 0'),
64
+ },
65
+ },
66
+ ]
67
+ }
68
+
69
+ if (ZERO_BUDGET.test(lint)) return []
70
+
71
+ return [
72
+ {
73
+ id: 'lint-flag',
74
+ level: 'error',
75
+ message: '`lint` is missing `--max-warnings 0`',
76
+ detail:
77
+ 'Every warn-level rule in the baseline is advisory until this flag ' +
78
+ 'is present.',
79
+ fix: {
80
+ kind: 'set-script',
81
+ name: 'lint',
82
+ value: `${lint.trim()} --max-warnings 0`,
83
+ },
84
+ },
85
+ ]
86
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Every project tsconfig must extend an `@syntopica/tsconfig` preset.
3
+ *
4
+ * A repository can carry the dependency, pass every other column, and still
5
+ * not be on the baseline: in verticagtm only `tsconfig.app.json` extended a
6
+ * preset, while `tsconfig.node.json` and `tsconfig.next.json` were
7
+ * hand-written and weaker than `base.json` - no `noUncheckedIndexedAccess`,
8
+ * no `exactOptionalPropertyTypes`, no `noImplicitOverride`, `allowJs` on the
9
+ * Next one. Nothing reported it, because nothing looked.
10
+ *
11
+ * The two root shapes are judged differently, and conflating them is the trap
12
+ * this check must not fall into. A single-project root extends a preset
13
+ * directly. A solution-style root must NOT: it stays
14
+ * `{"files": [], "references": [...]}` and the presets go on the leaves,
15
+ * because `baseline-type-coverage` walks a solution root's references to find
16
+ * the projects - a root that extends instead of referencing hands the runner
17
+ * one project and hides the rest.
18
+ *
19
+ * Only judged when the repository depends on `@syntopica/tsconfig`;
20
+ * `checkVersionRanges` owns the case of the package missing entirely. A leaf
21
+ * that failed to parse is skipped rather than judged - `checkTsconfigProjects`
22
+ * and `tsc` itself surface an unreadable reference.
23
+ */
24
+ export function checkTsconfigPresets({ tsconfigs, deps }) {
25
+ if (!tsconfigs || !deps['@syntopica/tsconfig']) return []
26
+
27
+ if (!tsconfigs.solution) {
28
+ return extendsPreset(tsconfigs.root) ? [] : [finding('tsconfig.json')]
29
+ }
30
+
31
+ return tsconfigs.leaves
32
+ .filter((leaf) => leaf.parsed && !extendsPreset(leaf.parsed))
33
+ .map((leaf) => finding(leaf.config))
34
+ }
35
+
36
+ // `extends` is a string, or an array since TypeScript 5.0.
37
+ function extendsPreset(parsed) {
38
+ const bases = Array.isArray(parsed.extends)
39
+ ? parsed.extends
40
+ : [parsed.extends]
41
+ return bases.some(
42
+ (base) =>
43
+ typeof base === 'string' && base.startsWith('@syntopica/tsconfig'),
44
+ )
45
+ }
46
+
47
+ function finding(config) {
48
+ return {
49
+ id: `tsconfig-preset:${config}`,
50
+ level: 'error',
51
+ message: `\`${config}\` does not extend an \`@syntopica/tsconfig\` preset`,
52
+ detail:
53
+ 'A hand-written tsconfig drifts below the baseline silently. Extend ' +
54
+ 'the matching preset in this file; in a multi-project repository the ' +
55
+ 'presets go on the leaves and the solution root stays ' +
56
+ '`{"files": [], "references": [...]}`.',
57
+ }
58
+ }
@@ -0,0 +1,47 @@
1
+ import { expandScripts } from './expandScripts.mjs'
2
+
3
+ // `tsc -b` (or `vue-tsc -b`) with no project argument builds the root
4
+ // solution, which reaches every reference; only flags may follow before the
5
+ // command ends. `tsc -b tsconfig.app.json` names projects instead, and those
6
+ // are matched per reference below.
7
+ const BARE_BUILD =
8
+ /\b(?:vue-tsc|tsc)\s+(?:-b|--build)(?:\s+-[\w-]+)*\s*(?:&&|\|\||;|$)/
9
+
10
+ /**
11
+ * Every project a solution root references must be reachable from
12
+ * `type-check`.
13
+ *
14
+ * The defect this catches is the expensive kind: a gate that exits 0 while
15
+ * reading almost nothing. verticagtm's root tsconfig.json referenced three
16
+ * projects and its `type-check` script named two of them, so `app/`,
17
+ * `proxy.ts` and `instrumentation.ts` - the largest surface in the repo -
18
+ * reached `check:ci` unchecked for months while the estate report called the
19
+ * repository conformant. The check is purely structural, no TypeScript
20
+ * needed: read the root's `references`, read the `type-check` script, diff.
21
+ *
22
+ * With no `type-check` script at all there is nothing to diff against;
23
+ * `checkGateCoverage` already reports the missing gate, and repeating it here
24
+ * would be the same finding twice.
25
+ */
26
+ export function checkTsconfigProjects({ tsconfigs, scripts, runners = {} }) {
27
+ if (!tsconfigs?.solution) return []
28
+
29
+ const { text } = expandScripts(scripts, ['type-check'], runners)
30
+ if (!text) return []
31
+ if (BARE_BUILD.test(text)) return []
32
+
33
+ const findings = []
34
+ for (const { reference } of tsconfigs.leaves) {
35
+ if (text.includes(reference)) continue
36
+ findings.push({
37
+ id: `tsconfig-project:${reference}`,
38
+ level: 'error',
39
+ message: `\`${reference}\` is referenced by the solution root but never type-checked`,
40
+ detail:
41
+ 'The root tsconfig.json references this project and `type-check` ' +
42
+ 'never names it, so its files pass CI unread. Run `tsc -b` at the ' +
43
+ 'root, or add `tsc -p <project> --noEmit` for each reference.',
44
+ })
45
+ }
46
+ return findings
47
+ }
@@ -0,0 +1,51 @@
1
+ import { rangeFloor } from './rangeFloor.mjs'
2
+
3
+ /**
4
+ * An installed range must be able to resolve the version this CLI pins.
5
+ *
6
+ * `baseline-versions.json` is the shipped source of truth: it travels with the
7
+ * CLI, so the check needs no registry call and gives the same answer offline
8
+ * and in CI.
9
+ *
10
+ * The failure this catches is quiet by design. Thirteen repositories sat on
11
+ * `@syntopica/prettier-config@^0.1.2` against a published `0.2.0`, and
12
+ * Renovate cannot close that gap on its own - a caret on a `0.x` line is
13
+ * locked to the minor, so the range has to be widened by hand before any
14
+ * update tool can see the new version at all. Nothing anywhere reported it.
15
+ */
16
+ export function checkVersionRanges({ deps, versions }) {
17
+ const findings = []
18
+
19
+ for (const [name, pinned] of Object.entries(versions)) {
20
+ const installed = deps[name]
21
+ if (installed == null) continue
22
+
23
+ const have = rangeFloor(installed)
24
+ const want = rangeFloor(pinned)
25
+ if (!have || !want) continue
26
+
27
+ if (compare(have, want) >= 0) continue
28
+
29
+ const stuck = want[0] === 0 && have[0] === 0 && have[1] < want[1]
30
+ findings.push({
31
+ id: `version:${name}`,
32
+ level: stuck ? 'error' : 'warn',
33
+ message: `${name} ${installed} is behind ${pinned}`,
34
+ detail: stuck
35
+ ? 'A caret on a 0.x line is locked to the minor, so this range can ' +
36
+ 'never resolve the pinned version. Widen it by hand; no update tool ' +
37
+ 'will do it for you.'
38
+ : 'Within range - a plain install will pick the newer version up.',
39
+ fix: { kind: 'set-dependency', name, value: pinned },
40
+ })
41
+ }
42
+
43
+ return findings
44
+ }
45
+
46
+ function compare(a, b) {
47
+ for (let i = 0; i < 3; i += 1) {
48
+ if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
49
+ }
50
+ return 0
51
+ }
@@ -0,0 +1,37 @@
1
+ // A package script invoked from a workflow step. `run:` blocks are shell, so
2
+ // this is the same set of forms scripts use to call each other, matched
3
+ // against the whole workflow text rather than parsed YAML - a dependency on a
4
+ // YAML parser would buy nothing here, since a step's `run:` is a shell string
5
+ // either way.
6
+ const INVOCATION = /\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?([a-z][\w:-]*)/g
7
+ const TURBO_INVOCATION =
8
+ /\b(?:turbo|nx)\s+run\s+((?:[a-z][\w:-]*\s+)*[a-z][\w:-]*)/g
9
+
10
+ /**
11
+ * The package scripts CI actually runs.
12
+ *
13
+ * Asserting that a workflow names `check:ci` would have been the wrong
14
+ * question. verticagtm runs every gate in CI as its own step - `pnpm run
15
+ * type-check`, `pnpm run lint`, `pnpm run dupes` - and never says `check:ci`
16
+ * anywhere; it is the best-wired repository in the estate and a name-matching
17
+ * check called it unwired. What matters is which gates the pipeline reaches,
18
+ * so that is what gets measured.
19
+ *
20
+ * Only scripts the project defines are returned: `pnpm install` and
21
+ * `pnpm audit` are not entrypoints, and a workflow is full of shell that is
22
+ * not a package script.
23
+ */
24
+ export function ciEntrypoints(workflows, scripts) {
25
+ const entries = new Set()
26
+
27
+ for (const workflow of workflows) {
28
+ for (const match of workflow.text.matchAll(INVOCATION)) {
29
+ if (Object.hasOwn(scripts, match[1])) entries.add(match[1])
30
+ }
31
+ for (const match of workflow.text.matchAll(TURBO_INVOCATION)) {
32
+ for (const target of match[1].trim().split(/\s+/)) entries.add(target)
33
+ }
34
+ }
35
+
36
+ return [...entries]
37
+ }
@@ -0,0 +1,76 @@
1
+ // A script reference inside another script's command line, in every form the
2
+ // adopting repos actually use: `pnpm x`, `pnpm run x`, `npm run x`,
3
+ // `yarn x`, `bun run x`, and `turbo run x y z` (which names several at once).
4
+ const RUN_REFERENCE = /\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?([a-z][\w:-]*)/g
5
+ const TURBO_REFERENCE =
6
+ /\b(?:turbo|nx)\s+run\s+((?:[a-z][\w:-]*\s+)*[a-z][\w:-]*)/g
7
+
8
+ // A local file a script hands the work to instead of chaining the steps
9
+ // inline: `node scripts/check-quality.mjs`, `bash scripts/ci.sh`, `./run.sh`.
10
+ const RUNNER_FILE =
11
+ /(?:\bnode\s+|\bbash\s+|\bsh\s+|\B)([\w./-]+\.(?:mjs|cjs|js|ts|sh))\b/g
12
+
13
+ /**
14
+ * Everything reachable from `entries`: the set of script names, and the
15
+ * concatenated text of their commands.
16
+ *
17
+ * Three kinds of reference are followed, because all three are in use across
18
+ * the estate:
19
+ *
20
+ * - another script, which is how half the repositories compose their gates
21
+ * (`check:ci` calls `check:all` calls `lint`);
22
+ * - a `turbo run <task>` target, recorded as reached even when the root
23
+ * defines no script by that name - in a monorepo the task lives in each
24
+ * workspace's manifest, and requiring it at the root would report every
25
+ * monorepo as missing the gates it actually runs;
26
+ * - a local runner file named in `runners`, whose text is read as though it
27
+ * were part of the command. The baseline repo's own `check:quality` is
28
+ * `node scripts/check-quality.mjs`, a step runner that exists so a failure
29
+ * names the gate that produced it; without following it into the file, the
30
+ * reference implementation reports its own gates as uninvoked.
31
+ *
32
+ * Both halves of the return value are needed downstream: a gate can be
33
+ * invoked as a script (`pnpm knip`) or as a bare tool (`depcruise src`).
34
+ */
35
+ export function expandScripts(scripts, entries, runners = {}) {
36
+ const names = new Set()
37
+ const commands = []
38
+ const queue = entries.filter((name) => Object.hasOwn(scripts, name))
39
+ const readRunners = new Set()
40
+
41
+ const follow = (command) => {
42
+ commands.push(command)
43
+
44
+ for (const match of command.matchAll(RUN_REFERENCE)) {
45
+ const target = match[1]
46
+ if (Object.hasOwn(scripts, target) && !names.has(target)) {
47
+ queue.push(target)
48
+ }
49
+ }
50
+ for (const match of command.matchAll(TURBO_REFERENCE)) {
51
+ for (const target of match[1].trim().split(/\s+/)) {
52
+ if (names.has(target)) continue
53
+ if (Object.hasOwn(scripts, target)) queue.push(target)
54
+ else names.add(target)
55
+ }
56
+ }
57
+ for (const match of command.matchAll(RUNNER_FILE)) {
58
+ const path = match[1].replace(/^\.\//, '')
59
+ if (readRunners.has(path) || !Object.hasOwn(runners, path)) continue
60
+ readRunners.add(path)
61
+ follow(runners[path])
62
+ }
63
+ }
64
+
65
+ while (queue.length) {
66
+ const name = queue.shift()
67
+ if (names.has(name)) continue
68
+ names.add(name)
69
+
70
+ const command = scripts[name]
71
+ if (!command) continue
72
+ follow(command)
73
+ }
74
+
75
+ return { names, text: commands.join(' && ') }
76
+ }
@@ -0,0 +1,36 @@
1
+ const MARKER = { error: 'FAIL', warn: 'WARN', info: 'note' }
2
+
3
+ /**
4
+ * A conformance report as text.
5
+ *
6
+ * One line per finding with its id first: the id is what goes into
7
+ * `baseline.exceptions.json` to waive it, so it has to be copy-pasteable
8
+ * rather than reconstructed from prose. The detail is indented under it,
9
+ * wrapped by the caller's terminal rather than hard-wrapped here.
10
+ */
11
+ export function formatFindings({ findings, waived }) {
12
+ const lines = []
13
+
14
+ for (const finding of findings) {
15
+ lines.push(
16
+ ` ${MARKER[finding.level] ?? finding.level} ${finding.id} ${finding.message}`,
17
+ )
18
+ if (finding.detail) lines.push(` ${finding.detail}`)
19
+ if (finding.fix) lines.push(' (fixable with --fix)')
20
+ }
21
+
22
+ if (waived.length) {
23
+ lines.push('', ' Waived by baseline.exceptions.json:')
24
+ for (const finding of waived) {
25
+ const expiry = finding.waiver.expires
26
+ ? ` (expires ${finding.waiver.expires})`
27
+ : ''
28
+ lines.push(
29
+ ` ${finding.id} ${finding.message}${expiry}`,
30
+ ` ${finding.waiver.reason}`,
31
+ )
32
+ }
33
+ }
34
+
35
+ return lines.join('\n')
36
+ }
@@ -0,0 +1,175 @@
1
+ import { access, readFile } from 'node:fs/promises'
2
+ import { resolve } from 'node:path'
3
+
4
+ import { collectDeps } from '../scaffold/collectDeps.mjs'
5
+ import { readManifest } from '../scaffold/readManifest.mjs'
6
+ import { workspaceRoots } from '../scaffold/workspaceRoots.mjs'
7
+ import { readWorkflows } from './readWorkflows.mjs'
8
+
9
+ const TEST_CONFIGS = [
10
+ 'vitest.config.ts',
11
+ 'vitest.config.mts',
12
+ 'vitest.config.js',
13
+ 'vitest.config.mjs',
14
+ 'vite.config.ts',
15
+ 'vite.config.mts',
16
+ 'vite.config.js',
17
+ 'vite.config.mjs',
18
+ 'jest.config.ts',
19
+ 'jest.config.js',
20
+ 'jest.config.mjs',
21
+ 'jest.config.cjs',
22
+ ]
23
+
24
+ /**
25
+ * Everything the conformance checks read, gathered once.
26
+ *
27
+ * Each check is a pure function of this object, which is what makes the suite
28
+ * cheap enough to run over the whole estate: one pass over a repository's
29
+ * files, then ten checks against the result.
30
+ */
31
+ export async function loadContext(root, versions) {
32
+ const manifest = await readManifest(root)
33
+
34
+ // Workspace manifests first so the root's own entry wins a version clash and
35
+ // the report names the version the repo installs at its top level. Without
36
+ // this, a monorepo that declares the baseline per workspace reads as having
37
+ // none of it - which is how intelifactu, running the whole toolchain, was
38
+ // told it had nothing installed.
39
+ const deps = {}
40
+ for (const workspace of await workspaceRoots(root)) {
41
+ try {
42
+ Object.assign(deps, collectDeps(await readManifest(workspace)))
43
+ } catch {
44
+ /* a directory without a manifest is not a workspace */
45
+ }
46
+ }
47
+ Object.assign(deps, collectDeps(manifest))
48
+
49
+ const scripts = manifest.scripts ?? {}
50
+
51
+ return {
52
+ root,
53
+ manifest,
54
+ scripts,
55
+ deps,
56
+ versions,
57
+ runners: await readRunners(root, scripts),
58
+ tsconfigs: await readTsconfigs(root),
59
+ workflows: await readWorkflows(root),
60
+ testConfig: await findTestConfig(root),
61
+ hooks: { installed: await hooksInstalled(root) },
62
+ }
63
+ }
64
+
65
+ // Git hooks belong to the repository, not to the directory the check runs in.
66
+ // A template or workspace nested inside a repo shares its hooks, so looking
67
+ // only at `<root>/.git` reports every one of them as unwired - eight
68
+ // templates, all of them covered by the hooks installed at the repo root.
69
+ async function hooksInstalled(root) {
70
+ let dir = root
71
+ for (;;) {
72
+ if (await exists(resolve(dir, '.git'))) {
73
+ return exists(resolve(dir, '.git/hooks/pre-commit'))
74
+ }
75
+ const parent = resolve(dir, '..')
76
+ if (parent === dir) return false
77
+ dir = parent
78
+ }
79
+ }
80
+
81
+ // A local file a script hands its steps to, rather than chaining them inline.
82
+ // Only paths that appear in a script command are read, and only files that
83
+ // exist - this walks nothing and guesses nothing.
84
+ const RUNNER_PATH =
85
+ /(?:\bnode\s+|\bbash\s+|\bsh\s+)([\w./-]+\.(?:mjs|cjs|js|ts|sh))\b/g
86
+
87
+ async function readRunners(root, scripts) {
88
+ const runners = {}
89
+ for (const command of Object.values(scripts)) {
90
+ if (typeof command !== 'string') continue
91
+ for (const match of command.matchAll(RUNNER_PATH)) {
92
+ const path = match[1].replace(/^\.\//, '')
93
+ // A path that climbs out of the project is not this project's runner.
94
+ if (path.startsWith('../') || Object.hasOwn(runners, path)) continue
95
+ try {
96
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
97
+ runners[path] = await readFile(resolve(root, path), 'utf8')
98
+ } catch {
99
+ /* named but not present: nothing to follow */
100
+ }
101
+ }
102
+ }
103
+ return runners
104
+ }
105
+
106
+ // tsconfig permits comments and trailing commas; strip both before parsing.
107
+ // A file this cannot parse contributes `null`, never a guess.
108
+ async function parseTsconfig(path) {
109
+ try {
110
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
111
+ const raw = (await readFile(path, 'utf8'))
112
+ .replaceAll(/\/\*[\s\S]*?\*\//g, '')
113
+ .replaceAll(/(^|[^:])\/\/.*$/gm, '$1')
114
+ .replaceAll(/,(\s*[}\]])/g, '$1')
115
+ return JSON.parse(raw)
116
+ } catch {
117
+ return null
118
+ }
119
+ }
120
+
121
+ // The root tsconfig and, when it is solution-style, the projects it
122
+ // references. Each leaf carries the reference as the root spells it (what a
123
+ // `type-check` script would name) and the config file it resolves to - `tsc`
124
+ // accepts either a directory holding a tsconfig.json or the file itself.
125
+ async function readTsconfigs(root) {
126
+ const parsed = await parseTsconfig(resolve(root, 'tsconfig.json'))
127
+ if (!parsed) return null
128
+
129
+ const solution =
130
+ Array.isArray(parsed.files) &&
131
+ parsed.files.length === 0 &&
132
+ parsed.include === undefined &&
133
+ Array.isArray(parsed.references)
134
+
135
+ const leaves = []
136
+ if (solution) {
137
+ for (const entry of parsed.references) {
138
+ if (typeof entry?.path !== 'string') continue
139
+ const reference = entry.path.replace(/^\.\//, '')
140
+ const viaDirectory = await exists(
141
+ resolve(root, reference, 'tsconfig.json'),
142
+ )
143
+ const config = viaDirectory ? `${reference}/tsconfig.json` : reference
144
+ leaves.push({
145
+ reference,
146
+ config,
147
+ parsed: await parseTsconfig(resolve(root, config)),
148
+ })
149
+ }
150
+ }
151
+
152
+ return { root: parsed, solution, leaves }
153
+ }
154
+
155
+ async function findTestConfig(root) {
156
+ for (const name of TEST_CONFIGS) {
157
+ const path = resolve(root, name)
158
+ try {
159
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
160
+ return { name, path, text: await readFile(path, 'utf8') }
161
+ } catch {
162
+ /* next candidate */
163
+ }
164
+ }
165
+ return null
166
+ }
167
+
168
+ async function exists(path) {
169
+ try {
170
+ await access(path)
171
+ return true
172
+ } catch {
173
+ return false
174
+ }
175
+ }
@@ -0,0 +1,73 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { resolve } from 'node:path'
3
+
4
+ const FILE = 'baseline.exceptions.json'
5
+
6
+ /**
7
+ * Documented deviations from the baseline, read from `baseline.exceptions.json`.
8
+ *
9
+ * Shape: `{ "<finding id>": { "reason": "...", "expires": "YYYY-MM-DD" } }`.
10
+ *
11
+ * `reason` is required. An exception without one is rejected rather than
12
+ * honoured, because a silent waiver and a missing gate are the same thing from
13
+ * outside - the whole point of the file is that the deviation stays visible in
14
+ * review instead of being absent from the report.
15
+ *
16
+ * `expires` is optional and, when present, enforced: a stale waiver becomes a
17
+ * finding of its own. That is the difference between this file and the prose
18
+ * exceptions that accumulated in TODO.md, where nothing ever re-checked them.
19
+ */
20
+ export async function loadExceptions(root, today) {
21
+ let raw
22
+ try {
23
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
24
+ raw = await readFile(resolve(root, FILE), 'utf8')
25
+ } catch {
26
+ return { waived: new Map(), findings: [] }
27
+ }
28
+
29
+ let parsed
30
+ try {
31
+ parsed = JSON.parse(raw)
32
+ } catch (error) {
33
+ return {
34
+ waived: new Map(),
35
+ findings: [
36
+ {
37
+ id: 'exceptions',
38
+ level: 'error',
39
+ message: `${FILE} is not valid JSON`,
40
+ detail: String(error.message),
41
+ },
42
+ ],
43
+ }
44
+ }
45
+
46
+ const waived = new Map()
47
+ const findings = []
48
+
49
+ for (const [id, entry] of Object.entries(parsed)) {
50
+ if (!entry?.reason) {
51
+ findings.push({
52
+ id: `exceptions:${id}`,
53
+ level: 'error',
54
+ message: `waiver for \`${id}\` has no reason`,
55
+ detail:
56
+ 'An undocumented waiver is indistinguishable from a missing gate.',
57
+ })
58
+ continue
59
+ }
60
+ if (entry.expires && entry.expires < today) {
61
+ findings.push({
62
+ id: `exceptions:${id}`,
63
+ level: 'error',
64
+ message: `waiver for \`${id}\` expired on ${entry.expires}`,
65
+ detail: `Reason given: ${entry.reason}. Re-check it, then renew or remove it.`,
66
+ })
67
+ continue
68
+ }
69
+ waived.set(id, entry)
70
+ }
71
+
72
+ return { waived, findings }
73
+ }