lintobot 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +144 -3
  2. package/dist/cli.js +541 -222
  3. package/package.json +1 -1
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.1.0",
10
+ version: "0.2.1",
11
11
  description: "AI code linter: rules are plain-language sentences answered by a decision model (Jev)",
12
12
  keywords: [
13
13
  "lint",
@@ -387,7 +387,7 @@ function withSchema(text) {
387
387
  const document = YAML.parseDocument(text);
388
388
  const edits = [];
389
389
  const files = isMap2(document.contents) ? document.contents.get("files", true) : undefined;
390
- const lists = (isSeq(files) ? files.items : []).flatMap((entry2) => isMap2(entry2) ? [entry2.get("rules", true), entry2.get("info", true)] : []);
390
+ const lists = (isSeq(files) ? files.items : []).flatMap((entry) => isMap2(entry) ? [entry.get("rules", true), entry.get("info", true)] : []);
391
391
  for (const list of lists) {
392
392
  for (const item of isSeq(list) ? list.items : []) {
393
393
  if (isScalar(item) && typeof item.value === "string" && item.range) {
@@ -437,14 +437,56 @@ 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
- var itemsOf = (entry2) => [...entry2.rules, ...entry2.info];
489
+ var itemsOf = (entry) => [...entry.rules, ...entry.info];
448
490
  var sentences = (value) => (value ?? "").split(/[\n;]/).map((item) => item.trim()).filter(Boolean);
449
491
  function loadConfig(file, env = process.env) {
450
492
  const explicit = file !== undefined;
@@ -498,7 +540,7 @@ function parseConfig(text, env = {}, file = CONFIG_FILE) {
498
540
  } else if (data.files !== undefined) {
499
541
  if (!Array.isArray(data.files))
500
542
  throw new ConfigError(`${file}: files must be a list`);
501
- config.entries = data.files.map((entry2, n) => entryOf(entry2, config, `${file}: files[${n + 1}]`));
543
+ config.entries = data.files.map((entry, n) => entryOf(entry, config, `${file}: files[${n + 1}]`));
502
544
  } else {
503
545
  config.entries = [implicit(rulesOf(YAML2.parse(RECOMMENDED), config, "lintobot/recommended"))];
504
546
  }
@@ -570,10 +612,10 @@ function strings(value, where) {
570
612
  throw new ConfigError(`${where} must be text or a list of texts`);
571
613
  return list;
572
614
  }
573
- function entryOf(entry2, config, where) {
574
- if (!isMap3(entry2))
615
+ function entryOf(entry, config, where) {
616
+ if (!isMap3(entry))
575
617
  throw new ConfigError(`${where} must be a map with pattern and rules`);
576
- const { pattern, except, rules = [], info = [], context, max_lines, ...conditions } = entry2;
618
+ const { pattern, except, rules = [], info = [], context, max_lines, ...conditions } = entry;
577
619
  const patterns = strings(pattern, `${where}.pattern`);
578
620
  if (!patterns.length)
579
621
  throw new ConfigError(`${where} needs a pattern`);
@@ -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;
@@ -671,9 +756,9 @@ ${YAML2.stringify(placeholders)}`;
671
756
  const rule = data.files?.[n - 1]?.[list]?.[i - 1];
672
757
  return typeof rule === "string" ? rule : isMap3(rule) ? Object.keys(rule)[0] : undefined;
673
758
  };
674
- const named = (problem) => String(problem).replace(new RegExp(`files\\[(\\d+)\\]\\.(rules|info)\\[(\\d+)\\](\\.${RULE_KEY})?`), (path4, n, list, i) => {
675
- const text2 = sentence(Number(n), list, Number(i));
676
- return text2 === undefined ? path4 : `"${text2}"`;
759
+ const named = (problem) => String(problem).replace(new RegExp(`files\\[(\\d+)\\]\\.(rules|info)\\[(\\d+)\\](\\.${RULE_KEY})?`), (path, n, list, i) => {
760
+ const text = sentence(Number(n), list, Number(i));
761
+ return text === undefined ? path : `"${text}"`;
677
762
  }).replace(/"([^"]+)" is not a field of the schema$/, 'unknown key "$1"');
678
763
  const errors = problems.filter((problem) => problem.severity === "error" || isUnknownField(problem));
679
764
  if (errors.length)
@@ -682,15 +767,16 @@ ${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),
689
775
  env: literal(config.env),
690
- files: entries.map((entry2, n) => ({
691
- ...entry2.conditions,
776
+ files: entries.map((entry, n) => ({
777
+ ...entry.conditions,
692
778
  n,
693
- rules: itemsOf(entry2).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 {
@@ -718,14 +804,23 @@ ${named.map((line) => ` ${line}`).join(`
718
804
  }
719
805
  function inspectFormulas(config) {
720
806
  const document = documentFor(config, config.entries, PLACEHOLDER_FACTS, () => 0);
721
- config.entries.forEach((entry2, n) => {
722
- itemsOf(entry2).forEach((rule, i) => {
807
+ config.entries.forEach((entry, n) => {
808
+ itemsOf(entry).forEach((rule, i) => {
723
809
  const loaded = document.data.files[n].rules[i][`r${i}`];
724
810
  for (const key of ["$if", "$unless"]) {
725
811
  if (loaded[key]?.reads.includes("confidence")) {
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}!`]]));
@@ -742,25 +837,25 @@ function matchesAny(globs, file) {
742
837
  matchers.set(globs, matcher(globs));
743
838
  return matchers.get(globs)(file);
744
839
  }
745
- var matches = (entry2, file) => (!entry2.patterns || matchesAny(entry2.patterns, file)) && !matchesAny(entry2.except, file);
746
- function resolveRules(config, file, confidences) {
747
- const entries = config.entries.filter((entry2) => matches(entry2, file.path));
840
+ var matches = (entry, file) => (!entry.patterns || matchesAny(entry.patterns, file)) && !matchesAny(entry.except, file);
841
+ function resolveRules(config, file, confidences, shares) {
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
  }
756
851
  const applied = new Map;
757
- for (const entry2 of resolved.files) {
758
- entry2.rules.forEach((item, i) => {
852
+ for (const entry of resolved.files) {
853
+ entry.rules.forEach((item, i) => {
759
854
  const options = item[`r${i}`];
760
- const rule = itemsOf(entries[entry2.n])[i];
855
+ const rule = itemsOf(entries[entry.n])[i];
761
856
  if (!options || matchesAny(rule.except, file.path))
762
857
  return;
763
- applied.set(`${rule.info}:${rule.sentence}`, { rule, entry: entries[entry2.n], error: options.error, warning: options.warning, show: options.show });
858
+ applied.set(`${rule.info}:${rule.sentence}`, { rule, entry: entries[entry.n], error: options.error, warning: options.warning, show: options.show });
764
859
  });
765
860
  }
766
861
  return [...applied.values()];
@@ -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`);
@@ -806,7 +901,7 @@ var lineCount = (text) => text.split(`
806
901
  `).length - (text.endsWith(`
807
902
  `) ? 1 : 0);
808
903
  function cutPieces(text, maxBytes, maxLines = Infinity) {
809
- const fits = (size2, lines2) => size2 <= maxBytes && lines2 <= maxLines;
904
+ const fits = (size, lines) => size <= maxBytes && lines <= maxLines;
810
905
  if (fits(cost(text), lineCount(text)))
811
906
  return [text];
812
907
  const blocks = [];
@@ -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";
@@ -904,21 +1024,21 @@ function fileVariables(file) {
904
1024
  function contextFor(file, config) {
905
1025
  const variables = fileVariables(file);
906
1026
  const read = new Map;
907
- const textOf = (entry2) => {
908
- if (!read.has(entry2))
909
- read.set(entry2, attempt(() => head(load(entry2, variables, config), entry2.maxBytes)));
910
- return read.get(entry2);
1027
+ const textOf = (entry) => {
1028
+ if (!read.has(entry))
1029
+ read.set(entry, attempt(() => head(load(entry, variables, config), entry.maxBytes)));
1030
+ return read.get(entry);
911
1031
  };
912
1032
  return ({ rule, entry: group }) => {
913
1033
  const merged = { ...config.context, ...group.context, ...rule.context };
914
1034
  const result = { sections: {} };
915
- for (const [name, entry2] of Object.entries(merged)) {
916
- if (!entry2)
1035
+ for (const [name, entry] of Object.entries(merged)) {
1036
+ if (!entry)
917
1037
  continue;
918
- const text = textOf(entry2);
1038
+ const text = textOf(entry);
919
1039
  if (typeof text === "string")
920
1040
  result.sections[name] = text;
921
- else if (rule.context[name] === entry2)
1041
+ else if (rule.context[name] === entry)
922
1042
  result.missing ??= `context "${name}": ${text.message}`;
923
1043
  }
924
1044
  return result;
@@ -931,12 +1051,12 @@ function attempt(read) {
931
1051
  return error;
932
1052
  }
933
1053
  }
934
- function load(entry2, variables, config) {
935
- if (entry2.kind === "text")
936
- return entry2.source;
1054
+ function load(entry, variables, config) {
1055
+ if (entry.kind === "text")
1056
+ return entry.source;
937
1057
  const folder = path5.dirname(config.file);
938
- if (entry2.kind === "file") {
939
- const name = entry2.source.replace(/\$\{?(FILE|DIR|STEM|EXT)\b\}?/g, (_, variable) => variables[variable]);
1058
+ if (entry.kind === "file") {
1059
+ const name = entry.source.replace(/\$\{?(FILE|DIR|STEM|EXT)\b\}?/g, (_, variable) => variables[variable]);
940
1060
  const target = path5.resolve(folder, name);
941
1061
  if (!fs4.statSync(target, { throwIfNoEntry: false })?.isFile())
942
1062
  throw new Error(`no file ${name}`);
@@ -944,7 +1064,7 @@ function load(entry2, variables, config) {
944
1064
  }
945
1065
  if (!config.shell)
946
1066
  throw new Error("commands are off (--no-shell)");
947
- const ran = spawnSync(entry2.source, { shell: true, cwd: folder, env: { ...process.env, ...variables }, timeout: SHELL_TIMEOUT_MS, encoding: "utf8" });
1067
+ const ran = spawnSync(entry.source, { shell: true, cwd: folder, env: { ...process.env, ...variables }, timeout: SHELL_TIMEOUT_MS, encoding: "utf8" });
948
1068
  if (ran.error)
949
1069
  throw new Error(`the command did not finish: ${ran.error.message}`);
950
1070
  if (ran.status !== 0)
@@ -953,53 +1073,34 @@ function load(entry2, 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
- const contextOf2 = contextFor(file, config);
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
- const { sections, missing } = contextOf2(item);
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),
@@ -1087,19 +1211,22 @@ No when: ${q.criteria.false}` : q.instructions
1087
1211
  }
1088
1212
  function parseResponse(target, data, keys) {
1089
1213
  const answers = Object.fromEntries(keys.map((key) => [key, null]));
1090
- const usage = (u, cost2) => ({
1214
+ const usage = (u, cost) => ({
1091
1215
  input_tokens: u?.input_tokens ?? 0,
1092
1216
  output_tokens: u?.output_tokens ?? 0,
1093
- ...(u?.cost ?? cost2) !== undefined && { cost: u?.cost ?? cost2 }
1217
+ ...(u?.cost ?? cost) !== undefined && { cost: u?.cost ?? cost }
1094
1218
  });
1095
1219
  if (target.wire === "typesafe") {
1096
- const body2 = typesafeResponse.parse(data);
1220
+ const body = typesafeResponse.parse(data);
1097
1221
  for (const key of keys) {
1098
- const answer = noul.safeParse(body2.answers[key]);
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
- return { answers, usage: usage(body2.usage), model: body2.model ?? target.model };
1229
+ return { answers, usage: usage(body.usage), model: body.model ?? target.model };
1103
1230
  }
1104
1231
  const body = openaiResponse.parse(data);
1105
1232
  for (const item of body.answers) {
@@ -1113,7 +1240,7 @@ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1113
1240
  function createClient(target, options = {}) {
1114
1241
  const { retries = 3, backoffMs = 500, timeoutMs = 60000 } = options;
1115
1242
  const send = options.fetch ?? fetch;
1116
- async function attempt2(body, keys) {
1243
+ async function attempt(body, keys) {
1117
1244
  let response;
1118
1245
  let text;
1119
1246
  try {
@@ -1143,7 +1270,7 @@ function createClient(target, options = {}) {
1143
1270
  const started = performance.now();
1144
1271
  for (let tries = 0;; tries++) {
1145
1272
  try {
1146
- const result = await attempt2(body, keys);
1273
+ const result = await attempt(body, keys);
1147
1274
  return { ...result, ms: Math.round(performance.now() - started) };
1148
1275
  } catch (error) {
1149
1276
  const status = error.status;
@@ -1251,8 +1378,8 @@ async function lint(files, engine, reporter) {
1251
1378
  }
1252
1379
  reporter.file(result);
1253
1380
  }
1254
- const cost2 = run.stats.cost === undefined ? {} : { cost: Math.round(run.stats.cost * 1e6) / 1e6 };
1255
- const summary = { type: "summary", ...count, ...run.stats, ...cost2, ms: Math.round(performance.now() - started) };
1381
+ const cost = run.stats.cost === undefined ? {} : { cost: Math.round(run.stats.cost * 1e6) / 1e6 };
1382
+ const summary = { type: "summary", ...count, ...run.stats, ...cost, ms: Math.round(performance.now() - started) };
1256
1383
  reporter.end(summary);
1257
1384
  return summary;
1258
1385
  }
@@ -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
- const tallies = new Map(plan.unasked.map(({ applied: applied2, reason }) => [applied2.rule, { missing: reason, parts: [] }]));
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) {
@@ -1375,6 +1560,88 @@ function areaThreshold(applied, defaults) {
1375
1560
  return Math.min(defaults.warning, ...thresholds);
1376
1561
  }
1377
1562
 
1563
+ // src/files/diff.ts
1564
+ import { execFileSync } from "node:child_process";
1565
+
1566
+ class GitError extends Error {
1567
+ hint;
1568
+ constructor(message, hint) {
1569
+ super(message);
1570
+ this.hint = hint;
1571
+ }
1572
+ }
1573
+ var MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
1574
+ function git(args) {
1575
+ return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: MAX_OUTPUT_BYTES });
1576
+ }
1577
+ var list = (output) => output.split("\x00").filter(Boolean);
1578
+ function isRevision(ref) {
1579
+ try {
1580
+ git(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`]);
1581
+ return true;
1582
+ } catch {
1583
+ return false;
1584
+ }
1585
+ }
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) {
1613
+ try {
1614
+ git(["rev-parse", "--is-inside-work-tree"]);
1615
+ } catch {
1616
+ throw new GitError("--diff and --staged need a git repository", "Run inside the repository, or name the files instead");
1617
+ }
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]));
1621
+ if (scope.staged)
1622
+ return { files: list(git([...names, "--cached", "--"])), added: lines("--cached") };
1623
+ let base = "HEAD";
1624
+ if (scope.ref) {
1625
+ if (!isRevision(scope.ref))
1626
+ throw new GitError(`--diff: git does not know "${scope.ref}"`, "Give a branch, tag or commit, for example --diff origin/main");
1627
+ try {
1628
+ base = git(["merge-base", scope.ref, "HEAD"]).trim();
1629
+ } catch {
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)");
1631
+ }
1632
+ }
1633
+ const untracked = list(git(["ls-files", "-z", "--others", "--exclude-standard"]));
1634
+ let tracked;
1635
+ try {
1636
+ tracked = list(git([...names, base, "--"]));
1637
+ } catch {
1638
+ return { files: [...new Set([...list(git(["ls-files", "-z"])), ...untracked])].sort(), added: () => null };
1639
+ }
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) };
1643
+ }
1644
+
1378
1645
  // src/model/providers.ts
1379
1646
  var PROVIDERS = {
1380
1647
  openrouter: { url: () => "https://openrouter.ai/api/alpha/decisions", key: "OPENROUTER_API_KEY", wire: "typesafe" },
@@ -1406,11 +1673,11 @@ function parseModel(value, env = process.env) {
1406
1673
  }
1407
1674
 
1408
1675
  // src/report/json.ts
1409
- var isProblem = (record2) => record2.type === "info" ? record2.skipped === true : record2.severity !== "ok";
1676
+ var isProblem = (record) => record.type === "info" ? record.skipped === true : record.severity !== "ok";
1410
1677
  var shown = (records, quiet) => quiet ? records.filter(isProblem) : records;
1411
1678
  function jsonlReporter(write, options = {}) {
1412
1679
  return {
1413
- file: (result) => shown(result.records, options.quiet).forEach((record2) => write(`${JSON.stringify(record2)}
1680
+ file: (result) => shown(result.records, options.quiet).forEach((record) => write(`${JSON.stringify(record)}
1414
1681
  `)),
1415
1682
  end: (summary) => write(`${JSON.stringify(summary)}
1416
1683
  `)
@@ -1430,46 +1697,78 @@ import pc from "picocolors";
1430
1697
  var COLUMN = 56;
1431
1698
  var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1432
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}`;
1433
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
+ }
1434
1712
  function prettyReporter(write, options = {}) {
1435
1713
  const color = pc.createColors(options.color ?? false);
1436
1714
  const row = (icon, label, value, paint = (text) => text) => ` ${icon} ${paint(label)}${value && value.padStart(Math.max(value.length + 2, COLUMN - label.length))}`;
1437
- const place = (record2) => record2.areas?.length ? ` lines ${record2.areas.map((area) => `${area.start}–${area.end}`).join(", ")}` : "";
1438
- const noteLabel = (record2) => record2.id ? `${record2.statement} (${record2.id})` : record2.statement;
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(", ")}` : "";
1716
+ const noteLabel = (record) => record.id ? `${record.statement} (${record.id})` : record.statement;
1439
1717
  function noteLine(records) {
1440
1718
  const text = records.map(noteLabel).join(", ");
1441
1719
  return text ? [color.dim(text[0].toUpperCase() + text.slice(1))] : [];
1442
1720
  }
1443
- function line(record2) {
1444
- const label = record2.id ? `${record2.rule} (${record2.id})` : record2.rule;
1445
- const where = place(record2);
1446
- switch (record2.severity) {
1721
+ function line(record) {
1722
+ const label = record.id ? `${record.rule} (${record.id})` : record.rule;
1723
+ const where = place(record);
1724
+ switch (record.severity) {
1447
1725
  case "error":
1448
- return row("❌", label, percent(record2.confidence), color.red) + where;
1726
+ return row("❌", label, percent(record.confidence), color.red) + where;
1449
1727
  case "warning":
1450
- return row("⚠️ ", label, percent(record2.confidence), color.yellow) + where;
1728
+ return row("⚠️ ", label, percent(record.confidence), color.yellow) + where;
1451
1729
  case "skipped":
1452
- return `${row("⏭️ ", label, "")} ${color.dim(`skipped: ${record2.reason}`)}`;
1730
+ return `${row("⏭️ ", label, "")} ${color.dim(`skipped: ${record.reason}`)}`;
1453
1731
  default:
1454
- return row("✅", label, record2.min === undefined ? "" : range(record2.min, record2.max ?? record2.min));
1732
+ return row("✅", label, record.min === undefined ? "" : range(record.min, record.max ?? record.min));
1455
1733
  }
1456
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
+ }
1457
1754
  return {
1458
- file({ file, lines, parts, records }) {
1459
- const checks = records.filter((record2) => record2.type === "check");
1460
- const info = records.filter((record2) => record2.type === "info");
1461
- const notes = noteLine(info.filter((record2) => record2.shown && !record2.skipped && !options.quiet));
1462
- const skipped = info.filter((record2) => record2.skipped).map((record2) => `${row("⏭️ ", noteLabel(record2), "")} ${color.dim(`skipped: ${record2.reason}`)}`);
1463
- const clean = checks.every((record2) => record2.severity === "ok");
1755
+ file({ file, lines, parts, added, records }) {
1756
+ const checks = records.filter((record) => record.type === "check");
1757
+ const info = records.filter((record) => record.type === "info");
1758
+ const notes = noteLine(info.filter((record) => record.shown && !record.skipped && !options.quiet));
1759
+ const skipped = info.filter((record) => record.skipped).map((record) => `${row("⏭️ ", noteLabel(record), "")} ${color.dim(`skipped: ${record.reason}`)}`);
1760
+ const clean = checks.every((record) => record.severity === "ok");
1464
1761
  const collapsed = checks.length ? [` ✅ ${plural(checks.length, "rule")}`] : [];
1762
+ const mixes = records.filter((record) => record.type === "composition");
1465
1763
  const rows = [
1466
1764
  ...notes,
1467
- ...clean && parts === 1 ? options.quiet ? [] : collapsed : checks.filter((record2) => !options.quiet || record2.severity !== "ok").map(line),
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),
1468
1767
  ...skipped
1469
1768
  ];
1470
1769
  if (!rows.length)
1471
1770
  return;
1472
- 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)`) : "";
1473
1772
  write(`${color.bold(file)}${size}
1474
1773
  ${rows.join(`
1475
1774
  `)}
@@ -1523,20 +1822,25 @@ function reportPlan(plans, format, write) {
1523
1822
  const name = rule.info ? { info: rule.sentence } : { rule: rule.sentence };
1524
1823
  if (unasked)
1525
1824
  return { ...name, skipped: unasked.reason };
1825
+ if (rule.composition) {
1826
+ const { instructions, options } = compositionQuestion(rule.composition.categories, rule.ask);
1827
+ return { composition: rule.sentence, question: instructions, options: Object.keys(options) };
1828
+ }
1526
1829
  return rule.asksModel ? { ...name, question: toQuestion(rule.sentence, rule.ask, rule.info).instructions } : { ...name, formula: rule.formulas.error ?? rule.formulas.warning ?? rule.formulas.show };
1527
1830
  }),
1528
1831
  sent: plan.calls.map((call) => ({
1529
1832
  ...call.lines && { lines: call.lines },
1833
+ ...call.added && { added: call.added },
1530
1834
  bytes: callBytes(call),
1531
1835
  context: Object.fromEntries(Object.entries(call.state).filter(([name]) => !OWN_SECTIONS.includes(name)).map(([name, text]) => [name, Buffer.byteLength(text)])),
1532
1836
  rules: call.planned.map((planned) => planned.applied.rule.sentence)
1533
1837
  }))
1534
1838
  }));
1535
- const bytes = records.reduce((sum, record2) => sum + record2.bytes, 0);
1839
+ const bytes = records.reduce((sum, record) => sum + record.bytes, 0);
1536
1840
  const summary = {
1537
1841
  type: "plan-summary",
1538
1842
  files: records.length,
1539
- calls: records.reduce((sum, record2) => sum + record2.calls, 0),
1843
+ calls: records.reduce((sum, record) => sum + record.calls, 0),
1540
1844
  bytes,
1541
1845
  tokens: Math.ceil(bytes / BYTES_PER_TOKEN)
1542
1846
  };
@@ -1544,22 +1848,24 @@ function reportPlan(plans, format, write) {
1544
1848
  return write(`${JSON.stringify({ plan: records, summary }, null, 2)}
1545
1849
  `);
1546
1850
  if (format === "jsonl")
1547
- return [...records, summary].forEach((record2) => write(`${JSON.stringify(record2)}
1851
+ return [...records, summary].forEach((record) => write(`${JSON.stringify(record)}
1548
1852
  `));
1549
- for (const record2 of records) {
1550
- write(`${record2.file}
1551
- ${plural2(record2.calls, "call")} · ${record2.bytes} bytes
1853
+ for (const record of records) {
1854
+ write(`${record.file}
1855
+ ${plural2(record.calls, "call")} · ${record.bytes} bytes
1552
1856
  `);
1553
- for (const call of record2.sent) {
1857
+ for (const call of record.sent) {
1554
1858
  const context = Object.entries(call.context).map(([name, size]) => `${name} ${size} bytes`).join(", ");
1555
- const where = call.lines ? `lines ${call.lines.start}–${call.lines.end}` : "whole file";
1859
+ const span = (lines) => lines.start === lines.end ? `${lines.start}` : `${lines.start}–${lines.end}`;
1860
+ const where = call.added ? `added lines ${call.added.map(span).join(", ")}` : call.lines ? `lines ${span(call.lines)}` : "whole file";
1556
1861
  write(` ${where} · ${call.bytes} bytes · ${plural2(call.rules.length, "question")}${context && ` · context: ${context}`}
1557
1862
  `);
1558
1863
  }
1559
- for (const rule of record2.rules) {
1864
+ for (const rule of record.rules) {
1560
1865
  const detail = "skipped" in rule ? `skipped: ${rule.skipped}` : ("question" in rule) ? rule.question : `formula: ${rule.formula}`;
1561
- write(` ${"info" in rule ? `info: ${rule.info}` : rule.rule}
1562
- ${detail}
1866
+ const name = "composition" in rule ? `composition: ${rule.composition}` : ("info" in rule) ? `info: ${rule.info}` : rule.rule;
1867
+ write(` ${name}
1868
+ ${detail}${"options" in rule && rule.options ? ` [${rule.options.join(", ")}]` : ""}
1563
1869
  `);
1564
1870
  }
1565
1871
  write(`
@@ -1572,126 +1878,114 @@ function reportPlan(plans, format, write) {
1572
1878
  // src/skill/SKILL.md
1573
1879
  var SKILL_default = `---
1574
1880
  name: lintobot
1575
- description: Lint code with plain-language rules answered by a decision model. Use when asked to run lintobot, read its report, add or tune a rule in lintobot.yml, or find out why a file failed a rule.
1881
+ 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.
1576
1882
  ---
1577
1883
 
1578
1884
  # lintobot
1579
1885
 
1580
- lintobot asks a decision model yes/no questions about each file. A rule is a sentence that must hold for the file. The model returns only a probability, so a result is a **confidence that the rule is broken** (0–100%), never an explanation.
1581
-
1582
- ## Run
1886
+ 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.
1583
1887
 
1584
- \`\`\`bash
1585
- lintobot # every file matched by lintobot.yml
1586
- lintobot src/user.js "lib/**/*.ts" # only these
1587
- lintobot src --rule "no magic numbers"
1588
- lintobot src --dry-run # what would be sent and the exact questions; sends nothing
1589
- lintobot src --format jsonl # one JSON record per check (default when piped)
1590
- \`\`\`
1888
+ ## What it is and is not
1591
1889
 
1592
- It needs \`LINTOBOT_MODEL\` (for example \`openrouter/typesafe/jev-1.14\`) and the provider's key (\`OPENROUTER_API_KEY\`), from the environment or a \`.env\` file in the working directory.
1890
+ - **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.
1891
+ - **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.
1892
+ - **Not deterministic.** The same file can score a few points differently between runs, and the scores are not calibrated. Nothing here is strict.
1893
+ - **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.
1894
+ - **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.
1895
+ - **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.
1593
1896
 
1594
- Exit codes: \`0\` clean, \`1\` errors found, \`2\` bad usage or config, \`3\` the model could not be reached or some checks were skipped.
1897
+ 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.
1595
1898
 
1596
- ## Read the report
1899
+ ## Run
1597
1900
 
1598
- \`\`\`
1599
- lib/helper/Playwright.js (5025 lines, 17 parts)
1600
- ❌ no deprecated methods 99% lines 3229–4048
1601
- ⚠️ no direct CDP access 75% lines 4049–4896
1602
- ✅ no secret values exposed 5–6%
1901
+ \`\`\`bash
1902
+ lintobot # every file matched by lintobot.yml
1903
+ lintobot app/jobs # only this folder or file
1904
+ lintobot src --rule "no magic numbers"
1905
+ lintobot src --dry-run # shows the exact questions, sends nothing
1906
+ lintobot --diff # only lines added since the last commit (a new file whole)
1907
+ lintobot --diff origin/main # only lines this branch adds
1603
1908
  \`\`\`
1604
1909
 
1605
- - ❌ error, ⚠️ warning, ✅ passed, ⏭️ skipped (the reason follows).
1606
- - A dim sentence directly under the file name lists the info items that are true of the file: observations, not problems, shown when the model is at least 90% sure. Nothing to fix; use it to know what the file does. The confidence is in the \`jsonl\` record.
1607
- - For rules, the percent is how sure the model is that the rule is **broken**.
1608
- - A large file is sent in parts. A failed check names the line ranges of the parts that failed: look there, the model cannot say more. A passed check shows the lowest–highest value across parts.
1609
- - In \`jsonl\`, each check record has \`file\`, \`rule\`, \`severity\`, \`confidence\`, \`question\`, and for multi-part files \`min\`, \`max\`, \`areas\`, \`parts\`. An info record has \`"type":"info"\`, \`statement\`, \`confidence\` and \`shown\` (true or false) instead of a severity.
1910
+ 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.
1610
1911
 
1611
- To act on a finding: read the named area (or the whole file when there is none), judge it against the rule's sentence yourself, then fix the code or report that the finding looks wrong. Do not treat a finding as proof.
1912
+ 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.
1612
1913
 
1613
1914
  ## Write rules
1614
1915
 
1615
- \`lintobot.yml\` is YAML where \`key!:\` marks a formula (scripted-yaml, FEEL syntax).
1616
-
1617
1916
  \`\`\`yaml
1618
- model: openrouter/typesafe/jev-1.14
1619
-
1620
1917
  files:
1621
- - pattern: "src/**/*.js"
1918
+ - pattern: "app/jobs/**_job.rb"
1919
+ except: "app/jobs/legacy/**"
1622
1920
  rules:
1623
- - "no magic numbers" # default thresholds: warning 0.7, error 0.9
1624
- - "no secret values exposed":
1625
- error: 0.6 # stricter
1626
- - "comments explain intent":
1627
- $if!: file.comment_lines > 5 # only applies to such files
1921
+ - "all methods are private except perform"
1628
1922
  - "no direct database access":
1923
+ error: 0.8
1629
1924
  ask: Does the code open a database connection or run a query itself?
1630
- criteria:
1631
- yes: Calls a driver or builds SQL in this file
1632
- no: Goes through a repository or service
1633
1925
  - "file is too long":
1634
- error!: file.lines > 800 # no model call at all
1926
+ error!: file.lines > 800
1927
+ info:
1928
+ - "sends email"
1635
1929
  \`\`\`
1636
1930
 
1637
- - A sentence starting with \`no \` is asked as "does the code contain …?"; any other sentence as "is it true that …?". \`ask:\` replaces the wording but not the direction: under a \`no …\` sentence yes means broken, under any other sentence yes means fine. Prefer questions where yes means the thing is present; avoid negations.
1638
- - \`error\` / \`warning\`: a number (threshold on confidence), \`false\` to switch that level off, or a formula giving true/false. Formulas read \`confidence\` and \`file\`.
1639
- - \`$if!\`: whether the rule applies; may read only \`file\`.
1640
- - \`except\`: a glob or a list of globs of files the rule does not apply to. On a \`files\` entry, beside \`pattern\`, it takes those files out of the entry altogether.
1641
- - \`whole: true\`: a rule about the file as a whole (asked once, no area).
1642
- - \`file\` facts: \`path\`, \`dir\`, \`name\`, \`ext\`, \`lines\`, \`code_lines\`, \`comment_lines\`, \`blank_lines\`, \`longest_line\`, \`max_depth\`, \`complexity\`, lists \`imports\` and \`exports\`.
1643
- - FEEL reminders: equals is one \`=\`, \`not(x)\`, \`a and b\`, \`count(list)\`, \`some i in file.imports satisfies starts with(i, "../db")\`.
1931
+ - 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".
1932
+ - \`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.
1933
+ - Options, all optional:
1934
+ - \`error\`, \`warning\`: confidence threshold (defaults 0.9 and 0.7), or \`false\` to switch the level off
1935
+ - \`ask\`: the question to send instead of the generated one. Under a \`no …\` sentence yes means broken, otherwise yes means fine
1936
+ - \`criteria\`: \`yes:\` / \`no:\` descriptions of what counts
1937
+ - \`except\`: globs the rule skips
1938
+ - \`whole: true\`: the rule is about the file as a whole
1939
+ - 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.
1644
1940
 
1645
- Extra material for the model, by name, at the top, on a \`files\` entry or on a rule:
1941
+ 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:
1646
1942
 
1647
1943
  \`\`\`yaml
1648
- context:
1649
- style!file: docs/conventions.md
1650
- docs!file: docs/$STEM.md
1651
- recent!sh: git log -5 --format=%s -- "$FILE"
1944
+ - composition:
1945
+ code:
1946
+ sql: Raw SQL strings or query fragments
1947
+ error!: share.sql > 0.1
1652
1948
  \`\`\`
1653
1949
 
1654
- Refer to it in the sentence: "follows the conventions in the \`style\` section". Variables: \`$FILE\`, \`$DIR\`, \`$STEM\`, \`$EXT\`.
1655
-
1656
- Part size: \`parts: { max_lines: 300 }\` at the top is the default; \`max_lines: N\` (20 or more) on a \`files\` entry or on one rule changes it there. The rule wins over its entry, the entry over the top. A rule with its own \`max_lines\` is asked on its own cutting of the file, so its \`parts\` and areas differ from the other checks of that file; it cannot also be \`whole: true\`.
1950
+ 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.
1657
1951
 
1658
1952
  \`\`\`yaml
1659
- files:
1660
- - pattern: "app/controllers/**/*.rb"
1661
- except: "app/controllers/legacy/**"
1662
- max_lines: 600
1953
+ - pattern: "app/controllers/projects/**/*.rb"
1663
1954
  rules:
1664
- - "no magic numbers":
1665
- except: ["app/controllers/api/**", "**/*_concern.rb"]
1666
- - "no direct SQL":
1667
- max_lines: 150
1955
+ - composition:
1956
+ project: focused on a single Project and has a @project instance
1957
+ nonproject: works across projects or without any project
1958
+ error!: share.project < 0.7 # or cap the catch-all: share.other > 0.7
1959
+ \`\`\`
1960
+
1961
+ \`\`\`
1962
+ ❌ works across projects or without any project (64%) project project 31% < 70%
1668
1963
  \`\`\`
1669
1964
 
1670
- Observations go in an \`info:\` list beside \`rules:\`. They are asked as "does the code …?", so start them with a verb ("launches a job"); give \`ask:\` with what to look for when one stays quiet. They are listed under the file name when true, and never fail the run:
1965
+ 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.
1966
+
1967
+ A good start for any code file is a few basic checks, then the project's own intentions on top:
1671
1968
 
1672
1969
  \`\`\`yaml
1673
- files:
1674
- - pattern: "src/**/*.ts"
1675
- rules:
1676
- - "no magic numbers"
1677
- info:
1678
- - "has I/O interactions"
1679
- - "talks to the database":
1680
- show: 0.8
1681
- ask: Does the code run a database query or open a connection?
1682
- - "is a large module":
1683
- show!: file.lines > 400
1970
+ rules:
1971
+ - "no duplicated code"
1972
+ - "no magic numbers"
1973
+ - "no comments that restate the code"
1684
1974
  \`\`\`
1685
1975
 
1686
- The threshold is global: \`defaults: { info: 0.9 }\` (the default). \`show\` sets an item's own threshold, \`show!\` a formula; \`error\` and \`warning\` do not belong on an info item, nor \`show\` on a rule. The other rule options apply. \`LINTOBOT_INFO="a; b"\` gives statements without a config.
1976
+ ## Start from the agent rules
1977
+
1978
+ 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:
1979
+
1980
+ 1. \`lintobot init\` writes a starter \`lintobot.yml\` when there is none.
1981
+ 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".
1982
+ 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.
1983
+ 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\`.
1984
+ 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.
1687
1985
 
1688
- ## Tune a rule
1986
+ Show the list of rules taken from the agent files, with the line each came from, before writing them.
1689
1987
 
1690
- 1. \`lintobot <file> --rule "<sentence>" --dry-run\` to see the question as sent and the line range of every call.
1691
- 2. A rule that fires on most files, or sits near 50% everywhere, is too vague: add \`ask:\` and \`criteria:\` that say what counts.
1692
- 3. Set thresholds from what real good and bad files score, not from a guess.
1693
- 4. A finding that names a 300-line area, or a rule that misses something small in a long file: give the rule a smaller \`max_lines\`.
1694
- 5. Answers are cached in \`.lintobot/cache/\`; \`--no-cache\` asks again.
1988
+ 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.
1695
1989
  `;
1696
1990
 
1697
1991
  // src/skill/linto-lint/SKILL.md
@@ -1876,6 +2170,12 @@ function projectRoot(args, flags) {
1876
2170
  return { cwd };
1877
2171
  }
1878
2172
  async function main(args, flags) {
2173
+ if (flags.diff && flags.staged)
2174
+ throw new UsageError("--diff and --staged do not go together");
2175
+ if (typeof flags.diff === "string" && fs6.existsSync(flags.diff) && !isRevision(flags.diff)) {
2176
+ args.unshift(flags.diff);
2177
+ flags.diff = true;
2178
+ }
1879
2179
  const root = projectRoot(args, flags);
1880
2180
  args.push(...flags.files);
1881
2181
  for (const file of new Set([path7.resolve(".env"), path7.join(root.cwd, ".env")])) {
@@ -1895,16 +2195,19 @@ async function main(args, flags) {
1895
2195
  for (const warning of config.warnings)
1896
2196
  process.stderr.write(`warning: ${warning}
1897
2197
  `);
1898
- const fromConfig = config.entries.every((entry2) => entry2.patterns);
1899
- if (!fromConfig && !args.length) {
2198
+ const fromConfig = config.entries.every((entry) => entry.patterns);
2199
+ const change = flags.diff || flags.staged ? changes({ ref: typeof flags.diff === "string" ? flags.diff : undefined, staged: flags.staged }) : null;
2200
+ const changed = change && new Set(change.files);
2201
+ if (!fromConfig && !args.length && !changed) {
1900
2202
  throw new UsageError("Nothing to lint: no files were given", `Name files or folders (lintobot src/), or list patterns under files: in ${config.file}`);
1901
2203
  }
1902
- const files = findFiles(args, fromConfig ? config.entries.flatMap((entry2) => entry2.patterns) : null, config.ignore);
2204
+ const found = findFiles(args, fromConfig ? config.entries.flatMap((entry) => entry.patterns) : null, config.ignore);
2205
+ const files = changed ? found.filter((file) => changed.has(file)) : found;
1903
2206
  const chunks = [];
1904
2207
  const write = flags.output ? (text) => void chunks.push(text) : (text) => void process.stdout.write(text);
1905
2208
  const save = () => flags.output && fs6.writeFileSync(flags.output, chunks.join(""));
1906
2209
  if (flags.dryRun) {
1907
- const plans = files.flatMap((file) => planFile(file, fs6.readFileSync(file, "utf8"), config, flags.rule) ?? []);
2210
+ const plans = files.flatMap((file) => planFile(file, fs6.readFileSync(file, "utf8"), config, flags.rule, change?.added(file) ?? undefined) ?? []);
1908
2211
  reportPlan(plans, format, write);
1909
2212
  save();
1910
2213
  return EXIT.clean;
@@ -1919,7 +2222,7 @@ async function main(args, flags) {
1919
2222
  };
1920
2223
  const cache = flags.cache ? new Cache(env.LINTOBOT_CACHE_DIR || ".lintobot/cache") : undefined;
1921
2224
  const reporter = createReporter(format, write, { quiet: flags.quiet, color: !flags.output && process.stdout.isTTY });
1922
- const summary = await lint(files, { config, client, cache, only: flags.rule }, reporter);
2225
+ const summary = await lint(files, { config, client, cache, only: flags.rule, added: change?.added }, reporter);
1923
2226
  save();
1924
2227
  if (summary.errors > 0 || maxWarnings !== undefined && summary.warnings > maxWarnings)
1925
2228
  return EXIT.problems;
@@ -1939,7 +2242,23 @@ process.stdout.on("error", (error) => {
1939
2242
  if (error.code !== "EPIPE")
1940
2243
  throw error;
1941
2244
  });
1942
- 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("--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").exitOverride().action(async (args, flags) => {
2245
+ var ABOUT = `
2246
+ What to expect:
2247
+ Rules are intentions: lintobot.yml describes what good code is for you, in plain sentences.
2248
+ Results are signals, not problems: a finding is advice to look, not a call to action.
2249
+ Pass findings to an agent or a reviewer to judge against the code.
2250
+ Results are not deterministic: the model answers with a probability, which can move
2251
+ a few points between runs.
2252
+ Each rule is as strict as you make it: lower its \`error\` threshold to enforce it harder,
2253
+ raise it or set it to false to keep it as a hint.
2254
+ It checks what a linter cannot (a comment matching its code, a function belonging in its
2255
+ file) and costs far less than a subagent. Run it from an agent hook or on a pull request:
2256
+ lintobot --diff lines added since the last commit
2257
+ lintobot --diff origin/main lines this branch adds
2258
+ Rules that must hold exactly belong in a real linter: the linto-lint skill moves them
2259
+ (lintobot skill --install).
2260
+ `;
2261
+ 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) => {
1943
2262
  process.exitCode = await main(args, flags);
1944
2263
  });
1945
2264
  var SKILLS = { lintobot: SKILL_default, "linto-lint": SKILL_default2 };
@@ -1976,7 +2295,7 @@ try {
1976
2295
  } catch (error) {
1977
2296
  if (error instanceof CommanderError)
1978
2297
  process.exitCode = error.exitCode === 0 ? EXIT.clean : EXIT.usage;
1979
- else if (error instanceof UsageError)
2298
+ else if (error instanceof UsageError || error instanceof GitError)
1980
2299
  process.exitCode = fail(error.message, error.hint);
1981
2300
  else if (error instanceof ConfigError)
1982
2301
  process.exitCode = fail(error.message);