lawcheck 0.0.0 → 0.1.0-alpha.1

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 (75) hide show
  1. package/README.md +34 -2
  2. package/dist/args.js +168 -0
  3. package/dist/bin.cjs +20 -0
  4. package/dist/check.js +472 -0
  5. package/dist/cli.js +182 -0
  6. package/dist/config.js +278 -0
  7. package/dist/docs.js +41 -0
  8. package/dist/doctor.js +273 -0
  9. package/dist/environment.js +73 -0
  10. package/dist/explain.js +446 -0
  11. package/dist/files.js +388 -0
  12. package/dist/glob.js +268 -0
  13. package/dist/grammars/LICENSES.txt +353 -0
  14. package/dist/grammars/tree-sitter-c.wasm +0 -0
  15. package/dist/grammars/tree-sitter-c_sharp.wasm +0 -0
  16. package/dist/grammars/tree-sitter-cpp.wasm +0 -0
  17. package/dist/grammars/tree-sitter-go.wasm +0 -0
  18. package/dist/grammars/tree-sitter-java.wasm +0 -0
  19. package/dist/grammars/tree-sitter-javascript.wasm +0 -0
  20. package/dist/grammars/tree-sitter-kotlin.wasm +0 -0
  21. package/dist/grammars/tree-sitter-php.wasm +0 -0
  22. package/dist/grammars/tree-sitter-python.wasm +0 -0
  23. package/dist/grammars/tree-sitter-ruby.wasm +0 -0
  24. package/dist/grammars/tree-sitter-rust.wasm +0 -0
  25. package/dist/grammars/tree-sitter-tsx.wasm +0 -0
  26. package/dist/grammars/tree-sitter-typescript.wasm +0 -0
  27. package/dist/guard.js +179 -0
  28. package/dist/init.js +131 -0
  29. package/dist/keys.js +55 -0
  30. package/dist/law.js +416 -0
  31. package/dist/lawchange.js +208 -0
  32. package/dist/limits.js +207 -0
  33. package/dist/main.js +77 -0
  34. package/dist/names.js +117 -0
  35. package/dist/output.js +325 -0
  36. package/dist/prime.js +211 -0
  37. package/dist/programs.js +177 -0
  38. package/dist/progress.js +42 -0
  39. package/dist/prompt.js +317 -0
  40. package/dist/providers/anthropic.js +33 -0
  41. package/dist/providers/claude-code.js +41 -0
  42. package/dist/providers/codex.js +75 -0
  43. package/dist/providers/copilot-cli.js +56 -0
  44. package/dist/providers/gemini-cli.js +30 -0
  45. package/dist/providers/google.js +31 -0
  46. package/dist/providers/http.js +138 -0
  47. package/dist/providers/index.js +96 -0
  48. package/dist/providers/ollama.js +39 -0
  49. package/dist/providers/openai-compatible.js +41 -0
  50. package/dist/providers/openai.js +17 -0
  51. package/dist/providers/program.js +282 -0
  52. package/dist/readers.js +286 -0
  53. package/dist/review.js +116 -0
  54. package/dist/rules.js +418 -0
  55. package/dist/runner.js +177 -0
  56. package/dist/setup.js +388 -0
  57. package/dist/try.js +346 -0
  58. package/dist/types.js +99 -0
  59. package/dist/uses.js +78 -0
  60. package/dist/verdicts.js +337 -0
  61. package/dist/waivers.js +70 -0
  62. package/dist/work.js +21 -0
  63. package/docs/change.md +62 -0
  64. package/docs/ci.md +133 -0
  65. package/docs/codes.md +60 -0
  66. package/docs/config.md +117 -0
  67. package/docs/first-law.md +189 -0
  68. package/docs/json.md +72 -0
  69. package/docs/languages.md +87 -0
  70. package/docs/law.md +95 -0
  71. package/docs/providers.md +105 -0
  72. package/docs/reviewer-rules.md +96 -0
  73. package/docs/script-rules.md +90 -0
  74. package/docs/waivers.md +56 -0
  75. package/package.json +59 -3
