lintobot 0.2.0 → 0.2.2

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 (3) hide show
  1. package/README.md +133 -11
  2. package/dist/cli.js +462 -77
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -24,6 +24,7 @@ Reads or writes files on disk
24
24
 
25
25
  `lintobot.yml` is where you describe what good code is for you. Its rules are **intentions**, the code you would like to see, not laws.
26
26
 
27
+ - **It knows what a file is for.** Name the purposes a file may have and lintobot says which one it serves, and fails the file that serves the wrong one: a job doing a controller's work, a project-scoped controller that is not about one project. See [Composition](#composition).
27
28
  - **Smarter than a linter, cheaper than an agent.** It can tell whether a comment matches the code under it, whether a function belongs in its file, whether a file is about one thing. It answers in a fraction of the time and cost of a subagent reading the same file.
28
29
  - **Signals, not problems.** A finding is advice to look, not a call to action. Hand findings to an agent or a reviewer, who reads the code and decides whether there is anything to fix.
29
30
  - **Not deterministic.** The answer is a probability; it can move a few points between runs. Results are not strict and should not be read as proof.
@@ -49,9 +50,9 @@ lintobot --diff origin/main # what this branch changes: on a pull request
49
50
  lintobot --staged # what is staged: in a pre-commit hook
50
51
  ```
51
52
 
52
- Only changed files that the config's patterns match are checked, deleted ones are left out, and no change means no file is checked. See [Changed files only](#changed-files-only).
53
+ Only the lines a change adds are checked, in files the config's patterns match; no change means nothing is checked. See [Changed code only](#changed-code-only).
53
54
 
54
- > Early version. Yes/no rules, formulas, file facts, context and large-file handling work. Composition rules, checking only the changed lines of a file, and calibration are specified in [SPEC.md](SPEC.md) but not built yet.
55
+ > Early version. Yes/no rules, formulas, file facts, context and large-file handling work. Calibration and the other items of the roadmap are specified in [SPEC.md](SPEC.md) but not built yet.
55
56
 
56
57
  ## Install
57
58
 
@@ -181,6 +182,84 @@ The config is [scripted-yaml](https://www.npmjs.com/package/scripted-yaml): a ke
181
182
 
182
183
  `file` has `path`, `dir`, `name`, `ext`, `lines`, `code_lines`, `comment_lines`, `blank_lines`, `longest_line`, `max_depth`, `complexity`, and the lists `imports` and `exports`. A rule whose formulas never read `confidence` makes no model call.
183
184
 
185
+ ### Composition
186
+
187
+ A composition measures what a file is made of. You name the categories; the result is the share of the file in each, and formulas over `share` say which mix is wrong:
188
+
189
+ ```yaml
190
+ files:
191
+ - pattern: "app/controllers/**/*.rb"
192
+ rules:
193
+ - composition:
194
+ code: Ordinary Ruby logic
195
+ sql: Raw SQL strings or query fragments
196
+ template: HTML or other markup built in code
197
+ error!: share.sql > 0.1
198
+ warning!: share.template > 0.05
199
+ ```
200
+
201
+ ```
202
+ app/controllers/orders_controller.rb
203
+ ❌ Ordinary Ruby logic (51%) sql|template sql 31% > 10% lines 31–45
204
+
205
+ app/controllers/users_controller.rb
206
+ ✅ Ordinary Ruby logic (100%) sql|template
207
+ ```
208
+
209
+ One line per composition: the largest category, in the words of its description (its name when it has none), with its percent, then the names of the other categories, separated by `|`. The same names joined by `|` are the composition's name in the records and for `--rule`, unless it has an `id`. A failed one adds the comparison that is true and the lines where that category is. All the shares are in the `json` and `jsonl` record.
210
+
211
+ Every key is a category and its value an optional description for the model; a name that says enough needs none. `other` is always added, so a piece is never forced into a wrong category: do not add your own `neither` or `none`. Formulas read it like any category (`error!: share.other > 0.3`), and writing `other: <description>` yourself tells the model what belongs there. Category names are identifiers: `raw_sql`, not `raw-sql`.
212
+
213
+ The file is cut into pieces of about 15 lines and each is asked which category it mostly is. A share is the model's probabilities weighted by the size of the piece, so a piece that is half SQL counts as half. Shares run from 0 to 1 and add up to 1.
214
+
215
+ | Key beside the categories | Meaning |
216
+ |---|---|
217
+ | `error!`, `warning!` | Formulas over `share.<category>` and `file`. Without either, the composition is only shown and never fails |
218
+ | `$if!`, `except` | Which files it applies to, as on a rule |
219
+ | `max_lines` | Piece size, 5 or more (default 15). Smaller pieces give finer shares for more calls |
220
+ | `ask` | The question to send instead of "which of these is most of the code?" |
221
+ | `id` | Short name, printed and usable with `--rule` |
222
+ | `context` | Extra material, as on a rule |
223
+
224
+ A composition has no `confidence` and no thresholds: `share.sql > 0.1` is the rule. Useful shapes: `share.exports > 0.9 and file.lines > 300`, `share.assertions < 0.1` for a test file, `share.state > 0.4 and share.template < 0.3` for a component.
225
+
226
+ #### The purpose of a file
227
+
228
+ The categories do not have to be kinds of code. Make them the **purposes** a file may have, described as statements about the file, and a composition tells you what each file is for, and fails the ones in the wrong place:
229
+
230
+ ```yaml
231
+ files:
232
+ - pattern: "app/controllers/projects/**/*.rb"
233
+ rules:
234
+ - composition:
235
+ project: focused on a single Project and has a @project instance
236
+ nonproject: works across projects or without any project
237
+ error!: share.project < 0.7
238
+
239
+ - pattern: "app/jobs/**_job.rb"
240
+ rules:
241
+ - composition:
242
+ bulk: processes many records in batches
243
+ external: calls an outside service or API
244
+ io: reads or writes files
245
+ error!: share.other > 0.7 # a job that does none of the things a job is for
246
+ ```
247
+
248
+ ```
249
+ app/controllers/projects/runs_controller.rb
250
+ ✅ focused on a single Project and has a @project instance (93%) nonproject
251
+
252
+ app/controllers/projects/search_controller.rb
253
+ ❌ works across projects or without any project (64%) project project 31% < 70%
254
+
255
+ app/jobs/cleanup_job.rb
256
+ ❌ other (94%) bulk|external|io other 94% > 70% lines 1–47
257
+ ```
258
+
259
+ The report reads as a sentence about the file because the largest category is printed by its description, so write descriptions that way. Two ways to fail a wrong purpose: require the right one (`share.project < 0.7`) or cap the catch-all (`share.other > 0.7`). With no formula at all you get a map of what every file is for and nothing fails.
260
+
261
+ It is always listed in the report, passed or not; `--quiet` drops the passed ones. The `json` and `jsonl` record has `"type":"composition"` with `share`, and `areas`: per category, the lines of the pieces that are mostly it. One call is made per piece, so a long file costs more calls than a check does. With `--diff`, a composition is measured only on new files: added lines alone cannot say what a file is made of. It needs a provider on the TypeSafe wire (OpenRouter, AI/ML API, TypeSafe); the Vercel gateway is not supported for it yet.
262
+
184
263
  ### Context
185
264
 
186
265
  Named extra material sent beside the code, at the top of the config, on a `files` entry, or on one rule:
@@ -233,12 +312,12 @@ Other variables: `LINTOBOT_ERROR`, `LINTOBOT_WARNING`, `LINTOBOT_PART_LINES`, `L
233
312
 
