lintobot 0.0.0-stage → 0.2.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +301 -2
  3. package/dist/cli.js +2022 -0
  4. package/package.json +52 -4
package/dist/cli.js ADDED
@@ -0,0 +1,2022 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import fs6 from "node:fs";
5
+ import path7 from "node:path";
6
+ import { Command, CommanderError } from "commander";
7
+ // package.json
8
+ var package_default = {
9
+ name: "lintobot",
10
+ version: "0.2.0",
11
+ description: "AI code linter: rules are plain-language sentences answered by a decision model (Jev)",
12
+ keywords: [
13
+ "lint",
14
+ "linter",
15
+ "ai",
16
+ "code-quality",
17
+ "decision-model",
18
+ "jev",
19
+ "cli"
20
+ ],
21
+ homepage: "https://github.com/testomatio/lintobot#readme",
22
+ bugs: {
23
+ url: "https://github.com/testomatio/lintobot/issues"
24
+ },
25
+ repository: {
26
+ type: "git",
27
+ url: "git+https://github.com/testomatio/lintobot.git"
28
+ },
29
+ license: "MIT",
30
+ type: "module",
31
+ bin: {
32
+ lintobot: "dist/cli.js"
33
+ },
34
+ files: [
35
+ "dist"
36
+ ],
37
+ scripts: {
38
+ build: "bun build src/cli.ts --target=node --packages=external --outdir=dist && chmod +x dist/cli.js",
39
+ typecheck: "tsc --noEmit",
40
+ test: "bun test",
41
+ prepublishOnly: "bun run typecheck && bun test && bun run build"
42
+ },
43
+ engines: {
44
+ node: ">=22"
45
+ },
46
+ dependencies: {
47
+ commander: "^15.1.0",
48
+ picocolors: "^1.1.1",
49
+ picomatch: "^4.0.7",
50
+ "scripted-yaml": "0.3",
51
+ sloc: "^0.3.2",
52
+ yaml: "^2.9.1",
53
+ zod: "^4.6.7"
54
+ },
55
+ devDependencies: {
56
+ "@types/bun": "^1.4.5",
57
+ "@types/node": "^26.6.11",
58
+ "@types/picomatch": "^4.0.3",
59
+ typescript: "^7.0.2"
60
+ }
61
+ };
62
+
63
+ // src/config/init.ts
64
+ import path from "node:path";
65
+ var OUTPUT_DIRS = ["dist", "build", "vendor", "coverage", "tmp", "log"];
66
+ var MAX_EXTENSIONS = 3;
67
+ function starterConfig(files, model = "openrouter/typesafe/jev-1.14") {
68
+ const source = files.filter((file) => !OUTPUT_DIRS.includes(file.split("/")[0]));
69
+ const counts = new Map;
70
+ for (const file of source) {
71
+ const ext = path.extname(file).slice(1).toLowerCase();
72
+ counts.set(ext, (counts.get(ext) ?? 0) + 1);
73
+ }
74
+ const extensions = [...counts].sort((a, b) => b[1] - a[1]).slice(0, MAX_EXTENSIONS).map(([ext]) => ext);
75
+ const pattern = extensions.length > 1 ? `**/*.{${extensions.join(",")}}` : `**/*.${extensions[0] ?? "js"}`;
76
+ const ignore = OUTPUT_DIRS.filter((dir) => files.some((file) => file.startsWith(`${dir}/`)));
77
+ return `model: ${model}
78
+
79
+ defaults:
80
+ error: 0.9
81
+ warning: 0.7
82
+ info: 0.9
83
+
84
+ ${ignore.length ? `ignore:
85
+ ${ignore.map((dir) => ` - "${dir}/**"`).join(`
86
+ `)}
87
+
88
+ ` : ""}files:
89
+ - pattern: "${pattern}"
90
+ rules:
91
+ - "no secret values exposed"
92
+ - "no magic numbers"
93
+ - "no global state polluted"
94
+ - "file is focused on a single thing":
95
+ whole: true
96
+ - "no comments that restate the code":
97
+ $if!: file.comment_lines > 5
98
+ - "file is not too long":
99
+ warning!: file.lines > 500
100
+ info:
101
+ - "reads or writes files on disk"
102
+ - "makes network requests"
103
+ `;
104
+ }
105
+
106
+ // src/config/load.ts
107
+ import fs2 from "node:fs";
108
+ import YAML2 from "yaml";
109
+ import { ScriptedYaml, ScriptedYamlError } from "scripted-yaml";
110
+
111
+ // src/facts/facts.ts
112
+ import path2 from "node:path";
113
+ import sloc from "sloc";
114
+ var SLOC_ALIAS = { cjs: "js", mts: "ts", cts: "ts" };
115
+ var IMPORTS = [
116
+ /^\s*import\s+(?:[^'"]*?\sfrom\s+)?['"]([^'"]+)['"]/gm,
117
+ /^\s*export\s+[^'"\n]*?\sfrom\s+['"]([^'"]+)['"]/gm,
118
+ /\b(?:require|import)\(\s*['"]([^'"]+)['"]\s*\)/g,
119
+ /^\s*(?:require|require_relative|load)\s+['"]([^'"]+)['"]/gm,
120
+ /^\s*from\s+([\w.]+)\s+import\b/gm,
121
+ /^import\s+([\w.]+)(?:\s+as\s+\w+)?\s*$/gm,
122
+ /^\s*(?:import|use)\s+(?:static\s+)?([\w.\\:]+(?:\.\*)?)\s*;/gm,
123
+ /^\s*#include\s+[<"]([^>"]+)[>"]/gm
124
+ ];
125
+ var GO_IMPORT = /^\s*(?:import\s+)?(?:[\w.]+\s+)?"([\w./-]+)"\s*$/gm;
126
+ var EXPORTS = [
127
+ /^\s*export\s+(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\*?|class|const|let|var|interface|type|enum)\s+([\w$]+)/gm,
128
+ /^\s*(?:module\.)?exports\.([\w$]+)\s*=/gm
129
+ ];
130
+ var BRANCHES = /\b(?:if|elif|elsif|unless|for|foreach|while|until|case|when|catch|except|rescue)\b|&&|\|\||\?\?/g;
131
+ function computeFacts(file, text) {
132
+ const ext = path2.extname(file).slice(1).toLowerCase();
133
+ const lines = text === "" ? [] : text.replace(/\r?\n$/, "").split(/\r?\n/);
134
+ return {
135
+ path: file,
136
+ ext,
137
+ dir: path2.dirname(file),
138
+ name: path2.basename(file),
139
+ lines: lines.length,
140
+ ...countLines(text, ext, lines),
141
+ longest_line: lines.reduce((max, line) => Math.max(max, line.length), 0),
142
+ max_depth: maxDepth(lines),
143
+ imports: unique((ext === "go" ? [GO_IMPORT] : IMPORTS).flatMap((pattern) => captures(text, pattern))),
144
+ exports: exportsOf(text),
145
+ complexity: 1 + (text.match(BRANCHES)?.length ?? 0)
146
+ };
147
+ }
148
+ var PLACEHOLDER_FACTS = { ...computeFacts("", ""), imports: [""], exports: [""] };
149
+ function countLines(text, ext, lines) {
150
+ const language = SLOC_ALIAS[ext] ?? ext;
151
+ if (sloc.extensions.includes(language)) {
152
+ try {
153
+ const stats = sloc(text, language);
154
+ return { code_lines: stats.source, comment_lines: stats.comment, blank_lines: Math.min(stats.empty, lines.length) };
155
+ } catch {}
156
+ }
157
+ const blank = lines.filter((line) => line.trim() === "").length;
158
+ return { code_lines: lines.length - blank, comment_lines: 0, blank_lines: blank };
159
+ }
160
+ function maxDepth(lines) {
161
+ const indents = lines.filter((line) => line.trim() !== "").map((line) => line.match(/^[ \t]*/)[0]);
162
+ const spaces = indents.filter((indent) => indent.length > 0 && !indent.includes("\t")).map((indent) => indent.length);
163
+ const unit = spaces.length ? Math.max(2, Math.min(...spaces)) : 4;
164
+ return indents.reduce((max, indent) => {
165
+ const tabs = indent.split("\t").length - 1;
166
+ return Math.max(max, tabs + Math.floor((indent.length - tabs) / unit));
167
+ }, 0);
168
+ }
169
+ function exportsOf(text) {
170
+ const names = EXPORTS.flatMap((pattern) => captures(text, pattern));
171
+ for (const list of captures(text, /^\s*export\s*\{([^}]*)\}/gm)) {
172
+ names.push(...list.split(",").map((item) => item.trim().split(/\s+as\s+/).pop()).filter(Boolean));
173
+ }
174
+ if (/^\s*export\s+default\b/m.test(text) || /^\s*module\.exports\s*=/m.test(text))
175
+ names.push("default");
176
+ return unique(names);
177
+ }
178
+ function captures(text, pattern) {
179
+ return [...text.matchAll(pattern)].map((match) => match[1]);
180
+ }
181
+ function unique(list) {
182
+ return [...new Set(list)];
183
+ }
184
+
185
+ // src/files/find.ts
186
+ import fs from "node:fs";
187
+ import path3 from "node:path";
188
+ import picomatch from "picomatch";
189
+
190
+ // src/facts/language.ts
191
+ var LANGUAGES = {
192
+ js: "javascript",
193
+ mjs: "javascript",
194
+ cjs: "javascript",
195
+ jsx: "javascript",
196
+ ts: "typescript",
197
+ mts: "typescript",
198
+ cts: "typescript",
199
+ tsx: "typescript",
200
+ py: "python",
201
+ rb: "ruby",
202
+ go: "go",
203
+ php: "php",
204
+ java: "java",
205
+ kt: "kotlin",
206
+ rs: "rust",
207
+ c: "c",
208
+ h: "c",
209
+ cc: "cpp",
210
+ cpp: "cpp",
211
+ hpp: "cpp",
212
+ cs: "csharp",
213
+ swift: "swift",
214
+ scala: "scala",
215
+ sh: "shell",
216
+ bash: "shell",
217
+ sql: "sql",
218
+ lua: "lua",
219
+ dart: "dart",
220
+ ex: "elixir",
221
+ exs: "elixir",
222
+ vue: "vue",
223
+ svelte: "svelte"
224
+ };
225
+ var languageOf = (ext) => LANGUAGES[ext];
226
+
227
+ // src/files/find.ts
228
+ var DEFAULT_IGNORE = ["**/node_modules/**", "**/.git/**", "**/.lintobot/**", "**/.env*", "**/*.pem", "**/*.key", "**/*.min.js"];
229
+ var SKIP_DIRS = new Set(["node_modules", ".git", ".lintobot"]);
230
+ function matcher(patterns) {
231
+ const matches = picomatch(patterns, { dot: true });
232
+ return (file) => matches(file);
233
+ }
234
+ function walk(dir) {
235
+ const found = [];
236
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
237
+ const file = path3.posix.join(dir, entry.name);
238
+ if (entry.isDirectory()) {
239
+ if (!SKIP_DIRS.has(entry.name))
240
+ found.push(...walk(file));
241
+ } else if (entry.isFile()) {
242
+ found.push(file);
243
+ }
244
+ }
245
+ return found;
246
+ }
247
+ var isCode = (file) => languageOf(path3.extname(file).slice(1).toLowerCase()) !== undefined;
248
+ function findFiles(args, patterns, ignore) {
249
+ const ignored = matcher([...DEFAULT_IGNORE, ...ignore]);
250
+ const wanted = patterns ? matcher(patterns) : null;
251
+ const files = new Set;
252
+ const add = (file, named = false) => {
253
+ const relative = path3.posix.normalize(file.split(path3.sep).join("/"));
254
+ if (ignored(relative))
255
+ return;
256
+ if (wanted ? wanted(relative) : named || isCode(relative))
257
+ files.add(relative);
258
+ };
259
+ if (args.length === 0)
260
+ walk(".").forEach((file) => add(file));
261
+ for (const arg of args) {
262
+ const stat = fs.statSync(arg, { throwIfNoEntry: false });
263
+ if (stat?.isFile())
264
+ add(arg, true);
265
+ else if (stat?.isDirectory())
266
+ walk(arg).forEach((file) => add(file));
267
+ else
268
+ walk(".").filter(matcher([arg])).forEach((file) => add(file));
269
+ }
270
+ return [...files].sort();
271
+ }
272
+
273
+ // src/config/error.ts
274
+ class ConfigError extends Error {
275
+ }
276
+
277
+ // src/config/context.ts
278
+ var ENTRY_MAX_BYTES = 4000;
279
+ var CONTEXT_MARKERS = ["file", "sh"];
280
+ var LATER = ["mdq", "outline"];
281
+ var RESERVED = ["path", "language", "outline", "code", "part"];
282
+ var isMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
283
+ function contextOf(value, where) {
284
+ if (value === undefined || value === null)
285
+ return {};
286
+ if (!isMap(value))
287
+ throw new ConfigError(`${where}: context must be a map of named entries`);
288
+ const entries = {};
289
+ for (const [key, written] of Object.entries(value)) {
290
+ const [name, marker] = split(key);
291
+ const at = `${where}: context "${key}"`;
292
+ if (!/^[A-Za-z_]\w*$/.test(name))
293
+ throw new ConfigError(`${at}: the name must be an identifier, it becomes a section of the state`);
294
+ if (RESERVED.includes(name))
295
+ throw new ConfigError(`${at}: "${name}" is a section lintobot sends itself; pick another name`);
296
+ if (name in entries)
297
+ throw new ConfigError(`${at}: "${name}" is given twice`);
298
+ if (marker === undefined && written === null) {
299
+ entries[name] = null;
300
+ } else if (marker === undefined && isMap(written)) {
301
+ const { max_bytes = ENTRY_MAX_BYTES, ...rest } = written;
302
+ const [[fromKey, source] = []] = Object.entries(rest);
303
+ const [from, fromMarker] = split(fromKey ?? "");
304
+ if (Object.keys(rest).length !== 1 || from !== "from")
305
+ throw new ConfigError(`${at}: a map needs from (or from!file, from!sh) and may set max_bytes`);
306
+ if (typeof max_bytes !== "number" || max_bytes <= 0)
307
+ throw new ConfigError(`${at}: max_bytes must be a positive number`);
308
+ entries[name] = entry(fromMarker, source, max_bytes, at);
309
+ } else {
310
+ entries[name] = entry(marker, written, ENTRY_MAX_BYTES, at);
311
+ }
312
+ }
313
+ return entries;
314
+ }
315
+ function split(key) {
316
+ const mark = key.indexOf("!");
317
+ return mark < 0 ? [key, undefined] : [key.slice(0, mark), key.slice(mark + 1)];
318
+ }
319
+ function entry(marker, source, maxBytes, at) {
320
+ if (marker !== undefined && LATER.includes(marker))
321
+ throw new ConfigError(`${at}: !${marker} is not supported yet; use !file, !sh or plain text`);
322
+ if (marker !== undefined && !CONTEXT_MARKERS.includes(marker))
323
+ throw new ConfigError(`${at}: unknown marker !${marker}; use !file, !sh or plain text`);
324
+ if (typeof source !== "string" || !source.trim())
325
+ throw new ConfigError(`${at}: the value must be text`);
326
+ return { kind: marker ?? "text", source, maxBytes };
327
+ }
328
+
329
+ // src/config/schema.ts
330
+ import YAML, { isMap as isMap2, isScalar, isSeq } from "yaml";
331
+ var SCHEMA = `
332
+ $schema:
333
+ optional: [model, defaults:Defaults, parts:Parts, ignore+, context, files*:Entry]
334
+ Defaults:
335
+ optional: [error, warning, info, context:Mode]
336
+ rules:
337
+ - valid!: error = null or (error >= 0 and error <= 1)
338
+ message: error must be a number from 0 to 1
339
+ - valid!: warning = null or (warning >= 0 and warning <= 1)
340
+ message: warning must be a number from 0 to 1
341
+ - valid!: info = null or (info >= 0 and info <= 1)
342
+ message: info must be a number from 0 to 1
343
+ Mode: [none, outline, full]
344
+ Parts:
345
+ optional: [max_lines, max_bytes]
346
+ rules:
347
+ - valid!: max_lines = null or max_lines >= 1
348
+ message: max_lines must be a number, 1 or more
349
+ - valid!: max_bytes = null or max_bytes >= 1
350
+ message: max_bytes must be a number, 1 or more
351
+ Entry:
352
+ required: [pattern+]
353
+ optional: [rules*:RuleItem, info*:InfoItem, except+, max_lines, context, parts]
354
+ rules:
355
+ - valid!: rules != null or info != null
356
+ message: an entry needs rules or info
357
+ - valid!: max_lines = null or max_lines >= 20
358
+ message: max_lines must be a whole number, 20 or more
359
+ RuleItem:
360
+ optional: [rule:Rule, composition]
361
+ Rule:
362
+ optional: [error, warning, id, ask, criteria, whole:Bool, except+, max_lines, context]
363
+ rules:
364
+ - valid!: error = null or error = false or (error >= 0 and error <= 1)
365
+ message: error must be a number from 0 to 1, or false to switch it off
366
+ - valid!: warning = null or warning = false or (warning >= 0 and warning <= 1)
367
+ message: warning must be a number from 0 to 1, or false to switch it off
368
+ - valid!: max_lines = null or max_lines >= 20
369
+ message: max_lines must be a whole number, 20 or more
370
+ - valid!: not(whole = true and max_lines != null)
371
+ message: "whole: true asks about the file as a whole, max_lines about its parts; give one of them"
372
+ InfoItem:
373
+ optional: [rule:Info]
374
+ Info:
375
+ optional: [show, id, ask, criteria, whole:Bool, except+, max_lines, context]
376
+ rules:
377
+ - valid!: show = null or (show >= 0 and show <= 1)
378
+ message: show must be a number from 0 to 1
379
+ - valid!: max_lines = null or max_lines >= 20
380
+ message: max_lines must be a whole number, 20 or more
381
+ - valid!: not(whole = true and max_lines != null)
382
+ message: "whole: true asks about the file as a whole, max_lines about its parts; give one of them"
383
+ Bool: [true, false]
384
+ `;
385
+ var RULE_KEY = "rule";
386
+ function withSchema(text) {
387
+ const document = YAML.parseDocument(text);
388
+ const edits = [];
389
+ const files = isMap2(document.contents) ? document.contents.get("files", true) : undefined;
390
+ const lists = (isSeq(files) ? files.items : []).flatMap((entry) => isMap2(entry) ? [entry.get("rules", true), entry.get("info", true)] : []);
391
+ for (const list of lists) {
392
+ for (const item of isSeq(list) ? list.items : []) {
393
+ if (isScalar(item) && typeof item.value === "string" && item.range) {
394
+ edits.push({ from: item.range[0], to: item.range[1], text: "{}" });
395
+ } else if (isMap2(item) && item.items.length === 1) {
396
+ const { key, value } = item.items[0];
397
+ if (!isScalar(key) || !key.range || key.value === "composition")
398
+ continue;
399
+ const empty = value === null || isScalar(value) && value.value === null;
400
+ if (empty)
401
+ edits.push({ from: key.range[0], to: text.indexOf(":", key.range[1]) + 1, text: "{}" });
402
+ else
403
+ edits.push({ from: key.range[0], to: key.range[1], text: RULE_KEY });
404
+ }
405
+ }
406
+ }
407
+ let result = text;
408
+ for (const edit of edits.sort((a, b) => b.from - a.from)) {
409
+ const lines = result.slice(edit.from, edit.to).split(`
410
+ `).length - 1;
411
+ result = result.slice(0, edit.from) + edit.text + `
412
+ `.repeat(lines) + result.slice(edit.to);
413
+ }
414
+ return `${result}
415
+ ${SCHEMA}`;
416
+ }
417
+
418
+ // src/config/preset.ts
419
+ var RECOMMENDED = `
420
+ - "file is focused on a single thing":
421
+ whole: true
422
+ ask: In the \`code\` section, is the file focused on a single thing?
423
+ - "no global state polluted":
424
+ ask: In the \`code\` section, does the code modify global state?
425
+ - "no magic numbers"
426
+ - "comments actually explain intent and not the code inside":
427
+ $if!: file.comment_lines > 5
428
+ ask: In the \`code\` section, do the comments explain intent rather than restate the code?
429
+ - "no secret values exposed":
430
+ error: 0.6
431
+ ask: In the \`code\` section, is a secret value such as a password, token or API key hardcoded?
432
+ - "one export per file":
433
+ $if!: file.lines > 150
434
+ whole: true
435
+ ask: In the \`code\` section, does the file export exactly one thing?
436
+ - "logic is easy to follow":
437
+ $if!: file.complexity > 15
438
+ `;
439
+
440
+ // src/config/load.ts
441
+ var CONFIG_FILE = "lintobot.yml";
442
+ var RESERVED2 = ["file", "env", "confidence"];
443
+ var OWN_KEYS = ["$dsl", "model", "defaults", "ignore", "files", "parts", "context"];
444
+ var COMPUTED = ["error", "warning", "error!", "warning!", "show", "show!", "$if!", "$unless!"];
445
+ var MIN_PART_LINES = 20;
446
+ var isMap3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
447
+ var itemsOf = (entry) => [...entry.rules, ...entry.info];
448
+ var sentences = (value) => (value ?? "").split(/[\n;]/).map((item) => item.trim()).filter(Boolean);
449
+ function loadConfig(file, env = process.env) {
450
+ const explicit = file !== undefined;
451
+ file ??= CONFIG_FILE;
452
+ let text = "";
453
+ if (fs2.existsSync(file))
454
+ text = fs2.readFileSync(file, "utf8");
455
+ else if (explicit)
456
+ throw new ConfigError(`Config file ${file} not found`);
457
+ return parseConfig(text, env, file);
458
+ }
459
+ function parseConfig(text, env = {}, file = CONFIG_FILE) {
460
+ let data;
461
+ try {
462
+ data = YAML2.parse(text) ?? {};
463
+ } catch (error) {
464
+ throw new ConfigError(`${file}: ${error.message}`);
465
+ }
466
+ if (!isMap3(data))
467
+ throw new ConfigError(`${file}: the config must be a map of keys`);
468
+ for (const key of RESERVED2)
469
+ if (key in data)
470
+ throw new ConfigError(`${file}: "${key}" is a name lintobot provides; rename the key`);
471
+ if ("$extends" in data)
472
+ throw new ConfigError(`${file}: $extends is not supported yet`);
473
+ const names = [...text.matchAll(/\benv\.([A-Za-z_]\w*)/g)].map((match) => match[1]);
474
+ const envKeys = Object.fromEntries(names.map((name) => [name, env[name] || null]));
475
+ const warnings = validateText(text, file, envKeys, data);
476
+ const config = {
477
+ file,
478
+ model: env.LINTOBOT_MODEL || modelOf(data.model, file).id,
479
+ concurrency: number(env.LINTOBOT_CONCURRENCY, "LINTOBOT_CONCURRENCY") ?? modelOf(data.model, file).concurrency ?? 8,
480
+ parts: { maxLines: 300, maxBytes: 30000, ...partsOf(data.parts, `${file}: parts`) },
481
+ context: contextOf(data.context, file),
482
+ shell: true,
483
+ defaults: defaultsOf(data.defaults, env, file),
484
+ ignore: strings(data.ignore, `${file}: ignore`),
485
+ entries: [],
486
+ top: Object.fromEntries(Object.entries(data).filter(([key]) => !OWN_KEYS.includes(key))),
487
+ env: envKeys,
488
+ warnings
489
+ };
490
+ const partLines = number(env.LINTOBOT_PART_LINES, "LINTOBOT_PART_LINES");
491
+ if (partLines !== undefined && !(partLines >= 1))
492
+ throw new ConfigError("LINTOBOT_PART_LINES must be 1 or more");
493
+ const implicit = (rules, info = []) => ({ patterns: null, except: [], conditions: {}, rules, info, context: {} });
494
+ const rulesFromEnv = sentences(env.LINTOBOT_RULES);
495
+ const infoFromEnv = sentences(env.LINTOBOT_INFO);
496
+ if (rulesFromEnv.length || infoFromEnv.length) {
497
+ config.entries = [implicit(rulesOf(rulesFromEnv, config, "LINTOBOT_RULES"), rulesOf(infoFromEnv, config, "LINTOBOT_INFO", true))];
498
+ } else if (data.files !== undefined) {
499
+ if (!Array.isArray(data.files))
500
+ throw new ConfigError(`${file}: files must be a list`);
501
+ config.entries = data.files.map((entry, n) => entryOf(entry, config, `${file}: files[${n + 1}]`));
502
+ } else {
503
+ config.entries = [implicit(rulesOf(YAML2.parse(RECOMMENDED), config, "lintobot/recommended"))];
504
+ }
505
+ if (partLines !== undefined)
506
+ config.parts.maxLines = partLines;
507
+ inspectFormulas(config);
508
+ return config;
509
+ }
510
+ function partsOf(value, where) {
511
+ if (value === undefined || value === null)
512
+ return {};
513
+ if (!isMap3(value))
514
+ throw new ConfigError(`${where} must be a map with max_lines and max_bytes`);
515
+ const { max_lines, max_bytes } = value;
516
+ for (const [key, limit] of Object.entries({ max_lines, max_bytes })) {
517
+ if (limit !== undefined && !(typeof limit === "number" && limit >= 1))
518
+ throw new ConfigError(`${where}.${key} must be a number, 1 or more`);
519
+ }
520
+ return { ...max_lines !== undefined && { maxLines: max_lines }, ...max_bytes !== undefined && { maxBytes: max_bytes } };
521
+ }
522
+ function maxLinesOf(value, where) {
523
+ if (value === undefined)
524
+ return;
525
+ if (!Number.isInteger(value) || value < MIN_PART_LINES)
526
+ throw new ConfigError(`${where}: max_lines must be a whole number, ${MIN_PART_LINES} or more`);
527
+ return value;
528
+ }
529
+ function modelOf(value, file) {
530
+ if (value === undefined || value === null)
531
+ return {};
532
+ if (typeof value === "string")
533
+ return { id: value };
534
+ if (!isMap3(value) || typeof value.id !== "string")
535
+ throw new ConfigError(`${file}: model must be "<provider>/<model>" or a map with id`);
536
+ if ("max_bytes" in value)
537
+ throw new ConfigError(`${file}: model.max_bytes moved to parts.max_bytes`);
538
+ const { concurrency } = value;
539
+ if (concurrency !== undefined && !(typeof concurrency === "number" && concurrency > 0))
540
+ throw new ConfigError(`${file}: model.concurrency must be a positive number`);
541
+ return value;
542
+ }
543
+ function defaultsOf(value, env, file) {
544
+ if (value !== undefined && !isMap3(value))
545
+ throw new ConfigError(`${file}: defaults must be a map`);
546
+ const error = number(env.LINTOBOT_ERROR, "LINTOBOT_ERROR") ?? value?.error ?? 0.9;
547
+ const warning = number(env.LINTOBOT_WARNING, "LINTOBOT_WARNING") ?? value?.warning ?? 0.7;
548
+ const info = number(env.LINTOBOT_INFO_CONFIDENCE, "LINTOBOT_INFO_CONFIDENCE") ?? value?.info ?? 0.9;
549
+ const context = value?.context ?? "outline";
550
+ for (const [key, threshold] of Object.entries({ error, warning, info })) {
551
+ if (typeof threshold !== "number" || threshold < 0 || threshold > 1)
552
+ throw new ConfigError(`${file}: defaults.${key} must be a number from 0 to 1`);
553
+ }
554
+ if (context !== "none" && context !== "outline" && context !== "full")
555
+ throw new ConfigError(`${file}: defaults.context must be none, outline or full`);
556
+ return { error, warning, info, context: context === "none" ? "none" : "outline" };
557
+ }
558
+ function number(value, name) {
559
+ if (!value)
560
+ return;
561
+ if (Number.isNaN(Number(value)))
562
+ throw new ConfigError(`${name} must be a number, got "${value}"`);
563
+ return Number(value);
564
+ }
565
+ function strings(value, where) {
566
+ if (value === undefined || value === null)
567
+ return [];
568
+ const list = Array.isArray(value) ? value : [value];
569
+ if (!list.every((item) => typeof item === "string"))
570
+ throw new ConfigError(`${where} must be text or a list of texts`);
571
+ return list;
572
+ }
573
+ function entryOf(entry, config, where) {
574
+ if (!isMap3(entry))
575
+ throw new ConfigError(`${where} must be a map with pattern and rules`);
576
+ const { pattern, except, rules = [], info = [], context, max_lines, ...conditions } = entry;
577
+ const patterns = strings(pattern, `${where}.pattern`);
578
+ if (!patterns.length)
579
+ throw new ConfigError(`${where} needs a pattern`);
580
+ if ("parts" in conditions)
581
+ throw new ConfigError(`${where}: parts belongs to the top level; on a files entry write max_lines: N`);
582
+ if (!Array.isArray(rules))
583
+ throw new ConfigError(`${where}.rules must be a list`);
584
+ if (!Array.isArray(info))
585
+ throw new ConfigError(`${where}.info must be a list`);
586
+ return {
587
+ patterns,
588
+ except: strings(except, `${where}.except`),
589
+ conditions,
590
+ rules: rulesOf(rules, config, where),
591
+ info: rulesOf(info, config, where, true),
592
+ context: contextOf(context, where),
593
+ maxLines: maxLinesOf(max_lines, where)
594
+ };
595
+ }
596
+ function rulesOf(items, config, where, info = false) {
597
+ const rules = [];
598
+ for (const item of items) {
599
+ if (typeof item === "string") {
600
+ rules.push(ruleOf(item, {}, where, info));
601
+ continue;
602
+ }
603
+ const keys = isMap3(item) ? Object.keys(item) : [];
604
+ if (keys.length !== 1)
605
+ throw new ConfigError(`${where}: a rule is a sentence, or a sentence with its options under it`);
606
+ const [sentence] = keys;
607
+ if (sentence === "composition" && !info) {
608
+ config.warnings.push(`${where}: composition rules are not supported by this version and were skipped`);
609
+ continue;
610
+ }
611
+ const options = item[sentence] ?? {};
612
+ if (!isMap3(options))
613
+ throw new ConfigError(`${where}: the options of "${sentence}" must be a map`);
614
+ rules.push(ruleOf(sentence, options, where, info));
615
+ }
616
+ return rules;
617
+ }
618
+ function ruleOf(sentence, options, where, info) {
619
+ const at = `${where}: "${sentence}"`;
620
+ for (const key of info ? ["show"] : ["error", "warning"]) {
621
+ const value = options[key];
622
+ const off = !info && value === false;
623
+ if (value !== undefined && !off && !(typeof value === "number" && value >= 0 && value <= 1)) {
624
+ throw new ConfigError(`${at}: ${key} must be a number from 0 to 1${info ? "" : ", or false to switch it off"}; for a formula write ${key}!`);
625
+ }
626
+ if (value !== undefined && options[`${key}!`] !== undefined)
627
+ throw new ConfigError(`${at}: give ${key} or ${key}!, not both`);
628
+ }
629
+ for (const key of ["id", "ask"]) {
630
+ if (options[key] !== undefined && typeof options[key] !== "string")
631
+ throw new ConfigError(`${at}: ${key} must be text`);
632
+ }
633
+ if (options.whole !== undefined && typeof options.whole !== "boolean")
634
+ throw new ConfigError(`${at}: whole must be true or false`);
635
+ if (options.whole === true && options.max_lines !== undefined) {
636
+ throw new ConfigError(`${at}: whole: true asks about the file as a whole, max_lines about its parts; give one of them`);
637
+ }
638
+ return {
639
+ sentence,
640
+ info,
641
+ id: options.id,
642
+ ask: options.ask,
643
+ criteria: criteriaOf(options.criteria, at),
644
+ whole: options.whole === true,
645
+ except: strings(options.except, `${at}: except`),
646
+ maxLines: maxLinesOf(options.max_lines, at),
647
+ context: contextOf(options.context, at),
648
+ asksModel: true,
649
+ formulas: {},
650
+ options: Object.fromEntries(Object.entries(options).filter(([key]) => COMPUTED.includes(key)))
651
+ };
652
+ }
653
+ function criteriaOf(value, at) {
654
+ if (value === undefined)
655
+ return;
656
+ const yes = isMap3(value) ? value.yes ?? value.true : undefined;
657
+ const no = isMap3(value) ? value.no ?? value.false : undefined;
658
+ if (typeof yes !== "string" || typeof no !== "string")
659
+ throw new ConfigError(`${at}: criteria needs two texts, yes and no`);
660
+ return { true: yes, false: no };
661
+ }
662
+ var isUnknownField = (problem) => problem.message.includes("is not a field of the schema");
663
+ function validateText(text, file, env, data) {
664
+ if (!text.trim())
665
+ return [];
666
+ const placeholders = { file: PLACEHOLDER_FACTS, env, confidence: 0 };
667
+ const checked = `${withSchema(text.replace(/^\$dsl:.*$/m, ""))}
668
+ ${YAML2.stringify(placeholders)}`;
669
+ const problems = new ScriptedYaml({ markers: [...CONTEXT_MARKERS, "mdq", "outline"] }).validateText(checked, { file }).filter((problem) => !/\.composition(\.|$)/.test(problem.key)).filter((problem) => !(isUnknownField(problem) && !/[.[]/.test(problem.key)));
670
+ const sentence = (n, list, i) => {
671
+ const rule = data.files?.[n - 1]?.[list]?.[i - 1];
672
+ return typeof rule === "string" ? rule : isMap3(rule) ? Object.keys(rule)[0] : undefined;
673
+ };
674
+ const named = (problem) => String(problem).replace(new RegExp(`files\\[(\\d+)\\]\\.(rules|info)\\[(\\d+)\\](\\.${RULE_KEY})?`), (path, n, list, i) => {
675
+ const text = sentence(Number(n), list, Number(i));
676
+ return text === undefined ? path : `"${text}"`;
677
+ }).replace(/"([^"]+)" is not a field of the schema$/, 'unknown key "$1"');
678
+ const errors = problems.filter((problem) => problem.severity === "error" || isUnknownField(problem));
679
+ if (errors.length)
680
+ throw new ConfigError(`${file} has problems:
681
+ ${errors.map((problem) => ` ${named(problem)}`).join(`
682
+ `)}`);
683
+ return problems.map(named);
684
+ }
685
+ function documentFor(config, entries, file, confidence) {
686
+ const data = {
687
+ ...config.top,
688
+ file: literal(file),
689
+ env: literal(config.env),
690
+ files: entries.map((entry, n) => ({
691
+ ...entry.conditions,
692
+ n,
693
+ rules: itemsOf(entry).map((rule, i) => ({ [`r${i}`]: { ...rule.options, confidence: confidence(rule) } }))
694
+ }))
695
+ };
696
+ try {
697
+ return new ScriptedYaml().loadTextSync(data, { file: config.file });
698
+ } catch (error) {
699
+ throw asConfigError(error, config);
700
+ }
701
+ }
702
+ function literal(value) {
703
+ if (typeof value === "string")
704
+ return value.replaceAll("{{", "{ {");
705
+ if (Array.isArray(value))
706
+ return value.map(literal);
707
+ if (isMap3(value))
708
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, literal(item)]));
709
+ return value;
710
+ }
711
+ function asConfigError(error, config) {
712
+ if (!(error instanceof ScriptedYamlError))
713
+ return error;
714
+ const named = error.problems.map((problem) => String(problem).replace(/files\[(\d+)\]\.rules\[\d+\]\.r(\d+)/, (_, n, i) => `"${itemsOf(config.entries[n - 1])[i]?.sentence}"`));
715
+ return new ConfigError(`${config.file} has problems:
716
+ ${named.map((line) => ` ${line}`).join(`
717
+ `)}`);
718
+ }
719
+ function inspectFormulas(config) {
720
+ const document = documentFor(config, config.entries, PLACEHOLDER_FACTS, () => 0);
721
+ config.entries.forEach((entry, n) => {
722
+ itemsOf(entry).forEach((rule, i) => {
723
+ const loaded = document.data.files[n].rules[i][`r${i}`];
724
+ for (const key of ["$if", "$unless"]) {
725
+ if (loaded[key]?.reads.includes("confidence")) {
726
+ throw new ConfigError(`${config.file}: "${rule.sentence}": ${key}! decides before the model is asked, so it cannot read confidence`);
727
+ }
728
+ }
729
+ const levels = rule.info ? ["show"] : ["error", "warning"];
730
+ const formulas = levels.map((level) => rule.options[`${level}!`] && loaded[level]).filter(Boolean);
731
+ rule.formulas = Object.fromEntries(levels.map((level) => [level, rule.options[`${level}!`]]));
732
+ const numbers = levels.some((level) => typeof rule.options[level] === "number");
733
+ rule.asksModel = numbers || formulas.length === 0 || formulas.some((formula) => formula.reads.includes("confidence"));
734
+ });
735
+ });
736
+ }
737
+ var matchers = new WeakMap;
738
+ function matchesAny(globs, file) {
739
+ if (!globs.length)
740
+ return false;
741
+ if (!matchers.has(globs))
742
+ matchers.set(globs, matcher(globs));
743
+ return matchers.get(globs)(file);
744
+ }
745
+ var matches = (entry, file) => (!entry.patterns || matchesAny(entry.patterns, file)) && !matchesAny(entry.except, file);
746
+ function resolveRules(config, file, confidences) {
747
+ const entries = config.entries.filter((entry) => matches(entry, file.path));
748
+ if (!entries.length)
749
+ return [];
750
+ let resolved;
751
+ try {
752
+ resolved = documentFor(config, entries, file, (rule) => confidences?.get(rule) ?? 0).resolve({ vars: {} });
753
+ } catch (error) {
754
+ throw asConfigError(error, config);
755
+ }
756
+ const applied = new Map;
757
+ for (const entry of resolved.files) {
758
+ entry.rules.forEach((item, i) => {
759
+ const options = item[`r${i}`];
760
+ const rule = itemsOf(entries[entry.n])[i];
761
+ if (!options || matchesAny(rule.except, file.path))
762
+ return;
763
+ applied.set(`${rule.info}:${rule.sentence}`, { rule, entry: entries[entry.n], error: options.error, warning: options.warning, show: options.show });
764
+ });
765
+ }
766
+ return [...applied.values()];
767
+ }
768
+
769
+ // src/engine/cache.ts
770
+ import { createHash } from "node:crypto";
771
+ import fs3 from "node:fs";
772
+ import path4 from "node:path";
773
+
774
+ class Cache {
775
+ dir;
776
+ constructor(dir) {
777
+ this.dir = dir;
778
+ }
779
+ static key(model, question, state) {
780
+ return createHash("sha256").update(JSON.stringify([model, question.instructions, question.criteria ?? null, state])).digest("hex");
781
+ }
782
+ file(key) {
783
+ return path4.join(this.dir, key.slice(0, 2), `${key.slice(2)}.json`);
784
+ }
785
+ get(key) {
786
+ try {
787
+ return JSON.parse(fs3.readFileSync(this.file(key), "utf8"));
788
+ } catch {
789
+ return;
790
+ }
791
+ }
792
+ set(key, answer) {
793
+ const file = this.file(key);
794
+ fs3.mkdirSync(path4.dirname(file), { recursive: true });
795
+ fs3.writeFileSync(file, JSON.stringify(answer));
796
+ }
797
+ }
798
+
799
+ // src/engine/plan.ts
800
+ import path6 from "node:path";
801
+
802
+ // src/files/pieces.ts
803
+ var cost = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
804
+ var splitLines = (text) => text.split(/(?<=\n)/);
805
+ var lineCount = (text) => text.split(`
806
+ `).length - (text.endsWith(`
807
+ `) ? 1 : 0);
808
+ function cutPieces(text, maxBytes, maxLines = Infinity) {
809
+ const fits = (size, lines) => size <= maxBytes && lines <= maxLines;
810
+ if (fits(cost(text), lineCount(text)))
811
+ return [text];
812
+ const blocks = [];
813
+ let block = "";
814
+ const lines = splitLines(text);
815
+ lines.forEach((line, i) => {
816
+ if (block && /^\S/.test(line) && lines[i - 1].trim() === "") {
817
+ blocks.push(block);
818
+ block = "";
819
+ }
820
+ block += line;
821
+ });
822
+ blocks.push(block);
823
+ const units = blocks.flatMap((b) => fits(cost(b), lineCount(b)) ? [b] : splitLines(b).flatMap((line) => halve(line, maxBytes)));
824
+ const pieces = [];
825
+ let piece = "";
826
+ let size = 0;
827
+ let count = 0;
828
+ for (const unit of units) {
829
+ const unitSize = cost(unit);
830
+ const unitLines = lineCount(unit);
831
+ if (piece && !fits(size + unitSize, count + unitLines)) {
832
+ pieces.push(piece);
833
+ piece = "";
834
+ size = 0;
835
+ count = 0;
836
+ }
837
+ piece += unit;
838
+ size += unitSize;
839
+ count += unitLines;
840
+ }
841
+ pieces.push(piece);
842
+ return pieces;
843
+ }
844
+ function lineRanges(pieces) {
845
+ let line = 1;
846
+ return pieces.map((piece) => {
847
+ const breaks = piece.split(`
848
+ `).length - 1;
849
+ const start = line;
850
+ line += breaks;
851
+ return { start, end: piece.endsWith(`
852
+ `) ? Math.max(start, line - 1) : line };
853
+ });
854
+ }
855
+ function halve(text, budget) {
856
+ if (cost(text) <= budget || text.length < 2)
857
+ return [text];
858
+ const middle = text.length >> 1;
859
+ return [...halve(text.slice(0, middle), budget), ...halve(text.slice(middle), budget)];
860
+ }
861
+ function head(text, budget) {
862
+ if (cost(text) <= budget)
863
+ return text;
864
+ let result = "";
865
+ let size = 0;
866
+ for (const line of splitLines(text)) {
867
+ size += cost(line);
868
+ if (size > budget)
869
+ break;
870
+ result += line;
871
+ }
872
+ return result || halve(text, budget)[0];
873
+ }
874
+ var IMPORT = /^(import|from|require|require_relative|use|using|include|#include|package)\b|^(const|let|var)\s.*=\s*require\(/;
875
+ var DECLARATION = /^(export|async|function|class|def|module|interface|type|enum|func|fn|pub|struct|impl|trait|public|private|protected|abstract|static|final|const|let|var|namespace|object)\b/;
876
+ var OUTLINE_LIMIT = 60;
877
+ function outline(text) {
878
+ const entries = [];
879
+ for (const line of text.split(`
880
+ `)) {
881
+ if (IMPORT.test(line)) {
882
+ if (entries.at(-1) !== "imports")
883
+ entries.push("imports");
884
+ } else if (DECLARATION.test(line)) {
885
+ entries.push(line.replace(/\s*[{(:=]?\s*$/, "").slice(0, 80));
886
+ }
887
+ if (entries.length > OUTLINE_LIMIT) {
888
+ entries[OUTLINE_LIMIT] = "...";
889
+ break;
890
+ }
891
+ }
892
+ return entries;
893
+ }
894
+
895
+ // src/engine/context.ts
896
+ import { spawnSync } from "node:child_process";
897
+ import fs4 from "node:fs";
898
+ import path5 from "node:path";
899
+ var SHELL_TIMEOUT_MS = 1e4;
900
+ function fileVariables(file) {
901
+ const ext = path5.extname(file);
902
+ return { FILE: file, DIR: path5.dirname(file), STEM: path5.basename(file, ext), EXT: ext.slice(1) };
903
+ }
904
+ function contextFor(file, config) {
905
+ const variables = fileVariables(file);
906
+ const read = new Map;
907
+ const textOf = (entry) => {
908
+ if (!read.has(entry))
909
+ read.set(entry, attempt(() => head(load(entry, variables, config), entry.maxBytes)));
910
+ return read.get(entry);
911
+ };
912
+ return ({ rule, entry: group }) => {
913
+ const merged = { ...config.context, ...group.context, ...rule.context };
914
+ const result = { sections: {} };
915
+ for (const [name, entry] of Object.entries(merged)) {
916
+ if (!entry)
917
+ continue;
918
+ const text = textOf(entry);
919
+ if (typeof text === "string")
920
+ result.sections[name] = text;
921
+ else if (rule.context[name] === entry)
922
+ result.missing ??= `context "${name}": ${text.message}`;
923
+ }
924
+ return result;
925
+ };
926
+ }
927
+ function attempt(read) {
928
+ try {
929
+ return read();
930
+ } catch (error) {
931
+ return error;
932
+ }
933
+ }
934
+ function load(entry, variables, config) {
935
+ if (entry.kind === "text")
936
+ return entry.source;
937
+ const folder = path5.dirname(config.file);
938
+ if (entry.kind === "file") {
939
+ const name = entry.source.replace(/\$\{?(FILE|DIR|STEM|EXT)\b\}?/g, (_, variable) => variables[variable]);
940
+ const target = path5.resolve(folder, name);
941
+ if (!fs4.statSync(target, { throwIfNoEntry: false })?.isFile())
942
+ throw new Error(`no file ${name}`);
943
+ return fs4.readFileSync(target, "utf8");
944
+ }
945
+ if (!config.shell)
946
+ throw new Error("commands are off (--no-shell)");
947
+ const ran = spawnSync(entry.source, { shell: true, cwd: folder, env: { ...process.env, ...variables }, timeout: SHELL_TIMEOUT_MS, encoding: "utf8" });
948
+ if (ran.error)
949
+ throw new Error(`the command did not finish: ${ran.error.message}`);
950
+ if (ran.status !== 0)
951
+ throw new Error(`the command failed with ${ran.status}: ${ran.stderr.trim().split(`
952
+ `)[0] ?? ""}`.replace(/: $/, ""));
953
+ return ran.stdout;
954
+ }
955
+
956
+ // src/rules/question.ts
957
+ var SCOPE = "In the `code` section, ";
958
+ function toQuestion(sentence, ask, statement = false) {
959
+ const text = sentence.trim().replace(/[.!]+$/, "");
960
+ if (statement)
961
+ return { instructions: ask ?? aboutCode(text), detects: true };
962
+ const detects = /^no\s/i.test(text);
963
+ if (ask)
964
+ return { instructions: ask, detects };
965
+ const instructions = detects ? `${SCOPE}does the code contain ${text.replace(/^no\s+/i, "")}?` : `${SCOPE}is it true that ${text}?`;
966
+ return { instructions, detects };
967
+ }
968
+ function aboutCode(statement) {
969
+ const [, verb, rest] = /^(is|are|has|have)\s+(.*)$/i.exec(statement) ?? [];
970
+ if (!verb)
971
+ return `${SCOPE}does the code ${statement}?`;
972
+ return /^(is|are)$/i.test(verb) ? `${SCOPE}is the code ${rest}?` : `${SCOPE}does the code have ${rest}?`;
973
+ }
974
+ var violation = (asked, yes) => asked.detects ? yes : 1 - yes;
975
+ function questionKey(name, taken) {
976
+ let base = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 48) || "rule";
977
+ if (/^\d/.test(base))
978
+ base = `r_${base}`;
979
+ let key = base;
980
+ for (let n = 2;taken.has(key); n++)
981
+ key = `${base}_${n}`;
982
+ taken.add(key);
983
+ return key;
984
+ }
985
+
986
+ // src/engine/plan.ts
987
+ var MIN_CODE_BYTES = 1000;
988
+ function planFile(file, text, config, only = []) {
989
+ const facts = computeFacts(file, text);
990
+ const applied = resolveRules(config, facts).filter(({ rule }) => !only.length || only.includes(rule.sentence) || rule.id !== undefined && only.includes(rule.id));
991
+ if (!applied.length)
992
+ return null;
993
+ const contextOf = contextFor(file, config);
994
+ const taken = new Set;
995
+ const unasked = [];
996
+ const groups = new Map;
997
+ for (const item of applied.filter(({ rule }) => rule.asksModel)) {
998
+ const { sections, missing } = contextOf(item);
999
+ if (missing) {
1000
+ unasked.push({ applied: item, reason: missing });
1001
+ continue;
1002
+ }
1003
+ const asked = toQuestion(item.rule.sentence, item.rule.ask, item.rule.info);
1004
+ const question = { instructions: asked.instructions, ...item.rule.criteria && { criteria: item.rule.criteria } };
1005
+ const maxLines = item.rule.maxLines ?? item.entry.maxLines ?? config.parts.maxLines;
1006
+ const group = JSON.stringify([sections, maxLines]);
1007
+ if (!groups.has(group))
1008
+ groups.set(group, { sections, maxLines, planned: [] });
1009
+ groups.get(group).planned.push({ applied: item, key: questionKey(item.rule.id ?? item.rule.sentence, taken), asked, question });
1010
+ }
1011
+ const language = languageOf(path6.extname(file).slice(1).toLowerCase());
1012
+ const about = { path: file, ...language && { language } };
1013
+ const withOutline = { ...about, outline: outline(text) };
1014
+ const start = config.defaults.context === "outline" ? withOutline : about;
1015
+ const room = (state) => Math.max(MIN_CODE_BYTES, config.parts.maxBytes - Buffer.byteLength(JSON.stringify({ ...state, code: "" })));
1016
+ const calls = [];
1017
+ const cuttings = new Map;
1018
+ for (const { sections, maxLines, planned } of groups.values()) {
1019
+ const state = { ...start, ...sections };
1020
+ const pieces = cutPieces(text, room(state), maxLines);
1021
+ const ranges = lineRanges(pieces);
1022
+ cuttings.set(JSON.stringify(ranges), pieces.length);
1023
+ const perPiece = pieces.length === 1 ? planned : planned.filter((item) => !item.applied.rule.whole);
1024
+ if (perPiece.length) {
1025
+ pieces.forEach((code, i) => calls.push({ state: { ...state, code }, planned: perPiece, ...pieces.length > 1 && { lines: ranges[i] } }));
1026
+ }
1027
+ const whole = planned.filter((item) => item.applied.rule.whole);
1028
+ if (pieces.length > 1 && whole.length) {
1029
+ const entire = { ...withOutline, ...sections };
1030
+ calls.push({ state: { ...entire, code: head(text, room(entire)) }, planned: whole });
1031
+ }
1032
+ }
1033
+ const [parts = 1] = cuttings.size > 1 ? [undefined] : cuttings.values();
1034
+ return { file, facts, applied, calls, unasked, ...cuttings.size <= 1 && { parts } };
1035
+ }
1036
+ var callBytes = (call) => Buffer.byteLength(JSON.stringify(call.state)) + call.planned.reduce((sum, planned) => sum + Buffer.byteLength(JSON.stringify(planned.question)), 0);
1037
+
1038
+ // src/engine/run.ts
1039
+ import fs5 from "node:fs";
1040
+
1041
+ // src/model/client.ts
1042
+ import { z } from "zod";
1043
+
1044
+ class ModelError extends Error {
1045
+ status;
1046
+ constructor(message, status) {
1047
+ super(message);
1048
+ this.status = status;
1049
+ }
1050
+ }
1051
+ var usageShape = z.object({ input_tokens: z.number(), output_tokens: z.number(), cost: z.number() }).partial().optional();
1052
+ var typesafeResponse = z.object({
1053
+ model: z.string().optional(),
1054
+ answers: z.record(z.string(), z.unknown()).default({}),
1055
+ usage: usageShape
1056
+ });
1057
+ var openaiResponse = z.object({
1058
+ model: z.string().optional(),
1059
+ answers: z.array(z.unknown()).default([]),
1060
+ usage: usageShape,
1061
+ provider_metadata: z.object({ gateway: z.object({ cost: z.coerce.number() }).partial() }).partial().optional()
1062
+ });
1063
+ var noul = z.object({ type: z.literal("noul"), noul: z.number().min(0).max(1) });
1064
+ var predicate = z.object({ type: z.literal("predicate"), name: z.string(), probability: z.number().min(0).max(1) });
1065
+ function requestBody(target, state, questions) {
1066
+ if (target.wire === "typesafe") {
1067
+ return {
1068
+ model: target.model,
1069
+ state,
1070
+ questions: Object.fromEntries(Object.entries(questions).map(([key, q]) => [
1071
+ key,
1072
+ { type: "noul", instructions: q.instructions, ...q.criteria && { criteria: q.criteria } }
1073
+ ]))
1074
+ };
1075
+ }
1076
+ return {
1077
+ model: target.model,
1078
+ input: typeof state === "string" ? state : JSON.stringify(state),
1079
+ questions: Object.entries(questions).map(([name, q]) => ({
1080
+ type: "predicate",
1081
+ name,
1082
+ instructions: q.criteria ? `${q.instructions}
1083
+ Yes when: ${q.criteria.true}
1084
+ No when: ${q.criteria.false}` : q.instructions
1085
+ }))
1086
+ };
1087
+ }
1088
+ function parseResponse(target, data, keys) {
1089
+ const answers = Object.fromEntries(keys.map((key) => [key, null]));
1090
+ const usage = (u, cost) => ({
1091
+ input_tokens: u?.input_tokens ?? 0,
1092
+ output_tokens: u?.output_tokens ?? 0,
1093
+ ...(u?.cost ?? cost) !== undefined && { cost: u?.cost ?? cost }
1094
+ });
1095
+ if (target.wire === "typesafe") {
1096
+ const body = typesafeResponse.parse(data);
1097
+ for (const key of keys) {
1098
+ const answer = noul.safeParse(body.answers[key]);
1099
+ if (answer.success)
1100
+ answers[key] = answer.data.noul;
1101
+ }
1102
+ return { answers, usage: usage(body.usage), model: body.model ?? target.model };
1103
+ }
1104
+ const body = openaiResponse.parse(data);
1105
+ for (const item of body.answers) {
1106
+ const answer = predicate.safeParse(item);
1107
+ if (answer.success && answer.data.name in answers)
1108
+ answers[answer.data.name] = answer.data.probability;
1109
+ }
1110
+ return { answers, usage: usage(body.usage, body.provider_metadata?.gateway?.cost), model: body.model ?? target.model };
1111
+ }
1112
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1113
+ function createClient(target, options = {}) {
1114
+ const { retries = 3, backoffMs = 500, timeoutMs = 60000 } = options;
1115
+ const send = options.fetch ?? fetch;
1116
+ async function attempt(body, keys) {
1117
+ let response;
1118
+ let text;
1119
+ try {
1120
+ response = await send(target.url, {
1121
+ method: "POST",
1122
+ headers: { Authorization: `Bearer ${target.apiKey}`, "Content-Type": "application/json" },
1123
+ body,
1124
+ signal: AbortSignal.timeout(timeoutMs)
1125
+ });
1126
+ text = await response.text();
1127
+ } catch (error) {
1128
+ throw new ModelError(`${target.provider} is unreachable: ${error.message}`);
1129
+ }
1130
+ if (!response.ok)
1131
+ throw new ModelError(`${target.provider} answered ${response.status}: ${errorMessage(text)}`, response.status);
1132
+ try {
1133
+ return parseResponse(target, JSON.parse(text), keys);
1134
+ } catch {
1135
+ throw new ModelError(`${target.provider} sent an answer lintobot cannot read: ${text.slice(0, 200)}`, response.status);
1136
+ }
1137
+ }
1138
+ return {
1139
+ model: target.model,
1140
+ async decide(state, questions) {
1141
+ const body = JSON.stringify(requestBody(target, state, questions));
1142
+ const keys = Object.keys(questions);
1143
+ const started = performance.now();
1144
+ for (let tries = 0;; tries++) {
1145
+ try {
1146
+ const result = await attempt(body, keys);
1147
+ return { ...result, ms: Math.round(performance.now() - started) };
1148
+ } catch (error) {
1149
+ const status = error.status;
1150
+ const again = status === undefined || status === 429 || status >= 500 && status < 600;
1151
+ if (!again || tries >= retries)
1152
+ throw error;
1153
+ await sleep(backoffMs * 2 ** tries);
1154
+ }
1155
+ }
1156
+ }
1157
+ };
1158
+ }
1159
+ function errorMessage(text) {
1160
+ try {
1161
+ const { error } = JSON.parse(text);
1162
+ if (error?.message)
1163
+ return error.code ? `${error.message} (${error.code})` : error.message;
1164
+ } catch {}
1165
+ return text.slice(0, 300);
1166
+ }
1167
+
1168
+ // src/engine/areas.ts
1169
+ function areas(parts, threshold) {
1170
+ const merged = [];
1171
+ let open;
1172
+ for (const part of [...parts].sort((a, b) => a.start - b.start)) {
1173
+ if (part.confidence < threshold) {
1174
+ open = undefined;
1175
+ } else if (open && part.start <= open.end + 1) {
1176
+ open.end = part.end;
1177
+ } else {
1178
+ open = { start: part.start, end: part.end };
1179
+ merged.push(open);
1180
+ }
1181
+ }
1182
+ return merged;
1183
+ }
1184
+
1185
+ // src/engine/pool.ts
1186
+ function pool(limit) {
1187
+ let running = 0;
1188
+ const waiting = [];
1189
+ return async function run(task) {
1190
+ if (running >= limit)
1191
+ await new Promise((resolve) => waiting.push(resolve));
1192
+ else
1193
+ running++;
1194
+ try {
1195
+ return await task();
1196
+ } finally {
1197
+ const next = waiting.shift();
1198
+ if (next)
1199
+ next();
1200
+ else
1201
+ running--;
1202
+ }
1203
+ };
1204
+ }
1205
+
1206
+ // src/engine/severity.ts
1207
+ function verdict(applied, confidence, defaults) {
1208
+ const { rule } = applied;
1209
+ const reached = (level) => {
1210
+ const value = applied[level] ?? (rule.asksModel ? defaults[level] : false);
1211
+ return typeof value === "number" ? confidence !== undefined && confidence >= value : value === true;
1212
+ };
1213
+ for (const severity of ["error", "warning"]) {
1214
+ if (reached(severity))
1215
+ return { severity, formula: rule.formulas[severity] };
1216
+ }
1217
+ return { severity: "ok" };
1218
+ }
1219
+
1220
+ // src/engine/run.ts
1221
+ var FAILURES_TO_STOP = 3;
1222
+ var isBinary = (text) => text.includes("\x00");
1223
+ var round = (value) => Math.round(value * 1e4) / 1e4;
1224
+ async function lint(files, engine, reporter) {
1225
+ const started = performance.now();
1226
+ const run = { ...engine, calls: pool(engine.config.concurrency), stats: { calls: 0, cached: 0, tokens: 0 }, failures: 0 };
1227
+ const files_ = pool(engine.config.concurrency * 2);
1228
+ const results = files.map((file) => files_(() => lintFile(file, run)));
1229
+ for (const result of results)
1230
+ result.catch(() => {});
1231
+ const count = { files: 0, errors: 0, warnings: 0, skipped: 0, notes: 0 };
1232
+ for (const pending of results) {
1233
+ const result = await pending;
1234
+ if (!result)
1235
+ continue;
1236
+ count.files++;
1237
+ for (const record of result.records) {
1238
+ if (record.type === "info") {
1239
+ if (record.shown)
1240
+ count.notes++;
1241
+ if (record.skipped)
1242
+ count.skipped++;
1243
+ continue;
1244
+ }
1245
+ if (record.severity === "error")
1246
+ count.errors++;
1247
+ if (record.severity === "warning")
1248
+ count.warnings++;
1249
+ if (record.severity === "skipped")
1250
+ count.skipped++;
1251
+ }
1252
+ reporter.file(result);
1253
+ }
1254
+ const cost = run.stats.cost === undefined ? {} : { cost: Math.round(run.stats.cost * 1e6) / 1e6 };
1255
+ const summary = { type: "summary", ...count, ...run.stats, ...cost, ms: Math.round(performance.now() - started) };
1256
+ reporter.end(summary);
1257
+ return summary;
1258
+ }
1259
+ async function lintFile(file, run) {
1260
+ const text = fs5.readFileSync(file, "utf8");
1261
+ if (isBinary(text))
1262
+ return null;
1263
+ const plan = planFile(file, text, run.config, run.only);
1264
+ if (!plan)
1265
+ return null;
1266
+ const tallies = new Map(plan.unasked.map(({ applied, reason }) => [applied.rule, { missing: reason, parts: [] }]));
1267
+ await Promise.all(plan.calls.map((call) => ask(call, run, tallies)));
1268
+ let applied = plan.applied;
1269
+ if (applied.some(({ rule }) => rule.formulas.error || rule.formulas.warning || rule.formulas.show)) {
1270
+ const confidences = new Map;
1271
+ for (const [rule, tally] of tallies)
1272
+ if (tally.confidence !== undefined)
1273
+ confidences.set(rule, tally.confidence);
1274
+ const final = new Map(resolveRules(run.config, plan.facts, confidences).map((item) => [item.rule, item]));
1275
+ applied = applied.map((item) => final.get(item.rule) ?? item);
1276
+ }
1277
+ return { file, lines: plan.facts.lines, parts: plan.parts, records: applied.map((item) => (item.rule.info ? note : record)(file, item, tallies.get(item.rule), run.config)) };
1278
+ }
1279
+ function record(file, applied, tally, config) {
1280
+ const { rule } = applied;
1281
+ const base = { type: "check", file, rule: rule.sentence, ...rule.id && { id: rule.id } };
1282
+ if (!rule.asksModel) {
1283
+ const { severity, formula } = verdict(applied, undefined, config.defaults);
1284
+ return { ...base, severity, formula: formula ?? rule.formulas.error ?? rule.formulas.warning };
1285
+ }
1286
+ const result = tally?.confidence === undefined ? undefined : verdict(applied, tally.confidence, config.defaults);
1287
+ const skipped = !result || tally?.missing !== undefined && result.severity === "ok";
1288
+ return {
1289
+ ...base,
1290
+ severity: skipped ? "skipped" : result.severity,
1291
+ ...!skipped && { confidence: round(tally.confidence) },
1292
+ ...!skipped && tally.parts.length > 0 && squashed(tally.parts, result.severity === "ok" ? [] : areas(tally.parts, areaThreshold(applied, config.defaults))),
1293
+ question: toQuestion(rule.sentence, rule.ask).instructions,
1294
+ ...!skipped && result.formula && { formula: result.formula },
1295
+ ...tally?.model && { model: tally.model },
1296
+ ...skipped && { reason: tally?.missing ?? "not asked" }
1297
+ };
1298
+ }
1299
+ function note(file, applied, tally, config) {
1300
+ const { rule } = applied;
1301
+ const base = { type: "info", file, statement: rule.sentence, ...rule.id && { id: rule.id } };
1302
+ if (!rule.asksModel)
1303
+ return { ...base, shown: applied.show === true, formula: rule.formulas.show };
1304
+ const threshold = typeof applied.show === "number" ? applied.show : config.defaults.info;
1305
+ const confidence = tally?.confidence;
1306
+ const shown = confidence !== undefined && (typeof applied.show === "boolean" ? applied.show : confidence >= threshold);
1307
+ const skipped = confidence === undefined || tally?.missing !== undefined && !shown;
1308
+ return {
1309
+ ...base,
1310
+ ...!skipped && { confidence: round(confidence) },
1311
+ shown,
1312
+ ...!skipped && tally.parts.length > 0 && squashed(tally.parts, shown ? areas(tally.parts, threshold) : []),
1313
+ question: toQuestion(rule.sentence, rule.ask, true).instructions,
1314
+ ...shown && rule.formulas.show && { formula: rule.formulas.show },
1315
+ ...tally?.model && { model: tally.model },
1316
+ ...skipped && { skipped: true, reason: tally?.missing ?? "not asked" }
1317
+ };
1318
+ }
1319
+ function squashed(parts, failed) {
1320
+ const values = parts.map((part) => part.confidence);
1321
+ return { min: round(Math.min(...values)), max: round(Math.max(...values)), areas: failed, parts: parts.length };
1322
+ }
1323
+ async function ask(call, run, tallies) {
1324
+ const tally = (rule) => tallies.get(rule) ?? tallies.set(rule, { parts: [] }).get(rule);
1325
+ const state = JSON.stringify(call.state);
1326
+ const pending = [];
1327
+ for (const planned of call.planned) {
1328
+ const key = Cache.key(run.client.model, planned.question, state);
1329
+ const hit = run.cache?.get(key);
1330
+ if (!hit) {
1331
+ pending.push({ planned, key });
1332
+ continue;
1333
+ }
1334
+ run.stats.cached++;
1335
+ tallyUp(tally(planned.applied.rule), violation(planned.asked, hit.yes), hit.model, call.lines);
1336
+ }
1337
+ if (!pending.length)
1338
+ return;
1339
+ const fail = (reason) => pending.forEach(({ planned }) => tally(planned.applied.rule).missing = reason);
1340
+ try {
1341
+ const decision = await run.calls(() => {
1342
+ if (run.stopped)
1343
+ throw new ModelError(run.stopped);
1344
+ return run.client.decide(call.state, Object.fromEntries(pending.map(({ planned }) => [planned.key, planned.question])));
1345
+ });
1346
+ run.failures = 0;
1347
+ run.stats.calls++;
1348
+ run.stats.tokens += decision.usage.input_tokens + decision.usage.output_tokens;
1349
+ if (decision.usage.cost !== undefined)
1350
+ run.stats.cost = (run.stats.cost ?? 0) + decision.usage.cost;
1351
+ for (const { planned, key } of pending) {
1352
+ const yes = decision.answers[planned.key];
1353
+ if (yes === null || yes === undefined) {
1354
+ tally(planned.applied.rule).missing = "the model gave no answer";
1355
+ continue;
1356
+ }
1357
+ run.cache?.set(key, { yes, model: decision.model });
1358
+ tallyUp(tally(planned.applied.rule), violation(planned.asked, yes), decision.model, call.lines);
1359
+ }
1360
+ } catch (error) {
1361
+ const { status, message } = error;
1362
+ if (status === 401 || status === 403 || ++run.failures >= FAILURES_TO_STOP)
1363
+ run.stopped ??= message;
1364
+ fail(message);
1365
+ }
1366
+ }
1367
+ function tallyUp(tally, confidence, model, lines) {
1368
+ tally.confidence = Math.max(tally.confidence ?? 0, confidence);
1369
+ tally.model = model;
1370
+ if (lines)
1371
+ tally.parts.push({ ...lines, confidence });
1372
+ }
1373
+ function areaThreshold(applied, defaults) {
1374
+ const thresholds = [applied.warning ?? defaults.warning, applied.error ?? defaults.error].filter((value) => typeof value === "number");
1375
+ return Math.min(defaults.warning, ...thresholds);
1376
+ }
1377
+
1378
+ // src/files/diff.ts
1379
+ import { execFileSync } from "node:child_process";
1380
+
1381
+ class GitError extends Error {
1382
+ hint;
1383
+ constructor(message, hint) {
1384
+ super(message);
1385
+ this.hint = hint;
1386
+ }
1387
+ }
1388
+ var MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
1389
+ function git(args) {
1390
+ return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: MAX_OUTPUT_BYTES });
1391
+ }
1392
+ var list = (output) => output.split("\x00").filter(Boolean);
1393
+ function isRevision(ref) {
1394
+ try {
1395
+ git(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`]);
1396
+ return true;
1397
+ } catch {
1398
+ return false;
1399
+ }
1400
+ }
1401
+ function changedFiles(scope) {
1402
+ try {
1403
+ git(["rev-parse", "--is-inside-work-tree"]);
1404
+ } catch {
1405
+ throw new GitError("--diff and --staged need a git repository", "Run inside the repository, or name the files instead");
1406
+ }
1407
+ const names = ["diff", "--name-only", "-z", "--relative", "--diff-filter=d"];
1408
+ if (scope.staged)
1409
+ return list(git([...names, "--cached", "--"]));
1410
+ let base = "HEAD";
1411
+ if (scope.ref) {
1412
+ if (!isRevision(scope.ref))
1413
+ throw new GitError(`--diff: git does not know "${scope.ref}"`, "Give a branch, tag or commit, for example --diff origin/main");
1414
+ try {
1415
+ base = git(["merge-base", scope.ref, "HEAD"]).trim();
1416
+ } catch {
1417
+ throw new GitError(`--diff: no common history with "${scope.ref}"`, "A shallow clone hides it: fetch more history (git fetch --unshallow, or fetch-depth: 0 in CI)");
1418
+ }
1419
+ }
1420
+ let tracked;
1421
+ try {
1422
+ tracked = list(git([...names, base, "--"]));
1423
+ } catch {
1424
+ tracked = list(git(["ls-files", "-z"]));
1425
+ }
1426
+ const untracked = list(git(["ls-files", "-z", "--others", "--exclude-standard"]));
1427
+ return [...new Set([...tracked, ...untracked])].sort();
1428
+ }
1429
+
1430
+ // src/model/providers.ts
1431
+ var PROVIDERS = {
1432
+ openrouter: { url: () => "https://openrouter.ai/api/alpha/decisions", key: "OPENROUTER_API_KEY", wire: "typesafe" },
1433
+ aimlapi: { url: () => "https://api.aimlapi.com/v1/decisions", key: "AIMLAPI_API_KEY", wire: "typesafe" },
1434
+ typesafe: {
1435
+ url: (env) => env.TYPESAFE_BASE_URL && `${env.TYPESAFE_BASE_URL.replace(/\/$/, "")}/v1/systemone`,
1436
+ urlHint: "TYPESAFE_BASE_URL",
1437
+ key: "TYPESAFE_API_KEY",
1438
+ wire: "typesafe"
1439
+ },
1440
+ gateway: { url: () => "https://ai-gateway.vercel.sh/v1/decisions", key: "AI_GATEWAY_API_KEY", wire: "openai" }
1441
+ };
1442
+ function parseModel(value, env = process.env) {
1443
+ if (!value)
1444
+ throw new Error("No model set. Set LINTOBOT_MODEL, for example LINTOBOT_MODEL=openrouter/typesafe/jev-1.14");
1445
+ const slash = value.indexOf("/");
1446
+ const name = slash < 0 ? value : value.slice(0, slash);
1447
+ const provider = PROVIDERS[name];
1448
+ if (!provider || slash < 0 || slash === value.length - 1) {
1449
+ throw new Error(`The model must be <provider>/<model>, provider one of: ${Object.keys(PROVIDERS).join(", ")}. Got "${value}"`);
1450
+ }
1451
+ const url = env.LINTOBOT_BASE_URL || provider.url(env);
1452
+ if (!url)
1453
+ throw new Error(`Provider "${name}" needs ${provider.urlHint} (or LINTOBOT_BASE_URL)`);
1454
+ const apiKey = env.LINTOBOT_API_KEY || env[provider.key];
1455
+ if (!apiKey)
1456
+ throw new Error(`Provider "${name}" needs ${provider.key} (or LINTOBOT_API_KEY)`);
1457
+ return { provider: name, model: value.slice(slash + 1), url, apiKey, wire: provider.wire };
1458
+ }
1459
+
1460
+ // src/report/json.ts
1461
+ var isProblem = (record) => record.type === "info" ? record.skipped === true : record.severity !== "ok";
1462
+ var shown = (records, quiet) => quiet ? records.filter(isProblem) : records;
1463
+ function jsonlReporter(write, options = {}) {
1464
+ return {
1465
+ file: (result) => shown(result.records, options.quiet).forEach((record) => write(`${JSON.stringify(record)}
1466
+ `)),
1467
+ end: (summary) => write(`${JSON.stringify(summary)}
1468
+ `)
1469
+ };
1470
+ }
1471
+ function jsonReporter(write, options = {}) {
1472
+ const results = [];
1473
+ return {
1474
+ file: (result) => void results.push(...shown(result.records, options.quiet)),
1475
+ end: (summary) => write(`${JSON.stringify({ results, summary }, null, 2)}
1476
+ `)
1477
+ };
1478
+ }
1479
+
1480
+ // src/report/pretty.ts
1481
+ import pc from "picocolors";
1482
+ var COLUMN = 56;
1483
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1484
+ var tokens = (n) => n < 1000 ? String(n) : `${Math.round(n / 1000)}k`;
1485
+ var percent = (confidence) => confidence === undefined ? "" : `${Math.round(confidence * 100)}%`;
1486
+ function prettyReporter(write, options = {}) {
1487
+ const color = pc.createColors(options.color ?? false);
1488
+ const row = (icon, label, value, paint = (text) => text) => ` ${icon} ${paint(label)}${value && value.padStart(Math.max(value.length + 2, COLUMN - label.length))}`;
1489
+ const place = (record) => record.areas?.length ? ` lines ${record.areas.map((area) => `${area.start}–${area.end}`).join(", ")}` : "";
1490
+ const noteLabel = (record) => record.id ? `${record.statement} (${record.id})` : record.statement;
1491
+ function noteLine(records) {
1492
+ const text = records.map(noteLabel).join(", ");
1493
+ return text ? [color.dim(text[0].toUpperCase() + text.slice(1))] : [];
1494
+ }
1495
+ function line(record) {
1496
+ const label = record.id ? `${record.rule} (${record.id})` : record.rule;
1497
+ const where = place(record);
1498
+ switch (record.severity) {
1499
+ case "error":
1500
+ return row("❌", label, percent(record.confidence), color.red) + where;
1501
+ case "warning":
1502
+ return row("⚠️ ", label, percent(record.confidence), color.yellow) + where;
1503
+ case "skipped":
1504
+ return `${row("⏭️ ", label, "")} ${color.dim(`skipped: ${record.reason}`)}`;
1505
+ default:
1506
+ return row("✅", label, record.min === undefined ? "" : range(record.min, record.max ?? record.min));
1507
+ }
1508
+ }
1509
+ return {
1510
+ file({ file, lines, parts, records }) {
1511
+ const checks = records.filter((record) => record.type === "check");
1512
+ const info = records.filter((record) => record.type === "info");
1513
+ const notes = noteLine(info.filter((record) => record.shown && !record.skipped && !options.quiet));
1514
+ const skipped = info.filter((record) => record.skipped).map((record) => `${row("⏭️ ", noteLabel(record), "")} ${color.dim(`skipped: ${record.reason}`)}`);
1515
+ const clean = checks.every((record) => record.severity === "ok");
1516
+ const collapsed = checks.length ? [` ✅ ${plural(checks.length, "rule")}`] : [];
1517
+ const rows = [
1518
+ ...notes,
1519
+ ...clean && parts === 1 ? options.quiet ? [] : collapsed : checks.filter((record) => !options.quiet || record.severity !== "ok").map(line),
1520
+ ...skipped
1521
+ ];
1522
+ if (!rows.length)
1523
+ return;
1524
+ const size = parts === undefined ? color.dim(` (${lines} lines)`) : parts > 1 ? color.dim(` (${lines} lines, ${parts} parts)`) : "";
1525
+ write(`${color.bold(file)}${size}
1526
+ ${rows.join(`
1527
+ `)}
1528
+
1529
+ `);
1530
+ },
1531
+ end(summary) {
1532
+ const parts = [
1533
+ plural(summary.files, "file"),
1534
+ plural(summary.errors, "error"),
1535
+ plural(summary.warnings, "warning"),
1536
+ ...summary.notes ? [plural(summary.notes, "note")] : [],
1537
+ ...summary.skipped ? [`${summary.skipped} skipped`] : [],
1538
+ plural(summary.calls, "call"),
1539
+ `${tokens(summary.tokens)} tokens`,
1540
+ ...summary.cost === undefined ? [] : [`$${summary.cost.toFixed(4)}`],
1541
+ `${(summary.ms / 1000).toFixed(1)}s`
1542
+ ];
1543
+ write(`${parts.join(" · ")}
1544
+ `);
1545
+ }
1546
+ };
1547
+ }
1548
+ function range(min, max) {
1549
+ const low = Math.round(min * 100);
1550
+ return low === Math.round(max * 100) ? `${low}%` : `${low}–${percent(max)}`;
1551
+ }
1552
+
1553
+ // src/report/index.ts
1554
+ var FORMATS = ["pretty", "json", "jsonl"];
1555
+ function createReporter(format, write, options) {
1556
+ if (format === "json")
1557
+ return jsonReporter(write, options);
1558
+ if (format === "jsonl")
1559
+ return jsonlReporter(write, options);
1560
+ return prettyReporter(write, options);
1561
+ }
1562
+
1563
+ // src/report/plan.ts
1564
+ var BYTES_PER_TOKEN = 4;
1565
+ var OWN_SECTIONS = ["path", "language", "outline", "code"];
1566
+ var plural2 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1567
+ function reportPlan(plans, format, write) {
1568
+ const records = plans.map((plan) => ({
1569
+ type: "plan",
1570
+ file: plan.file,
1571
+ calls: plan.calls.length,
1572
+ bytes: plan.calls.reduce((sum, call) => sum + callBytes(call), 0),
1573
+ rules: plan.applied.map(({ rule }) => {
1574
+ const unasked = plan.unasked.find((item) => item.applied.rule === rule);
1575
+ const name = rule.info ? { info: rule.sentence } : { rule: rule.sentence };
1576
+ if (unasked)
1577
+ return { ...name, skipped: unasked.reason };
1578
+ return rule.asksModel ? { ...name, question: toQuestion(rule.sentence, rule.ask, rule.info).instructions } : { ...name, formula: rule.formulas.error ?? rule.formulas.warning ?? rule.formulas.show };
1579
+ }),
1580
+ sent: plan.calls.map((call) => ({
1581
+ ...call.lines && { lines: call.lines },
1582
+ bytes: callBytes(call),
1583
+ context: Object.fromEntries(Object.entries(call.state).filter(([name]) => !OWN_SECTIONS.includes(name)).map(([name, text]) => [name, Buffer.byteLength(text)])),
1584
+ rules: call.planned.map((planned) => planned.applied.rule.sentence)
1585
+ }))
1586
+ }));
1587
+ const bytes = records.reduce((sum, record) => sum + record.bytes, 0);
1588
+ const summary = {
1589
+ type: "plan-summary",
1590
+ files: records.length,
1591
+ calls: records.reduce((sum, record) => sum + record.calls, 0),
1592
+ bytes,
1593
+ tokens: Math.ceil(bytes / BYTES_PER_TOKEN)
1594
+ };
1595
+ if (format === "json")
1596
+ return write(`${JSON.stringify({ plan: records, summary }, null, 2)}
1597
+ `);
1598
+ if (format === "jsonl")
1599
+ return [...records, summary].forEach((record) => write(`${JSON.stringify(record)}
1600
+ `));
1601
+ for (const record of records) {
1602
+ write(`${record.file}
1603
+ ${plural2(record.calls, "call")} · ${record.bytes} bytes
1604
+ `);
1605
+ for (const call of record.sent) {
1606
+ const context = Object.entries(call.context).map(([name, size]) => `${name} ${size} bytes`).join(", ");
1607
+ const where = call.lines ? `lines ${call.lines.start}–${call.lines.end}` : "whole file";
1608
+ write(` ${where} · ${call.bytes} bytes · ${plural2(call.rules.length, "question")}${context && ` · context: ${context}`}
1609
+ `);
1610
+ }
1611
+ for (const rule of record.rules) {
1612
+ const detail = "skipped" in rule ? `skipped: ${rule.skipped}` : ("question" in rule) ? rule.question : `formula: ${rule.formula}`;
1613
+ write(` ${"info" in rule ? `info: ${rule.info}` : rule.rule}
1614
+ ${detail}
1615
+ `);
1616
+ }
1617
+ write(`
1618
+ `);
1619
+ }
1620
+ write(`${plural2(summary.files, "file")} · ${plural2(summary.calls, "call")} · ${summary.bytes} bytes · about ${summary.tokens} tokens · nothing was sent
1621
+ `);
1622
+ }
1623
+
1624
+ // src/skill/SKILL.md
1625
+ var SKILL_default = `---
1626
+ name: lintobot
1627
+ description: What lintobot is, how to treat its results and how to write its rules. Use when asked to run lintobot, read or act on its report, set it up in a project, or add or change a rule in lintobot.yml.
1628
+ ---
1629
+
1630
+ # lintobot
1631
+
1632
+ A linter whose rules are plain sentences: \`lintobot.yml\` describes what good code is for this project. For each file it asks a decision model whether a sentence holds and gets back only a probability: the **confidence that the rule is broken**, never an explanation or a line.
1633
+
1634
+ ## What it is and is not
1635
+
1636
+ - **Rules are intentions, not laws.** They say what the team would like to see in the code. A rule that must hold exactly and can be read from syntax belongs in the real linter: \`/linto-lint\` moves it there.
1637
+ - **Results are signals, not problems.** A finding is advice to look, never a call to action. Pass it to an agent or a person to review: read the code, judge it against the sentence, then fix it or dismiss it. Never fix code just to silence a finding.
1638
+ - **Not deterministic.** The same file can score a few points differently between runs, and the scores are not calibrated. Nothing here is strict.
1639
+ - **Between a linter and a subagent.** It checks what a linter cannot (does a comment match the code, does a function belong in this file, is the file about one thing) and is much faster and cheaper than a subagent reading the file.
1640
+ - **Flexible.** Each rule has its own thresholds: lower \`error\` to enforce a rule harder, raise it or set it to \`false\` to keep the rule as a quiet hint.
1641
+
1642
+ Run it as an agent hook after edits (\`lintobot --diff\`) or on a pull request (\`lintobot --diff origin/main\`), and hand the findings to the agent as things to review.
1643
+
1644
+ ## Run
1645
+
1646
+ \`\`\`bash
1647
+ lintobot # every file matched by lintobot.yml
1648
+ lintobot app/jobs # only this folder or file
1649
+ lintobot src --rule "no magic numbers"
1650
+ lintobot src --dry-run # shows the exact questions, sends nothing
1651
+ lintobot --diff # only files changed since the last commit
1652
+ lintobot --diff origin/main # only files this branch changes
1653
+ \`\`\`
1654
+
1655
+ Needs \`LINTOBOT_MODEL\` and the provider's key in the environment or \`.env\`. Exit codes: \`0\` clean, \`1\` errors, \`2\` bad config, \`3\` model unreachable.
1656
+
1657
+ In the report ❌ is an error, ⚠️ a warning, ✅ passed. The percent is the confidence that the rule is broken; \`lines 120–300\` is the part of a large file where it failed.
1658
+
1659
+ ## Write rules
1660
+
1661
+ \`\`\`yaml
1662
+ files:
1663
+ - pattern: "app/jobs/**_job.rb"
1664
+ except: "app/jobs/legacy/**"
1665
+ rules:
1666
+ - "all methods are private except perform"
1667
+ - "no direct database access":
1668
+ error: 0.8
1669
+ ask: Does the code open a database connection or run a query itself?
1670
+ - "file is too long":
1671
+ error!: file.lines > 800
1672
+ info:
1673
+ - "sends email"
1674
+ \`\`\`
1675
+
1676
+ - A rule is a sentence that must hold for the file. One starting with \`no \` is asked as "does the code contain …?", any other as "is it true that …?". State what is present; avoid negations, "only" and "always".
1677
+ - \`info:\` items are observations, not rules: start them with a verb. The true ones are printed under the file name and never fail the run.
1678
+ - Options, all optional:
1679
+ - \`error\`, \`warning\`: confidence threshold (defaults 0.9 and 0.7), or \`false\` to switch the level off
1680
+ - \`ask\`: the question to send instead of the generated one. Under a \`no …\` sentence yes means broken, otherwise yes means fine
1681
+ - \`criteria\`: \`yes:\` / \`no:\` descriptions of what counts
1682
+ - \`except\`: globs the rule skips
1683
+ - \`whole: true\`: the rule is about the file as a whole
1684
+ - A key ending in \`!\` is a formula over \`confidence\` and \`file\` (\`lines\`, \`complexity\`, \`imports\`, \`path\`, …): \`error!: confidence > 0.8 and file.lines > 300\`. \`$if!:\` decides whether the rule applies. A formula that does not read \`confidence\` makes no model call.
1685
+
1686
+ A good start for any code file is a few basic checks, then the project's own intentions on top:
1687
+
1688
+ \`\`\`yaml
1689
+ rules:
1690
+ - "no duplicated code"
1691
+ - "no magic numbers"
1692
+ - "no comments that restate the code"
1693
+ \`\`\`
1694
+
1695
+ ## Start from the agent rules
1696
+
1697
+ A project that has \`CLAUDE.md\` or \`AGENTS.md\` (at the root or in subfolders) has already written down what good code is. Use them as the first source of rules:
1698
+
1699
+ 1. \`lintobot init\` writes a starter \`lintobot.yml\` when there is none.
1700
+ 2. Read the agent files and keep every statement about **how the code should look** that can be judged by reading one file: "jobs only call services", "no business logic in controllers", "comments explain why".
1701
+ 3. Rewrite each as a rule sentence, in the \`no …\` form where it fits, under the \`pattern\` of the files it speaks about. A file in a subfolder gives rules for that folder.
1702
+ 4. Leave out what is not about one file's code: how to run tests, commit and PR habits, tool usage, anything that needs several files. Send strict syntax rules ("all methods private except perform") to the linter with \`/linto-lint\`.
1703
+ 5. \`lintobot --dry-run\` to read the questions, then run it on a few known good and bad files and set thresholds from what they score.
1704
+
1705
+ Show the list of rules taken from the agent files, with the line each came from, before writing them.
1706
+
1707
+ A rule that fires on most files is too vague: add \`ask\` and \`criteria\`, check the wording with \`--dry-run\`. The README has the rest: context, part sizes, output formats.
1708
+ `;
1709
+
1710
+ // src/skill/linto-lint/SKILL.md
1711
+ var SKILL_default2 = `---
1712
+ name: linto-lint
1713
+ description: Move lintobot rules that a real linter can check (RuboCop, ESLint, Biome, Ruff, ...) out of lintobot.yml - enable or write the linter rule, then comment the lintobot rule out with a \`# moved to linter\` marker. Use when asked to delegate, move or offload lintobot rules to the linter, or to cut model calls for rules that are plain syntax checks.
1714
+ argument-hint: "[path to lintobot.yml] [--report]"
1715
+ ---
1716
+
1717
+ # linto-lint
1718
+
1719
+ lintobot asks a model about every rule, on every file, for a probability. A rule that can be decided from syntax alone is cheaper, exact and instant in the project's own linter. This skill finds those rules, makes the linter enforce them, and comments them out of \`lintobot.yml\`.
1720
+
1721
+ A rule is commented out **only after the linter demonstrably enforces it**. Otherwise the check is silently lost.
1722
+
1723
+ With \`--report\`, stop after step 3: print the list and change nothing.
1724
+
1725
+ ## 1. Find the lintofile and the linter
1726
+
1727
+ - The lintofile is the path in the arguments, else the nearest \`lintobot.yml\` at or above the working directory. Its folder is the project.
1728
+ - The linter is the one the project already runs. Look for its config and for how it is called in CI or the package scripts:
1729
+
1730
+ | Language | Config | Custom rules live in |
1731
+ |---|---|---|
1732
+ | Ruby | \`.rubocop.yml\` | a custom cop: \`lib/rubocop/cop/<dept>/*.rb\`, loaded with \`require:\` |
1733
+ | JS / TS | \`eslint.config.*\`, \`.eslintrc*\` | \`no-restricted-syntax\` / \`no-restricted-imports\` selectors first; a local plugin only when a selector cannot say it |
1734
+ | JS / TS | \`biome.json\` | a GritQL plugin (\`plugins:\`) |
1735
+ | Python | \`ruff.toml\`, \`pyproject.toml\` | none: built-in rules only |
1736
+ | Go | \`.golangci.yml\` | built-in linters, \`forbidigo\`, \`depguard\` |
1737
+
1738
+ One \`files\` entry is checked by the linter of its language; a project may have several. If an entry's language has no linter set up, its rules stay. Do not install a linter to make room for this.
1739
+
1740
+ ## 2. Classify every rule
1741
+
1742
+ Read each active rule under \`files[].rules\` (skip lines already commented out). Decide:
1743
+
1744
+ **Delegable** - the answer follows from the file's syntax tree, tokens, names or path, with no judgement:
1745
+
1746
+ - visibility, kind or count of declarations ("all methods are private except perform", "no class level methods declared", "one class per file")
1747
+ - a forbidden or required call, constant, import, inheritance or macro ("no \`puts\`", "no direct \`ActiveRecord::Base.connection\`", "inherits from ApplicationJob")
1748
+ - naming and placement ("class name ends with Job")
1749
+ - size, nesting, complexity, line length
1750
+
1751
+ **Stays in lintobot** - anything that needs to understand what the code means:
1752
+
1753
+ - intent, responsibility, quality ("focused on a single thing", "logic is easy to follow", "comments explain intent")
1754
+ - behaviour reached through other code ("mutates and persists data or performs i/o", "does not call services" when a service is not recognisable by name)
1755
+ - a rule with \`context:\` - it is judged against outside material
1756
+ - a rule whose \`ask\` / \`criteria\` describe meaning, even if the sentence looks syntactic: the options are the real rule, read them
1757
+ - everything under \`info:\` - observations, not rules; a linter has nowhere to put them
1758
+ - a formula rule that never reads \`confidence\` (\`error!: file.lines > 800\`): it already makes no model call. Move it only when the linter has the exact same check
1759
+
1760
+ When unsure, the rule stays. A syntactic-looking rule whose honest linter version would miss half the cases ("no database access" via any of ten gems) stays.
1761
+
1762
+ For each delegable rule pick the target, in this order:
1763
+
1764
+ 1. a rule the linter already has (built in or in an installed plugin) - check its docs or \`rubocop --show-cops\`, \`eslint --print-config\`, do not rely on memory for the name or its options
1765
+ 2. a custom rule already in the project that covers it or nearly does
1766
+ 3. a new custom rule, where the table above allows one
1767
+
1768
+ ## 3. List what can move
1769
+
1770
+ Print the rules that can be moved, and only those, before changing anything; then carry on unless \`--report\` was given. Rules that stay are not listed and not explained.
1771
+
1772
+ \`\`\`
1773
+ app/jobs/**_job.rb
1774
+ all methods are private except perform -> rubocop Lintobot/JobPublicInterface (new cop)
1775
+ no class level methods declared -> rubocop Lintobot/NoClassMethods (new cop)
1776
+ \`\`\`
1777
+
1778
+ If nothing can move, say so in one line and stop.
1779
+
1780
+ ## 4. Make the linter enforce it
1781
+
1782
+ For every listed rule:
1783
+
1784
+ - **Same files.** Limit the linter rule to the entry's \`pattern\` minus the entry's and the rule's \`except\` (RuboCop \`Include\` / \`Exclude\`, an ESLint \`files\` / \`ignores\` block, a Biome \`overrides\` entry). Check the glob in the linter's own dialect: lintobot's \`app/jobs/**_job.rb\` is RuboCop's \`app/jobs/**/*_job.rb\`. A rule that appears in several entries gets all of their patterns.
1785
+ - **Same strength.** A rule that could only warn (\`error: false\`) becomes a warning in the linter, everything else an error.
1786
+ - **Same meaning.** Keep exceptions the sentence states ("except perform"). Put the lintobot sentence into the custom rule's message so the offence reads the same as before.
1787
+ - **Custom rules** follow the project's existing ones in location, namespace and tests; with none, use the place in the table and add a spec beside it when the project tests its linter rules.
1788
+ - Never edit application code to make it pass, and no autocorrect.
1789
+
1790
+ Then prove it, per rule:
1791
+
1792
+ 1. It fires: feed the linter a small violating sample under a path inside the pattern, on stdin, with only this rule on (\`rubocop --only Dept/Cop --stdin app/jobs/sample_job.rb\`, \`eslint --stdin --stdin-filename src/sample.ts --rule ...\`). No offence means the rule or its scope is wrong: fix it or drop the rule from the list.
1793
+ 2. It stays quiet on a conforming sample, and on a path outside the pattern.
1794
+ 3. Run it over the real files the pattern matches and keep the offence count for the report.
1795
+
1796
+ A rule that cannot be proven is reverted in the linter config and stays in lintobot.
1797
+
1798
+ ## 5. Comment the rule out
1799
+
1800
+ Edit \`lintobot.yml\` as text - never load and re-dump it, that drops comments and formulas. Put the marker line above the rule, at the rule's indentation, and comment out every line of the rule, options included:
1801
+
1802
+ \`\`\`yaml
1803
+ rules:
1804
+ # moved to linter: rubocop Lintobot/JobPublicInterface
1805
+ # - "all methods are private except perform"
1806
+ # moved to linter: rubocop Lintobot/NoClassMethods
1807
+ # - "no class level methods declared":
1808
+ # warning: 0.8
1809
+ # except: "app/jobs/legacy/**"
1810
+ - "mutates and persists data or performs i/o operation"
1811
+ \`\`\`
1812
+
1813
+ - The marker always starts with \`# moved to linter\`, followed by \`: <linter> <rule name>\`.
1814
+ - Delete nothing. Leave the other rules, \`info:\`, blank lines and existing comments as they are.
1815
+ - A rule already under a \`# moved to linter\` marker is done: skip it on a second run.
1816
+ - An entry needs \`rules\` or \`info\`. If every rule of an entry moved, comment out the \`rules:\` key as well; if the entry has no \`info:\` either, comment out the whole entry from \`- pattern:\` down, markers inside.
1817
+
1818
+ Check the file still loads: \`lintobot --dry-run\` sends nothing and exits \`2\` on a broken config.
1819
+
1820
+ ## 6. Report
1821
+
1822
+ - the rules that were moved and where to; a rule from the list that failed its proof, with the reason in a few words
1823
+ - files changed: \`lintobot.yml\`, the linter config, any new custom rule and its spec
1824
+ - existing offences the linter now reports for each moved rule, with counts and the worst files. These were lintobot findings before; they will now fail the linter run. Leave fixing them, or adding them to a todo / baseline file, to the user.
1825
+ `;
1826
+
1827
+ // src/cli.ts
1828
+ var EXIT = { clean: 0, problems: 1, usage: 2, model: 3 };
1829
+
1830
+ class UsageError extends Error {
1831
+ hint;
1832
+ constructor(message, hint) {
1833
+ super(message);
1834
+ this.hint = hint;
1835
+ }
1836
+ }
1837
+ function count(value, flag) {
1838
+ if (value === undefined)
1839
+ return;
1840
+ if (!/^\d+$/.test(value))
1841
+ throw new UsageError(`${flag} must be a whole number, got "${value}"`);
1842
+ return Number(value);
1843
+ }
1844
+ var CONFIG_NAME = "lintobot.yml";
1845
+ function loadEnv(file) {
1846
+ for (const line of fs6.readFileSync(file, "utf8").split(/\r?\n/)) {
1847
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
1848
+ if (!match || process.env[match[1]])
1849
+ continue;
1850
+ process.env[match[1]] = match[2].replace(/^(['"])(.*)\1$/, "$2");
1851
+ }
1852
+ }
1853
+ function findUp(dir) {
1854
+ for (;; ) {
1855
+ if (fs6.existsSync(path7.join(dir, CONFIG_NAME)))
1856
+ return dir;
1857
+ const parent = path7.dirname(dir);
1858
+ if (parent === dir)
1859
+ return;
1860
+ dir = parent;
1861
+ }
1862
+ }
1863
+ function projectRoot(args, flags) {
1864
+ const cwd = process.cwd();
1865
+ const first = args[0];
1866
+ if (!flags.config) {
1867
+ if (first && /\.ya?ml$/.test(first) && fs6.existsSync(first) && fs6.statSync(first).isFile())
1868
+ flags.config = args.shift();
1869
+ else {
1870
+ const start = first && fs6.existsSync(first) ? path7.resolve(first) : cwd;
1871
+ const found = findUp(fs6.statSync(start).isDirectory() ? start : path7.dirname(start));
1872
+ if (found)
1873
+ flags.config = path7.join(found, CONFIG_NAME);
1874
+ if (found && first && found === start && found !== cwd)
1875
+ args.shift();
1876
+ }
1877
+ }
1878
+ if (!flags.config)
1879
+ return { cwd };
1880
+ const config = path7.resolve(flags.config);
1881
+ if (!fs6.existsSync(config))
1882
+ throw new UsageError(`No config file ${flags.config}`);
1883
+ const root = path7.dirname(config);
1884
+ args.splice(0, args.length, ...args.map((arg) => path7.relative(root, path7.resolve(cwd, arg)) || "."));
1885
+ if (flags.output)
1886
+ flags.output = path7.resolve(cwd, flags.output);
1887
+ process.chdir(root);
1888
+ flags.config = path7.basename(config);
1889
+ return { cwd };
1890
+ }
1891
+ async function main(args, flags) {
1892
+ if (flags.diff && flags.staged)
1893
+ throw new UsageError("--diff and --staged do not go together");
1894
+ if (typeof flags.diff === "string" && fs6.existsSync(flags.diff) && !isRevision(flags.diff)) {
1895
+ args.unshift(flags.diff);
1896
+ flags.diff = true;
1897
+ }
1898
+ const root = projectRoot(args, flags);
1899
+ args.push(...flags.files);
1900
+ for (const file of new Set([path7.resolve(".env"), path7.join(root.cwd, ".env")])) {
1901
+ if (fs6.existsSync(file))
1902
+ loadEnv(file);
1903
+ }
1904
+ const env = process.env;
1905
+ const format = flags.format ?? env.LINTOBOT_FORMAT ?? (process.stdout.isTTY ? "pretty" : "jsonl");
1906
+ if (!FORMATS.includes(format))
1907
+ throw new UsageError(`Unknown format "${format}"`, `Formats: ${FORMATS.join(", ")}`);
1908
+ const maxWarnings = count(flags.maxWarnings, "--max-warnings");
1909
+ const config = loadConfig(flags.config);
1910
+ config.concurrency = count(flags.concurrency, "--concurrency") ?? config.concurrency;
1911
+ config.shell = flags.shell;
1912
+ if (config.concurrency < 1)
1913
+ throw new UsageError("Concurrency must be at least 1");
1914
+ for (const warning of config.warnings)
1915
+ process.stderr.write(`warning: ${warning}
1916
+ `);
1917
+ const fromConfig = config.entries.every((entry) => entry.patterns);
1918
+ const changed = flags.diff || flags.staged ? new Set(changedFiles({ ref: typeof flags.diff === "string" ? flags.diff : undefined, staged: flags.staged })) : null;
1919
+ if (!fromConfig && !args.length && !changed) {
1920
+ throw new UsageError("Nothing to lint: no files were given", `Name files or folders (lintobot src/), or list patterns under files: in ${config.file}`);
1921
+ }
1922
+ const found = findFiles(args, fromConfig ? config.entries.flatMap((entry) => entry.patterns) : null, config.ignore);
1923
+ const files = changed ? found.filter((file) => changed.has(file)) : found;
1924
+ const chunks = [];
1925
+ const write = flags.output ? (text) => void chunks.push(text) : (text) => void process.stdout.write(text);
1926
+ const save = () => flags.output && fs6.writeFileSync(flags.output, chunks.join(""));
1927
+ if (flags.dryRun) {
1928
+ const plans = files.flatMap((file) => planFile(file, fs6.readFileSync(file, "utf8"), config, flags.rule) ?? []);
1929
+ reportPlan(plans, format, write);
1930
+ save();
1931
+ return EXIT.clean;
1932
+ }
1933
+ let connected;
1934
+ const connect = () => connected ??= createClient(parseModel(config.model));
1935
+ const client = {
1936
+ get model() {
1937
+ return connect().model;
1938
+ },
1939
+ decide: (state, questions) => connect().decide(state, questions)
1940
+ };
1941
+ const cache = flags.cache ? new Cache(env.LINTOBOT_CACHE_DIR || ".lintobot/cache") : undefined;
1942
+ const reporter = createReporter(format, write, { quiet: flags.quiet, color: !flags.output && process.stdout.isTTY });
1943
+ const summary = await lint(files, { config, client, cache, only: flags.rule }, reporter);
1944
+ save();
1945
+ if (summary.errors > 0 || maxWarnings !== undefined && summary.warnings > maxWarnings)
1946
+ return EXIT.problems;
1947
+ return summary.skipped > 0 ? EXIT.model : EXIT.clean;
1948
+ }
1949
+ function fail(message, hint) {
1950
+ if (process.stderr.isTTY)
1951
+ process.stderr.write(`lintobot: ${message}
1952
+ ${hint ? ` ${hint}
1953
+ ` : ""}`);
1954
+ else
1955
+ process.stderr.write(`${JSON.stringify({ type: "error", code: "usage", message, ...hint && { hint } })}
1956
+ `);
1957
+ return EXIT.usage;
1958
+ }
1959
+ process.stdout.on("error", (error) => {
1960
+ if (error.code !== "EPIPE")
1961
+ throw error;
1962
+ });
1963
+ var ABOUT = `
1964
+ What to expect:
1965
+ Rules are intentions: lintobot.yml describes what good code is for you, in plain sentences.
1966
+ Results are signals, not problems: a finding is advice to look, not a call to action.
1967
+ Pass findings to an agent or a reviewer to judge against the code.
1968
+ Results are not deterministic: the model answers with a probability, which can move
1969
+ a few points between runs.
1970
+ Each rule is as strict as you make it: lower its \`error\` threshold to enforce it harder,
1971
+ raise it or set it to false to keep it as a hint.
1972
+ It checks what a linter cannot (a comment matching its code, a function belonging in its
1973
+ file) and costs far less than a subagent. Run it from an agent hook or on a pull request:
1974
+ lintobot --diff what changed since the last commit
1975
+ lintobot --diff origin/main what this branch changes
1976
+ Rules that must hold exactly belong in a real linter: the linto-lint skill moves them
1977
+ (lintobot skill --install).
1978
+ `;
1979
+ var program = new Command().name("lintobot").description("A code linter whose rules are plain-language sentences answered by a decision model").version(package_default.version).argument("[files...]", "files, folders or globs; all files matched by lintobot.yml when omitted. A first argument that is a config file, or a folder holding lintobot.yml, selects that project").option("--format <format>", `output format: ${FORMATS.join(", ")} (pretty on a terminal, jsonl otherwise)`).option("-o, --output <file>", "write the report to a file").option("--files <path>", "file, folder or glob relative to the project, i.e. to the config (repeatable)", (value, list) => [...list, value], []).option("--rule <id>", "run only this rule, by id or sentence (repeatable)", (value, list) => [...list, value], []).option("--diff [ref]", "only files changed since the branch left <ref> (a branch, tag or commit), uncommitted and new files included; without <ref>, since the last commit").option("--staged", "only files staged for the next commit").option("--dry-run", "show what would be sent to the model, send nothing").option("--quiet", "report problems only").option("--no-cache", "ask the model again for pieces already answered").option("--no-shell", "do not run the !sh commands of the config").option("--concurrency <n>", "model calls at a time").option("-c, --config <path>", "config file (default: lintobot.yml); its folder becomes the working directory").option("--max-warnings <n>", "exit with 1 when there are more warnings than this").addHelpText("after", ABOUT).exitOverride().action(async (args, flags) => {
1980
+ process.exitCode = await main(args, flags);
1981
+ });
1982
+ var SKILLS = { lintobot: SKILL_default, "linto-lint": SKILL_default2 };
1983
+ program.command("init").description(`write a starter ${CONFIG_NAME} into the current folder`).option("--force", `replace an existing ${CONFIG_NAME}`).action((flags) => {
1984
+ if (fs6.existsSync(CONFIG_NAME) && !flags.force) {
1985
+ throw new UsageError(`${CONFIG_NAME} already exists here`, "Use --force to replace it");
1986
+ }
1987
+ const files = findFiles(["."], null, DEFAULT_IGNORE);
1988
+ fs6.writeFileSync(CONFIG_NAME, starterConfig(files, process.env.LINTOBOT_MODEL || undefined));
1989
+ process.stdout.write(`Created ${CONFIG_NAME} for ${files.length} code file${files.length === 1 ? "" : "s"}.
1990
+ ` + ` Edit its rules, then run: lintobot --dry-run
1991
+ ` + ` Add .lintobot/ to .gitignore: it holds the cache of answers.
1992
+ `);
1993
+ });
1994
+ program.command("skill [name]").description(`print an agent skill (${Object.keys(SKILLS).join(", ")}), or install them all into .claude/skills/`).option("--install", "write every SKILL.md into .claude/skills/<name>/").action((name, flags) => {
1995
+ if (!flags.install) {
1996
+ const text = SKILLS[name ?? "lintobot"];
1997
+ if (!text)
1998
+ program.error(`Unknown skill "${name}". Available: ${Object.keys(SKILLS).join(", ")}`, { exitCode: EXIT.usage });
1999
+ return void process.stdout.write(text);
2000
+ }
2001
+ for (const [dir, text] of Object.entries(SKILLS)) {
2002
+ if (name && name !== dir)
2003
+ continue;
2004
+ const file = path7.join(".claude", "skills", dir, "SKILL.md");
2005
+ fs6.mkdirSync(path7.dirname(file), { recursive: true });
2006
+ fs6.writeFileSync(file, text);
2007
+ process.stdout.write(`Installed ${file}
2008
+ `);
2009
+ }
2010
+ });
2011
+ try {
2012
+ await program.parseAsync();
2013
+ } catch (error) {
2014
+ if (error instanceof CommanderError)
2015
+ process.exitCode = error.exitCode === 0 ? EXIT.clean : EXIT.usage;
2016
+ else if (error instanceof UsageError || error instanceof GitError)
2017
+ process.exitCode = fail(error.message, error.hint);
2018
+ else if (error instanceof ConfigError)
2019
+ process.exitCode = fail(error.message);
2020
+ else
2021
+ process.exitCode = fail(error.message);
2022
+ }