@shivaedev/quality 0.48.1 → 0.49.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 (108) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +58 -11
  3. package/biome/plugins/ambient-runtime.grit +67 -1
  4. package/biome/plugins/type-re-exports.grit +33 -4
  5. package/dist/adapters/biome/run.js +4 -4
  6. package/dist/adapters/biome/run.js.map +1 -1
  7. package/dist/adapters/fixJsxConditionals.d.ts.map +1 -1
  8. package/dist/adapters/fixJsxConditionals.js +2 -5
  9. package/dist/adapters/fixJsxConditionals.js.map +1 -1
  10. package/dist/adapters/knip/configuration.d.ts +5 -2
  11. package/dist/adapters/knip/configuration.d.ts.map +1 -1
  12. package/dist/adapters/knip/configuration.js +12 -5
  13. package/dist/adapters/knip/configuration.js.map +1 -1
  14. package/dist/adapters/knip/run.d.ts +2 -3
  15. package/dist/adapters/knip/run.d.ts.map +1 -1
  16. package/dist/adapters/knip/run.js +25 -7
  17. package/dist/adapters/knip/run.js.map +1 -1
  18. package/dist/adapters/knip/sourceConfig.d.ts.map +1 -1
  19. package/dist/adapters/knip/sourceConfig.js +3 -0
  20. package/dist/adapters/knip/sourceConfig.js.map +1 -1
  21. package/dist/baseline/looseStagedEntries.d.ts +4 -0
  22. package/dist/baseline/looseStagedEntries.d.ts.map +1 -0
  23. package/dist/baseline/looseStagedEntries.js +31 -0
  24. package/dist/baseline/looseStagedEntries.js.map +1 -0
  25. package/dist/baseline/update.d.ts +1 -1
  26. package/dist/baseline/update.d.ts.map +1 -1
  27. package/dist/baseline/update.js +3 -3
  28. package/dist/baseline/update.js.map +1 -1
  29. package/dist/cli/args.d.ts +1 -1
  30. package/dist/cli/args.d.ts.map +1 -1
  31. package/dist/cli/args.js +5 -5
  32. package/dist/cli/args.js.map +1 -1
  33. package/dist/cli/baseline.d.ts +1 -1
  34. package/dist/cli/baseline.d.ts.map +1 -1
  35. package/dist/cli/baseline.js +19 -2
  36. package/dist/cli/baseline.js.map +1 -1
  37. package/dist/cli/lint.d.ts +1 -1
  38. package/dist/cli/lint.d.ts.map +1 -1
  39. package/dist/cli/lint.js +11 -2
  40. package/dist/cli/lint.js.map +1 -1
  41. package/dist/cli/messages.d.ts +1 -1
  42. package/dist/cli/messages.d.ts.map +1 -1
  43. package/dist/cli/messages.js +3 -3
  44. package/dist/cli/program.d.ts.map +1 -1
  45. package/dist/cli/program.js +3 -2
  46. package/dist/cli/program.js.map +1 -1
  47. package/dist/hooks/preCommit.js +1 -1
  48. package/dist/hooks/preCommit.js.map +1 -1
  49. package/dist/inventory/collect.js +3 -3
  50. package/dist/inventory/collect.js.map +1 -1
  51. package/dist/inventory/shadcnFiles.d.ts +4 -0
  52. package/dist/inventory/shadcnFiles.d.ts.map +1 -0
  53. package/dist/inventory/shadcnFiles.js +83 -0
  54. package/dist/inventory/shadcnFiles.js.map +1 -0
  55. package/dist/report/render.d.ts.map +1 -1
  56. package/dist/report/render.js +3 -10
  57. package/dist/report/render.js.map +1 -1
  58. package/dist/report/staleSections.js +1 -1
  59. package/dist/report/staleSections.js.map +1 -1
  60. package/dist/rules/builtIn.d.ts +1 -1
  61. package/dist/rules/importOrigins.d.ts +4 -0
  62. package/dist/rules/importOrigins.d.ts.map +1 -0
  63. package/dist/rules/importOrigins.js +36 -0
  64. package/dist/rules/importOrigins.js.map +1 -0
  65. package/dist/rules/noBarrel.d.ts.map +1 -1
  66. package/dist/rules/noBarrel.js +19 -7
  67. package/dist/rules/noBarrel.js.map +1 -1
  68. package/dist/rules/react/jsxChildDecision.d.ts +5 -0
  69. package/dist/rules/react/jsxChildDecision.d.ts.map +1 -0
  70. package/dist/rules/react/jsxChildDecision.js +74 -0
  71. package/dist/rules/react/jsxChildDecision.js.map +1 -0
  72. package/dist/rules/react/jsxConditionals.d.ts.map +1 -1
  73. package/dist/rules/react/jsxConditionals.js +9 -33
  74. package/dist/rules/react/jsxConditionals.js.map +1 -1
  75. package/dist/rules/secondNames.d.ts +7 -0
  76. package/dist/rules/secondNames.d.ts.map +1 -0
  77. package/dist/rules/secondNames.js +98 -0
  78. package/dist/rules/secondNames.js.map +1 -0
  79. package/dist/rules/stories/importBindings.d.ts.map +1 -1
  80. package/dist/rules/stories/importBindings.js +3 -0
  81. package/dist/rules/stories/importBindings.js.map +1 -1
  82. package/dist/rules/unusedCode.d.ts +1 -1
  83. package/dist/rules/unusedCode.d.ts.map +1 -1
  84. package/docs/debt-and-hooks.md +5 -5
  85. package/package.json +4 -4
  86. package/src/adapters/biome/run.ts +4 -4
  87. package/src/adapters/fixJsxConditionals.ts +2 -8
  88. package/src/adapters/knip/configuration.ts +12 -5
  89. package/src/adapters/knip/run.ts +27 -7
  90. package/src/adapters/knip/sourceConfig.ts +3 -0
  91. package/src/baseline/looseStagedEntries.ts +32 -0
  92. package/src/baseline/update.ts +5 -2
  93. package/src/cli/args.ts +6 -7
  94. package/src/cli/baseline.ts +19 -1
  95. package/src/cli/lint.ts +11 -1
  96. package/src/cli/messages.ts +3 -3
  97. package/src/cli/program.ts +3 -2
  98. package/src/hooks/preCommit.ts +1 -1
  99. package/src/inventory/collect.ts +3 -3
  100. package/src/inventory/shadcnFiles.ts +87 -0
  101. package/src/report/render.ts +3 -10
  102. package/src/report/staleSections.ts +1 -1
  103. package/src/rules/importOrigins.ts +38 -0
  104. package/src/rules/noBarrel.ts +21 -8
  105. package/src/rules/react/jsxChildDecision.ts +84 -0
  106. package/src/rules/react/jsxConditionals.ts +9 -35
  107. package/src/rules/secondNames.ts +121 -0
  108. package/src/rules/stories/importBindings.ts +3 -0
