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/output.js ADDED
@@ -0,0 +1,325 @@
1
+ import { hide } from './keys.js';
2
+ import { FILE_TEXT_BYTES, mib, RUN_TEXT_BYTES } from './limits.js';
3
+ export const WHY = {
4
+ 'waiver-unknown-rule': 'a waiver that names no rule of the law waives nothing',
5
+ 'waiver-without-reason': 'a waiver without a reason cannot be weighed later',
6
+ 'waiver-unused': 'a waiver that drops nothing would hide the next finding on its line',
7
+ usage: 'the tool does only what its usage line says',
8
+ 'unsupported-environment': 'Lawcheck answers only where its rules and readers are known to run',
9
+ 'not-initialized': 'without a law there is nothing to check the code against',
10
+ 'no-git': 'the files and the change come from git',
11
+ 'law-invalid': 'a misspelled key changes the law without a word',
12
+ 'rule-missing-file': 'a rule without its file would never be checked',
13
+ 'rule-file-without-entry': 'a rule file that the law does not name never runs',
14
+ 'file-unreadable': 'a file that cannot be read cannot be typed or judged',
15
+ 'type-overlap': 'a file has one type, so the rules that bind it are never in doubt',
16
+ 'base-unreachable': 'without its base a change cannot be told from debt',
17
+ 'runner-failed': 'a runner that does not start says nothing about the rules',
18
+ 'rule-crashed': 'a broken rule says nothing about the code',
19
+ 'link-outside-root': 'a script rule reads nothing outside the work tree, and a link that leads out of it would let it',
20
+ 'path-unsupported': 'a script rule reads nothing outside the root and Lawcheck\'s folder, and the runner can keep that only on such a path',
21
+ internal: 'a fault of Lawcheck says nothing about the code',
22
+ 'not-reviewed': 'a reviewer rule says nothing about content it has not judged',
23
+ 'too-large-to-review': 'the reviewer is never sent more than reviewer.max_chars characters',
24
+ 'config-invalid': 'a misspelled setting changes the reviewer without a word',
25
+ 'reviewer-not-configured': 'reviewer rules need a reviewer to judge them',
26
+ 'too-many-reviews': 'reviewer.max_calls bounds what one run spends',
27
+ 'reviewer-unreachable': "without the reviewer's answer a reviewer rule says nothing",
28
+ 'reviewer-bad-answer': 'an answer that is no verdict cannot be recorded',
29
+ 'forbidden-use': "a type's may_use names every type its files may use",
30
+ 'uses-not-read': 'a restriction that cannot be checked is not shown as kept',
31
+ 'parser-failed': 'a file whose uses were not read is not taken to use nothing',
32
+ 'already-initialized': 'a second law would split one repository\'s rules between two files',
33
+ 'file-too-large': 'a run holds every file it reads as text in memory, so one file may hold only so much',
34
+ 'text-too-large': 'a run holds the text it reads in memory, so all of it may hold only so much',
35
+ 'too-many-findings': 'a run holds every finding in memory, so it may hold only so many',
36
+ 'rules-too-slow': 'a run that never ends gives no answer',
37
+ 'file-unwritable': 'what Lawcheck cannot write is lost, so the run cannot say it is done',
38
+ stopped: 'a run stopped before its end says nothing about the code',
39
+ 'memory-too-large': 'a run past its memory would be ended by the system',
40
+ 'step-too-slow': 'a step that never ends gives no answer, so one step of a run has a limit of time',
41
+ };
42
+ export const CODES = new Set([...Object.keys(WHY)]);
43
+ export function forCommand(text, command) {
44
+ if (command === 'check')
45
+ return text;
46
+ const at = text.indexOf('then run lawcheck check');
47
+ return at < 0 ? text : `${text.slice(0, at)}then run lawcheck ${command} again`;
48
+ }
49
+ function nextFor(raw, command) {
50
+ const error = raw.file === null ? raw : { ...raw, file: hide(raw.file) };
51
+ if (error.next !== undefined)
52
+ return forCommand(error.next, command ?? 'check');
53
+ if (error.code === 'usage') {
54
+ return command === null ? 'run lawcheck as its usage line says: lawcheck --help' : `run lawcheck ${command} as its usage line says: lawcheck ${command} --help`;
55
+ }
56
+ if (error.code === 'no-git')
57
+ return `run lawcheck ${command ?? 'check'} inside a git work tree, with git on the PATH`;
58
+ return forCommand(fixedNext(error, command ?? 'check'), command ?? 'check');
59
+ }
60
+ function fixedNext(error, command) {
61
+ switch (error.code) {
62
+ case 'not-initialized':
63
+ return 'write .lawcheck/law.yaml at the root of the code to check, then run lawcheck check';
64
+ case 'law-invalid':
65
+ return 'fix .lawcheck/law.yaml, then run lawcheck check';
66
+ case 'config-invalid':
67
+ return 'fix .lawcheck/config.yaml, then run lawcheck check';
68
+ case 'rule-missing-file':
69
+ return 'ask the user to write the rule files the law names or to take their rules out of the law, then run lawcheck check';
70
+ case 'rule-file-without-entry':
71
+ return `add a rule for ${error.file} to the law, or move the file to .lawcheck/rules/lib/, then run lawcheck check`;
72
+ case 'file-unreadable':
73
+ return `make ${error.file} readable, then run lawcheck check`;
74
+ case 'file-too-large':
75
+ return `leave ${error.file} out of the types with a pattern that starts with ! in .lawcheck/law.yaml, or make it smaller than ${mib(FILE_TEXT_BYTES)}, then run lawcheck check`;
76
+ case 'text-too-large':
77
+ return `narrow the paths of the types in .lawcheck/law.yaml, so that the files they match hold at most ${mib(RUN_TEXT_BYTES)} of text, then run lawcheck check`;
78
+ case 'too-many-findings':
79
+ return `make the rules return fewer findings, or narrow the types that list them, then run lawcheck check`;
80
+ case 'rules-too-slow':
81
+ return `make the slow rules faster, or narrow the types that list them, then run lawcheck check`;
82
+ case 'file-unwritable':
83
+ return `make ${error.file ?? 'the place named'} writable, then run lawcheck ${command} again`;
84
+ case 'stopped':
85
+ return `run lawcheck ${command} again and let it end`;
86
+ case 'step-too-slow':
87
+ return `make the step named faster, such as a type's content pattern that backtracks, then run lawcheck ${command} again`;
88
+ case 'type-overlap':
89
+ return 'narrow the paths or content of the types that overlap in .lawcheck/law.yaml, then run lawcheck check';
90
+ case 'base-unreachable':
91
+ return 'pass --base with a branch or a commit that exists here';
92
+ case 'rule-crashed':
93
+ return `fix ${error.file}, then run lawcheck check`;
94
+ case 'link-outside-root':
95
+ return `remove the link ${error.file}, or let it lead inside the work tree, then run lawcheck check`;
96
+ case 'path-unsupported':
97
+ return 'move the repository, or Lawcheck itself, to a path with no * or backslash, then run lawcheck check; Lawcheck grants a rule read access to its own folder for the readers it ships, so that path must be as plain as the root';
98
+ case 'runner-failed':
99
+ return 'reinstall Lawcheck, then run lawcheck check';
100
+ case 'reviewer-unreachable':
101
+ if (/\bHTTP 40[13]\b/.test(error.message)) {
102
+ return 'check the reviewer key in the environment, then run the same command again; what was answered is kept, so it asks only the rest';
103
+ }
104
+ return 'run the same command again; what was answered is kept, so it asks only the rest';
105
+ case 'reviewer-bad-answer':
106
+ return 'run the same command again; what was answered is kept, so it asks only the rest';
107
+ default:
108
+ return `run lawcheck ${command} again, and report the error if it stays`;
109
+ }
110
+ }
111
+ // spec/check-slice.md, section 6: no text output holds these, and no JSON document holds them raw. Format characters (Unicode category Cf) all count but the joiners U+200C and U+200D, which scripts and emoji sequences need.
112
+ const FORBIDDEN = /[\x00-\x09\x0b-\x1f\x7f-\x9f\u2028\u2029]|(?![\u200c\u200d])\p{Cf}/gu;
113
+ const RAW_IN_JSON = /[\x7f-\x9f\u2028\u2029]|(?![\u200c\u200d])\p{Cf}/gu;
114
+ // A line that starts like a command of GitHub Actions or Azure Pipelines; GitHub reads a command after leading white space, and Azure reads ##vso[ anywhere in a line.
115
+ const FORGED = /^(\s*)(::|##\[)/;
116
+ const AZURE = /##vso\[/g;
117
+ const NAMED = { '\n': '\\n', '\r': '\\r', '\t': '\\t' };
118
+ function units(c) {
119
+ return [...Array(c.length).keys()].map((i) => `\\u${c.charCodeAt(i).toString(16).padStart(4, '0')}`).join('');
120
+ }
121
+ function escaped(c) {
122
+ const code = c.charCodeAt(0);
123
+ return NAMED[c] ?? (code < 0x80 ? `\\x${code.toString(16).padStart(2, '0')}` : units(c));
124
+ }
125
+ export function shown(text) {
126
+ return hide(text).replace(/\n/g, escaped).replace(FORBIDDEN, escaped);
127
+ }
128
+ export function plain(text) {
129
+ return text.replace(/\n/g, escaped).replace(FORBIDDEN, escaped);
130
+ }
131
+ function shownPlace(file, line) {
132
+ return line === null || line === undefined ? shown(file) : `${shown(file)}:${line}`;
133
+ }
134
+ export function safeText(output) {
135
+ return output
136
+ .split('\n')
137
+ .map((line) => line
138
+ .replace(FORBIDDEN, escaped)
139
+ .replace(AZURE, '\\x23#vso[')
140
+ .replace(FORGED, (_, space, start) => space + escaped(start[0]) + start.slice(1)))
141
+ .join('\n');
142
+ }
143
+ export function safeJson(output) {
144
+ return output.replace(RAW_IN_JSON, units);
145
+ }
146
+ export function plural(count, word) {
147
+ return `${count} ${word}${count === 1 ? '' : 's'}`;
148
+ }
149
+ function compare(a, b) {
150
+ return a < b ? -1 : a > b ? 1 : 0;
151
+ }
152
+ export function sortErrors(errors) {
153
+ return [...errors].sort((a, b) => compare(a.file ?? '', b.file ?? '') || (a.line ?? 0) - (b.line ?? 0) || compare(a.code, b.code));
154
+ }
155
+ export function sortFindings(findings) {
156
+ return [...findings].sort((a, b) => compare(a.file, b.file) || (a.line ?? 0) - (b.line ?? 0) || compare(a.code, b.code));
157
+ }
158
+ export function placeOf(file, line) {
159
+ if (file === null)
160
+ return null;
161
+ return line === null || line === undefined ? file : `${file}:${line}`;
162
+ }
163
+ // The command a next line asks to run first, or null when its first step is no command, such as installing Node or passing a base: one its error names, else a line that is a Lawcheck command, or one whose only step is the command after its colon.
164
+ export function commandIn(text, given) {
165
+ if (given !== undefined)
166
+ return given;
167
+ if (text.startsWith('lawcheck '))
168
+ return text.split(' (')[0];
169
+ const after = /^run lawcheck [a-z]* ?as its usage line says: (lawcheck [^,;()]+)$/.exec(text);
170
+ return after === null ? null : after[1].trim();
171
+ }
172
+ export function nextOfErrors(input, command = 'check') {
173
+ return nextFor(sortErrors(input)[0], command);
174
+ }
175
+ export function errorLines(errors, limit = Infinity) {
176
+ const lines = [];
177
+ const seen = new Set();
178
+ let printed = 0;
179
+ for (const error of errors) {
180
+ if (printed === limit)
181
+ break;
182
+ printed++;
183
+ const place = placeOf(error.file, error.line);
184
+ lines.push(`${place === null ? '' : shownPlace(error.file, error.line) + ' '}error[${error.code}] ${shown(error.message)}`);
185
+ if (!seen.has(error.code)) {
186
+ seen.add(error.code);
187
+ lines.push(` why: ${WHY[error.code] ?? ''}`);
188
+ }
189
+ }
190
+ if (errors.length > printed)
191
+ lines.push(`... and ${plural(errors.length - printed, 'more error')} (lawcheck check lists all)`);
192
+ return lines;
193
+ }
194
+ export function renderErrors(input, json, command = 'check', limit = Infinity) {
195
+ const errors = sortErrors(input);
196
+ const next = nextFor(errors[0], command);
197
+ if (json) {
198
+ const document = {
199
+ schema: 'lawcheck-error/1',
200
+ errors: errors.map((e) => ({ code: e.code, file: e.file, line: e.line, message: e.message, why: WHY[e.code] ?? '' })),
201
+ next: { command: commandIn(next, errors[0].command), text: next },
202
+ };
203
+ return JSON.stringify(document, null, 2) + '\n';
204
+ }
205
+ const refused = errors.find((e) => e.code === 'unsupported-environment');
206
+ const lines = [`lawcheck: ERROR ${refused === undefined ? plural(errors.length, 'error') : shown(refused.message)}`, '', ...errorLines(errors, limit)];
207
+ lines.push('', `next: ${plain(next)}`);
208
+ return lines.join('\n') + '\n';
209
+ }
210
+ function waiverPart(count) {
211
+ return count === 0 ? '' : `, ${plural(count, 'waiver')}`;
212
+ }
213
+ function unresolvedPart(count) {
214
+ return count === 0 ? '' : `, ${plural(count, 'unresolved use')}`;
215
+ }
216
+ export function firstError(report) {
217
+ return report.findings.find((f) => f.severity === 'error');
218
+ }
219
+ export function fixNext(finding) {
220
+ return `fix ${placeOf(hide(finding.file), finding.line)}`;
221
+ }
222
+ export function renderReport(report, json) {
223
+ const errors = report.findings.filter((f) => f.severity === 'error').length;
224
+ const warnings = report.findings.length - errors;
225
+ const failing = errors > 0;
226
+ const blocking = firstError(report);
227
+ const nextOf = report.next !== undefined ? report.next : blocking ? { command: null, text: fixNext(blocking) } : null;
228
+ const next = nextOf === null ? null : nextOf.text;
229
+ const reviews = report.reviews ?? { missing: 0, calls_made: 0, passes_recorded: 0 };
230
+ const calls = reviews.calls_made === 0 ? '' : `, ${plural(reviews.calls_made, 'reviewer call')}`;
231
+ const changeWaivers = report.waivers.filter((w) => !w.debt).length;
232
+ const debtWaivers = report.waivers.length - changeWaivers;
233
+ const unresolved = report.unresolved ?? [];
234
+ const changeUnresolved = unresolved.filter((u) => !u.debt).length;
235
+ const debtUnresolved = unresolved.length - changeUnresolved;
236
+ if (json) {
237
+ const shape = (f) => {
238
+ const out = {
239
+ code: f.code,
240
+ rule: f.rule,
241
+ severity: f.severity,
242
+ blocking: f.severity === 'error',
243
+ debt: f.debt,
244
+ file: f.file,
245
+ };
246
+ if (f.line !== undefined)
247
+ out.line = f.line;
248
+ out.type = f.type;
249
+ out.message = f.message;
250
+ out.why = f.why;
251
+ return out;
252
+ };
253
+ const document = {
254
+ schema: 'lawcheck-check/0',
255
+ result: failing ? 'fail' : 'pass',
256
+ scope: {
257
+ mode: report.mode,
258
+ base: report.base,
259
+ files: report.changed,
260
+ law_changed: report.lawChanged ?? false,
261
+ ...(report.lawChanges !== undefined && report.lawChanges.length > 0 ? { law_changes: report.lawChanges } : {}),
262
+ },
263
+ summary: { errors, warnings, debt: report.debt.length, waivers: changeWaivers, unresolved: changeUnresolved },
264
+ findings: [...report.findings, ...report.debt].map(shape),
265
+ waivers: report.waivers.map((w) => ({ file: w.file, line: w.line, rule: w.rule, debt: w.debt, waived: w.waived, reason: w.reason })),
266
+ unresolved: unresolved.map((u) => ({ file: u.file, line: u.line, what: u.what, answer: u.answer, reason: u.reason, candidates: u.candidates, debt: u.debt })),
267
+ reviews: { missing: reviews.missing, calls_made: reviews.calls_made, passes_recorded: reviews.passes_recorded },
268
+ next: nextOf === null ? null : { command: nextOf.command, text: nextOf.text },
269
+ };
270
+ return JSON.stringify(document, null, 2) + '\n';
271
+ }
272
+ const verdict = failing ? 'FAIL' : 'PASS';
273
+ const lines = [];
274
+ if (report.mode !== 'paths' && report.base !== null && report.changed === 0) {
275
+ lines.push(`lawcheck: ${verdict} nothing changed against ${shown(report.base)}${calls}`);
276
+ }
277
+ else {
278
+ const counts = [errors > 0 ? plural(errors, 'error') : '', warnings > 0 ? plural(warnings, 'warning') : '']
279
+ .filter(Boolean)
280
+ .join(', ');
281
+ const scope = report.mode === 'paths'
282
+ ? plural(report.changed, 'named file')
283
+ : report.base === null
284
+ ? `${plural(report.changed, 'file')} (no base: every file counts as changed)`
285
+ : `${plural(report.changed, 'changed file')} (against ${shown(report.base)})`;
286
+ lines.push(`lawcheck: ${verdict} ${counts === '' ? '' : counts + ' in '}${scope}${waiverPart(changeWaivers)}${unresolvedPart(changeUnresolved)}${calls}`);
287
+ }
288
+ if (report.note)
289
+ lines.push(report.note);
290
+ const limit = 50;
291
+ const total = report.findings.length + report.debt.length;
292
+ const more = `... ${plural(total - limit, 'more finding')} (--json lists all)`;
293
+ const seen = new Set();
294
+ let printed = 0;
295
+ const print = (finding) => {
296
+ lines.push(`${shownPlace(finding.file, finding.line)} ${finding.severity}[${finding.code}] ${shown(finding.message)}`);
297
+ printed++;
298
+ if (!seen.has(finding.code)) {
299
+ seen.add(finding.code);
300
+ lines.push(` why: ${finding.why}`);
301
+ }
302
+ };
303
+ if (report.findings.length > 0) {
304
+ lines.push('');
305
+ for (const finding of report.findings)
306
+ if (printed < limit)
307
+ print(finding);
308
+ if (report.findings.length > limit)
309
+ lines.push(more);
310
+ }
311
+ if (report.mode === 'full') {
312
+ lines.push('');
313
+ const files = new Set(report.debt.map((f) => f.file)).size;
314
+ const heading = report.debt.length === 0 ? 'none' : `${plural(report.debt.length, 'finding')} in ${plural(files, 'file')}`;
315
+ lines.push(`debt (outside this change): ${heading}${waiverPart(debtWaivers)}${unresolvedPart(debtUnresolved)}`);
316
+ for (const finding of report.debt)
317
+ if (printed < limit)
318
+ print(finding);
319
+ if (report.findings.length <= limit && total > limit)
320
+ lines.push(more);
321
+ }
322
+ if (next !== null)
323
+ lines.push('', `next: ${plain(next)}`);
324
+ return lines.join('\n') + '\n';
325
+ }
package/dist/prime.js ADDED
@@ -0,0 +1,211 @@
1
+ import { CONFIG_BYTES, readWhole } from './limits.js';
2
+ import { decode } from './types.js';
3
+ import { join } from 'node:path';
4
+ import { documentOf, noWords, usageError } from './args.js';
5
+ import { CONFIG, RUNNER_COMMANDS, runnerOf } from './config.js';
6
+ import { plural, renderErrors, shown } from './output.js';
7
+ import { findRoot, loadLaw, loadRuleFiles, requireGit, stopped } from './setup.js';
8
+ import { listInForce } from './uses.js';
9
+ const PLAIN_PLAN = 'the file types and the rules each type keeps';
10
+ const PLAN_WITH_USES = 'the file types, the rules each type keeps, and which types may use which';
11
+ export function firstPart(reviewers, mayUse) {
12
+ return [
13
+ `Lawcheck checks this repository's code against its law: ${mayUse ? PLAN_WITH_USES : PLAIN_PLAN}. The law is .lawcheck/law.yaml; rule files are in .lawcheck/rules/.`,
14
+ '',
15
+ 'How to work here',
16
+ '- Before you create a file, or first edit a file of a type new to you: lawcheck explain <path>',
17
+ '- After you change code: lawcheck check. If it says "no base", run lawcheck check --base <the branch you started from>.',
18
+ '- Exit 0: nothing blocks; warnings are advisory. Exit 1: the code breaks the law; fix the code. Exit 2: Lawcheck or the law is broken; fix what the error names, not the code.',
19
+ '- Never report work as done while lawcheck check exits 1.',
20
+ "- A failing run ends with a next line; do what it says. When it asks for something listed below as the user's, or a finding cannot be fixed in the code, ask the user.",
21
+ ...(reviewers ? ['- not-reviewed: fix every other finding first, then run lawcheck check --review'] : []),
22
+ '- A plain check judges only changed files. After you change the law or a rule file, run lawcheck check --full and tell the user how many findings it lists outside your change.',
23
+ '- Findings outside your change are debt. Leave them unless the user asks.',
24
+ '',
25
+ "Only on the user's word",
26
+ '- a waiver comment: lawcheck-waive <rule> -- <reason> (lawcheck docs waivers), or taking a rule off a type',
27
+ '- deleting a rule, or changing its status or its why',
28
+ ...(mayUse ? ['- widening may_use'] : []),
29
+ ...(reviewers ? ['- lawcheck check --review --again, or --max-calls above reviewer.max_calls'] : []),
30
+ '- any edit of .lawcheck/verdicts or of .lawcheck/config.yaml',
31
+ '',
32
+ 'You may, unasked',
33
+ '- add a type for a new kind of file, or make a type finer',
34
+ `- write a rule the user asked for, and try it first: lawcheck try <rule> <files>${reviewers ? '; a reviewer rule pays one call per file, so add --dry-run first' : ''}`,
35
+ '',
36
+ ].join('\n');
37
+ }
38
+ export const FIRST_PART = firstPart(true, true);
39
+ export const NO_LAW = [
40
+ 'Lawcheck is installed, and this directory has no law (.lawcheck/law.yaml here or above).',
41
+ 'Run lawcheck init only when the user asks for a law here.',
42
+ '',
43
+ ].join('\n');
44
+ export const BUDGET = 8000;
45
+ const MORE = 'More: lawcheck docs';
46
+ const SHORTENED = 'shortened to fit; lawcheck explain --type <id> shows a type in full, lawcheck explain --rule <id> a rule';
47
+ export function length(text) {
48
+ let count = 0;
49
+ for (const _ of text)
50
+ count++;
51
+ return count;
52
+ }
53
+ export function cut(text) {
54
+ const points = [...text];
55
+ return points.length > 60 ? points.slice(0, 59).join('') + '…' : text;
56
+ }
57
+ export function mayUsePart(type, gap = ' ') {
58
+ const inForce = listInForce(type);
59
+ if (inForce === null)
60
+ return null;
61
+ const list = inForce.list.length === 0 ? 'nothing' : inForce.list.join(', ');
62
+ return inForce.from === type ? list : `${list}${gap}(from ${inForce.from.id})`;
63
+ }
64
+ export function walk(types, visit, depth = 0) {
65
+ for (const type of types) {
66
+ visit(type, depth);
67
+ walk(type.types, visit, depth + 1);
68
+ }
69
+ }
70
+ export function ruleKind(kinds, id) {
71
+ return kinds.scripts.has(id) ? 'script' : 'reviewer';
72
+ }
73
+ function typeLine(type, depth, step) {
74
+ const short = step >= 3 && depth > 0;
75
+ const parts = [type.id];
76
+ if (!short) {
77
+ parts.push(shown(type.paths.join(', ')));
78
+ if (type.expression !== null)
79
+ parts.push(`content: ${shown(type.expression)}`);
80
+ }
81
+ if (type.about !== null)
82
+ parts.push(shown(step >= 2 ? cut(type.about) : type.about));
83
+ if (type.rules.length > 0)
84
+ parts.push(`rules: ${type.rules.join(', ')}`);
85
+ const mayUse = mayUsePart(type);
86
+ if (mayUse !== null)
87
+ parts.push(`may use: ${mayUse}`);
88
+ return ' '.repeat(depth) + parts.join(' ');
89
+ }
90
+ function listed(law) {
91
+ const out = new Set();
92
+ walk(law.types, (type) => type.rules.forEach((rule) => out.add(rule)));
93
+ return out;
94
+ }
95
+ function ruleLine(law, kinds, id, onTypes, step) {
96
+ const rule = law.rules.get(id);
97
+ const parts = [id, ruleKind(kinds, id)];
98
+ if (rule.status === 'advisory')
99
+ parts.push('advisory');
100
+ if (!onTypes.has(id))
101
+ parts.push('on no type');
102
+ if (step < 3)
103
+ parts.push(step >= 2 ? cut(rule.why) : rule.why);
104
+ return parts.join(' ');
105
+ }
106
+ function rootLine(type) {
107
+ const parts = [type.id, type.paths.join(', ')];
108
+ if (type.expression !== null)
109
+ parts.push(`content: ${type.expression}`);
110
+ if (type.about !== null)
111
+ parts.push(shown(cut(type.about)));
112
+ let subtypes = 0;
113
+ const rules = new Set(type.rules);
114
+ walk(type.types, (sub) => {
115
+ subtypes++;
116
+ sub.rules.forEach((rule) => rules.add(rule));
117
+ });
118
+ if (subtypes > 0)
119
+ parts.push(`subtypes: ${subtypes}`);
120
+ if (rules.size > 0)
121
+ parts.push(`rules: ${rules.size}`);
122
+ return parts.join(' ');
123
+ }
124
+ function header(law) {
125
+ let count = 0;
126
+ walk(law.types, () => count++);
127
+ return `The law here: ${plural(count, 'type')}, ${plural(law.rules.size, 'rule')}`;
128
+ }
129
+ function assemble(first, head, typeLines, ruleLines, last) {
130
+ return [first + head, ...typeLines, '', 'Rules', ...ruleLines, '', last, ''].join('\n');
131
+ }
132
+ export function startPart(root) {
133
+ let runner = 'global';
134
+ try {
135
+ const bytes = readWhole(join(root, CONFIG), CONFIG);
136
+ if (bytes.length > CONFIG_BYTES)
137
+ return '';
138
+ runner = runnerOf(decode(bytes));
139
+ }
140
+ catch {
141
+ return '';
142
+ }
143
+ return runner === 'global' || !Object.hasOwn(RUNNER_COMMANDS, runner) ? '' : ` Start it here as: ${RUNNER_COMMANDS[runner].words.join(' ')}`;
144
+ }
145
+ export function withStart(first, start) {
146
+ const end = first.indexOf('\n');
147
+ return first.slice(0, end) + start + first.slice(end);
148
+ }
149
+ export function primeText(law, kinds, budget = BUDGET, start = '') {
150
+ const head = '\n' + header(law);
151
+ let mayUse = false;
152
+ walk(law.types, (type) => {
153
+ if (type.mayUse !== null)
154
+ mayUse = true;
155
+ });
156
+ const first = withStart(firstPart([...law.rules.keys()].some((id) => ruleKind(kinds, id) === 'reviewer'), mayUse), start);
157
+ const onTypes = listed(law);
158
+ const ids = [...law.rules.keys()];
159
+ const fits = (text) => length(text) <= budget;
160
+ for (const step of [1, 2, 3]) {
161
+ const typeLines = [];
162
+ walk(law.types, (type, depth) => typeLines.push(typeLine(type, depth, step)));
163
+ const text = assemble(first, head, typeLines, ids.map((id) => ruleLine(law, kinds, id, onTypes, step)), step === 1 ? MORE : SHORTENED);
164
+ if (fits(text))
165
+ return { text, step };
166
+ }
167
+ const roots = law.types.map(rootLine);
168
+ const render = (count, idsLine) => {
169
+ const lines = roots.slice(0, count);
170
+ if (count < roots.length)
171
+ lines.push(`... and ${roots.length - count} more root types`);
172
+ return assemble(first, head, lines, idsLine === '' ? [] : [idsLine], SHORTENED);
173
+ };
174
+ let idsLine = ids.join(', ');
175
+ if (!fits(render(0, idsLine))) {
176
+ let kept = ids.length - 1;
177
+ const shortened = (k) => `${ids.slice(0, k).join(', ')}, and ${ids.length - k} more`;
178
+ while (kept > 0 && !fits(render(0, shortened(kept))))
179
+ kept--;
180
+ idsLine = kept === 0 ? '' : shortened(kept);
181
+ }
182
+ let count = 0;
183
+ while (count < roots.length && fits(render(count + 1, idsLine)))
184
+ count++;
185
+ return { text: render(count, idsLine), step: 4 };
186
+ }
187
+ export async function prime(args, context, json) {
188
+ const extra = noWords(args);
189
+ if (extra !== null)
190
+ return usageError(extra, json, 'prime');
191
+ const root = findRoot(context.cwd);
192
+ const answer = (text, step) => ({
193
+ code: 0,
194
+ stdout: json ? documentOf({ schema: 'lawcheck-prime/0', text, step, characters: length(text) }) : text,
195
+ });
196
+ if (root === null)
197
+ return answer(NO_LAW, null);
198
+ const outcome = await stopped(() => {
199
+ requireGit(root);
200
+ const law = loadLaw(root);
201
+ const { kinds } = loadRuleFiles(root, law);
202
+ return { law, kinds };
203
+ });
204
+ if ('errors' in outcome) {
205
+ if (json)
206
+ return { code: 2, stdout: renderErrors(outcome.errors, true, 'prime') };
207
+ return { code: 2, stdout: withStart(FIRST_PART, startPart(root)) + '\n' + renderErrors(outcome.errors, false, 'prime', 20) };
208
+ }
209
+ const { text, step } = primeText(outcome.law, outcome.kinds, BUDGET, startPart(root));
210
+ return answer(text, step);
211
+ }