234
313
  ```
235
314
  lintobot [files...] files, folders or globs; everything in lintobot.yml when omitted
236
- --format pretty|json|jsonl pretty on a terminal, jsonl when piped
315
+ --format pretty|json|jsonl|markdown pretty on a terminal, jsonl when piped
237
316
  -o, --output <file>
238
317
  --files <path> relative to the project; repeatable
239
318
  --rule <id or sentence> a rule or an info item; repeatable
240
- --diff [ref] only changed files: since the branch left <ref>, or since the last commit
241
- --staged only files staged for the next commit
319
+ --diff [ref] only added lines: since the branch left <ref>, or since the last commit
320
+ --staged only lines staged for the next commit
242
321
  --dry-run
243
322
  --quiet problems only
244
323
  --no-cache answers are cached in .lintobot/cache/
@@ -265,16 +344,59 @@ Naming a folder or file narrows the run to the files in it that the config's pat
265
344
 
266
345
  Exit codes: `0` clean · `1` errors · `2` bad usage or config · `3` model unreachable or checks skipped.
267
346
 
268
- ### Changed files only
347
+ ### Markdown report
348
+
349
+ `--format markdown` writes a report for a pull request comment or a CI job summary. Each file is one collapsed line with the mark of its worst result; opening it shows a table of its checks. Files with problems come first.
350
+
351
+ ```bash
352
+ lintobot --diff origin/main --format markdown -o lintobot.md
353
+ ```
354
+
355
+ ```markdown
356
+ ### ❌ lintobot: 3 files · 1 error · 2 warnings
357
+
358
+ <details>
359
+ <summary>❌ <code>src/config/load.ts</code> — 1 error, 1 warning · 491 lines</summary>
360
+
361
+ *Reads or writes files on disk*
362
+
363
+ | | Check | Confidence | Lines |
364
+ | --- | --- | ---: | --- |
365
+ | ✅ | no secret values exposed | 4–5% | |
366
+ | ❌ | **no magic numbers** | 97% | 1–491 |
367
+ | ⚠️ | **no global state polluted** | 71% | 295–491 |
368
+
369
+ </details>
370
+
371
+ <details>
372
+ <summary>✅ <code>src/engine/pool.ts</code> — 7 rules</summary>
373
+ ...
374
+ ```
375
+
376
+ With `--quiet`, clean files and passed checks are left out. In GitHub Actions, `lintobot --format markdown >> "$GITHUB_STEP_SUMMARY"` puts it on the run's page.
377
+
378
+ ### Changed code only
269
379
 
270
380
  ```bash
271
- lintobot --diff # edited, staged and new untracked files since the last commit
272
- lintobot --diff origin/main # everything since this branch left origin/main, uncommitted work included
273
- lintobot --staged # what `git commit` would take
274
- lintobot app/jobs --diff main # changed files inside one folder
381
+ lintobot --diff # lines added since the last commit, staged or not, and new untracked files
382
+ lintobot --diff origin/main # lines added since this branch left origin/main, uncommitted work included
383
+ lintobot --staged # lines `git commit` would add
384
+ lintobot app/jobs --diff main # the same, inside one folder
385
+ ```
386
+
387
+ The ref is a branch, tag or commit. The changed files are narrowed by the config's patterns and by any paths you name; deleted files are left out. When nothing changed, nothing is checked and the exit code is `0`. It works from any folder of the repository, and when the project is a subfolder of it.
388
+
389
+ Only the lines the change **adds** are sent to the model, so a problem that was already in the file stays quiet:
390
+
391
+ ```
392
+ src/engine/cache.ts (3 added lines)
393
+ ❌ no magic numbers 96% lines 41–43
275
394
  ```
276
395
 
277
- The ref is a branch, tag or commit. The changed files are narrowed by the config's patterns and by any paths you name; deleted files are left out; a whole changed file is checked, not only its changed lines. When nothing changed, nothing is checked and the exit code is `0`. It works from any folder of the repository, and when the project is a subfolder of it.
396
+ - A changed line counts as added; a file that only lost lines is not checked. A new file is checked whole.
397
+ - Findings name the added lines they come from.
398
+ - Rules marked `whole: true` and rules settled from facts alone (`warning!: file.lines > 500`) are not run on an existing file: added lines cannot answer for the whole file. Conditions such as `$if!: file.lines > 100` still see the whole file.
399
+ - A rule that says what a file must have ("has a @project attribute") reads a few added lines as a file without it. Mark such rules `whole: true`; rules about what must not appear ("no …") work on added lines as they are.
278
400
 
279
401
  `--diff <ref>` needs the commit where the branch left the ref. A shallow clone does not have it: in GitHub Actions set `fetch-depth: 0` on the checkout step.
280
402
 
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ import { Command, CommanderError } from "commander";
7
7
  // package.json
8
8
  var package_default = {
9
9
  name: "lintobot",
10
- version: "0.2.0",
10
+ version: "0.2.2",
11
11
  description: "AI code linter: rules are plain-language sentences answered by a decision model (Jev)",
12
12
  keywords: [
13
13
  "lint",
@@ -437,12 +437,54 @@ var RECOMMENDED = `
437
437
  $if!: file.complexity > 15