@@ -12,7 +12,7 @@ The [README](../README.md) introduces the gate. This page explains how the basel
12
12
  The baseline is sharded: `packages/<package>/quality-baseline.jsonl` holds paths inside that package, and the root `quality-baseline.jsonl` holds all other paths. Packages without entries have no file. Each shard is JSON Lines with one entry per line: the violations of one rule in one file. `count` is how many violations the file may have. For a rule that counts occurrences, such as `comments/no-jsdoc`, that is the number of occurrences. For a rule with a limit, it is the amount over the limit: the entry above lets `src/server/db.ts` have 412 lines under a limit of 150. A new baseline is sorted by path and then rule. Later edits preserve unrelated lines, including their formatting and order, so the diff shows the entries that changed.
13
13
 
14
14
  `quality lint` fails when a baselined file has more violations than its `count`; the report then lists all of that file's violations for the rule. A file at or below its entry passes. An entry that allows more than is left, including a file with no violations left, is listed as a note and does not fail, so fixing debt never breaks the build; `tighten` and `prune` lower it. An entry for an unknown rule fails until it is pruned.
15
- - `quality baseline write` records every error-level violation when there is no baseline yet. Once a baseline exists it refuses, unless `--rule <id>` names the rules to record: it then replaces the entries of those rules with what the files have now, and leaves every other entry as it is.
15
+ - `quality baseline write` records every error-level violation when there is no baseline yet. Once a baseline exists, both `--rule <id>` and `--file <path>` are required. Repeat either option for multiple selections. Each path is relative to the config folder and must be changed since `HEAD`, staged or unstaged; new files need `git add` first. An unchanged file refuses the whole write. Only selected rule/file entries are replaced; all other entries stay as they are. With no baseline and no file selection, initial adoption records the repository once.
16
16
  - `quality baseline tighten` lowers and removes the entries of files changed since `HEAD`, and with `--staged`, of the files staged for the next commit. It carries the entry of a file that git sees as moved to the new path. Every other line stays byte for byte.
