lintsure 0.3.14 → 0.3.15

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.
package/dist/src/index.js CHANGED
@@ -2,20 +2,169 @@
2
2
  // npx lintsure scan [path] [options] npx lintsure baseline [path]
3
3
  // Writes reports into the current folder. Never sends anything over the network.
4
4
  import { execFileSync } from "node:child_process";
5
- import { existsSync } from "node:fs";
5
+ import { existsSync, statSync } from "node:fs";
6
+ import { homedir } from "node:os";
6
7
  import { access, mkdir, readFile, writeFile } from "node:fs/promises";
7
8
  import { basename, dirname, join, resolve } from "node:path";
8
9
  import { createInterface } from "node:readline/promises";
9
- import { status, pick, setup, undo } from "./agents.js";
10
+ import { AGENTS, CONNECT_NOTE, MANUAL, detected, status, pick, plan, setup, undo } from "./agents.js";
10
11
  import { parseActivity, toOtlp } from "./otel.js";
11
- import { ALL_FRAMEWORKS, BASELINE_FILE, DISCLAIMER, RULES_VERSION, classify, isOpen, nextSteps, readConfig, scan, toAssessmentHtml, toBaseline, toMarkdown, toSarif } from "@lintsure/core";
12
+ import { ALL_FRAMEWORKS, BASELINE_FILE, DISCLAIMER, RULES_VERSION, classify, isHygiene, isOpen, nextSteps, readConfig, scan, toAssessmentHtml, toBaseline, toMarkdown, toSarif } from "@lintsure/core";
13
+ import { choose, chooseMany } from "./menu.js";
14
+ import { installSkills, removeSkills, skillFolders, skills } from "./skills.js";
15
+ // The old Windows console can't draw block, line or diamond characters reliably, so it gets plain ones.
16
+ const legacy = (env = process.env) => process.platform === "win32" && !env.WT_SESSION && !env.TERM_PROGRAM && !env.ConEmuANSI && !env.FORCE_COLOR;
17
+ // Brand colours: the logo blue for names and choices, gold for the rail that ties the steps of one task together.
18
+ const BLUE = "38;2;98;137;254", GOLD = "38;2;224;176;64";
19
+ // A badge: dark text on the logo blue. Without colour the same words stand as they are.
20
+ const BADGE = "48;2;98;137;254;38;2;16;24;48";
21
+ const tint = (code, s) => ((process.stdout.isTTY || !!process.env.FORCE_COLOR) && !process.env.NO_COLOR && process.env.TERM !== "dumb" ? `\x1b[${code}m${s}\x1b[0m` : s);
22
+ /** One step of a task: a marked title, then its lines hung on a rail, so a screen reads as a sequence of steps. */
23
+ const step = (title, body = []) => { const rail = tint(GOLD, legacy() ? "|" : "│"); console.log([`${tint(GOLD, legacy() ? "*" : "◇")} ${title}`, ...body.map((b) => `${rail} ${b}`), rail].join("\n")); };
24
+ /** The Prism in half-block characters, to the proportions of the brand mark: four heavy bands with narrow gaps, a solid
25
+ * tip, and the bottom band split into a long piece and a square. Each character holds two square pixels; `band` and
26
+ * `gap` are heights in those pixels. Pure. */
27
+ function prism(band = 6, gap = 2) {
28
+ const SLOPE = 0.56, height = 4 * band + 3 * gap, half = Math.ceil(SLOPE * height);
29
+ const on = (c, h) => {
30
+ if (h % (band + gap) >= band || Math.abs(c - half) > SLOPE * (h + 1))
31
+ return false; // a gap, or outside the slope
32
+ if (h < 3 * band + 3 * gap)
33
+ return true;
34
+ const at = (c - half + SLOPE * height) / (2 * SLOPE * height); // bottom band: long piece, gap, square
35
+ return at <= 0.6 || (at >= 0.72 && at <= 0.9);
36
+ };
37
+ return Array.from({ length: height / 2 }, (_, r) => Array.from({ length: 2 * half + 1 }, (_, c) => { const t = on(c, 2 * r), b = on(c, 2 * r + 1); return t && b ? "█" : t ? "▀" : b ? "▄" : " "; }).join(""));
38
+ }
39
+ /** Start screen for a person at a terminal: the Prism in brand green beside the name, version and first commands.
40
+ * NO_COLOR is respected; the old Windows console, which can't draw the blocks, gets the name and version only. */
41
+ function banner(env = process.env) {
42
+ if (legacy(env))
43
+ return `Lintsure ${RULES_VERSION}\n`;
44
+ const color = !env.NO_COLOR && env.TERM !== "dumb";
45
+ const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
46
+ const text = [`${paint("38;2;98;137;254", "Lintsure")}${paint("2", ` ${RULES_VERSION}`)}`, "", paint("2", "Everything stays on this machine.")];
47
+ const mark = prism(), width = Math.max(...mark.map((l) => l.length)), top = Math.floor((mark.length - text.length) / 2);
48
+ return "\n" + mark.map((l, i) => (paint("38;2;98;137;254", l.padEnd(width)) + " " + (text[i - top] ?? "")).trimEnd()).join("\n") + "\n";
49
+ }
50
+ // Files and folders that mark the top of a software project, in any of the common stacks.
51
+ const PROJECT_MARKERS = [".git", "package.json", "pyproject.toml", "requirements.txt", "setup.py", "Pipfile", "go.mod", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts", "Gemfile", "composer.json", "pubspec.yaml", "Package.swift", "deno.json", "Dockerfile", "docker-compose.yml", "compose.yaml", "lintsure.config.yaml", ".lintsure"];
52
+ const isWholeDisk = (dir) => dir === homedir() || dirname(dir) === dir; // the home folder or a drive root
53
+ /** Whether a folder is a software project or sits inside one: a marker file in the folder itself, or a git repository
54
+ * around it. Folders above count only through .git, because a stray package.json in a temp or documents folder is
55
+ * common. The home folder and a drive root never count. */
56
+ export const looksLikeProject = (dir) => projectSign(dir) !== null;
57
+ /** What shows that a folder is a project, in words for a person, or null when nothing does. */
58
+ function projectSign(dir) {
59
+ if (isWholeDisk(dir))
60
+ return null;
61
+ const marker = PROJECT_MARKERS.find((m) => existsSync(join(dir, m)));
62
+ if (marker)
63
+ return marker === ".git" ? "a git repository" : `it has ${marker}`;
64
+ for (let at = dirname(dir); !isWholeDisk(at); at = dirname(at))
65
+ if (existsSync(join(at, ".git")))
66
+ return `inside the git repository ${basename(at)}`;
67
+ return null;
68
+ }
69
+ /** The folder and whether a project was found in it, as one step. */
70
+ function showFolder(title, dir) {
71
+ const sign = projectSign(dir);
72
+ step(`${title} ${tint(BLUE, basename(dir) || dir)}`, [tint("2", dir), sign ? `${tint("32", "Project found")}: ${sign}` : tint(GOLD, "No project found here")]);
73
+ }
74
+ /** Asks a person for their project folder. Returns its full path, "" for Enter alone (use this folder), or null to stop.
75
+ * A pasted path may carry quotes, and ~ stands for the home folder. Only call this at a terminal. */
76
+ async function askFolder(allowHere) {
77
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
78
+ try {
79
+ for (let tries = 0; tries < 3; tries++) {
80
+ const typed = (await rl.question(`Type or paste the path to your project folder, then press Enter.\n${allowHere ? "Enter alone checks this folder anyway. " : ""}q stops.\n> `)).trim().replace(/^["']|["']$/g, "");
81
+ if (typed.toLowerCase() === "q")
82
+ return null;
83
+ if (!typed) {
84
+ if (allowHere)
85
+ return "";
86
+ console.log("That would check every file you have. Name one project folder.\n");
87
+ continue;
88
+ }
89
+ const full = resolve(typed.replace(/^~(?=$|[\\/])/, homedir()));
90
+ if (existsSync(full) && statSync(full).isDirectory()) {
91
+ console.log(`\n${tint("32", "Found")} ${full}${looksLikeProject(full) ? "" : "\nIt doesn't look like a project, so Lintsure checks the folder as it is."}`);
92
+ return full;
93
+ }
94
+ console.log(`${tint(GOLD, "Not found:")} no folder at ${full}. Check the path and try again.\n`);
95
+ }
96
+ console.log("Stopped. When you have the path, run: lintsure scan <folder>");
97
+ return null;
98
+ }
99
+ finally {
100
+ rl.close();
101
+ }
102
+ }
103
+ // What the start menu offers, in the order a new user needs them. `run` is the command line it stands for.
104
+ const START = [
105
+ { label: "Check this folder", run: ["scan"] },
106
+ // `show` is the command to learn; the menu itself asks for the folder with --pick.
107
+ { label: "Check another folder", run: ["scan", "--pick"], show: "scan <folder>" },
108
+ { label: "Is everything set up?", run: ["status"] },
109
+ { label: "Connect your coding agent", run: ["setup"] },
110
+ { label: "Give your agent skills", run: ["skills"], badge: true },
111
+ { label: "Every command and option", run: ["--help"] },
112
+ { label: "Quit", run: null },
113
+ ];
114
+ // True once a command was picked from the start menu: that person is using menus, so every command ends with one too.
115
+ let viaMenu = false;
116
+ let sawMenu = false; // the command that just ran ended with its own menu
117
+ let wantsMenu = false; // the person chose "Main menu"
118
+ const HINT = " Up and Down to move, Enter to run, q to quit";
119
+ /** The menu a command ends with when it was started from the start menu: what fits next, then the way back.
120
+ * Returns the exit code of the command it ran, or undefined when nothing was run (Main menu or Quit). */
121
+ async function offer(rows, color) {
122
+ sawMenu = true;
123
+ for (;;) {
124
+ const pick = await choose([...rows.map((r) => r.text), "Main menu", "Quit"], HINT, color);
125
+ if (pick === rows.length)
126
+ wantsMenu = true;
127
+ if (pick === null || pick >= rows.length)
128
+ return undefined;
129
+ const run = rows[pick].run;
130
+ // A row that only shows something comes back to this menu afterwards.
131
+ if (typeof run === "function") {
132
+ await run();
133
+ console.log("");
134
+ continue;
135
+ }
136
+ sawMenu = false; // the command run next gets its own ending
137
+ return main(run);
138
+ }
139
+ }
140
+ const COMMANDS = ["scan", "baseline", "init", "info", "setup", "skills", "status", "export"];
141
+ /** The command someone most likely meant: the same word without dashes, or one within two typing slips. Pure. */
142
+ function nearest(word) {
143
+ const slips = (a, b) => {
144
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
145
+ for (let i = 1; i <= a.length; i++) {
146
+ const next = [i];
147
+ for (let j = 1; j <= b.length; j++)
148
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
149
+ row = next;
150
+ }
151
+ return row[b.length];
152
+ };
153
+ return COMMANDS.find((c) => c === word) ?? COMMANDS.map((c) => [slips(c, word), c]).filter(([n]) => n <= 2).sort((x, y) => x[0] - y[0])[0]?.[1];
154
+ }
155
+ const startRows = () => START.map((s) => { const row = s.run ? `${s.label.padEnd(28)}lintsure ${s.show ?? s.run.join(" ")}` : s.label; return s.badge ? tint(BADGE, row) : row; });
12
156
  const HELP = `lintsure scan [path] [options]
13
157
  lintsure baseline [path]
14
158
  lintsure init [path] Three questions, saved to lintsure.config.yaml
15
159
  lintsure info [path] Show the settings a scan would use, and where each comes from
16
160
  lintsure setup [path] Add the Lintsure MCP server to this project's agent configs
17
161
  (shows the change; --yes writes it; --undo takes it out;
18
- --agents claude,cursor,vscode,gemini)
162
+ --agents claude,cursor,vscode,gemini,codex;
163
+ --manual for an agent set up in its own settings)
164
+ lintsure skills [path] Add Lintsure's skills to this project: short instruction files that
165
+ tell your agent when to check code and how to handle findings
166
+ (at a terminal you pick which; --yes adds all; --only a,b;
167
+ --undo takes them out)
19
168
  lintsure status [path] Check that this project is ready: Node, config, rules, agents
20
169
  lintsure export --otlp-json [path] Write .lintsure/activity.jsonl as an OpenTelemetry
21
170
  traces file (lintsure.otlp.json) for your own observability tool
@@ -35,6 +184,7 @@ scan options:
35
184
  --new-only With --fail-on: count only findings that are new since
36
185
  .lintsure/baseline.json
37
186
  --github Print GitHub Actions annotations, so findings show on the lines
187
+ --pick Ask which folder to check (at a terminal)
38
188
  --save-record Also save this run's readiness check record to
39
189
  .lintsure/records/<id>.json, building a dated history (no code inside)
40
190
 
@@ -49,7 +199,7 @@ fingerprint from lintsure-report.json, your reason, your name and the date.
49
199
  ${DISCLAIMER}
50
200
  Lintsure never sends your code anywhere.`;
51
201
  const VALUE_FLAGS = ["--framework", "--fail-on", "--project", "--diff"];
52
- const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all"];
202
+ const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all", "--pick"];
53
203
  /** Changed line numbers per file from `git diff -U0` output. Pure. */
54
204
  export function parseDiff(text) {
55
205
  const out = {};
@@ -185,23 +335,145 @@ async function main(argv) {
185
335
  console.log(`Wrote lintsure.otlp.json: ${rows.length} events. Nothing was sent; load the file into your collector or tool (OTLP/JSON).`);
186
336
  return 0;
187
337
  }
338
+ if (cmd === "skills") {
339
+ const root = resolve(raw.find((a, i) => !a.startsWith("--") && raw[i - 1] !== "--only") ?? ".");
340
+ const bad = raw.find((a) => a.startsWith("--") && !["--yes", "--undo", "--only"].includes(a));
341
+ if (bad) {
342
+ console.error(`Unknown option: ${bad}. Use --yes, --only <names> or --undo.`);
343
+ return 2;
344
+ }
345
+ if (!existsSync(root)) {
346
+ console.error(`No folder at ${root}.`);
347
+ return 2;
348
+ }
349
+ if (raw.includes("--undo")) {
350
+ const said = await removeSkills(root);
351
+ console.log(said.length ? said.join("\n") : "No Lintsure skills in this project.");
352
+ return 0;
353
+ }
354
+ const all = skills(), i = raw.indexOf("--only"), names = i >= 0 ? (raw[i + 1] ?? "").split(",").map((s) => s.trim()) : undefined;
355
+ const unknown = names?.filter((n) => !all.some((s) => s.name === n));
356
+ if (unknown?.length) {
357
+ console.error(`Unknown skill: ${unknown.join(", ")}. Choose from: ${all.map((s) => s.name).join(", ")}`);
358
+ return 2;
359
+ }
360
+ let chosen = names ? all.filter((s) => names.includes(s.name)) : all;
361
+ const folders = skillFolders(root), yes = raw.includes("--yes"), picking = !yes && !names && !!process.stdin.isTTY && !!process.stdout.isTTY;
362
+ console.log("");
363
+ step(tint(BADGE, " Lintsure skills "), ["A skill is a short instruction file. It tells your coding agent when to use Lintsure and what", "to do with what it finds. Connecting gives the agent the tools; skills give it the habit."]);
364
+ showFolder("Project", root);
365
+ step("Where they go", folders.map((f) => `${tint(BLUE, f)} ${tint("2", f.startsWith(".agents") ? "read by Codex, Cursor, Gemini CLI and many others" : "read by Claude Code")}`));
366
+ if (picking) {
367
+ step(`Found ${all.length} skills. Which do you want?`);
368
+ const width = Math.max(...all.map((s) => s.name.length)) + 2;
369
+ const picked = await chooseMany(all.map((s) => `${s.name.padEnd(width)}${s.about}`), (n) => (n ? `Install the ${n} selected` : "Install (none selected yet)"), " Up and Down to move, Enter to select or de-select, a for all, q to quit", !process.env.NO_COLOR && process.env.TERM !== "dumb");
370
+ if (!picked?.length) {
371
+ console.log("Nothing installed. Come back any time: lintsure skills");
372
+ return 0;
373
+ }
374
+ chosen = picked.map((n) => all[n]);
375
+ }
376
+ const apply = yes || picking;
377
+ const steps = await installSkills(root, chosen, apply);
378
+ const word = { add: apply ? "added" : "add", update: apply ? "updated, the earlier files kept as .lintsure-backup" : "update (the files there now are kept as backups)", same: "already there" };
379
+ const lines = steps.map((s) => `${apply ? `${tint("32", "✓")} ` : ""}${s.folder} ${tint("2", word[s.state])}`);
380
+ if (!apply) {
381
+ step(`Would install ${chosen.length} skill${chosen.length === 1 ? "" : "s"}`, lines);
382
+ console.log(`Nothing written yet. To apply, run: lintsure skills ${names ? `--only ${names.join(",")} ` : ""}--yes`);
383
+ return 0;
384
+ }
385
+ step(tint("32", `Done! Installed ${chosen.length} skill${chosen.length === 1 ? "" : "s"}`), lines);
386
+ console.log("Restart the agent so it reads them. Take them out any time with: lintsure skills --undo");
387
+ return 0;
388
+ }
188
389
  if (cmd === "setup" || cmd === "status") {
189
390
  const root = resolve(raw.find((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents") ?? ".");
190
391
  if (cmd === "status")
191
392
  return status(root);
393
+ if (raw.includes("--manual")) {
394
+ console.log(MANUAL());
395
+ return 0;
396
+ }
397
+ const named = raw.includes("--agents"), here = named ? [] : await detected(root);
398
+ // From the menu, ask which agent. Claude Code used to be the silent choice when the project had no agent folder yet.
399
+ if (viaMenu && !named && !raw.includes("--yes") && !raw.includes("--undo") && process.stdin.isTTY && process.stdout.isTTY) {
400
+ console.log("");
401
+ step("Connect your coding agent", CONNECT_NOTE.split("\n"));
402
+ showFolder("Project", root);
403
+ step("Which agent?");
404
+ const rows = AGENTS.map((a) => ({ text: `${a.name.padEnd(22)}${a.file.padEnd(24)}${here.includes(a) ? "used in this project" : ""}`.trimEnd(), run: ["setup", ...raw, "--agents", a.id] }));
405
+ rows.push({ text: "Another agent (Devin, Windsurf, Zed, ...)", run: ["setup", ...raw, "--manual"] });
406
+ if (here.length > 1)
407
+ rows.unshift({ text: `All ${here.length} used in this project`, run: ["setup", ...raw, "--agents", here.map((a) => a.id).join(",")] });
408
+ return (await offer(rows, !process.env.NO_COLOR && process.env.TERM !== "dumb")) ?? 0;
409
+ }
410
+ // Typed by hand with no agent named and none found here: say which one this is for, and how to pick another.
411
+ if (!named && !here.length && !raw.includes("--undo"))
412
+ console.log(`No agent folder in this project, so this is for Claude Code. For another one: lintsure setup --agents ${AGENTS.slice(1).map((a) => a.id).join(" | ")}\nFor an agent set up in its own settings (Devin, Windsurf, Zed): lintsure setup --manual\n`);
192
413
  const i = raw.indexOf("--agents");
193
414
  const agents = await pick(root, i >= 0 ? raw[i + 1]?.split(",").map((s) => s.trim()) : undefined);
194
415
  if (typeof agents === "string") {
195
416
  console.error(agents);
196
417
  return 2;
197
418
  }
198
- return raw.includes("--undo") ? undo(root, agents) : setup(root, agents, raw.includes("--yes"));
419
+ if (raw.includes("--undo"))
420
+ return undo(root, agents);
421
+ const code = await setup(root, agents, raw.includes("--yes"));
422
+ // From the menu, the preview is followed by the choice to write it, so nobody has to retype the command with --yes.
423
+ // Once the agent is connected, the next thing on offer is the skills that tell it when to use Lintsure.
424
+ if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
425
+ const pending = !raw.includes("--yes") && (await Promise.all(agents.map((a) => plan(root, a)))).some((p) => p.text);
426
+ const folder = raw.filter((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents").slice(0, 1);
427
+ console.log("");
428
+ const ran = await offer([pending ? { text: `${"Write these changes".padEnd(54)}lintsure setup --yes`, run: ["setup", ...raw, "--yes"] } : { text: `${"Install Lintsure's skills for your agent".padEnd(54)}lintsure skills`, run: ["skills", ...folder] }], !process.env.NO_COLOR && process.env.TERM !== "dumb");
429
+ if (ran !== undefined)
430
+ return ran;
431
+ }
432
+ return code;
199
433
  }
200
434
  if (cmd === "init" || cmd === "info")
201
435
  return (cmd === "init" ? init : info)(resolve(raw.find((a) => !a.startsWith("--")) ?? "."));
436
+ // The start screen is for a person at a terminal. Piped output and CI logs stay exactly as they were.
437
+ // With no command, a person at a terminal gets the start screen: a menu when keys can be read, a short list when
438
+ // they can't. Piped output and CI logs get the full help text, exactly as before.
439
+ if (!cmd && (process.stdout.isTTY || process.env.FORCE_COLOR)) {
440
+ console.log(banner());
441
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
442
+ console.log(startRows().slice(0, -1).map((r) => ` ${r}`).join("\n") + "\n");
443
+ return 0;
444
+ }
445
+ // The menu is home. After each command the person can come back here, so no screen is a dead end.
446
+ const color = !process.env.NO_COLOR && process.env.TERM !== "dumb";
447
+ for (let code = 0;;) {
448
+ showFolder("You are in", process.cwd());
449
+ const pick = await choose(startRows(), HINT, color);
450
+ const run = pick === null ? null : START[pick].run;
451
+ if (!run)
452
+ return code;
453
+ viaMenu = true;
454
+ sawMenu = false;
455
+ wantsMenu = false;
456
+ code = await main(run);
457
+ if (!sawMenu)
458
+ await offer([], color); // a command with no menu of its own still ends with the way back
459
+ if (!wantsMenu)
460
+ return code;
461
+ console.log(`\n${tint(BLUE, "Lintsure")} ${RULES_VERSION}\n`);
462
+ }
463
+ }
464
+ if (cmd === "--version" || cmd === "-v") {
465
+ console.log(RULES_VERSION);
466
+ return 0;
467
+ }
202
468
  if (cmd !== "scan" && cmd !== "baseline") {
203
- console.log(HELP);
204
- return cmd ? 2 : 0;
469
+ if (!cmd || ["--help", "-h", "help"].includes(cmd)) {
470
+ console.log(HELP);
471
+ return 0;
472
+ }
473
+ // A command typed with dashes (lintsure --scan) or misspelt: say what was meant, not the whole manual.
474
+ const guess = nearest(cmd.replace(/^-+/, ""));
475
+ console.error(`Unknown command: ${cmd}${guess ? `\nDid you mean: lintsure ${guess}` : ""}\nRun lintsure --help for every command and option.`);
476
+ return 2;
205
477
  }
206
478
  const parsed = parseArgs(raw);
207
479
  if ("error" in parsed) {
@@ -216,11 +488,40 @@ async function main(argv) {
216
488
  console.error(`No folder at ${path}. Pass the project folder to scan, for example: lintsure scan .`);
217
489
  return 2;
218
490
  }
491
+ // No folder was named and this one isn't a project. Lintsure can't guess where the project is: at a terminal it asks,
492
+ // elsewhere it says how to name it. A named folder is taken at its word.
493
+ const namedFolder = rest.some((a, i) => !a.startsWith("--") && !VALUE_FLAGS.includes(rest[i - 1]));
494
+ // --pick: ask for the folder. It is what "Check another folder" in the menu runs.
495
+ if (rest.includes("--pick")) {
496
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
497
+ console.error(`--pick asks a question, so it needs a terminal. Name the folder: lintsure ${cmd} <folder>`);
498
+ return 2;
499
+ }
500
+ console.log("");
501
+ const where = await askFolder(false);
502
+ return where ? main([cmd, where, ...rest.filter((a) => a !== "--pick")]) : 0;
503
+ }
504
+ if (!namedFolder && !looksLikeProject(path)) {
505
+ const why = `This folder doesn't look like a project: ${path}\nLintsure checks one project folder at a time, and it can't tell where yours is.`;
506
+ if (process.stdin.isTTY && process.stdout.isTTY) {
507
+ console.log(`\n${why}\n`);
508
+ const where = await askFolder(!isWholeDisk(path));
509
+ if (where === null)
510
+ return 0;
511
+ if (where)
512
+ return main([cmd, where, ...rest]);
513
+ }
514
+ else {
515
+ console.error(`${why}\nGo to your project folder first, or name it: lintsure ${cmd} <folder>`);
516
+ if (isWholeDisk(path))
517
+ return 2; // a whole home folder or drive is never what was meant
518
+ }
519
+ }
219
520
  const config = await readConfig(path);
220
521
  // Checked after the config loads its rule packs, so a pack's framework id is accepted.
221
522
  const bad = wanted?.filter((f) => !ALL_FRAMEWORKS.includes(f));
222
523
  if (bad?.length) {
223
- console.error(`Unknown framework: ${bad.join(", ")}`);
524
+ console.error(`Unknown framework: ${bad.join(", ")}\nChoose from: ${ALL_FRAMEWORKS.join(", ")}`);
224
525
  return 2;
225
526
  }
226
527
  if (config.problems.length) {
@@ -236,10 +537,10 @@ async function main(argv) {
236
537
  let changed;
237
538
  if (base) {
238
539
  try {
239
- changed = { base, lines: parseDiff(execFileSync("git", ["-c", "core.quotePath=false", "diff", "-U0", "--no-color", "--no-ext-diff", "--relative", base, "--"], { cwd: path, encoding: "utf8", maxBuffer: 64 << 20 })) };
540
+ changed = { base, lines: parseDiff(execFileSync("git", ["-c", "core.quotePath=false", "diff", "-U0", "--no-color", "--no-ext-diff", "--relative", base, "--"], { cwd: path, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 << 20 })) };
240
541
  }
241
542
  catch {
242
- console.error(`--diff: git could not compare with "${base}". Fetch it first (for example git fetch origin main).`);
543
+ console.error(`--diff: git could not compare with "${base}".\nCheck that this folder is inside a git repository and that "${base}" exists here (for example: git fetch origin main).`);
243
544
  return 2;
244
545
  }
245
546
  }
@@ -256,6 +557,11 @@ async function main(argv) {
256
557
  process.exit(2);
257
558
  }
258
559
  }
560
+ // A large project takes a few seconds: say that work has started, so the screen isn't blank.
561
+ if (process.stdout.isTTY) {
562
+ console.log("");
563
+ showFolder(`${tint(BLUE, "Lintsure")} is checking`, path);
564
+ }
259
565
  const report = await scan(path, wanted ?? config.frameworks ?? ALL_FRAMEWORKS, { why, source, all: rest.includes("--all") || undefined, changed, workspaceRules });
260
566
  const date = new Date().toISOString().slice(0, 10);
261
567
  if (cmd === "baseline") {
@@ -283,30 +589,131 @@ async function main(argv) {
283
589
  const open = report.findings.filter(isOpen);
284
590
  const n = (s) => open.filter((f) => f.status === s).length;
285
591
  const accepted = report.findings.length - open.length;
592
+ const hygiene = open.filter(isHygiene).length;
286
593
  if (report.record)
287
594
  console.log(`Record ${report.record.id} · ${report.record.createdAt.replace("T", " ").slice(0, 16)} UTC · ${report.record.counts.checkPoints} check points${report.policy ? ` · Policy #${report.policy.fingerprint}` : ""}`);
288
595
  // A check mark only when nothing is open: "✓ 3 gaps" read as a pass.
289
- console.log(`${open.length ? "!" : "✓"} ${open.length} open findings · ${n("gap")} gap · ${n("partial")} partial${accepted ? ` · ${accepted} accepted` : ""} · ${report.met.length} rules met · ${report.outside.length} outside code`);
596
+ console.log(`${open.length ? "!" : "✓"} ${open.length} open findings${hygiene ? ` (${open.length - hygiene} in the code, ${hygiene} repo hygiene)` : ""} · ${n("gap")} gap · ${n("partial")} partial${accepted ? ` · ${accepted} accepted` : ""} · ${report.met.length} rules met · ${report.outside.length} outside code`);
290
597
  console.log(` Read ${report.filesChecked} file${report.filesChecked === 1 ? "" : "s"}${report.filesSkipped ? `, skipped ${report.filesSkipped} (over 1 MB, binary or unreadable)` : ""}`);
291
598
  if (report.diffBase)
292
599
  console.log(` Only lines changed since ${report.diffBase}`);
600
+ {
601
+ const far = open.filter((f) => f.reach?.status === "unreachable" && !isHygiene(f)).length;
602
+ if (far)
603
+ console.log(` ${far} of the findings in the code ${far === 1 ? "is" : "are"} in files no route or entry point reaches (ranked lower in the report)`);
604
+ }
293
605
  if (report.held)
294
606
  console.log(` ${report.held} more at medium confidence: run with --all to see ${report.held === 1 ? "it" : "them"}`);
295
607
  if (report.baseline)
296
608
  console.log(` Since the baseline of ${report.baseline.created}: ${report.baseline.newCount} new, ${report.baseline.fixed.length} fixed, ${report.baseline.unchangedCount} unchanged`);
297
- for (const f of report.findings)
298
- console.log(`${(f.accepted && !f.accepted.expired ? "accepted" : f.status).padEnd(8)} ${f.file}:${f.line} ${f.title}${f.change === "new" ? " (new)" : ""}`);
609
+ // Findings in the code first; repo hygiene under its own label (sort is stable, so file order holds within each group).
610
+ const listed = [...report.findings].sort((a, b) => +isHygiene(a) - +isHygiene(b));
611
+ // For a person at a terminal the findings stand apart from the summary and the notes: a ruled heading per group, each
612
+ // file on its own line, and the status in colour. Piped output keeps one line per finding, which other tools read.
613
+ const pretty = (process.stdout.isTTY || !!process.env.FORCE_COLOR) && !rest.includes("--github");
614
+ const color = pretty && !process.env.NO_COLOR && process.env.TERM !== "dumb";
615
+ const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
616
+ const width = Math.min(process.stdout.columns || 100, 100);
617
+ // The old Windows console can't draw line characters reliably, so it gets plain dashes.
618
+ const dash = legacy() ? "-" : "─";
619
+ const ruled = (title) => `\n${paint("38;2;98;137;254", `${dash}${dash} ${title} `)}${paint("2", dash.repeat(Math.max(3, width - title.length - 4)))}`;
620
+ const group = (title, items) => {
621
+ if (!items.length)
622
+ return;
623
+ console.log(ruled(`${title} (${items.length})`));
624
+ let file = "";
625
+ for (const f of items) {
626
+ if (f.file !== file) {
627
+ file = f.file;
628
+ console.log(`\n ${paint("38;2;98;137;254", file)}`);
629
+ }
630
+ const status = f.accepted && !f.accepted.expired ? "accepted" : f.status;
631
+ const badge = status === "gap" ? paint("1;31", "GAP ") : status === "partial" ? paint("33", "PARTIAL ") : paint("2", "ACCEPTED");
632
+ console.log(` ${badge} ${paint("2", String(f.line).padStart(5))} ${f.title}${f.change === "new" ? paint("36", " (new)") : ""}`);
633
+ }
634
+ };
635
+ // The first few to fix: gaps before partials, higher risk first, reached code first.
636
+ const inCode = open.filter((f) => !isHygiene(f));
637
+ const order = (f) => (f.status === "gap" ? 0 : 3) + { high: 0, medium: 1, low: 2 }[f.severity] + (f.reach?.status === "unreachable" ? 0.5 : 0);
638
+ const ranked = [...inCode].sort((a, b) => order(a) - order(b)), first = ranked.slice(0, 3);
639
+ const fold = (t, pad) => t.replace(new RegExp(`(.{1,${width - pad.length - 2}})(\\s+|$)`, "g"), `$1\n${pad}`).trimEnd();
640
+ const reportFile = resolve("lintsure-report.md");
641
+ // A request a person can paste into any coding agent, connected or not: it names the finding and where the proposal is.
642
+ const request = (fs) => `Fix ${fs.length === 1 ? "this Lintsure finding" : "these Lintsure findings, one at a time"}: ${fs.map((f) => `${f.id} "${f.title}" at ${f.file}:${f.line}`).join("; ")}. The proposal for ${fs.length === 1 ? "it" : "each"} is in ${reportFile}. Show me ${fs.length === 1 ? "the" : "each"} change before you apply it, then check the file with Lintsure again.`;
643
+ if (pretty) {
644
+ // One line that fits the outcome, so the result is clear before any detail. It reports what the rules found and
645
+ // never calls a project safe: "nothing found" is said in those words.
646
+ const gaps = inCode.filter((f) => f.status === "gap");
647
+ const headline = !open.length ? paint("1;32", "Done! Nothing found by the current rules.")
648
+ : !inCode.length ? paint("1;32", "Done! Nothing in the code. Only housekeeping is left.")
649
+ : gaps.some((f) => f.severity === "high") ? `${paint(BLUE, "Lintsure")} ${paint("1;31", "found something that needs your attention.")}`
650
+ : gaps.length ? `${paint(BLUE, "Lintsure")} ${paint("1;33", "found something interesting.")}`
651
+ : inCode.every((f) => f.severity === "low") ? paint("1;33", inCode.length === 1 ? "A minor finding, worth a look." : "Minor findings, worth a look.")
652
+ : paint("1;33", "Worth a look.");
653
+ console.log(`\n${headline}`);
654
+ group("Findings in the code", listed.filter((f) => !isHygiene(f)));
655
+ group("Repo hygiene: housekeeping, not flaws in the code", listed.filter(isHygiene));
656
+ if (first.length) {
657
+ console.log(ruled(`Start here (${first.length} of ${inCode.length})`));
658
+ first.forEach((f, i) => console.log(`\n ${i + 1}. ${f.title}\n ${paint("2", `${f.file}:${f.line}`)}\n ${paint("36", "Fix:")} ${fold(f.fix, " ")}`));
659
+ if (inCode.length > first.length)
660
+ console.log(`\n ${paint("2", `The fix for every finding is in ${resolve("lintsure-report.md")}`)}`);
661
+ }
662
+ console.log(ruled("What next") + "\n");
663
+ }
664
+ else
665
+ for (const f of listed)
666
+ console.log(`${f === listed.find(isHygiene) ? "Repo hygiene (housekeeping, not flaws in the code):\n" : ""}${(f.accepted && !f.accepted.expired ? "accepted" : f.status).padEnd(8)} ${f.file}:${f.line} ${f.title}${f.change === "new" ? " (new)" : ""}`);
299
667
  if (rest.includes("--github"))
300
668
  for (const f of open) {
301
669
  const msg = `${f.title}. Proposed change, needs your approval: ${f.proposal.what}`.replace(/%/g, "%25").replace(/\r?\n/g, " ");
302
670
  console.log(`::${f.status === "gap" ? "error" : "warning"} file=${f.file},line=${f.line},title=Lintsure ${f.ruleId}::${msg}`);
303
671
  }
304
- console.log("Report saved to lintsure-report.md");
672
+ console.log(`Report saved to ${pretty ? resolve("lintsure-report.md") : "lintsure-report.md"}`);
305
673
  if (rest.includes("--report"))
306
674
  console.log("Assessment saved to lintsure-assessment.html (open it in a browser to read, print or save as PDF). It is a draft until a qualified person reviews and signs it.");
307
675
  console.log("\nNext steps:");
308
676
  nextSteps(report).forEach((x, i) => console.log(` ${i + 1}. ${x}`));
309
- console.log(`\n${DISCLAIMER}`);
677
+ // The steps above say what to decide. These are the commands that act on this scan, written out so they can be
678
+ // copied; only the ones that apply are listed.
679
+ const given = rest.find((a, i) => !a.startsWith("--") && !VALUE_FLAGS.includes(rest[i - 1]));
680
+ const here = given ? [given] : [];
681
+ const follow = [
682
+ ...(report.held ? [{ label: `Also show the ${report.held} held-back finding${report.held === 1 ? "" : "s"}`, run: ["scan", ...here, "--all"] }] : []),
683
+ ...(open.length && !report.baseline ? [{ label: "Remember these, so later scans show only what is new", run: ["baseline", ...here] }] : []),
684
+ ...(rest.includes("--report") ? [] : [{ label: "Write a printable assessment", run: ["scan", ...here, "--report"] }]),
685
+ { label: "Connect your coding agent, then ask it to fix one", run: ["setup", ...here] },
686
+ ];
687
+ // Menu only: the full proposal for one finding, and a request to paste into a coding agent. Lintsure never edits code.
688
+ const showFix = async () => {
689
+ const list = [...ranked, ...open.filter(isHygiene)].slice(0, 15);
690
+ console.log(`\nWhich finding?${open.length > list.length ? ` (the first ${list.length} of ${open.length}; the rest are in the report)` : ""}`);
691
+ const pick = await choose([...list.map((f) => `${f.id} ${f.title} ${f.file}:${f.line}`.slice(0, width - 6)), "Back"], HINT, color);
692
+ if (pick === null || pick >= list.length)
693
+ return;
694
+ const f = list[pick], row = (name, text) => console.log(` ${paint(GOLD, name.padEnd(8))}${fold(text, " ")}`);
695
+ console.log(ruled(`${f.id} ${f.title}`) + "\n");
696
+ row("Where", f.proposal.where);
697
+ row("Change", f.proposal.what);
698
+ row("Why", f.proposal.why);
699
+ row("Gain", f.proposal.benefit);
700
+ console.log(`\n ${paint("2", "Nothing was changed. To hand it over, paste this into your coding agent:")}\n\n ${fold(request([f]), " ")}`);
701
+ };
702
+ const fixRows = open.length ? [{ text: "Show the fix for a finding", run: showFix }, ...(first.length ? [{ text: `Hand the first ${first.length === 1 ? "one" : first.length} to your coding agent`, run: async () => console.log(`\n ${paint("2", "Paste this into your coding agent:")}\n\n ${fold(request(first), " ")}`) }] : [])] : [];
703
+ // A folder with a space in its name is quoted, so the line can be pasted as it is.
704
+ const followRows = follow.map((f) => `${f.label.padEnd(54)}lintsure ${f.run.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(" ")}`);
705
+ const asMenu = viaMenu && !!process.stdin.isTTY && !!process.stdout.isTTY;
706
+ if (pretty && !asMenu)
707
+ console.log(`\nRun next:\n${followRows.map((r) => ` ${r}`).join("\n")}`);
708
+ // In a terminal the closing note is dimmed and wrapped at word ends, so it reads as a footnote and never splits a word.
709
+ const wrap = (t) => t.split("\n").map((p) => p.replace(new RegExp(`(.{1,${width - 2}})(\\s+|$)`, "g"), "$1\n").trimEnd()).join("\n");
710
+ console.log(`\n${pretty ? paint("2", wrap(DISCLAIMER)) : DISCLAIMER}`);
711
+ if (asMenu) {
712
+ console.log("\nRun next:");
713
+ const ran = await offer([...fixRows, ...follow.map((f, i) => ({ text: followRows[i], run: f.run }))], color);
714
+ if (ran !== undefined)
715
+ return ran;
716
+ }
310
717
  const failOn = flag("--fail-on")?.toLowerCase();
311
718
  const counted = rest.includes("--new-only") && report.baseline ? open.filter((f) => f.change === "new") : open;
312
719
  if (failOn === "gap" && counted.some((f) => f.status === "gap"))
@@ -0,0 +1,15 @@
1
+ /** Where the highlight goes for a key: arrows (or k and j) wrap around, Home and End jump. Pure. */
2
+ export declare function moved(key: string | undefined, at: number, count: number): number;
3
+ /** The menu as lines of text, with the chosen row marked. The marker is a character, so it reads without colour too.
4
+ * The row is coloured, not bold: on a light theme bold text can come out grey, which made the choice look faded. Pure. */
5
+ export declare function frame(rows: string[], at: number, color: boolean): string[];
6
+ /** A pick-any list as lines: a circle before each row, filled when picked (green in colour), then the closing rows,
7
+ * which have no circle. The filled and empty circles differ in shape, so the list reads without colour too. Pure. */
8
+ export declare function frameMany(rows: string[], picked: ReadonlySet<number>, closing: string[], at: number, color: boolean): string[];
9
+ /** Shows the menu and waits for a choice. Resolves with the row number, or null for q, Esc or Ctrl+C.
10
+ * Only call this when both stdin and stdout are a terminal. */
11
+ export declare function choose(rows: string[], hint: string, color: boolean): Promise<number | null>;
12
+ /** Shows a pick-any list. Enter (or Space) on a row picks it or lets it go; "a" picks all, or none when all are picked.
13
+ * Under the rows come a row that finishes, named by `finish` from the number picked, and Quit. Resolves with the
14
+ * picked row numbers (it may be empty), or null for Quit, q, Esc or Ctrl+C. Only call this at a terminal. */
15
+ export declare function chooseMany(rows: string[], finish: (picked: number) => string, hint: string, color: boolean): Promise<number[] | null>;