438
438
  `;
439
439
 
440
+ // src/rules/question.ts
441
+ var SCOPE = "In the `code` section, ";
442
+ function toQuestion(sentence, ask, statement = false) {
443
+ const text = sentence.trim().replace(/[.!]+$/, "");
444
+ if (statement)
445
+ return { instructions: ask ?? aboutCode(text), detects: true };
446
+ const detects = /^no\s/i.test(text);
447
+ if (ask)
448
+ return { instructions: ask, detects };
449
+ const instructions = detects ? `${SCOPE}does the code contain ${text.replace(/^no\s+/i, "")}?` : `${SCOPE}is it true that ${text}?`;
450
+ return { instructions, detects };
451
+ }
452
+ function aboutCode(statement) {
453
+ const [, verb, rest] = /^(is|are|has|have)\s+(.*)$/i.exec(statement) ?? [];
454
+ if (!verb)
455
+ return `${SCOPE}does the code ${statement}?`;
456
+ return /^(is|are)$/i.test(verb) ? `${SCOPE}is the code ${rest}?` : `${SCOPE}does the code have ${rest}?`;
457
+ }
458
+ var OTHER = "other";
459
+ var OTHER_DESCRIPTION = "None of the other options";
460
+ function compositionQuestion(categories, ask) {
461
+ return {
462
+ instructions: ask ?? `${SCOPE}which of these is most of the code?`,
463
+ options: { ...categories, ...!(OTHER in categories) && { [OTHER]: OTHER_DESCRIPTION } }
464
+ };
465
+ }
466
+ var violation = (asked, yes) => asked.detects ? yes : 1 - yes;
467
+ function questionKey(name, taken) {
468
+ let base = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 48) || "rule";
469
+ if (/^\d/.test(base))
470
+ base = `r_${base}`;
471
+ let key = base;
472
+ for (let n = 2;taken.has(key); n++)
473
+ key = `${base}_${n}`;
474
+ taken.add(key);
475
+ return key;
476
+ }
477
+
440
478
  // src/config/load.ts
441
479
  var CONFIG_FILE = "lintobot.yml";
442
- var RESERVED2 = ["file", "env", "confidence"];
480
+ var RESERVED2 = ["file", "env", "confidence", "share"];
443
481
  var OWN_KEYS = ["$dsl", "model", "defaults", "ignore", "files", "parts", "context"];
444
482
  var COMPUTED = ["error", "warning", "error!", "warning!", "show", "show!", "$if!", "$unless!"];
445
483
  var MIN_PART_LINES = 20;
484
+ var COMPOSITION_KEYS = ["error!", "warning!", "$if!", "$unless!", "id", "ask", "context", "except", "max_lines"];
485
+ var COMPOSITION_LINES = 15;
486
+ var MIN_COMPOSITION_LINES = 5;
487
+ var CATEGORY_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
446
488
  var isMap3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
447
489
  var itemsOf = (entry) => [...entry.rules, ...entry.info];
448
490
  var sentences = (value) => (value ?? "").split(/[\n;]/).map((item) => item.trim()).filter(Boolean);
@@ -604,13 +646,15 @@ function rulesOf(items, config, where, info = false) {
604
646
  if (keys.length !== 1)
605
647
  throw new ConfigError(`${where}: a rule is a sentence, or a sentence with its options under it`);
606
648
  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
649
  const options = item[sentence] ?? {};
612
650
  if (!isMap3(options))
613
651
  throw new ConfigError(`${where}: the options of "${sentence}" must be a map`);
652
+ if (sentence === "composition") {
653
+ if (info)
654
+ throw new ConfigError(`${where}: a composition belongs under rules; without error! or warning! it only shows what the file is made of`);
655
+ rules.push(compositionOf(options, where));
656
+ continue;
657
+ }
614
658
  rules.push(ruleOf(sentence, options, where, info));
615
659
  }
616
660
  return rules;
@@ -650,6 +694,47 @@ function ruleOf(sentence, options, where, info) {
650
694
  options: Object.fromEntries(Object.entries(options).filter(([key]) => COMPUTED.includes(key)))
651
695
  };
652
696
  }
697
+ function compositionOf(options, where) {
698
+ const at = `${where}: composition`;
699
+ for (const key of ["error", "warning"]) {
700
+ if (key in options)
701
+ throw new ConfigError(`${at}: a composition has no thresholds; write a formula, for example ${key}!: share.sql > 0.1 (a category cannot be called ${key})`);
702
+ }
703
+ const names = Object.keys(options).filter((key) => !COMPOSITION_KEYS.includes(key));
704
+ const categories = {};
705
+ for (const name of names) {
706
+ if (!CATEGORY_NAME.test(name))
707
+ throw new ConfigError(`${at}: "${name}" is not a category name; use letters, digits and _ (raw_sql, not raw-sql)`);
708
+ const description = options[name];
709
+ if (description !== null && typeof description !== "string")
710
+ throw new ConfigError(`${at}: the description of "${name}" must be text, or left empty`);
711
+ categories[name] = description ?? "";
712
+ }
713
+ if (!names.length)
714
+ throw new ConfigError(`${at} needs at least one category`);
715
+ for (const key of ["id", "ask"]) {
716
+ if (options[key] !== undefined && typeof options[key] !== "string")
717
+ throw new ConfigError(`${at}: ${key} must be text`);
718
+ }
719
+ const { max_lines = COMPOSITION_LINES } = options;
720
+ if (!Number.isInteger(max_lines) || max_lines < MIN_COMPOSITION_LINES) {
721
+ throw new ConfigError(`${at}: max_lines must be a whole number, ${MIN_COMPOSITION_LINES} or more`);
722
+ }
723
+ const question = compositionQuestion(categories, options.ask);
724
+ return {
725
+ sentence: names.join("|"),
726
+ info: false,
727
+ id: options.id,
728
+ ask: options.ask,
729
+ whole: true,
730
+ except: strings(options.except, `${at}: except`),
731
+ context: contextOf(options.context, at),
732
+ asksModel: true,
733
+ formulas: {},
734
+ options: Object.fromEntries(Object.entries(options).filter(([key]) => COMPUTED.includes(key))),
735
+ composition: { categories: question.options, maxLines: max_lines }
736
+ };
737
+ }
653
738
  function criteriaOf(value, at) {
654
739
  if (value === undefined)
655
740
  return;
@@ -682,7 +767,8 @@ ${errors.map((problem) => ` ${named(problem)}`).join(`
682
767
  `)}`);
683
768
  return problems.map(named);
684
769
  }