17
17
  - `quality baseline prune` does the same for every entry. It carries the entries of files moved since the merge base (see `--against` under [Command line](../README.md#command-line)), and prunes without following moves outside a git work tree.
18
18
  - `quality baseline migrate` moves a baseline from the earlier JSON format, `quality/baseline.json` or the file `--from` names, to the root and package shards, and removes the old one. `--from quality/baseline.jsonl` splits a single JSON Lines baseline without changing its counts. An old entry that stored a size, such as a line count, becomes that size less the rule's current limit; an entry whose file is now within the limit is dropped.
@@ -23,7 +23,7 @@ Git merges shards through the driver described in the [README](../README.md#base
23
23
 
24
24
  ### Pre-commit
25
25
 
26
- Lowering entries in the commit that fixes them keeps the baseline current. Run these commands explicitly before committing:
26
+ The commit check rejects a staged baseline count that allows more than the file currently has. It reads baseline entries from the index, so lowering the working copy without staging it still fails. It checks entries for staged source files and changed entries in staged baseline shards; unrelated loose debt stays a lint note. Lower entries in the commit that fixes them: Run these commands explicitly before committing:
27
27
 
28
28
  ```sh
29
29
  quality baseline tighten --staged
@@ -35,11 +35,11 @@ quality lint
35
35
 
36
36
  ### Baseline growth
37
37
 
38
- An error-level finding that neither the config exceptions nor the baseline covers fails `quality lint`; that is how new debt gets noticed. The baseline itself may grow: a reviewer sees each new or raised entry in the diff and judges it. When the failing findings are debt the baseline should keep, such as the debt of a file that moved or was renamed, record the rule again with `quality baseline write --rule <id>`. The report ends with that command for the rules that failed. Then call out the baseline growth in the pull request description.
38
+ An error-level finding that neither the config exceptions nor the baseline covers fails `quality lint`; that is how new debt gets noticed. The baseline itself may grow: a reviewer sees each new or raised entry in the diff and judges it. For moved files, run `quality baseline prune --against <base>` to carry existing counts to the new paths. The failing report ends with that guidance. For retained findings in a changed file, use `quality baseline write --rule <id> --file <path>` and call out new or raised counts in the pull request. Writing a rule does not absorb findings from other files.
39
39
 
40
40
  ### Counts after a policy change
41
41
 
42
- A count depends on the rule's limit, so a Quality policy change that adjusts a limit shifts every count of that rule. A looser limit leaves entries that allow more than is left: they pass, and `tighten` and `prune` lower them. A stricter limit can make an error-level rule's files fail `quality lint`, since each is now further over the limit. Inspect the findings under the new policy before recording retained debt again with `quality baseline write --rule <id>`. Commit the counts with the policy upgrade. The raised entries show in the diff, and the pull request calls them out.
42
+ A count depends on the rule's limit, so a Quality policy change that adjusts a limit shifts every count of that rule. A looser limit leaves entries that allow more than is left: they pass, and `tighten` and `prune` lower them. A stricter limit can make an error-level rule's files fail `quality lint`, since each is now further over the limit. Inspect the findings under the new policy before recording retained debt again with `quality baseline write --rule <id> --file <path>`. Commit the counts with the policy upgrade. The raised entries show in the diff, and the pull request calls them out.
43
43
 
44
44
  ## Exceptions
45
45
 
@@ -65,7 +65,7 @@ Export an object or `defineConfig({ ... })` without spreads for automatic editin
65
65
 
66
66
  ## Pre-commit hook
67
67
 
68
- `quality hooks install` installs a git pre-commit hook that runs `quality hooks pre-commit` before every commit: `quality lint`, then the `typecheck` script, then an optional `quality:commit` script, as the [README](../README.md) describes. A repository opts in by running the command, usually from the setup script each checkout runs once. Running it again is safe.
68
+ `quality hooks install` installs a git pre-commit hook that runs `quality hooks pre-commit` before every commit: `quality lint` with a staged-baseline count check, then the `typecheck` script, then an optional `quality:commit` script, as the [README](../README.md) describes. A repository opts in by running the command, usually from the setup script each checkout runs once. Running it again is safe.
69
69
 
70
70
  Scripts run from the config's folder, or the current directory when there is no config. Without a manifest or either script, the hook runs lint alone. An invalid manifest stops the run. Baseline tightening is an explicit command; the hook does not change or stage debt records.
71
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/quality",
3
- "version": "0.48.1",
3
+ "version": "0.49.0",
4
4
  "description": "Repository quality gate with typed rules, a baseline of existing debt and a registry of reasoned exceptions",
5
5
  "homepage": "https://github.com/ShivaeDev/platform/tree/main/packages/quality#readme",
6
6
  "bugs": {
@@ -53,8 +53,8 @@
53
53
  "@biomejs/biome": "2.6.2",
54
54
  "@shivaedev/types": "0.3.0",
55
55
  "@vitest/coverage-v8": "5.0.5",
56
- "ignore": "7.0.13",
57
- "knip": "6.42.1",
56
+ "ignore": "7.0.14",
57
+ "knip": "6.43.0",
58
58
  "sort-package-json": "4.1.0",
59
59
  "typescript": "npm:@typescript/typescript6@6.0.2"
60
60
  },
@@ -62,7 +62,7 @@
62
62
  "@effect/platform-node": "4.0.6",
63
63
  "@effect/platform-node-shared": "4.0.6",
64
64
  "@effect/vitest": "4.0.6",
65
- "@shivaedev/test-story": "0.26.3",
65
+ "@shivaedev/test-story": "0.29.0",
66
66
  "@types/node": "24.19.2",
67
67
  "@typescript/native": "npm:typescript@7.0.2",
68
68
  "effect": "4.0.6",
@@ -4,7 +4,7 @@ import { Effect, Stream } from "effect";
4
4
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
5
5
  import { withExceptionConfig } from "#biome/exceptionConfig.ts";
6
6
  import type { ExceptionDeclaration } from "#exceptions/declaration.ts";
7
- import { shadcnFolders } from "#inventory/shadcnFolders.ts";
7
+ import { shadcnFiles } from "#inventory/shadcnFiles.ts";
8
8
 
9
9
  export interface BiomeRun {
10
10
  readonly code: number;
@@ -19,11 +19,11 @@ export const runBiome = Effect.fn("Biome.runBiome")(function* (
19
19
  args: readonly string[],
20
20
  exceptions: readonly ExceptionDeclaration[] = [],
21
21
  ) {
22
- const folders = yield* shadcnFolders(root);
22
+ const files = yield* shadcnFiles(root);
23
23
  const toolOwned: readonly ExceptionDeclaration[] = [
24
24
  {
25
- files: ["**", "!**/pnpm-lock.yaml", ...folders.map((folder) => `!${folder}`)],
26
- reason: "pnpm writes its lockfiles; components.json assigns UI folders to the shadcn CLI.",
25
+ files: ["**", "!**/pnpm-lock.yaml", ...files.map((file) => `!${file}`)],
26
+ reason: "pnpm writes its lockfiles; canonical shadcn component filenames in the configured UI folder belong to its CLI.",
27
27
  rules: ["biome/files/includes"],
28
28
  },
29
29
  ];
@@ -1,6 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import type { SourceFile } from "#rule.ts";
3
3
  import { parse } from "#rules/parse.ts";
4
+ import { jsxChildDecision } from "#rules/react/jsxChildDecision.ts";
4
5
 
5
6
  interface Edit {
6
7
  readonly end: number;
@@ -35,14 +36,7 @@ function conditionalChild(node: ts.Expression): ts.Expression | undefined {
35
36
  return undefined;
36
37
  }
37
38
  const expression = unwrap(child.expression);
38
- return isConditional(expression) ? child.expression : undefined;
39
- }
40
-
41
- function isConditional(expression: ts.Expression): boolean {
42
- return (
43
- ts.isConditionalExpression(expression)
44
- || (ts.isBinaryExpression(expression) && expression.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken)
45
- );
39
+ return jsxChildDecision(expression) === undefined ? undefined : child.expression;
46
40
  }
47
41
 
48
42
  function returnedExpression(node: ts.Node): ts.Expression | undefined {
@@ -2,7 +2,7 @@ import { posix } from "node:path";
2
2
  import { readPackageManifest } from "#adapters/manifestInventory.ts";
3
3
  import { exportedModule, exportTargets } from "#imports/packageExports.ts";
4
4
  import { packageOf, workspacePackages } from "#imports/workspace.ts";
5
- import { isMigrationFile } from "#naming/migrationFile.ts";
5
+ import { SHADCN_FILE_GLOB } from "#inventory/shadcnFiles.ts";
6
6
  import type { RuleInputs } from "#rule.ts";
7
7
  import { KNIP_ISSUES } from "./findings.ts";
8
8
 
@@ -18,7 +18,7 @@ function importPaths(imports: Readonly<Record<string, unknown>>) {
18
18
  );
19
19
  }
20
20
 
21
- export async function knipConfiguration(inputs: RuleInputs) {
21
+ export async function knipConfiguration(inputs: RuleInputs, toolOwned: readonly string[] = []) {
22
22
  const packages = await workspacePackages(inputs);
23
23
  const manifests = await Promise.all(
24
24
  [".", ...packages.map(({ directory }) => directory)].map(async (directory) => {
@@ -42,13 +42,20 @@ export async function knipConfiguration(inputs: RuleInputs) {
42
42
  );
43
43
  const publicFiles = sources.filter((path) => exportedModule(manifest.exports, path));
44
44
  // Migration runners load these files from their directory, so no import reaches them.
45
- const migrations = sources.filter((path) => isMigrationFile(posix.join(directory, path)));
45
+ const migrations = sources.filter((path) => /(?:^|\/)server\/migrations\//u.test(path));
46
+ const ui = toolOwned
47
+ .filter((folder) => (packageOf(packages, `${folder}/component.ts`)?.directory ?? ".") === directory)
48
+ .map((folder) => `${posix.relative(directory, folder)}/**/${SHADCN_FILE_GLOB}`);
49
+ const styles = inputs.files
50
+ .filter((path) => path.endsWith(".css") && (packageOf(packages, path)?.directory ?? ".") === directory)
51
+ .map((path) => posix.relative(directory, path));
46
52
  return [
47
53
  directory,
48
54
  {
49
- entry: [...ENTRIES, ...publicFiles, ...migrations, ...bins, ...binaries, ...scriptEntries],
55
+ entry: [...ENTRIES, ...publicFiles, ...migrations, ...bins, ...binaries, ...scriptEntries, ...ui, ...styles],
50
56
  paths: importPaths(manifest.imports ?? {}),
51
- project: sources,
57
+ project: [...sources, ...ui, ...styles],
58
+ vitest: { config: ["vitest*.config.{ts,mts,cts,js,mjs,cjs}", "vitest.{workspace,projects}.{ts,mts,cts,js,mjs,cjs,json}"] },
52
59
  },
53
60
  ] as const;
54
61
  });
@@ -1,21 +1,31 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { basename, dirname, join, posix } from "node:path";
3
3
  import process from "node:process";
4
+ import { pathToFileURL } from "node:url";
4
5
  import { Effect, FileSystem, Stream } from "effect";
5
6
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
6
7
  import { readPackageManifest } from "#adapters/manifestInventory.ts";
8
+ import { shadcnFolders } from "#inventory/shadcnFolders.ts";
7
9
  import type { RuleInputs } from "#rule.ts";
8
10
  import { knipConfiguration } from "./configuration.ts";
9
11
  import { entryPointFindings } from "./entryPointFindings.ts";
10
12
  import { KNIP_ISSUES, knipFindings } from "./findings.ts";
11
13
  import { sourceConfig } from "./sourceConfig.ts";
12
14
 
13
- const BIN = join(dirname(createRequire(import.meta.url).resolve("knip")), "..", "bin", "knip.js");
15
+ const API = createRequire(import.meta.url).resolve("knip");
16
+ const BIN = join(dirname(API), "..", "bin", "knip.js");
17
+ // Initialize the loader in isolation, then evaluate application configs from their checkout.
18
+ const LAUNCH = `
19
+ const [api, entry, root] = process.argv.splice(1, 3);
20
+ import(api).then(() => { process.chdir(root); return import(entry); })
21
+ .catch(error => { console.error(error); process.exitCode = 1; });
22
+ `;
14
23
  export const runKnip = Effect.fn("Knip.runKnip")(function* (inputs: RuleInputs) {
15
24
  if ((yield* Effect.promise(() => readPackageManifest(inputs.readText, "package.json"))) === undefined) {
16
25
  return [];
17
26
  }
18
- const configuration = yield* Effect.promise(() => knipConfiguration(inputs));
27
+ const folders = yield* shadcnFolders(inputs.root);
28
+ const configuration = yield* Effect.promise(() => knipConfiguration(inputs, folders));
19
29
  const checked = new Set([...inputs.files, ...Object.keys(configuration.workspaces).map((directory) => posix.join(directory, "package.json"))]);
20
30
  const findings = yield* Effect.scoped(
21
31
  Effect.gen(function* () {
@@ -24,13 +34,20 @@ export const runKnip = Effect.fn("Knip.runKnip")(function* (inputs: RuleInputs)
24
34
  const config = join(temporary, "knip.json");
25
35
  yield* fs.writeFileString(config, JSON.stringify(configuration));
26
36
  const tsconfig = yield* sourceConfig(inputs, Object.keys(configuration.workspaces), basename(temporary));
37
+ const cwd = join(inputs.root, posix.dirname(tsconfig), "run");
27
38
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
28
39
  const child = yield* spawner.spawn(
29
40
  ChildProcess.make(
30
41
  process.execPath,
31
42
  [
32
43
  "--conditions=source",
33
- BIN,
44
+ "--eval",
45
+ LAUNCH,
46
+ pathToFileURL(API).href,
47
+ pathToFileURL(BIN).href,
48
+ inputs.root,
49
+ "--directory",
50
+ inputs.root,
34
51
  "--config",
35
52
  config,
36
53
  "--tsConfig",
@@ -41,17 +58,20 @@ export const runKnip = Effect.fn("Knip.runKnip")(function* (inputs: RuleInputs)
41
58
  KNIP_ISSUES.join(","),
42
59
  "--no-progress",
43
60
  ],
44
- { cwd: inputs.root, env: { "JITI_TRY_NATIVE": "true" }, extendEnv: true, stdin: "ignore" },
61
+ { cwd, env: { "JITI_TRY_NATIVE": "true" }, extendEnv: true, stdin: "ignore" },
45
62
  ),
46
63
  );
47
64
  const [stdout, stderr, code] = yield* Effect.all(
48
65
  [Stream.mkString(Stream.decodeText(child.stdout)), Stream.mkString(Stream.decodeText(child.stderr)), child.exitCode],
49
66
  { concurrency: "unbounded" },
50
67
  );
51
- if (Number(code) > 1) {
52
- return yield* Effect.fail(new Error(`knip failed: ${stderr || `exit code ${code}`}`));
68
+ const report = yield* Effect.try(() => knipFindings(stdout)).pipe(
69
+ Effect.mapError(() => new Error(`knip exited ${code} without a valid report:\n${stderr || stdout || "No output."}`)),
70
+ );
71
+ if (Number(code) !== (report.length > 0 ? 1 : 0)) {
72
+ return yield* Effect.fail(new Error(`knip exited ${code} inconsistently with its report:\n${stderr || stdout}`));
53
73
  }
54
- return knipFindings(stdout).filter((finding) => checked.has(finding.file));
74
+ return report.filter((finding) => checked.has(finding.file));
55
75
  }),
56
76
  );
57
77
  return yield* Effect.promise(() => entryPointFindings(inputs, findings));
@@ -16,5 +16,8 @@ export const sourceConfig = Effect.fn("Knip.sourceConfig")(function* (inputs: Ru
16
16
  );
17
17
  yield* fs.writeFileString(join(folder, "tsconfig.json"), JSON.stringify({ extends: parents.flat(), files: [] }));
18
18
  }
19
+ // Knip's config loader searches from the parent of cwd, independently of --directory and --tsConfig.
20
+ const cwd = join(inputs.root, posix.dirname(relative), "run");
21
+ yield* fs.makeDirectory(cwd);
19
22
  return relative;
20
23
  });
@@ -0,0 +1,32 @@
1
+ import { Effect } from "effect";
2
+ import { validOrFail } from "#decoded.ts";
3
+ import type { Session } from "#engine/session.ts";
4
+ import { keyOf } from "#engine/violation.ts";
5
+ import { applyRegistry } from "#exceptions/registry.ts";
6
+ import { gitOrFail, run } from "#git/command.ts";
7
+ import { changesSince } from "#git/history.ts";
8
+ import { applyBaseline } from "./compare.ts";
9
+ import { type BaselineEntry, decodeBaseline } from "./format.ts";
10
+ import { shardOf } from "./shards.ts";
11
+
12
+ export const looseStagedEntries = Effect.fn("Baseline.looseStagedEntries")(function* (session: Session) {
13
+ const { root, baseline } = session.config;
14
+ const changed = yield* changesSince(root, ["--cached"]);
15
+ const shards = new Set([...changed.files].map((file) => shardOf(file, baseline)));
16
+ const paths = (yield* gitOrFail(root, ["ls-files", "-z", "--", baseline, "packages/*/quality-baseline.jsonl"]))
17
+ .split("\0")
18
+ .filter((path) => shards.has(path));
19
+ const head = yield* run(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
20
+ const entries: BaselineEntry[] = [];
21
+ for (const path of paths) {
22
+ const raw = yield* gitOrFail(root, ["show", `:./${path}`]);
23
+ const decoded = yield* validOrFail(path, yield* Effect.promise(() => decodeBaseline(raw)));
24
+ const tracked = head.code === 0 ? yield* gitOrFail(root, ["ls-tree", "HEAD", "--", path]) : "";
25
+ const previous = tracked === "" ? undefined : yield* gitOrFail(root, ["show", `HEAD:./${path}`]);
26
+ const before = yield* validOrFail(path, yield* Effect.promise(() => decodeBaseline(previous)));
27
+ const counts = new Map(before.map((entry) => [keyOf(entry.rule, entry.file), entry.count]));
28
+ entries.push(...decoded.filter((entry) => changed.files.has(entry.file) || counts.get(keyOf(entry.rule, entry.file)) !== entry.count));
29
+ }
30
+ const violations = applyRegistry(session.violations, session.registry, session.config).kept;
31
+ return applyBaseline(violations, entries, session.config).loose;
32
+ });
@@ -37,6 +37,7 @@ export function adopt(
37
37
  rules: readonly string[],
38
38
  violations: readonly Violation[],
39
39
  index: RuleIndex,
40
+ files?: ReadonlySet<string>,
40
41
  ): Adoption {
41
42
  if (existing !== undefined && rules.length === 0) {
42
43
  return { _tag: "Refused", reasons: ["a baseline exists. Record a rule with --rule <id>, or drop fixed debt with prune."] };
@@ -48,8 +49,10 @@ export function adopt(
48
49
  function named(rule: string): boolean {
49
50
  return rules.some((name) => covers(name, rule));
50
51
  }
51
- const kept = (existing ?? []).filter((entry) => !named(entry.rule));
52
- const adopted = violations.filter((violation) => rules.length === 0 || named(violation.rule));
52
+ const kept = (existing ?? []).filter((entry) => !(named(entry.rule) && (files === undefined || files.has(entry.file))));
53
+ const adopted = violations.filter(
54
+ (violation) => (rules.length === 0 || named(violation.rule)) && (files === undefined || files.has(violation.file)),
55
+ );
53
56
  const added = record(adopted);
54
57
  return { _tag: "Adopted", added: added.length, entries: [...kept, ...added], replaced: (existing ?? []).length - kept.length };
55
58
  }
package/src/cli/args.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { Result } from "effect";
3
- import { USAGE as COMMAND_USAGE, SUBCOMMANDS } from "./messages.ts";
3
+ import { SUBCOMMANDS } from "./messages.ts";
4
4
 
5
5
  export type Command =
6
6
  | { readonly _tag: "Ci"; readonly coverage: boolean }
@@ -10,7 +10,7 @@ export type Command =
10
10
  | { readonly _tag: "Fix"; readonly config: string | undefined; readonly rules: readonly string[] }
11
11
  | { readonly _tag: "BaselineMerge"; readonly base: string; readonly ours: string; readonly theirs: string }
12
12
  | { readonly _tag: "BaselineInstallDriver" }
13
- | { readonly _tag: "BaselineWrite"; readonly config: string | undefined; readonly rules: readonly string[] }
13
+ | { readonly _tag: "BaselineWrite"; readonly config: string | undefined; readonly rules: readonly string[]; readonly files: readonly string[] }
14
14
  | { readonly _tag: "BaselinePrune"; readonly config: string | undefined; readonly against: string | undefined }
15
15
  | { readonly _tag: "BaselineTighten"; readonly config: string | undefined; readonly staged: boolean }
16
16
  | { readonly _tag: "BaselineMigrate"; readonly config: string | undefined; readonly from: string | undefined }
@@ -22,12 +22,11 @@ export type Command =
22
22
 
23
23
  export type Parsed = { readonly _tag: "Parsed"; readonly command: Command } | { readonly _tag: "Usage"; readonly problem: string };
24
24
 
25
- export const USAGE = COMMAND_USAGE;
26
-
27
25
  const OPTIONS = {
28
26
  against: { type: "string" },
29
27
  config: { type: "string" },
30
28
  coverage: { type: "boolean" },
29
+ file: { multiple: true, type: "string" },
31
30
  force: { type: "boolean" },
32
31
  from: { type: "string" },
33
32
  help: { short: "h", type: "boolean" },
@@ -47,14 +46,14 @@ type Values = ReturnType<typeof parseArgs<{ options: typeof OPTIONS; allowPositi
47
46
 
48
47
  type Option = Exclude<keyof Values, "config" | "help">;
49
48
 
50
- const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "force", "from", "rule", "staged"];
49
+ const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "file", "force", "from", "rule", "staged"];
51
50
 
52
51
  const ACCEPTS: Readonly<Record<string, readonly Option[]>> = {
53
52
  "baseline install-driver": [],
54
53
  "baseline migrate": ["from"],
55
54
  "baseline prune": ["against"],
56
55
  "baseline tighten": ["staged"],
57
- "baseline write": ["rule"],
56
+ "baseline write": ["rule", "file"],
58
57
  ci: ["coverage"],
59
58
  "exceptions migrate": ["from"],
60
59
  fix: ["rule"],
@@ -92,7 +91,7 @@ function commandFor(name: string, values: Values): Parsed {
92
91
  case "baseline install-driver":
93
92
  return parsed({ _tag: "BaselineInstallDriver" });
94
93
  case "baseline write":
95
- return parsed({ _tag: "BaselineWrite", config, rules: values.rule ?? [] });
94
+ return parsed({ _tag: "BaselineWrite", config, files: values.file ?? [], rules: values.rule ?? [] });
96
95
  case "baseline prune":
97
96
  return ref(values.against, { _tag: "BaselinePrune", against: values.against, config });
98
97
  case "baseline tighten":
@@ -1,3 +1,4 @@
1
+ import { relative, resolve } from "node:path";
1
2
  import { Console, Effect, type FileSystem } from "effect";
2
3
  import type { BaselineEntry } from "#baseline/format.ts";
3
4
  import { saveShards } from "#baseline/shards.ts";
@@ -5,6 +6,7 @@ import { adopt, type Pruned, prune, type Scope } from "#baseline/update.ts";
5
6
  import { openSession, type Session } from "#engine/session.ts";
6
7
  import { applyRegistry } from "#exceptions/registry.ts";
7
8
  import { SetupFailure } from "#failure.ts";
9
+ import { changesSince } from "#git/history.ts";
8
10
  import { plural } from "#report/plural.ts";
9
11
  import type { RuleServices } from "#rule.ts";
10
12
 
@@ -20,10 +22,26 @@ export const writeBaseline = Effect.fn("Cli.writeBaseline")(function* (
20
22
  cwd: string,
21
23
  config: string | undefined,
22
24
  rules: readonly string[],
25
+ files: readonly string[],
23
26
  ): Effect.fn.Return<void, SetupFailure, RuleServices> {
24
27
  const session = yield* openSession(cwd, config);
25
28
  const existing = session.baseline.files.size === 0 ? undefined : session.baseline.entries;
26
- const adoption = adopt(existing, rules, unregistered(session), session.config);
29
+ if (existing !== undefined && files.length === 0) {
30
+ return yield* new SetupFailure({
31
+ message: "baseline write refused: a baseline exists. Record a rule with --rule <id> and --file <path>; use prune for moved or fixed debt.",
32
+ });
33
+ }
34
+ const selected = files.length === 0 ? undefined : new Set(files.map((file) => relative(session.config.root, resolve(session.config.root, file))));
35
+ if (selected !== undefined) {
36
+ const changed = yield* changesSince(session.config.root, ["HEAD"]);
37
+ const outside = [...selected].filter((file) => !changed.files.has(file));
38
+ if (outside.length > 0) {
39
+ return yield* new SetupFailure({
40
+ message: `baseline write refused: outside the current change set: ${outside.join(", ")}. Stage new files with git add first.`,
41
+ });
42
+ }
43
+ }
44
+ const adoption = adopt(existing, rules, unregistered(session), session.config, selected);
27
45
  if (adoption._tag === "Refused") {
28
46
  return yield* new SetupFailure({ message: `baseline write refused:\n${adoption.reasons.map((reason) => ` - ${reason}`).join("\n")}` });
29
47
  }
package/src/cli/lint.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { relative } from "node:path";
2
2
  import { Console, Effect } from "effect";
3
+ import { looseStagedEntries } from "#baseline/looseStagedEntries.ts";
3
4
  import { evaluate, passes } from "#engine/evaluate.ts";
4
5
  import { openSession } from "#engine/session.ts";
6
+ import { keyOf } from "#engine/violation.ts";
5
7
  import { GateFailed, type SetupFailure } from "#failure.ts";
6
8
  import { render } from "#report/render.ts";
7
9
  import type { RuleServices } from "#rule.ts";
@@ -9,9 +11,17 @@ import type { RuleServices } from "#rule.ts";
9
11
  export const lint = Effect.fn("Cli.lint")(function* (
10
12
  cwd: string,
11
13
  config: string | undefined,
14
+ staged = false,
12
15
  ): Effect.fn.Return<void, SetupFailure | GateFailed, RuleServices> {
13
16
  const session = yield* openSession(cwd, config);
14
- const outcome = evaluate(session.violations, session.registry, session.baseline.entries, session.config);
17
+ const evaluated = evaluate(session.violations, session.registry, session.baseline.entries, session.config);
18
+ const loose = staged ? yield* looseStagedEntries(session) : [];
19
+ const rejected = new Set(loose.map(({ entry }) => keyOf(entry.rule, entry.file)));
20
+ const outcome = {
21
+ ...evaluated,
22
+ looseBaseline: evaluated.looseBaseline.filter(({ entry }) => !rejected.has(keyOf(entry.rule, entry.file))),
23
+ staleBaseline: [...evaluated.staleBaseline, ...loose],
24
+ };
15
25
  yield* Console.log(
16
26
  render(outcome, {
17
27
  baseline: session.config.baseline,
@@ -6,7 +6,7 @@ export const USAGE = `Usage:
6
6
  quality exceptions migrate [--config <file>] [--from <registry>]
7
7
  quality baseline merge <ancestor> <current> <other>
8
8
  quality baseline install-driver
9
- quality baseline write [--config <file>] [--rule <id>]...
9
+ quality baseline write [--config <file>] [--rule <id>]... [--file <path>]...
10
10
  quality baseline prune [--config <file>] [--against <ref>]
11
11
  quality baseline tighten [--config <file>] [--staged]
12
12
  quality baseline migrate [--config <file>] [--from <file>]
@@ -24,7 +24,7 @@ fix Sort every package.json, apply Biome's lint fixes, unsafe ones
24
24
  exceptions migrate Move legacy registry entries and Biome declarations into quality.config.ts exceptions and remove matching root overrides.
25
25
  baseline merge Merge Git baseline versions into <current>: deletions win and counts take the minimum.
26
26
  baseline install-driver Configure only the repository-local merge.quality-baseline.driver setting.
27
- baseline write Record current error-level violations. Creates the baseline, or records the named rules again, replacing their entries.
27
+ baseline write Adopt initial debt once, or record named rules only for --file paths changed since HEAD. Stage new files first.
28
28
  baseline prune Drop fixed debt, lower entries to what is left and carry entries to files git saw move. Never adds or raises an entry.
29
29
  baseline tighten Prune only the entries of files changed since HEAD, or with --staged, in the index.
30
30
  baseline migrate Move a JSON or JSON Lines baseline (--from, quality/baseline.json by default) into root and package shards.
@@ -32,7 +32,7 @@ hooks install Install the git pre-commit hook, shared by every worktree, tha
32
32
  unless --force replaces it.
33
33
  hooks uninstall Remove quality's pre-commit hook. Keeps a hook that is not quality's.
34
34
  hooks status Check that git's effective hooks path runs Quality's pre-commit hook and report global chaining.
35
- hooks pre-commit What the hook runs: lint, then package.json scripts typecheck and quality:commit when present.
35
+ hooks pre-commit Check lint and staged baseline counts, then package.json scripts typecheck and quality:commit when present.
36
36
 
37
37
  --config <file> Config file; its directory is the repository root. Without this option, uses ./quality.config.ts when present, otherwise defaults.
38
38
  --against <ref> The branch the work merges into, whose merge base prune follows moves from. Defaults to origin/HEAD, then origin/main, then origin/master.
@@ -1,7 +1,7 @@
1
1
  import { Console, Effect } from "effect";
2
2
  import { installDriver } from "#baseline/installDriver.ts";
3
3
  import { mergeBaseline } from "#baseline/merge.ts";
4
- import { parseCommand, USAGE } from "#cli/args.ts";
4
+ import { parseCommand } from "#cli/args.ts";
5
5
  import { writeBaseline } from "#cli/baseline.ts";
6
6
  import { ci } from "#cli/ci.ts";
7
7
  import { fix } from "#cli/fix.ts";
@@ -17,6 +17,7 @@ import { preCommitHook } from "#hooks/preCommit.ts";
17
17
  import { setupHook } from "#hooks/setup.ts";
18
18
  import { hookStatus } from "#hooks/status.ts";
19
19
  import { uninstallHook } from "#hooks/uninstall.ts";
20
+ import { USAGE } from "./messages.ts";
20
21
 
21
22
  export interface Invocation {
22
23
  readonly cwd: string;
@@ -45,7 +46,7 @@ export const program = Effect.fn("Cli.program")(function* (args: readonly string
45
46
  case "BaselineInstallDriver":
46
47
  return yield* installDriver(cwd, launch);
47
48
  case "BaselineWrite":
48
- return yield* writeBaseline(cwd, command.config, command.rules);
49
+ return yield* writeBaseline(cwd, command.config, command.rules, command.files);
49
50
  case "BaselinePrune":
50
51
  return yield* pruneBaseline(cwd, command.config, command.against);
51
52
  case "BaselineTighten":
@@ -42,7 +42,7 @@ const runScript = Effect.fnUntraced(
42
42
  export const preCommitHook = Effect.fn("Hooks.preCommitHook")(function* (cwd: string, path: string | undefined) {
43
43
  const config = yield* loadConfig(cwd, path);
44
44
  const { manager, scripts } = yield* commitScripts(config.root);
45
- const linted = yield* lint(cwd, path).pipe(
45
+ const linted = yield* lint(cwd, path, true).pipe(
46
46
  Effect.as(true),
47
47
  Effect.catchTag("GateFailed", () => Effect.succeed(false)),
48
48
  );
@@ -7,7 +7,7 @@ import type { RuleServices, SourceFile } from "#rule.ts";
7
7
  import { FilesystemFailure, orWhenAbsent, readRequiredText } from "./filesystem.ts";
8
8
  import { posix } from "./ignoreScope.ts";
9
9
  import { linesOf } from "./linesOf.ts";
10
- import { shadcnFolders } from "./shadcnFolders.ts";
10
+ import { shadcnFiles } from "./shadcnFiles.ts";
11
11
  import { scopeAbove, walk } from "./walk.ts";
12
12
 
13
13
  export interface InventoryScope {
@@ -49,12 +49,12 @@ export const collectInventory = Effect.fn("Inventory.collectInventory")(function
49
49
  scope: InventoryScope,
50
50
  ): Effect.fn.Return<Inventory, FilesystemFailure | SetupFailure, RuleServices> {
51
51
  const excluded = ignore().add([...scope.exclude]);
52
- const toolOwned = yield* shadcnFolders(root);
52
+ const toolOwned = new Set(yield* shadcnFiles(root));
53
53
  const zones = yield* Effect.forEach(scope.sources, (zone) => zoneFiles(root, zone), { concurrency: READ_CONCURRENCY });
54
54
  const relativePaths = zones.flat().map((absolute) => posix(relative(root, absolute)));
55
55
  const files = [...new Set(relativePaths)]
56
56
  .filter((path) => !excluded.ignores(path))
57
- .filter((path) => !toolOwned.some((folder) => path.startsWith(`${folder}/`)))
57
+ .filter((path) => !toolOwned.has(path))
58
58
  .sort((left, right) => {
59
59
  if (left === right) {
60
60
  return 0;
@@ -0,0 +1,87 @@
1
+ import { basename, join, matchesGlob, relative } from "node:path";
2
+ import { Effect } from "effect";
3
+ import { posix } from "./ignoreScope.ts";
4
+ import { shadcnFolders } from "./shadcnFolders.ts";
5
+ import { walk } from "./walk.ts";
6
+
7
+ // Registry item names are the CLI ownership convention; custom names stay authored.
8
+ const COMPONENTS = [
9
+ "accordion",
10
+ "alert",
11
+ "alert-dialog",
12
+ "aspect-ratio",
13
+ "attachment",
14
+ "avatar",
15
+ "badge",
16
+ "breadcrumb",
17
+ "bubble",
18
+ "button",
19
+ "button-group",
20
+ "calendar",
21
+ "card",
22
+ "carousel",
23
+ "chart",
24
+ "checkbox",
25
+ "collapsible",
26
+ "combobox",
27
+ "command",
28
+ "context-menu",
29
+ "dialog",
30
+ "direction",
31
+ "drawer",
32
+ "dropdown-menu",
33
+ "empty",
34
+ "field",
35
+ "form",
36
+ "hover-card",
37
+ "input",
38
+ "input-group",
39
+ "input-otp",
40
+ "item",
41
+ "kbd",
42
+ "label",
43
+ "marker",
44
+ "menubar",
45
+ "message",
46
+ "message-scroller",
47
+ "native-select",
48
+ "navigation-menu",
49
+ "pagination",
50
+ "popover",
51
+ "progress",
52
+ "radio-group",
53
+ "resizable",
54
+ "scroll-area",
55
+ "select",
56
+ "separator",
57
+ "sheet",
58
+ "sidebar",
59
+ "skeleton",
60
+ "slider",
61
+ "sonner",
62
+ "spinner",
63
+ "switch",
64
+ "table",
65
+ "tabs",
66
+ "textarea",
67
+ "toast",
68
+ "toaster",
69
+ "toggle",
70
+ "toggle-group",
71
+ "tooltip",
72
+ ];
73
+
74
+ export const SHADCN_FILE_GLOB = `{${COMPONENTS.join(",")}}.{ts,tsx,js,jsx}`;
75
+
76
+ export const shadcnFiles = Effect.fn("Inventory.shadcnFiles")(function* (root: string) {
77
+ const folders = yield* shadcnFolders(root);
78
+ const files = yield* Effect.forEach(folders, (folder) => walk(join(root, folder)));
79
+ return [
80
+ ...new Set(
81
+ files
82
+ .flat()
83
+ .filter((path) => matchesGlob(basename(path), SHADCN_FILE_GLOB))
84
+ .map((path) => posix(relative(root, path))),
85
+ ),
86
+ ];
87
+ });