package/dist/config.js ADDED
@@ -0,0 +1,278 @@
1
+ import { statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { isAlias, isMap, isScalar, isSeq, LineCounter } from 'yaml';
4
+ import { distance, nearestKey, parseUnique } from './law.js';
5
+ import { decode } from './types.js';
6
+ import { CONFIG_BYTES, readFailure, readWhole } from './limits.js';
7
+ export const CONFIG = '.lawcheck/config.yaml';
8
+ export const PROVIDERS = ['anthropic', 'openai', 'google', 'openai-compatible', 'ollama', 'claude-code', 'codex', 'gemini-cli', 'copilot-cli'];
9
+ export const PROGRAM_PROVIDERS = { 'claude-code': 'claude', codex: 'codex', 'gemini-cli': 'gemini', 'copilot-cli': 'copilot' };
10
+ // A model name goes to a program as one argument; 256 characters is far above any real name and far below what a command line can carry.
11
+ const MAX_MODEL = 256;
12
+ const TOP_KEYS = ['reviewer', 'runner'];
13
+ const REVIEWER_KEYS = ['provider', 'model', 'timeout', 'temperature', 'max_chars', 'parallel', 'max_calls'];
14
+ export const RUNNERS = ['global', 'npx', 'pnpm', 'yarn', 'bun'];
15
+ export const RUNNER_COMMANDS = {
16
+ global: { words: ['lawcheck'], install: 'npm i -g lawcheck@alpha' },
17
+ npx: { words: ['npx', '--no-install', 'lawcheck'], install: 'npm install' },
18
+ pnpm: { words: ['pnpm', 'exec', 'lawcheck'], install: 'pnpm install' },
19
+ yarn: { words: ['yarn', 'run', 'lawcheck'], install: 'yarn install' },
20
+ bun: { words: ['bun', 'x', '--no-install', 'lawcheck'], install: 'bun install' },
21
+ };
22
+ export function runnerLine(text) {
23
+ const lines = text.replace(/^\uFEFF/, '').split('\n');
24
+ for (let i = 0; i < lines.length; i++) {
25
+ const line = lines[i].replace(/\r$/, '');
26
+ if (!line.startsWith('runner:'))
27
+ continue;
28
+ const rest = line.slice('runner:'.length);
29
+ const comment = rest.search(/[ \t]#/);
30
+ return { value: (comment < 0 ? rest : rest.slice(0, comment)).replace(/^[ \t]+|[ \t]+$/g, ''), line: i + 1 };
31
+ }
32
+ return null;
33
+ }
34
+ export function runnerOf(text) {
35
+ return runnerLine(text)?.value ?? 'global';
36
+ }
37
+ export function unknownRunner(value) {
38
+ const scored = RUNNERS.map((name) => ({ name, d: distance(value, name) })).filter(({ d }) => d <= 2);
39
+ const best = Math.min(...scored.map(({ d }) => d));
40
+ const near = scored.filter(({ d }) => d === best).map(({ name }) => `'${name}'`);
41
+ const part = near.length === 0 ? '' : ` (did you mean ${near.slice(0, 2).join(' or ')}?)`;
42
+ return `the runner '${value}' is unknown${part}; it takes ${RUNNERS.join(', ').replace(/, (?=[^,]*$)/, ' or ')}`;
43
+ }
44
+ export const RUNNER_ONE_LINE = 'write runner on one line of its own at the top level, as runner: pnpm';
45
+ export const DEFAULT_CONFIG = {
46
+ provider: null,
47
+ model: null,
48
+ timeout: 60,
49
+ temperature: 0,
50
+ maxChars: 50000,
51
+ parallel: 4,
52
+ maxCalls: 100,
53
+ };
54
+ const NO_KEYS = "a key never goes into a committed file; set LAWCHECK_REVIEWER_KEY, or the provider's own ANTHROPIC_API_KEY, OPENAI_API_KEY or GOOGLE_API_KEY, in the environment";
55
+ export class ConfigTooLarge extends Error {
56
+ bytes;
57
+ constructor(bytes) {
58
+ super(`${CONFIG} holds ${bytes} bytes`);
59
+ this.bytes = bytes;
60
+ }
61
+ }
62
+ export function readConfig(root) {
63
+ const path = join(root, CONFIG);
64
+ try {
65
+ if (!statSync(path).isFile())
66
+ return { problems: [{ line: 1, message: `${CONFIG} is no file` }] };
67
+ }
68
+ catch (error) {
69
+ const code = error.code;
70
+ if (code === 'ENOENT' || code === 'ENOTDIR')
71
+ return { config: { ...DEFAULT_CONFIG } };
72
+ return { problems: [{ line: 1, message: `${CONFIG} cannot be read (${code ?? 'an error'})` }] };
73
+ }
74
+ let bytes;
75
+ try {
76
+ bytes = readWhole(path, CONFIG);
77
+ }
78
+ catch (error) {
79
+ return { problems: [{ line: 1, message: `${CONFIG} cannot be read (${readFailure(error)})` }] };
80
+ }
81
+ if (bytes.length > CONFIG_BYTES)
82
+ throw new ConfigTooLarge(bytes.length);
83
+ return parseConfig(decode(bytes));
84
+ }
85
+ export function parseConfig(text) {
86
+ const counter = new LineCounter();
87
+ const { doc, errors } = parseUnique(text, counter);
88
+ if (errors.length > 0) {
89
+ return {
90
+ problems: errors.map((error) => ({
91
+ line: counter.linePos(error.pos).line,
92
+ message: `the config does not parse: ${error.message.split('\n')[0]}`,
93
+ })),
94
+ };
95
+ }
96
+ return new ConfigReader(doc, counter, text).read();
97
+ }
98
+ class ConfigReader {
99
+ doc;
100
+ counter;
101
+ text;
102
+ problems = [];
103
+ constructor(doc, counter, text) {
104
+ this.doc = doc;
105
+ this.counter = counter;
106
+ this.text = text;
107
+ }
108
+ read() {
109
+ const config = { ...DEFAULT_CONFIG };
110
+ const top = this.resolve(this.doc.contents);
111
+ if (top === null || (isScalar(top) && top.value === null))
112
+ return { config };
113
+ if (!isMap(top)) {
114
+ this.problem(this.lineOf(top), `the config takes a mapping, not ${describe(top)}`);
115
+ return { problems: this.problems };
116
+ }
117
+ for (const pair of top.items) {
118
+ const key = this.keyOf(pair);
119
+ if (key === null)
120
+ continue;
121
+ const line = this.lineOf(pair.key);
122
+ if (key === 'reviewer') {
123
+ const value = this.resolve(pair.value);
124
+ if (!isMap(value))
125
+ this.problem(line, `'reviewer' takes a mapping, not ${describe(value)}`);
126
+ else
127
+ this.readReviewer(value, line, config);
128
+ }
129
+ else if (key === 'runner') {
130
+ this.readRunner(this.resolve(pair.value), line);
131
+ }
132
+ else if (key === 'keys') {
133
+ this.problem(line, NO_KEYS);
134
+ }
135
+ else {
136
+ this.unknown(key, TOP_KEYS, line, 'at the top of the config');
137
+ }
138
+ }
139
+ return this.problems.length > 0 ? { problems: this.problems } : { config };
140
+ }
141
+ readRunner(value, line) {
142
+ const name = isScalar(value) && value.value !== null ? String(value.value) : '';
143
+ if (!RUNNERS.includes(name))
144
+ this.problem(line, unknownRunner(isScalar(value) ? (value.source ?? name) : name));
145
+ else if (runnerOf(this.text) !== name)
146
+ this.problem(line, RUNNER_ONE_LINE);
147
+ }
148
+ readReviewer(map, reviewerLine, config) {
149
+ const seen = new Map();
150
+ for (const pair of map.items) {
151
+ const key = this.keyOf(pair);
152
+ if (key === null)
153
+ continue;
154
+ const line = this.lineOf(pair.key);
155
+ if (key === 'keys')
156
+ this.problem(line, NO_KEYS);
157
+ else if (key === 'endpoint')
158
+ this.problem(line, 'reviewer.endpoint is not read: the address comes from the variable LAWCHECK_REVIEWER_ENDPOINT');
159
+ else if (!REVIEWER_KEYS.includes(key))
160
+ this.unknown(key, REVIEWER_KEYS, line, "in 'reviewer'");
161
+ else
162
+ seen.set(key, { value: this.resolve(pair.value), line });
163
+ }
164
+ const provider = seen.get('provider');
165
+ if (provider !== undefined) {
166
+ const name = this.string(provider.value);
167
+ if (name === null)
168
+ this.problem(provider.line, `reviewer.provider takes a string, not ${describe(provider.value)}`);
169
+ else if (PROVIDERS.includes(name))
170
+ config.provider = name;
171
+ else {
172
+ const near = nearestKey(name, [...PROVIDERS]);
173
+ this.problem(provider.line, `the provider '${name}' is unknown${near === null ? '' : ` (did you mean '${near}'?)`}; this version has ${PROVIDERS.join(', ')}`);
174
+ }
175
+ }
176
+ const model = seen.get('model');
177
+ if (model !== undefined) {
178
+ const text = this.string(model.value);
179
+ if (text === null || text.trim() === '' || text.length > MAX_MODEL || /[\u0000-\u001f\u007f]/.test(text)) {
180
+ const what = text !== null && text.length > MAX_MODEL ? `a string of ${text.length} characters` : describe(model.value);
181
+ this.problem(model.line, `reviewer.model takes a non-empty string of at most ${MAX_MODEL} characters with no control character, not ${what}`);
182
+ }
183
+ else {
184
+ config.model = text;
185
+ }
186
+ }
187
+ else if (config.provider !== null && PROGRAM_PROVIDERS[config.provider] === undefined) {
188
+ this.problem(reviewerLine, `the provider '${config.provider}' needs reviewer.model`);
189
+ }
190
+ const program = config.provider === null ? undefined : PROGRAM_PROVIDERS[config.provider];
191
+ if (program !== undefined) {
192
+ config.timeout = 300;
193
+ config.parallel = 1;
194
+ config.temperature = null;
195
+ }
196
+ else if (config.provider === 'ollama') {
197
+ config.timeout = 300;
198
+ }
199
+ this.integer(seen.get('timeout'), 'timeout', 1, 86400, 'an integer of seconds from 1 to 86400', (n) => (config.timeout = n));
200
+ this.integer(seen.get('max_chars'), 'max_chars', 1, Infinity, 'an integer of at least 1', (n) => (config.maxChars = n));
201
+ this.integer(seen.get('parallel'), 'parallel', 1, Infinity, 'an integer of at least 1', (n) => (config.parallel = n));
202
+ this.integer(seen.get('max_calls'), 'max_calls', 0, Infinity, 'an integer of at least 0', (n) => (config.maxCalls = n));
203
+ const temperature = seen.get('temperature');
204
+ if (temperature !== undefined) {
205
+ if (program !== undefined) {
206
+ this.problem(temperature.line, `the provider ${config.provider} takes no temperature: the ${program} program runs at its own`);
207
+ }
208
+ else {
209
+ const value = this.number(temperature.value);
210
+ if (value === null || value < 0)
211
+ this.problem(temperature.line, `reviewer.temperature takes a number of at least 0, not ${describe(temperature.value)}`);
212
+ else
213
+ config.temperature = value;
214
+ }
215
+ }
216
+ }
217
+ integer(entry, key, min, max, what, set) {
218
+ if (entry === undefined)
219
+ return;
220
+ const value = this.number(entry.value);
221
+ if (value === null || !Number.isInteger(value) || value < min || value > max) {
222
+ this.problem(entry.line, `reviewer.${key} takes ${what}, not ${describe(entry.value)}`);
223
+ return;
224
+ }
225
+ set(value);
226
+ }
227
+ number(value) {
228
+ return isScalar(value) && typeof value.value === 'number' && Number.isFinite(value.value) ? value.value : null;
229
+ }
230
+ string(value) {
231
+ return isScalar(value) && typeof value.value === 'string' ? value.value : null;
232
+ }
233
+ resolve(node) {
234
+ let current = node;
235
+ for (let depth = 0; isAlias(current) && depth < 100; depth++)
236
+ current = current.resolve(this.doc) ?? null;
237
+ return (current ?? null);
238
+ }
239
+ keyOf(pair) {
240
+ const key = this.resolve(pair.key);
241
+ if (isScalar(key) && typeof key.value === 'string')
242
+ return key.value;
243
+ const text = isScalar(key) ? (key.source ?? String(key.value)) : String(key);
244
+ this.problem(this.lineOf(pair.key), `the key '${text}' is no string; write it in quotes`);
245
+ return null;
246
+ }
247
+ lineOf(node) {
248
+ const range = node?.range;
249
+ return range ? this.counter.linePos(range[0]).line : 1;
250
+ }
251
+ problem(line, message) {
252
+ this.problems.push({ line, message });
253
+ }
254
+ unknown(key, known, line, where) {
255
+ const near = nearestKey(key, known);
256
+ this.problem(line, `unknown key '${key}' ${where}${near === null ? '' : ` (did you mean '${near}'?)`}`);
257
+ }
258
+ }
259
+ function describe(value) {
260
+ if (value === null)
261
+ return 'nothing';
262
+ if (isMap(value))
263
+ return 'a mapping';
264
+ if (isSeq(value))
265
+ return 'a sequence';
266
+ if (isScalar(value)) {
267
+ const v = value.value;
268
+ if (v === null)
269
+ return 'nothing';
270
+ if (typeof v === 'string')
271
+ return `the string ${JSON.stringify(v)}`;
272
+ if (typeof v === 'number' || typeof v === 'bigint')
273
+ return String(v);
274
+ if (typeof v === 'boolean')
275
+ return String(v);
276
+ }
277
+ return 'another kind of value';
278
+ }
package/dist/docs.js ADDED
@@ -0,0 +1,41 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { documentOf, usageError } from './args.js';
4
+ import { nearestKey } from './law.js';
5
+ export const TOPICS = [
6
+ { id: 'first-law', title: 'The first type and the first rule' },
7
+ { id: 'law', title: 'The law file' },
8
+ { id: 'change', title: 'What a check judges' },
9
+ { id: 'script-rules', title: 'Script rules' },
10
+ { id: 'reviewer-rules', title: 'Reviewer rules' },
11
+ { id: 'waivers', title: 'Waivers' },
12
+ { id: 'config', title: 'Settings' },
13
+ { id: 'providers', title: 'Reviewers and keys' },
14
+ { id: 'languages', title: 'Languages and uses' },
15
+ { id: 'ci', title: 'CI and git hooks' },
16
+ { id: 'json', title: 'JSON documents' },
17
+ { id: 'codes', title: 'Codes' },
18
+ ];
19
+ export const DOCS_DIR = fileURLToPath(new URL('../docs/', import.meta.url));
20
+ export function page(id) {
21
+ return readFileSync(`${DOCS_DIR}${id}.md`, 'utf8');
22
+ }
23
+ export function topicList() {
24
+ const lines = [`lawcheck docs: ${TOPICS.length} topics; lawcheck docs <topic> prints one`, '', ...TOPICS.map((t) => `${t.id} ${t.title}`)];
25
+ return lines.join('\n') + '\n';
26
+ }
27
+ export async function docs(args, _context, json) {
28
+ if (args.words.length > 1)
29
+ return usageError('docs takes one topic at most', json, 'docs');
30
+ const id = args.words[0];
31
+ if (id === undefined) {
32
+ return { code: 0, stdout: json ? documentOf({ schema: 'lawcheck-docs/0', topics: TOPICS }) : topicList() };
33
+ }
34
+ const topic = TOPICS.find((t) => t.id === id);
35
+ if (topic === undefined) {
36
+ const near = nearestKey(id, TOPICS.map((t) => t.id));
37
+ return usageError(`there is no topic '${id}'${near === null ? '' : ` (did you mean '${near}'?)`}; lawcheck docs lists them`, json, 'docs');
38
+ }
39
+ const text = page(id);
40
+ return { code: 0, stdout: json ? documentOf({ schema: 'lawcheck-docs/0', id, title: topic.title, text }) : text };
41
+ }
package/dist/doctor.js ADDED
@@ -0,0 +1,273 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { environmentRefusal, gitNow, gitRefusal, runtimeNow, runtimeRefusal } from './environment.js';
3
+ import { findProgram } from './programs.js';
4
+ import { join } from 'node:path';
5
+ import { documentOf, noWords, text as flagText, usageError } from './args.js';
6
+ import { CONFIG, runnerLine } from './config.js';
7
+ import { gitNext, listFiles, NoGit, showPrefix, workTreeProblem } from './files.js';
8
+ import { commandIn, forCommand, nextOfErrors, placeOf, plural, shown, sortErrors } from './output.js';
9
+ import { walk } from './prime.js';
10
+ import { checkAnswer } from './prompt.js';
11
+ import { createProvider } from './providers/index.js';
12
+ import { hide } from './keys.js';
13
+ import { LANGUAGES, loadGrammars, readerOf, siblingsOf } from './readers.js';
14
+ import { belowPart, configErrors, findRoot, lawsBelow, lawErrors, onceReader, ruleFileErrors, Stop, theChange, touchesLaw, typingErrors } from './setup.js';
15
+ import { extensionOf, listInForce } from './uses.js';
16
+ export const TEST_PROMPT = 'Answer with this JSON object and nothing else: {"verdict": "pass", "findings": []}';
17
+ const IDS = ['node', 'git', 'law', 'config', 'types', 'base', 'law-change', 'readers', 'reviewer'];
18
+ const WAITS = {
19
+ node: [],
20
+ git: [],
21
+ law: ['git'],
22
+ config: ['git', 'law-file'],
23
+ types: ['law'],
24
+ base: ['git', 'law-file'],
25
+ 'law-change': ['base'],
26
+ readers: ['types'],
27
+ reviewer: ['law', 'config'],
28
+ };
29
+ function next(text, given) {
30
+ return { command: commandIn(text, given), text };
31
+ }
32
+ function firstOf(errors) {
33
+ const first = sortErrors(errors)[0];
34
+ const place = placeOf(first.file, first.line);
35
+ const more = errors.length > 1 ? `; and ${errors.length - 1} more` : '';
36
+ return { message: `${place === null ? '' : `${place} `}${first.message}${more}`, next: next(nextOfErrors(errors, 'doctor'), first.command) };
37
+ }
38
+ // The program each runner starts first; its install line is the plugin's (spec/plugin-slice.md, section 3).
39
+ const RUNNER_PROGRAMS = { global: 'lawcheck', npx: 'npx', pnpm: 'pnpm', yarn: 'yarn', bun: 'bun' };
40
+ export async function runChecks(inputs) {
41
+ const checks = new Map();
42
+ const found = { root: findRoot(inputs.cwd), law: null, kinds: null, files: [], read: null, config: null, typed: [], change: null };
43
+ const passed = (id) => (id === 'law-file' ? found.root !== null : ['ok', 'note'].includes(checks.get(id)?.state ?? ''));
44
+ const set = (id, state, message, nextStep = null) => {
45
+ checks.set(id, { id, state, message, next: nextStep });
46
+ };
47
+ const steps = {
48
+ node: () => {
49
+ const runtime = { ...(inputs.runtime ?? runtimeNow()), ...(inputs.nodeVersion === undefined ? {} : { node: inputs.nodeVersion }) };
50
+ const refused = runtimeRefusal(runtime);
51
+ if (refused !== null)
52
+ return set('node', 'fail', refused.message, next(forCommand(refused.next, 'doctor')));
53
+ set('node', 'ok', `Node ${runtime.node}; Lawcheck needs 24 or later`);
54
+ },
55
+ git: () => {
56
+ const dir = found.root ?? inputs.cwd;
57
+ const version = (inputs.gitText ?? (() => gitNow(dir)))();
58
+ const old = version === null ? null : gitRefusal(version);
59
+ if (old !== null)
60
+ return set('git', 'fail', old.message, next(forCommand(old.next, 'doctor')));
61
+ let problem;
62
+ try {
63
+ problem = workTreeProblem(dir);
64
+ }
65
+ catch (error) {
66
+ if (!(error instanceof NoGit))
67
+ throw error;
68
+ problem = error.message;
69
+ }
70
+ if (problem !== null) {
71
+ const fix = gitNext(dir, problem);
72
+ return set('git', 'fail', problem, fix === undefined ? next('run lawcheck doctor inside a git work tree, with git on the PATH') : next(forCommand(fix.next, 'doctor'), fix.command));
73
+ }
74
+ if (found.root === null)
75
+ return set('git', 'ok', 'a git work tree');
76
+ const prefix = showPrefix(found.root);
77
+ set('git', 'ok', `a git work tree, and the law's root is ${prefix === '' ? 'its top' : `${prefix} below its top`}`);
78
+ },
79
+ law: () => {
80
+ if (found.root === null) {
81
+ const below = lawsBelow(inputs.cwd);
82
+ if (below.length > 0)
83
+ return set('law', 'fail', `no .lawcheck/law.yaml in this directory or any above it${belowPart(below)}`, next(`cd ${below[0]}, where a law is, then run lawcheck doctor again`));
84
+ return set('law', 'fail', 'no .lawcheck/law.yaml in this directory or any above it', next('lawcheck init (only when the user wants a law here)'));
85
+ }
86
+ const read = lawErrors(found.root);
87
+ if ('errors' in read) {
88
+ const first = firstOf(read.errors);
89
+ return set('law', 'fail', first.message, first.next);
90
+ }
91
+ const rules = ruleFileErrors(found.root, read.law);
92
+ found.files = rules.files;
93
+ found.read = rules.read;
94
+ if (rules.errors.length > 0) {
95
+ const first = firstOf(rules.errors);
96
+ return set('law', 'fail', first.message, first.next);
97
+ }
98
+ found.law = read.law;
99
+ found.kinds = rules.kinds;
100
+ let types = 0;
101
+ walk(read.law.types, () => types++);
102
+ const scripts = rules.kinds.scripts.size;
103
+ const reviewers = rules.kinds.reviewers.size;
104
+ set('law', 'ok', `.lawcheck/law.yaml: ${plural(types, 'type')}, ${plural(read.law.rules.size, 'rule')} (${scripts} script, ${reviewers} reviewer)`);
105
+ },
106
+ config: () => {
107
+ const read = configErrors(found.root);
108
+ if ('errors' in read) {
109
+ const first = firstOf(read.errors);
110
+ return set('config', 'fail', first.message, first.next);
111
+ }
112
+ found.config = read.config;
113
+ const configured = read.config;
114
+ if (!existsSync(join(found.root, CONFIG)))
115
+ return set('config', 'ok', 'no .lawcheck/config.yaml; every setting has its default');
116
+ const named = runnerLine(readFileSync(join(found.root, CONFIG), 'utf8'))?.value;
117
+ const program = named === undefined ? undefined : RUNNER_PROGRAMS[named];
118
+ const at = program === undefined ? null : findProgram(program, inputs.env);
119
+ if (program !== undefined && at === null) {
120
+ return set('config', 'fail', `.lawcheck/config.yaml: runner ${named}, and ${program} is not on the PATH`, next(`install ${program}, or set runner to the way this repository starts Lawcheck, then run lawcheck doctor again`));
121
+ }
122
+ const runner = program === undefined ? '' : `; runner ${named}, ${program} at ${at}`;
123
+ if (configured.provider === null)
124
+ return set('config', 'ok', `.lawcheck/config.yaml: no reviewer set${runner}`);
125
+ set('config', 'ok', `.lawcheck/config.yaml: reviewer ${configured.provider}${configured.model === null ? '' : `, model ${configured.model}`}${runner}`);
126
+ },
127
+ types: () => {
128
+ const { typed, errors } = typingErrors(found.root, found.law, found.files, found.read ?? onceReader(found.root));
129
+ if (errors.length > 0) {
130
+ const first = firstOf(errors);
131
+ return set('types', 'fail', first.message, first.next);
132
+ }
133
+ found.typed = typed;
134
+ set('types', 'ok', `${typed.length} of ${plural(found.files.length, 'file')} ${typed.length === 1 ? 'has' : 'have'} a type`);
135
+ },
136
+ base: () => {
137
+ const files = found.files.length > 0 ? found.files : listFiles(found.root);
138
+ try {
139
+ found.change = theChange(found.root, files, inputs.base, inputs.env);
140
+ }
141
+ catch (error) {
142
+ if (!(error instanceof Stop))
143
+ throw error;
144
+ const first = firstOf(error.errors);
145
+ return set('base', 'fail', first.message, first.next);
146
+ }
147
+ const { base, from, changed } = found.change;
148
+ if (base === null) {
149
+ return set('base', 'note', 'no base: no --base, LAWCHECK_BASE or origin/HEAD, so a plain check counts every file as changed', next('pass --base <branch>, or set LAWCHECK_BASE'));
150
+ }
151
+ set('base', 'ok', `${base}, from ${from}; the change holds ${plural(changed.size, 'file')}`);
152
+ },
153
+ 'law-change': () => {
154
+ const change = found.change;
155
+ if (change.base === null)
156
+ return set('law-change', 'ok', 'no base, so a plain check judges every file');
157
+ const touched = [...change.changed].filter(touchesLaw).sort();
158
+ if (touched.length === 0)
159
+ return set('law-change', 'ok', 'the change does not touch the law');
160
+ const shown = touched.slice(0, 3).join(', ') + (touched.length > 3 ? `, and ${touched.length - 3} more` : '');
161
+ const command = `lawcheck check --full${inputs.base === null ? '' : ` --base ${inputs.base}`}`;
162
+ set('law-change', 'note', `the change touches the law: ${shown}; a plain check judges only the files that changed`, next(`${command} (lists what the law finds in the rest of the code, as debt)`));
163
+ },
164
+ readers: async () => {
165
+ const failure = await loadGrammars(inputs.grammarDir);
166
+ if (failure !== null)
167
+ return set('readers', 'fail', failure.message, next(failure.next));
168
+ const grammars = `the ${LANGUAGES.length} grammars load`;
169
+ let anyList = false;
170
+ walk(found.law.types, (type) => {
171
+ if (type.mayUse !== null)
172
+ anyList = true;
173
+ });
174
+ if (!anyList)
175
+ return set('readers', 'ok', `no type has may_use, so no use is read; ${grammars}`);
176
+ const siblings = siblingsOf(found.files);
177
+ const languages = new Map();
178
+ const unread = [];
179
+ for (const file of found.typed) {
180
+ if (listInForce(file.type) === null)
181
+ continue;
182
+ const reader = readerOf(file.path, file.text, siblings);
183
+ if (!reader.reader) {
184
+ unread.push(file.path);
185
+ continue;
186
+ }
187
+ const language = reader.view?.language ?? extensionOf(file.path).slice(1);
188
+ languages.set(language, (languages.get(language) ?? 0) + 1);
189
+ }
190
+ if (unread.length > 0) {
191
+ const counts = new Map();
192
+ for (const path of unread)
193
+ counts.set(extensionOf(path), (counts.get(extensionOf(path)) ?? 0) + 1);
194
+ const parts = [...counts.keys()].sort().map((extension) => `${counts.get(extension)} ${extension}`);
195
+ return set('readers', 'note', `${plural(unread.length, 'file')} ${unread.length === 1 ? 'is' : 'are'} not read for uses: ${parts.join(', ')}, so check warns uses-not-read`, next('lawcheck docs languages'));
196
+ }
197
+ const read = [...languages.values()].reduce((sum, count) => sum + count, 0);
198
+ const parts = [...languages.keys()].sort().map((language) => `${language} ${languages.get(language)}`);
199
+ set('readers', 'ok', `uses are read in ${plural(read, 'file')}${parts.length === 0 ? '' : `: ${parts.join(', ')}`}; ${grammars}`);
200
+ },
201
+ reviewer: async () => {
202
+ const config = found.config;
203
+ const count = found.kinds.reviewers.size;
204
+ const rules = plural(count, 'reviewer rule');
205
+ if (config.provider === null) {
206
+ if (inputs.reviewer) {
207
+ return set('reviewer', 'fail', 'no reviewer is set, so --reviewer has nothing to call', next('ask the user to set reviewer.provider and reviewer.model in .lawcheck/config.yaml, then run lawcheck doctor --reviewer'));
208
+ }
209
+ if (count === 0)
210
+ return set('reviewer', 'ok', 'no reviewer rule, so no reviewer is needed');
211
+ return set('reviewer', 'fail', `${rules} and no reviewer set, so their files stay not-reviewed`, next('ask the user to set reviewer.provider and reviewer.model in .lawcheck/config.yaml, then run lawcheck doctor'));
212
+ }
213
+ if (count === 0 && !inputs.reviewer)
214
+ return set('reviewer', 'ok', 'no reviewer rule, so no reviewer is needed');
215
+ const provider = createProvider(config, inputs.env);
216
+ const problem = provider.ready();
217
+ if (problem !== null)
218
+ return set('reviewer', 'fail', `${rules}; ${config.provider} cannot be called: ${problem}`, next(`${provider.fix()}, then run lawcheck doctor`));
219
+ let at = '';
220
+ if (provider.probe !== undefined) {
221
+ const probed = await provider.probe();
222
+ if ('problem' in probed)
223
+ return set('reviewer', 'fail', `${rules}; ${config.provider} cannot be called: ${probed.problem}`, next(`${probed.fix}, then run lawcheck doctor`));
224
+ at = ` at ${probed.at}`;
225
+ }
226
+ if (!inputs.reviewer)
227
+ return set('reviewer', 'ok', `${rules}; ${config.provider} can be called${at} (lawcheck doctor --reviewer makes one call)`);
228
+ const asked = await provider.ask(TEST_PROMPT);
229
+ if ('failure' in asked)
230
+ return set('reviewer', 'fail', `${rules}; ${config.provider} did not answer a test call: ${hide(asked.failure)}`, next(`${asked.fix}, then run lawcheck doctor --reviewer`));
231
+ const checked = checkAnswer(asked.answer, 0);
232
+ if ('problem' in checked || checked.verdict !== 'pass') {
233
+ const what = 'problem' in checked ? 'answered with no verdict' : 'answered fail to a test call that asks for pass';
234
+ return set('reviewer', 'fail', `${rules}; ${config.provider} ${what}: ${[...hide(asked.answer)].slice(0, 200).join('')}`, next(`check reviewer.model in .lawcheck/config.yaml, or try another model, then run lawcheck doctor --reviewer`));
235
+ }
236
+ set('reviewer', 'ok', `${rules}; ${config.provider} answered a test call`);
237
+ },
238
+ };
239
+ for (const id of IDS) {
240
+ const missing = WAITS[id].find((wait) => !passed(wait));
241
+ if (missing !== undefined) {
242
+ set(id, 'skip', `needs ${missing === 'law-file' ? 'law' : missing}`);
243
+ continue;
244
+ }
245
+ await steps[id]();
246
+ }
247
+ return IDS.map((id) => checks.get(id));
248
+ }
249
+ export function doctorText(checks, refused = null) {
250
+ const problems = checks.filter((c) => c.state === 'fail').length;
251
+ const notes = checks.filter((c) => c.state === 'note').length;
252
+ const notePart = notes === 0 ? '' : `, ${plural(notes, 'note')}`;
253
+ const first = problems === 0 ? `lawcheck: PASS ${plural(checks.length, 'check')}${notePart}` : `lawcheck: FAIL ${plural(checks.length, 'check')}, ${plural(problems, 'problem')}${notePart}`;
254
+ const lines = [refused === null ? first : `lawcheck: ERROR ${refused}`, ''];
255
+ for (const check of checks) {
256
+ lines.push(`${check.state} ${check.id} ${shown(check.message)}`);
257
+ if ((check.state === 'note' || check.state === 'fail') && check.next !== null)
258
+ lines.push(` next: ${shown(check.next.text)}`);
259
+ }
260
+ return lines.join('\n') + '\n';
261
+ }
262
+ export async function doctor(args, context, json) {
263
+ const extra = noWords(args);
264
+ if (extra !== null)
265
+ return usageError(extra, json, 'doctor');
266
+ const runtime = context.runtime ?? runtimeNow();
267
+ const checks = await runChecks({ cwd: context.cwd, env: context.env, base: flagText(args, '--base'), reviewer: args.flags.has('--reviewer'), runtime });
268
+ const failed = checks.some((check) => check.state === 'fail');
269
+ // A refused environment leads the output, as it leads every other command's; the rows below still say what else holds.
270
+ const refused = environmentRefusal(runtime, () => gitNow(context.cwd));
271
+ const stdout = json ? documentOf({ schema: 'lawcheck-doctor/0', result: failed ? 'fail' : 'pass', checks }) : doctorText(checks, refused?.message ?? null);
272
+ return { code: failed ? 2 : 0, stdout };
273
+ }
@@ -0,0 +1,73 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { git } from './files.js';
4
+ import { findProgram } from './programs.js';
5
+ export const OLDEST_NODE = 24;
6
+ export const OLDEST_GIT = [2, 34];
7
+ function otherNode() {
8
+ const found = findProgram('node', process.env);
9
+ if (found === null)
10
+ return null;
11
+ try {
12
+ return realpathSync(found) === realpathSync(process.execPath) ? null : found;
13
+ }
14
+ catch {
15
+ return found;
16
+ }
17
+ }
18
+ export function runtimeNow() {
19
+ const versions = process.versions;
20
+ return { node: process.versions.node, bun: versions.bun, pnp: versions.pnp, packageDir: fileURLToPath(new URL('..', import.meta.url)), nodeOnPath: versions.bun === undefined ? null : otherNode() };
21
+ }
22
+ function refusal(message, next) {
23
+ return { code: 'unsupported-environment', file: null, line: null, message, next };
24
+ }
25
+ export function runtimeRefusal(runtime) {
26
+ if (runtime.bun !== undefined) {
27
+ if (runtime.nodeOnPath !== null) {
28
+ return refusal(`this run is on Bun ${runtime.bun}, and Lawcheck runs on Node ${OLDEST_NODE} or later; the node first on the PATH is ${runtime.nodeOnPath}`, `start Lawcheck without --bun, as bun x --no-install lawcheck, so that it runs on ${runtime.nodeOnPath}, then run lawcheck check`);
29
+ }
30
+ return refusal(`this run is on Bun ${runtime.bun}, and Lawcheck runs on Node ${OLDEST_NODE} or later; no node is on the PATH`, `install Node ${OLDEST_NODE} or later beside Bun, so that bun x starts Lawcheck on Node, then run lawcheck check`);
31
+ }
32
+ const major = Number(runtime.node.split('.')[0]);
33
+ if (!(major >= OLDEST_NODE)) {
34
+ return refusal(`Node ${runtime.node} is older than ${OLDEST_NODE}, the oldest Node Lawcheck runs on`, `install Node ${OLDEST_NODE} or later, then run lawcheck check`);
35
+ }
36
+ // Yarn's Plug'n'Play keeps packages inside zip archives that only its own loader can open, and a runner of script rules starts with no loader. A Lawcheck installed elsewhere and started from a project that uses Plug'n'Play runs from its own folder and works.
37
+ if (runtime.pnp !== undefined && /\.zip[\\/]/i.test(runtime.packageDir)) {
38
+ return refusal(`Yarn Plug'n'Play is not supported: Lawcheck is served from the archive ${runtime.packageDir.split(/[\\/]/).find((part) => /\.zip$/i.test(part))}, which the runner of script rules cannot open`, 'set nodeLinker: node-modules in .yarnrc.yml and run yarn install, then run lawcheck check');
39
+ }
40
+ return null;
41
+ }
42
+ export function gitVersionOf(text) {
43
+ const found = /^git version (\d+)\.(\d+)/.exec(text.trim());
44
+ return found === null ? null : [Number(found[1]), Number(found[2])];
45
+ }
46
+ export function gitRefusal(text) {
47
+ const version = gitVersionOf(text);
48
+ if (version === null)
49
+ return null;
50
+ const [major, minor] = version;
51
+ const [oldestMajor, oldestMinor] = OLDEST_GIT;
52
+ if (major > oldestMajor || (major === oldestMajor && minor >= oldestMinor))
53
+ return null;
54
+ const oldest = `${oldestMajor}.${oldestMinor}`;
55
+ return refusal(`git ${text.trim().slice('git version '.length)} is older than ${oldest}, the oldest git Lawcheck runs with`, `install git ${oldest} or later, then run lawcheck check`);
56
+ }
57
+ // A git that cannot start, or prints no version, is left to the command, which names it as no-git.
58
+ export function gitNow(cwd) {
59
+ try {
60
+ const result = git(cwd, ['--version']);
61
+ return result.status === 0 ? result.stdout.toString('utf8') : null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ export function environmentRefusal(runtime, gitText) {
68
+ const refused = runtimeRefusal(runtime);
69
+ if (refused !== null)
70
+ return refused;
71
+ const text = gitText();
72
+ return text === null ? null : gitRefusal(text);
73
+ }