685
- function documentFor(config, entries, file, confidence) {
770
+ function documentFor(config, entries, file, confidence, shares) {
771
+ const measured = (rule) => rule.composition ? { share: shares?.get(rule) ?? Object.fromEntries(Object.keys(rule.composition.categories).map((name) => [name, 0])) } : { confidence: confidence(rule) };
686
772
  const data = {
687
773
  ...config.top,
688
774
  file: literal(file),
@@ -690,7 +776,7 @@ function documentFor(config, entries, file, confidence) {
690
776
  files: entries.map((entry, n) => ({
691
777
  ...entry.conditions,
692
778
  n,
693
- rules: itemsOf(entry).map((rule, i) => ({ [`r${i}`]: { ...rule.options, confidence: confidence(rule) } }))
779
+ rules: itemsOf(entry).map((rule, i) => ({ [`r${i}`]: { ...rule.options, ...measured(rule) } }))
694
780
  }))
695
781
  };
696
782
  try {
@@ -726,6 +812,15 @@ function inspectFormulas(config) {
726
812
  throw new ConfigError(`${config.file}: "${rule.sentence}": ${key}! decides before the model is asked, so it cannot read confidence`);
727
813
  }
728
814
  }
815
+ if (rule.composition) {
816
+ for (const key of ["$if", "$unless"]) {
817
+ if (loaded[key]?.reads.some((name) => name === "share" || name.startsWith("share."))) {
818
+ throw new ConfigError(`${config.file}: composition "${rule.sentence}": ${key}! decides before the model is asked, so it cannot read share`);
819
+ }
820
+ }
821
+ rule.formulas = { error: rule.options["error!"], warning: rule.options["warning!"] };
822
+ return;
823
+ }
729
824
  const levels = rule.info ? ["show"] : ["error", "warning"];
730
825
  const formulas = levels.map((level) => rule.options[`${level}!`] && loaded[level]).filter(Boolean);
731
826
  rule.formulas = Object.fromEntries(levels.map((level) => [level, rule.options[`${level}!`]]));
@@ -743,13 +838,13 @@ function matchesAny(globs, file) {
743
838
  return matchers.get(globs)(file);
744
839
  }
745
840
  var matches = (entry, file) => (!entry.patterns || matchesAny(entry.patterns, file)) && !matchesAny(entry.except, file);
746
- function resolveRules(config, file, confidences) {
841
+ function resolveRules(config, file, confidences, shares) {
747
842
  const entries = config.entries.filter((entry) => matches(entry, file.path));
748
843
  if (!entries.length)
749
844
  return [];
750
845
  let resolved;
751
846
  try {
752
- resolved = documentFor(config, entries, file, (rule) => confidences?.get(rule) ?? 0).resolve({ vars: {} });
847
+ resolved = documentFor(config, entries, file, (rule) => confidences?.get(rule) ?? 0, shares).resolve({ vars: {} });
753
848
  } catch (error) {
754
849
  throw asConfigError(error, config);
755
850
  }
@@ -777,7 +872,7 @@ class Cache {
777
872
  this.dir = dir;
778
873
  }
779
874
  static key(model, question, state) {
780
- return createHash("sha256").update(JSON.stringify([model, question.instructions, question.criteria ?? null, state])).digest("hex");
875
+ return createHash("sha256").update(JSON.stringify([model, question.instructions, question.criteria ?? null, state, ...question.options ? [question.options] : []])).digest("hex");
781
876
  }
782
877
  file(key) {
783
878
  return path4.join(this.dir, key.slice(0, 2), `${key.slice(2)}.json`);
@@ -891,6 +986,31 @@ function outline(text) {
891
986
  }
892
987
  return entries;
893
988
  }
989
+ var GAP = `...
990
+ `;
991
+ function packAdded(hunks, maxBytes, maxLines = Infinity) {
992
+ const units = hunks.flatMap((hunk) => {
993
+ const cut = cutPieces(hunk.text, maxBytes, maxLines);
994
+ return lineRanges(cut).map((range, i) => ({ text: cut[i], start: range.start + hunk.start - 1, end: range.end + hunk.start - 1 }));
995
+ });
996
+ const pieces = [];
997
+ for (const unit of units) {
998
+ const last = pieces.at(-1);
999
+ const next = last?.added.at(-1)?.end === unit.start - 1;
1000
+ const more = (next ? "" : GAP) + unit.text;
1001
+ if (last && cost(last.code + more) <= maxBytes && last.lines + lineCount(unit.text) <= maxLines) {
1002
+ last.code += more;
1003
+ last.lines += lineCount(unit.text);
1004
+ if (next)
1005
+ last.added.at(-1).end = unit.end;
1006
+ else
1007
+ last.added.push({ start: unit.start, end: unit.end });
1008
+ } else {
1009
+ pieces.push({ code: unit.text, added: [{ start: unit.start, end: unit.end }], lines: lineCount(unit.text) });
1010
+ }
1011
+ }
1012
+ return pieces.map(({ code, added }) => ({ code, added }));
1013
+ }
894
1014
 
895
1015
  // src/engine/context.ts
896
1016
  import { spawnSync } from "node:child_process";
@@ -953,53 +1073,34 @@ function load(entry, variables, config) {
953
1073
  return ran.stdout;
954
1074
  }
955
1075
 
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
1076
  // src/engine/plan.ts
987
1077
  var MIN_CODE_BYTES = 1000;
988
- function planFile(file, text, config, only = []) {
1078
+ function planFile(file, text, config, only = [], hunks) {
989
1079
  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)
1080
+ const applied = resolveRules(config, facts).filter(({ rule }) => !only.length || only.includes(rule.sentence) || rule.id !== undefined && only.includes(rule.id)).filter(({ rule }) => !hunks || rule.asksModel && !rule.whole);
1081
+ if (!applied.length || hunks?.length === 0)
992
1082
  return null;
993
1083
  const contextOf = contextFor(file, config);
994
1084
  const taken = new Set;
995
1085
  const unasked = [];
996
1086
  const groups = new Map;
1087
+ const mixes = new Map;
997
1088
  for (const item of applied.filter(({ rule }) => rule.asksModel)) {
998
1089
  const { sections, missing } = contextOf(item);
999
1090
  if (missing) {
1000
1091
  unasked.push({ applied: item, reason: missing });
1001
1092
  continue;
1002
1093
  }
1094
+ const { composition } = item.rule;
1095
+ if (composition) {
1096
+ const question = compositionQuestion(composition.categories, item.rule.ask);
1097
+ const group = JSON.stringify([sections, composition.maxLines]);
1098
+ if (!mixes.has(group))
1099
+ mixes.set(group, { sections, maxLines: composition.maxLines, planned: [] });
1100
+ const key = questionKey(item.rule.id ?? item.rule.sentence, taken);
1101
+ mixes.get(group).planned.push({ applied: item, key, asked: { instructions: question.instructions, detects: true }, question });
1102
+ continue;
1103
+ }
1003
1104
  const asked = toQuestion(item.rule.sentence, item.rule.ask, item.rule.info);
1004
1105
  const question = { instructions: asked.instructions, ...item.rule.criteria && { criteria: item.rule.criteria } };
1005
1106
  const maxLines = item.rule.maxLines ?? item.entry.maxLines ?? config.parts.maxLines;
@@ -1017,6 +1118,13 @@ function planFile(file, text, config, only = []) {
1017
1118
  const cuttings = new Map;
1018
1119
  for (const { sections, maxLines, planned } of groups.values()) {
1019
1120
  const state = { ...start, ...sections };
1121
+ if (hunks) {
1122
+ const packed = packAdded(hunks, room(state), maxLines);
1123
+ cuttings.set(JSON.stringify(packed.map((piece) => piece.added)), packed.length);
1124
+ for (const { code, added } of packed)
1125
+ calls.push({ state: { ...state, code }, planned, added });
1126
+ continue;
1127
+ }
1020
1128
  const pieces = cutPieces(text, room(state), maxLines);
1021
1129
  const ranges = lineRanges(pieces);
1022
1130
  cuttings.set(JSON.stringify(ranges), pieces.length);
@@ -1030,8 +1138,20 @@ function planFile(file, text, config, only = []) {
1030
1138
  calls.push({ state: { ...entire, code: head(text, room(entire)) }, planned: whole });
1031
1139
  }
1032
1140
  }
1141
+ for (const { sections, maxLines, planned } of mixes.values()) {
1142
+ const state = { ...about, ...sections };
1143
+ const pieces = cutPieces(text, room(state), maxLines);
1144
+ const ranges = lineRanges(pieces);
1145
+ pieces.forEach((code, i) => {
1146
+ const weight = code.split(`
1147
+ `).filter((line) => line.trim()).length;
1148
+ if (weight)
1149
+ calls.push({ state: { ...state, code }, planned, lines: ranges[i], weight });
1150
+ });
1151
+ }
1033
1152
  const [parts = 1] = cuttings.size > 1 ? [undefined] : cuttings.values();
1034
- return { file, facts, applied, calls, unasked, ...cuttings.size <= 1 && { parts } };
1153
+ const added = hunks?.reduce((sum, hunk) => sum + hunk.end - hunk.start + 1, 0);
1154
+ return { file, facts, applied, calls, unasked, ...cuttings.size <= 1 && { parts }, ...added !== undefined && { added } };
1035
1155
  }
1036
1156
  var callBytes = (call) => Buffer.byteLength(JSON.stringify(call.state)) + call.planned.reduce((sum, planned) => sum + Buffer.byteLength(JSON.stringify(planned.question)), 0);
1037
1157
 
@@ -1061,6 +1181,7 @@ var openaiResponse = z.object({
1061
1181
  provider_metadata: z.object({ gateway: z.object({ cost: z.coerce.number() }).partial() }).partial().optional()
1062
1182
  });
1063
1183
  var noul = z.object({ type: z.literal("noul"), noul: z.number().min(0).max(1) });
1184
+ var choice = z.object({ type: z.literal("choice"), probabilities: z.record(z.string(), z.number().min(0).max(1)) });
1064
1185
  var predicate = z.object({ type: z.literal("predicate"), name: z.string(), probability: z.number().min(0).max(1) });
1065
1186
  function requestBody(target, state, questions) {
1066
1187
  if (target.wire === "typesafe") {
@@ -1069,10 +1190,13 @@ function requestBody(target, state, questions) {
1069
1190
  state,
1070
1191
  questions: Object.fromEntries(Object.entries(questions).map(([key, q]) => [
1071
1192
  key,
1072
- { type: "noul", instructions: q.instructions, ...q.criteria && { criteria: q.criteria } }
1193
+ q.options ? { type: "choice", instructions: q.instructions, criteria: q.options } : { type: "noul", instructions: q.instructions, ...q.criteria && { criteria: q.criteria } }
1073
1194
  ]))
1074
1195
  };
1075
1196
  }
1197
+ if (Object.values(questions).some((q) => q.options)) {
1198
+ throw new ModelError(`composition rules are not supported through the ${target.provider} provider yet`);
1199
+ }
1076
1200
  return {
1077
1201
  model: target.model,
1078
1202
  input: typeof state === "string" ? state : JSON.stringify(state),
@@ -1098,6 +1222,9 @@ function parseResponse(target, data, keys) {
1098
1222
  const answer = noul.safeParse(body.answers[key]);
1099
1223
  if (answer.success)
1100
1224
  answers[key] = answer.data.noul;
1225
+ const picked = choice.safeParse(body.answers[key]);
1226
+ if (picked.success)
1227
+ answers[key] = picked.data.probabilities;
1101
1228
  }
1102
1229
  return { answers, usage: usage(body.usage), model: body.model ?? target.model };
1103
1230
  }
@@ -1260,21 +1387,70 @@ async function lintFile(file, run) {
1260
1387
  const text = fs5.readFileSync(file, "utf8");
1261
1388
  if (isBinary(text))
1262
1389
  return null;
1263
- const plan = planFile(file, text, run.config, run.only);
1390
+ const plan = planFile(file, text, run.config, run.only, run.added?.(file) ?? undefined);
1264
1391
  if (!plan)
1265
1392
  return null;
1266
1393
  const tallies = new Map(plan.unasked.map(({ applied, reason }) => [applied.rule, { missing: reason, parts: [] }]));
1267
1394
  await Promise.all(plan.calls.map((call) => ask(call, run, tallies)));
1395
+ const shares = new Map;
1396
+ for (const [rule, tally] of tallies) {
1397
+ if (rule.composition && tally.mix?.length && tally.missing === undefined)
1398
+ shares.set(rule, sharesOf(rule, tally.mix));
1399
+ }
1268
1400
  let applied = plan.applied;
1269
1401
  if (applied.some(({ rule }) => rule.formulas.error || rule.formulas.warning || rule.formulas.show)) {
1270
1402
  const confidences = new Map;
1271
1403
  for (const [rule, tally] of tallies)
1272
1404
  if (tally.confidence !== undefined)
1273
1405
  confidences.set(rule, tally.confidence);
1274
- const final = new Map(resolveRules(run.config, plan.facts, confidences).map((item) => [item.rule, item]));
1406
+ const final = new Map(resolveRules(run.config, plan.facts, confidences, shares).map((item) => [item.rule, item]));
1275
1407
  applied = applied.map((item) => final.get(item.rule) ?? item);
1276
1408
  }
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)) };
1409
+ const records = applied.map((item) => {
1410
+ if (item.rule.composition)
1411
+ return composition(file, item, tallies.get(item.rule), shares.get(item.rule));
1412
+ return (item.rule.info ? note : record)(file, item, tallies.get(item.rule), run.config);
1413
+ });
1414
+ return { file, lines: plan.facts.lines, parts: plan.parts, ...plan.added !== undefined && { added: plan.added }, records };
1415
+ }
1416
+ function sharesOf(rule, pieces) {
1417
+ const total = pieces.reduce((sum, piece) => sum + piece.weight, 0);
1418
+ const share = Object.fromEntries(Object.keys(rule.composition.categories).map((name) => [name, 0]));
1419
+ for (const piece of pieces) {
1420
+ const sum = Object.keys(share).reduce((all, name) => all + (piece.probabilities[name] ?? 0), 0);
1421
+ if (!sum)
1422
+ continue;
1423
+ for (const name of Object.keys(share))
1424
+ share[name] += (piece.probabilities[name] ?? 0) / sum * (piece.weight / total);
1425
+ }
1426
+ return Object.fromEntries(Object.entries(share).map(([name, value]) => [name, round(value)]));
1427
+ }
1428
+ var topPick = (piece) => Object.entries(piece.probabilities).reduce((best, entry) => entry[1] > best[1] ? entry : best)[0];
1429
+ function composition(file, applied, tally, share) {
1430
+ const { rule } = applied;
1431
+ const base = { type: "composition", file, rule: rule.sentence, ...rule.id && { id: rule.id } };
1432
+ const question = compositionQuestion(rule.composition.categories, rule.ask).instructions;
1433
+ if (!share || !tally?.mix) {
1434
+ return { ...base, severity: "skipped", question, ...tally?.model && { model: tally.model }, reason: tally?.missing ?? "the file has no code to ask about" };
1435
+ }
1436
+ const severity = applied.error === true ? "error" : applied.warning === true ? "warning" : "ok";
1437
+ const where = {};
1438
+ for (const name of Object.keys(share)) {
1439
+ const mostly = areas(tally.mix.map((piece) => ({ start: piece.start, end: piece.end, confidence: topPick(piece) === name ? 1 : 0 })), 1);
1440
+ if (mostly.length)
1441
+ where[name] = mostly;
1442
+ }
1443
+ return {
1444
+ ...base,
1445
+ severity,
1446
+ share,
1447
+ categories: rule.composition.categories,
1448
+ areas: where,
1449
+ pieces: tally.mix.length,
1450
+ question,
1451
+ ...severity !== "ok" && { formula: rule.formulas[severity] },
1452
+ ...tally.model && { model: tally.model }
1453
+ };
1278
1454
  }
1279
1455
  function record(file, applied, tally, config) {
1280
1456
  const { rule } = applied;
@@ -1324,15 +1500,23 @@ async function ask(call, run, tallies) {
1324
1500
  const tally = (rule) => tallies.get(rule) ?? tallies.set(rule, { parts: [] }).get(rule);
1325
1501
  const state = JSON.stringify(call.state);
1326
1502
  const pending = [];
1503
+ const count = (planned, answer, model) => {
1504
+ const into = tally(planned.applied.rule);
1505
+ if (typeof answer === "number")
1506
+ return tallyUp(into, violation(planned.asked, answer), model, call);
1507
+ into.model = model;
1508
+ (into.mix ??= []).push({ ...call.lines, weight: call.weight ?? 1, probabilities: answer });
1509
+ };
1327
1510
  for (const planned of call.planned) {
1328
1511
  const key = Cache.key(run.client.model, planned.question, state);
1329
1512
  const hit = run.cache?.get(key);
1330
- if (!hit) {
1513
+ const known = planned.question.options ? hit?.options : hit?.yes;
1514
+ if (!hit || known === undefined) {
1331
1515
  pending.push({ planned, key });
1332
1516
  continue;
1333
1517
  }
1334
1518
  run.stats.cached++;
1335
- tallyUp(tally(planned.applied.rule), violation(planned.asked, hit.yes), hit.model, call.lines);
1519
+ count(planned, known, hit.model);
1336
1520
  }
1337
1521
  if (!pending.length)
1338
1522
  return;
@@ -1349,13 +1533,14 @@ async function ask(call, run, tallies) {
1349
1533
  if (decision.usage.cost !== undefined)
1350
1534
  run.stats.cost = (run.stats.cost ?? 0) + decision.usage.cost;
1351
1535
  for (const { planned, key } of pending) {
1352
- const yes = decision.answers[planned.key];
1353
- if (yes === null || yes === undefined) {
1536
+ const answer = decision.answers[planned.key];
1537
+ const choice = planned.question.options !== undefined;
1538
+ if (answer === null || answer === undefined || typeof answer === "object" !== choice) {
1354
1539
  tally(planned.applied.rule).missing = "the model gave no answer";
1355
1540
  continue;
1356
1541
  }
1357
- run.cache?.set(key, { yes, model: decision.model });
1358
- tallyUp(tally(planned.applied.rule), violation(planned.asked, yes), decision.model, call.lines);
1542
+ run.cache?.set(key, typeof answer === "object" ? { options: answer, model: decision.model } : { yes: answer, model: decision.model });
1543
+ count(planned, answer, decision.model);
1359
1544
  }
1360
1545
  } catch (error) {
1361
1546
  const { status, message } = error;
@@ -1364,10 +1549,10 @@ async function ask(call, run, tallies) {
1364
1549
  fail(message);
1365
1550
  }
1366
1551
  }
1367
- function tallyUp(tally, confidence, model, lines) {
1552
+ function tallyUp(tally, confidence, model, call) {
1368
1553
  tally.confidence = Math.max(tally.confidence ?? 0, confidence);
1369
1554
  tally.model = model;
1370
- if (lines)
1555
+ for (const lines of call.added ?? (call.lines ? [call.lines] : []))
1371
1556
  tally.parts.push({ ...lines, confidence });
1372
1557
  }
1373
1558
  function areaThreshold(applied, defaults) {
@@ -1398,15 +1583,43 @@ function isRevision(ref) {
1398
1583
  return false;
1399
1584
  }
1400
1585
  }
1401
- function changedFiles(scope) {
1586
+ function addedLines(patch) {
1587
+ const body = patch.search(/^@@ /m);
1588
+ if (body < 0)
1589
+ return [];
1590
+ if (/^--- \/dev\/null$/m.test(patch.slice(0, body)))
1591
+ return null;
1592
+ const hunks = [];
1593
+ let lines;
1594
+ for (const line of patch.slice(body).split(`
1595
+ `)) {
1596
+ const [, start, count = "1"] = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line) ?? [];
1597
+ if (start) {
1598
+ lines = undefined;
1599
+ if (count === "0")
1600
+ continue;
1601
+ lines = [];
1602
+ hunks.push({ start: Number(start), end: Number(start) + Number(count) - 1, text: "" });
1603
+ } else if (lines && line.startsWith("+")) {
1604
+ lines.push(line.slice(1));
1605
+ hunks.at(-1).text = `${lines.join(`
1606
+ `)}
1607
+ `;
1608
+ }
1609
+ }
1610
+ return hunks;
1611
+ }
1612
+ function changes(scope) {
1402
1613
  try {
1403
1614
  git(["rev-parse", "--is-inside-work-tree"]);
1404
1615
  } catch {
1405
1616
  throw new GitError("--diff and --staged need a git repository", "Run inside the repository, or name the files instead");
1406
1617
  }
1407
1618
  const names = ["diff", "--name-only", "-z", "--relative", "--diff-filter=d"];
1619
+ const patch = ["diff", "-U0", "--no-color", "--no-ext-diff", "--relative"];
1620
+ const lines = (against) => (file) => addedLines(git([...patch, against, "--", file]));
1408
1621
  if (scope.staged)
1409
- return list(git([...names, "--cached", "--"]));
1622
+ return { files: list(git([...names, "--cached", "--"])), added: lines("--cached") };
1410
1623
  let base = "HEAD";
1411
1624
  if (scope.ref) {
1412
1625
  if (!isRevision(scope.ref))
@@ -1417,14 +1630,16 @@ function changedFiles(scope) {
1417
1630
  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
1631
  }
1419
1632
  }
1633
+ const untracked = list(git(["ls-files", "-z", "--others", "--exclude-standard"]));
1420
1634
  let tracked;
1421
1635
  try {
1422
1636
  tracked = list(git([...names, base, "--"]));
1423
1637
  } catch {
1424
- tracked = list(git(["ls-files", "-z"]));
1638
+ return { files: [...new Set([...list(git(["ls-files", "-z"])), ...untracked])].sort(), added: () => null };
1425
1639
  }
1426
- const untracked = list(git(["ls-files", "-z", "--others", "--exclude-standard"]));
1427
- return [...new Set([...tracked, ...untracked])].sort();
1640
+ const fresh = new Set(untracked);
1641
+ const added = lines(base);
1642
+ return { files: [...new Set([...tracked, ...untracked])].sort(), added: (file) => fresh.has(file) ? null : added(file) };
1428
1643
  }
1429
1644
 
1430
1645
  // src/model/providers.ts
@@ -1482,11 +1697,22 @@ import pc from "picocolors";
1482
1697
  var COLUMN = 56;
1483
1698
  var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1484
1699
  var tokens = (n) => n < 1000 ? String(n) : `${Math.round(n / 1000)}k`;
1700
+ var span = (lines) => lines.start === lines.end ? `${lines.start}` : `${lines.start}–${lines.end}`;
1485
1701
  var percent = (confidence) => confidence === undefined ? "" : `${Math.round(confidence * 100)}%`;
1702
+ var COMPARISON = /share\.(\w+)\s*(>=|<=|>|<)\s*(\d*\.?\d+)/g;
1703
+ var holds = (left, sign, right) => sign === ">" ? left > right : sign === ">=" ? left >= right : sign === "<" ? left < right : left <= right;
1704
+ function reasons(formula, share) {
1705
+ const found = [...(formula ?? "").matchAll(COMPARISON)].filter(([, name, sign, limit]) => (name in share) && holds(share[name], sign, Number(limit)));
1706
+ return found.map(([, name, sign, limit]) => {
1707
+ const digits = Math.round(share[name] * 100) === Math.round(Number(limit) * 100) ? 1 : 0;
1708
+ const value = `${(share[name] * 100).toFixed(digits)}%`;
1709
+ return { text: `${name} ${value} ${sign} ${percent(Number(limit))}`, category: name, over: sign.startsWith(">") };
1710
+ });
1711
+ }
1486
1712
  function prettyReporter(write, options = {}) {
1487
1713
  const color = pc.createColors(options.color ?? false);
1488
1714
  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(", ")}` : "";
1715
+ const place = (record) => record.areas?.length ? ` ${record.areas.length === 1 && record.areas[0].start === record.areas[0].end ? "line" : "lines"} ${record.areas.map(span).join(", ")}` : "";
1490
1716
  const noteLabel = (record) => record.id ? `${record.statement} (${record.id})` : record.statement;
1491
1717
  function noteLine(records) {
1492
1718
  const text = records.map(noteLabel).join(", ");
@@ -1506,22 +1732,43 @@ function prettyReporter(write, options = {}) {
1506
1732
  return row("✅", label, record.min === undefined ? "" : range(record.min, record.max ?? record.min));
1507
1733
  }
1508
1734
  }
1735
+ function mix(record) {
1736
+ const id = record.id ? ` (${record.id})` : "";
1737
+ if (record.severity === "skipped" || !record.share)
1738
+ return `${row("⏭️ ", `${record.rule}${id}`, "")} ${color.dim(`skipped: ${record.reason}`)}`;
1739
+ const { share } = record;
1740
+ const names = Object.keys(share);
1741
+ const top = names.reduce((best, name) => share[name] > share[best] ? name : best);
1742
+ const meaning = record.categories?.[top];
1743
+ const title = meaning && !(top === OTHER && meaning === OTHER_DESCRIPTION) ? meaning : top;
1744
+ const others = names.filter((name) => name !== top && name !== OTHER).join("|");
1745
+ const line = (icon, paint = (text) => text) => ` ${icon} ${paint(`${title} (${percent(share[top])})`)}${others && ` ${color.dim(others)}`}${id}`;
1746
+ if (record.severity === "ok")
1747
+ return line("✅");
1748
+ const why = reasons(record.formula, share);
1749
+ const said = why.length ? why.map((reason) => reason.text).join(", ") : record.formula ?? "";
1750
+ const places = why.filter((reason) => reason.over && record.areas?.[reason.category]?.length).map((reason) => ` lines ${record.areas[reason.category].map(span).join(", ")}`);
1751
+ const head = record.severity === "error" ? line("❌", color.red) : line("⚠️ ", color.yellow);
1752
+ return `${head} ${said}${places.length === 1 ? places[0] : ""}`;
1753
+ }
1509
1754
  return {
1510
- file({ file, lines, parts, records }) {
1755
+ file({ file, lines, parts, added, records }) {
1511
1756
  const checks = records.filter((record) => record.type === "check");
1512
1757
  const info = records.filter((record) => record.type === "info");
1513
1758
  const notes = noteLine(info.filter((record) => record.shown && !record.skipped && !options.quiet));
1514
1759
  const skipped = info.filter((record) => record.skipped).map((record) => `${row("⏭️ ", noteLabel(record), "")} ${color.dim(`skipped: ${record.reason}`)}`);
1515
1760
  const clean = checks.every((record) => record.severity === "ok");
1516
1761
  const collapsed = checks.length ? [` ✅ ${plural(checks.length, "rule")}`] : [];
1762
+ const mixes = records.filter((record) => record.type === "composition");
1517
1763
  const rows = [
1518
1764
  ...notes,
1519
1765
  ...clean && parts === 1 ? options.quiet ? [] : collapsed : checks.filter((record) => !options.quiet || record.severity !== "ok").map(line),
1766
+ ...mixes.filter((record) => !options.quiet || record.severity !== "ok").map(mix),
1520
1767
  ...skipped
1521
1768
  ];
1522
1769
  if (!rows.length)
1523
1770
  return;
1524
- const size = parts === undefined ? color.dim(` (${lines} lines)`) : parts > 1 ? color.dim(` (${lines} lines, ${parts} parts)`) : "";
1771
+ const size = added !== undefined ? color.dim(` (${plural(added, "added line")})`) : parts === undefined ? color.dim(` (${lines} lines)`) : parts > 1 ? color.dim(` (${lines} lines, ${parts} parts)`) : "";
1525
1772
  write(`${color.bold(file)}${size}
1526
1773
  ${rows.join(`
1527
1774
  `)}
@@ -1550,13 +1797,116 @@ function range(min, max) {
1550
1797
  return low === Math.round(max * 100) ? `${low}%` : `${low}–${percent(max)}`;
1551
1798
  }
1552
1799
 
1800
+ // src/report/markdown.ts
1801
+ var ICON = { error: "❌", warning: "⚠️", skipped: "⏭️", ok: "✅" };
1802
+ var ORDER = ["error", "warning", "skipped", "ok"];
1803
+ var html = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1804
+ var plain = (text) => html(text).replace(/([\\`*_[\]#|~])/g, "\\$1").replace(/@(?=\w)/g, "@​");
1805
+ var markOf = (record) => record.type === "info" ? record.skipped ? "skipped" : "ok" : record.severity;
1806
+ var where = (areas) => areas?.length ? areas.map(span).join(", ") : "";
1807
+ var named = (text, id) => id ? `${plain(text)} (${plain(id)})` : plain(text);
1808
+ var code = (formula) => formula ? `\`${formula.replace(/\|/g, "\\|")}\`` : "";
1809
+ function check(record) {
1810
+ const label = named(record.rule, record.id);
1811
+ if (record.severity === "skipped")
1812
+ return ["⏭️", label, `skipped: ${plain(record.reason ?? "")}`, ""];
1813
+ if (record.severity === "ok")
1814
+ return ["✅", label, record.min === undefined ? percent(record.confidence) : range(record.min, record.max ?? record.min), ""];
1815
+ return [ICON[record.severity], `**${label}**`, record.confidence === undefined ? code(record.formula) : percent(record.confidence), where(record.areas)];
1816
+ }
1817
+ function composition2(record) {
1818
+ if (record.severity === "skipped" || !record.share)
1819
+ return ["⏭️", named(record.rule, record.id), `skipped: ${plain(record.reason ?? "")}`, ""];
1820
+ const { share } = record;
1821
+ const names = Object.keys(share);
1822
+ const top = names.reduce((best, name) => share[name] > share[best] ? name : best);
1823
+ const meaning = record.categories?.[top];
1824
+ const title = meaning && !(top === OTHER && meaning === OTHER_DESCRIPTION) ? meaning : top;
1825
+ const shares = names.filter((name) => name !== top).map((name) => `${plain(name)} ${percent(share[name])}`).join(", ");
1826
+ const text = `${named(title, record.id)} (${percent(share[top])})${shares && ` · ${shares}`}`;
1827
+ if (record.severity === "ok")
1828
+ return ["✅", text, "", ""];
1829
+ const why = reasons(record.formula, share);
1830
+ const said = why.length ? why.map((reason) => reason.text).join(", ") : code(record.formula);
1831
+ const places = why.filter((reason) => reason.over && record.areas?.[reason.category]?.length).map((reason) => where(record.areas[reason.category]));
1832
+ return [ICON[record.severity], `**${text}**`, said, places.length === 1 ? places[0] : ""];
1833
+ }
1834
+ function table(rows) {
1835
+ const cells = rows.some((row) => row[3]) ? rows : rows.map((row) => row.slice(0, 3));
1836
+ const head = ["", "Check", "Confidence", "Lines"].slice(0, cells[0].length);
1837
+ const align = ["---", "---", "---:", "---"].slice(0, head.length);
1838
+ return [head, align, ...cells].map((row) => `| ${row.join(" | ")} |`).join(`
1839
+ `);
1840
+ }
1841
+ function markdownReporter(write, options = {}) {
1842
+ const files = [];
1843
+ function block({ file, lines: total, parts, added, records }) {
1844
+ const marks = records.map(markOf);
1845
+ const mark = ORDER.find((candidate) => marks.includes(candidate)) ?? "ok";
1846
+ if (options.quiet && mark === "ok")
1847
+ return;
1848
+ const count = (wanted, word) => {
1849
+ const n = records.filter((record) => record.type !== "info" && record.severity === wanted).length;
1850
+ return n ? [plural(n, word)] : [];
1851
+ };
1852
+ const skipped = marks.filter((item) => item === "skipped").length;
1853
+ const rules = records.filter((record) => record.type !== "info").length;
1854
+ const found = [...count("error", "error"), ...count("warning", "warning"), ...skipped ? [`${skipped} skipped`] : []];
1855
+ const size = added !== undefined ? plural(added, "added line") : parts === undefined || parts > 1 ? `${total} lines` : "";
1856
+ const tail = [found.length ? found.join(", ") : plural(rules, "rule"), ...size ? [size] : []].join(" · ");
1857
+ const info = records.filter((record) => record.type === "info");
1858
+ const notes = options.quiet ? "" : info.filter((record) => record.shown && !record.skipped).map((record) => named(record.statement, record.id)).join(", ");
1859
+ const rows = [
1860
+ ...records.filter((record) => record.type === "check").map((record) => ({ record, text: check(record) })),
1861
+ ...records.filter((record) => record.type === "composition").map((record) => ({ record, text: composition2(record) })),
1862
+ ...info.filter((record) => record.skipped).map((record) => ({ record, text: ["⏭️", named(record.statement, record.id), `skipped: ${plain(record.reason ?? "")}`, ""] }))
1863
+ ].filter(({ record }) => !options.quiet || markOf(record) !== "ok");
1864
+ const body = [...notes ? [`*${notes[0].toUpperCase()}${notes.slice(1)}*`] : [], ...rows.length ? [table(rows.map((row) => row.text))] : []];
1865
+ const summary = `<summary>${ICON[mark]} <code>${html(file)}</code> — ${tail}</summary>`;
1866
+ files.push({ mark, text: `<details>
1867
+ ${summary}
1868
+
1869
+ ${body.join(`
1870
+
1871
+ `)}
1872
+
1873
+ </details>
1874
+ ` });
1875
+ }
1876
+ return {
1877
+ file: block,
1878
+ end(summary) {
1879
+ const worst = summary.errors ? "error" : summary.warnings ? "warning" : summary.skipped ? "skipped" : "ok";
1880
+ const totals = [
1881
+ plural(summary.files, "file"),
1882
+ plural(summary.errors, "error"),
1883
+ plural(summary.warnings, "warning"),
1884
+ ...summary.notes ? [plural(summary.notes, "note")] : [],
1885
+ ...summary.skipped ? [`${summary.skipped} skipped`] : []
1886
+ ];
1887
+ const spent = [plural(summary.calls, "call"), `${tokens(summary.tokens)} tokens`, ...summary.cost === undefined ? [] : [`$${summary.cost.toFixed(4)}`], `${(summary.ms / 1000).toFixed(1)}s`];
1888
+ write(`### ${ICON[worst]} lintobot: ${totals.join(" · ")}
1889
+
1890
+ `);
1891
+ for (const mark of ORDER)
1892
+ for (const file of files.filter((item) => item.mark === mark))
1893
+ write(`${file.text}
1894
+ `);
1895
+ write(`<sub>${spent.join(" · ")}</sub>
1896
+ `);
1897
+ }
1898
+ };
1899
+ }
1900
+
1553
1901
  // src/report/index.ts
1554
- var FORMATS = ["pretty", "json", "jsonl"];
1902
+ var FORMATS = ["pretty", "json", "jsonl", "markdown"];
1555
1903
  function createReporter(format, write, options) {
1556
1904
  if (format === "json")
1557
1905
  return jsonReporter(write, options);
1558
1906
  if (format === "jsonl")
1559
1907
  return jsonlReporter(write, options);
1908
+ if (format === "markdown")
1909
+ return markdownReporter(write, options);
1560
1910
  return prettyReporter(write, options);
1561
1911
  }
1562
1912
 
@@ -1575,10 +1925,15 @@ function reportPlan(plans, format, write) {
1575
1925
  const name = rule.info ? { info: rule.sentence } : { rule: rule.sentence };
1576
1926
  if (unasked)
1577
1927
  return { ...name, skipped: unasked.reason };
1928
+ if (rule.composition) {
1929
+ const { instructions, options } = compositionQuestion(rule.composition.categories, rule.ask);
1930
+ return { composition: rule.sentence, question: instructions, options: Object.keys(options) };
1931
+ }
1578
1932
  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
1933
  }),
1580
1934
  sent: plan.calls.map((call) => ({
1581
1935
  ...call.lines && { lines: call.lines },
1936
+ ...call.added && { added: call.added },
1582
1937
  bytes: callBytes(call),
1583
1938
  context: Object.fromEntries(Object.entries(call.state).filter(([name]) => !OWN_SECTIONS.includes(name)).map(([name, text]) => [name, Buffer.byteLength(text)])),
1584
1939
  rules: call.planned.map((planned) => planned.applied.rule.sentence)
@@ -1604,14 +1959,16 @@ function reportPlan(plans, format, write) {
1604
1959
  `);
1605
1960
  for (const call of record.sent) {
1606
1961
  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";
1962
+ const span = (lines) => lines.start === lines.end ? `${lines.start}` : `${lines.start}–${lines.end}`;
1963
+ const where = call.added ? `added lines ${call.added.map(span).join(", ")}` : call.lines ? `lines ${span(call.lines)}` : "whole file";
1608
1964
  write(` ${where} · ${call.bytes} bytes · ${plural2(call.rules.length, "question")}${context && ` · context: ${context}`}
1609
1965
  `);
1610
1966
  }
1611
1967
  for (const rule of record.rules) {
1612
1968
  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}
1969
+ const name = "composition" in rule ? `composition: ${rule.composition}` : ("info" in rule) ? `info: ${rule.info}` : rule.rule;
1970
+ write(` ${name}
1971
+ ${detail}${"options" in rule && rule.options ? ` [${rule.options.join(", ")}]` : ""}
1615
1972
  `);
1616
1973
  }
1617
1974
  write(`
@@ -1636,6 +1993,7 @@ A linter whose rules are plain sentences: \`lintobot.yml\` describes what good c
1636
1993
  - **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
1994
  - **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
1995
  - **Not deterministic.** The same file can score a few points differently between runs, and the scores are not calibrated. Nothing here is strict.
1996
+ - **It can say what a file is for.** A \`composition\` names the purposes a file may have, reports which one each file serves, and fails the file with the wrong one.
1639
1997
  - **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
1998
  - **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
1999
 
@@ -1648,8 +2006,8 @@ lintobot # every file matched by lintobot.yml
1648
2006
  lintobot app/jobs # only this folder or file
1649
2007
  lintobot src --rule "no magic numbers"
1650
2008
  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
2009
+ lintobot --diff # only lines added since the last commit (a new file whole)
2010
+ lintobot --diff origin/main # only lines this branch adds
1653
2011
  \`\`\`
1654
2012
 
1655
2013
  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.
@@ -1683,6 +2041,32 @@ files:
1683
2041
  - \`whole: true\`: the rule is about the file as a whole
1684
2042
  - 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
2043
 
2044
+ A \`composition\` measures what a file is made of. Each key is a category with an optional description; formulas over \`share.<category>\` (0 to 1) decide when the mix is wrong. \`other\` is always added and readable as \`share.other\`. With no formula it is only shown:
2045
+
2046
+ \`\`\`yaml
2047
+ - composition:
2048
+ code:
2049
+ sql: Raw SQL strings or query fragments
2050
+ error!: share.sql > 0.1
2051
+ \`\`\`
2052
+
2053
+ The strongest use is the **purpose of a file**: make the categories the purposes a file in this folder may have, each described as a statement about the file, and fail the file that serves the wrong one.
2054
+
2055
+ \`\`\`yaml
2056
+ - pattern: "app/controllers/projects/**/*.rb"
2057
+ rules:
2058
+ - composition:
2059
+ project: focused on a single Project and has a @project instance
2060
+ nonproject: works across projects or without any project
2061
+ error!: share.project < 0.7 # or cap the catch-all: share.other > 0.7
2062
+ \`\`\`
2063
+
2064
+ \`\`\`
2065
+ ❌ works across projects or without any project (64%) project project 31% < 70%
2066
+ \`\`\`
2067
+
2068
+ The report prints one line: the description of the largest category with its percent, the names of the others and, when it fails, the comparison that is true and the lines where that category is. Every share is in the \`jsonl\` record, so write descriptions that read well as a statement about the file.
2069
+
1686
2070
  A good start for any code file is a few basic checks, then the project's own intentions on top:
1687
2071
 
1688
2072
  \`\`\`yaml
@@ -1915,7 +2299,8 @@ async function main(args, flags) {
1915
2299
  process.stderr.write(`warning: ${warning}
1916
2300
  `);
1917
2301
  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;
2302
+ const change = flags.diff || flags.staged ? changes({ ref: typeof flags.diff === "string" ? flags.diff : undefined, staged: flags.staged }) : null;
2303
+ const changed = change && new Set(change.files);
1919
2304
  if (!fromConfig && !args.length && !changed) {
1920
2305
  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
2306
  }
@@ -1925,7 +2310,7 @@ async function main(args, flags) {
1925
2310
  const write = flags.output ? (text) => void chunks.push(text) : (text) => void process.stdout.write(text);
1926
2311
  const save = () => flags.output && fs6.writeFileSync(flags.output, chunks.join(""));
1927
2312
  if (flags.dryRun) {
1928
- const plans = files.flatMap((file) => planFile(file, fs6.readFileSync(file, "utf8"), config, flags.rule) ?? []);
2313
+ const plans = files.flatMap((file) => planFile(file, fs6.readFileSync(file, "utf8"), config, flags.rule, change?.added(file) ?? undefined) ?? []);
1929
2314
  reportPlan(plans, format, write);
1930
2315
  save();
1931
2316
  return EXIT.clean;
@@ -1940,7 +2325,7 @@ async function main(args, flags) {
1940
2325
  };
1941
2326
  const cache = flags.cache ? new Cache(env.LINTOBOT_CACHE_DIR || ".lintobot/cache") : undefined;
1942
2327
  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);
2328
+ const summary = await lint(files, { config, client, cache, only: flags.rule, added: change?.added }, reporter);
1944
2329
  save();
1945
2330
  if (summary.errors > 0 || maxWarnings !== undefined && summary.warnings > maxWarnings)
1946
2331
  return EXIT.problems;
@@ -1971,12 +2356,12 @@ What to expect:
1971
2356
  raise it or set it to false to keep it as a hint.
1972
2357
  It checks what a linter cannot (a comment matching its code, a function belonging in its
1973
2358
  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
2359
+ lintobot --diff lines added since the last commit
2360
+ lintobot --diff origin/main lines this branch adds
1976
2361
  Rules that must hold exactly belong in a real linter: the linto-lint skill moves them
1977
2362
  (lintobot skill --install).
1978
2363
  `;
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) => {
2364
+ 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 lines added since the branch left <ref> (a branch, tag or commit), uncommitted and new files included; without <ref>, since the last commit").option("--staged", "only lines 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
2365
  process.exitCode = await main(args, flags);
1981
2366
  });
1982
2367
  var SKILLS = { lintobot: SKILL_default, "linto-lint": SKILL_default2 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lintobot",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "AI code linter: rules are plain-language sentences answered by a decision model (Jev)",
5
5
  "keywords": [
6
6
  "lint",