lintsure 0.3.15 → 0.3.16

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
@@ -1,17 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  // npx lintsure scan [path] [options] npx lintsure baseline [path]
3
- // Writes reports into the current folder. Never sends anything over the network.
3
+ // Writes reports into the current folder. A scan never uses the network. One command does, lintsure deps, and only
4
+ // after it has said what it will send and been given --yes.
4
5
  import { execFileSync } from "node:child_process";
5
- import { existsSync, statSync } from "node:fs";
6
+ import { constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
6
7
  import { homedir } from "node:os";
7
- import { access, mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import { access, copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
8
9
  import { basename, dirname, join, resolve } from "node:path";
9
10
  import { createInterface } from "node:readline/promises";
10
- import { AGENTS, CONNECT_NOTE, MANUAL, detected, status, pick, plan, setup, undo } from "./agents.js";
11
+ import { AGENTS, CONNECT_NOTE, MANUAL, callingAgent, detected, status, pick, plan, setup, undo } from "./agents.js";
11
12
  import { parseActivity, toOtlp } from "./otel.js";
12
- import { ALL_FRAMEWORKS, BASELINE_FILE, DISCLAIMER, RULES_VERSION, classify, isHygiene, isOpen, nextSteps, readConfig, scan, toAssessmentHtml, toBaseline, toMarkdown, toSarif } from "@lintsure/core";
13
+ import { ALL_FRAMEWORKS, BASELINE_FILE, DISCLAIMER, RULES_VERSION, classify, isHygiene, isNonShipping, isOpen, nextSteps, readConfig, scan, toAssessmentHtml, toBaseline, toMarkdown, toSarif } from "@lintsure/core";
13
14
  import { choose, chooseMany } from "./menu.js";
14
15
  import { installSkills, removeSkills, skillFolders, skills } from "./skills.js";
16
+ import { advisories, pinned } from "./deps.js";
17
+ import { GUARD_AGENTS, PLUGIN_TAG, claudeCli, installGuards, pluginHome, planGuards, removeGuards } from "./plugin.js";
15
18
  // The old Windows console can't draw block, line or diamond characters reliably, so it gets plain ones.
16
19
  const legacy = (env = process.env) => process.platform === "win32" && !env.WT_SESSION && !env.TERM_PROGRAM && !env.ConEmuANSI && !env.FORCE_COLOR;
17
20
  // Brand colours: the logo blue for names and choices, gold for the rail that ties the steps of one task together.
@@ -66,10 +69,23 @@ function projectSign(dir) {
66
69
  return `inside the git repository ${basename(at)}`;
67
70
  return null;
68
71
  }
72
+ // Files that say "a project starts here". A git folder, a Lintsure folder or a Dockerfile can sit above several projects.
73
+ const MANIFESTS = PROJECT_MARKERS.filter((m) => ![".git", ".lintsure", "lintsure.config.yaml", "Dockerfile", "docker-compose.yml", "compose.yaml"].includes(m));
74
+ /** The projects directly inside a folder that is not one itself: a workspace. Empty for a normal project. */
75
+ export function subProjects(dir) {
76
+ if (MANIFESTS.some((m) => existsSync(join(dir, m))))
77
+ return [];
78
+ try {
79
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules" && [...MANIFESTS, ".git"].some((m) => existsSync(join(dir, e.name, m)))).map((e) => e.name);
80
+ }
81
+ catch {
82
+ return [];
83
+ }
84
+ }
69
85
  /** The folder and whether a project was found in it, as one step. */
70
86
  function showFolder(title, dir) {
71
87
  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")]);
88
+ step(`${title} ${tint(BLUE, basename(dir) || dir)}`, [tint("2", dir), subProjects(dir).length > 1 ? tint(GOLD, `A workspace: ${subProjects(dir).length} projects inside`) : sign ? `${tint("32", "Project found")}: ${sign}` : tint(GOLD, "No project found here")]);
73
89
  }
74
90
  /** Asks a person for their project folder. Returns its full path, "" for Enter alone (use this folder), or null to stop.
75
91
  * A pasted path may carry quotes, and ~ stands for the home folder. Only call this at a terminal. */
@@ -107,11 +123,20 @@ const START = [
107
123
  { label: "Check another folder", run: ["scan", "--pick"], show: "scan <folder>" },
108
124
  { label: "Is everything set up?", run: ["status"] },
109
125
  { label: "Connect your coding agent", run: ["setup"] },
110
- { label: "Give your agent skills", run: ["skills"], badge: true },
126
+ { label: "Give your agent skills", run: ["skills"] },
127
+ { label: "Add the Lintsure plugin", run: ["plugin"] },
111
128
  { label: "Every command and option", run: ["--help"] },
112
129
  { label: "Quit", run: null },
113
130
  ];
114
131
  // True once a command was picked from the start menu: that person is using menus, so every command ends with one too.
132
+ /** skills and plugin write into one project. Run with no folder named, from a folder that isn't a project (an agent's
133
+ * scratch folder, a home folder), they stop and say where to go. Returns the message, or null to carry on. */
134
+ function wrongPlace(cmd, raw, valueFlag) {
135
+ const named = raw.some((a, i) => !a.startsWith("--") && raw[i - 1] !== valueFlag);
136
+ if (viaMenu || named || raw.includes("--here") || raw.includes("--undo") || looksLikeProject(resolve(".")))
137
+ return null;
138
+ return `No project found in ${resolve(".")}.\nlintsure ${cmd} works on one project. Go to your project's folder and run it again, or name the folder:\n lintsure ${cmd} path/to/your/project\nTo use this folder anyway: lintsure ${cmd} --here`;
139
+ }
115
140
  let viaMenu = false;
116
141
  let sawMenu = false; // the command that just ran ended with its own menu
117
142
  let wantsMenu = false; // the person chose "Main menu"
@@ -137,7 +162,7 @@ async function offer(rows, color) {
137
162
  return main(run);
138
163
  }
139
164
  }
140
- const COMMANDS = ["scan", "baseline", "init", "info", "setup", "skills", "status", "export"];
165
+ const COMMANDS = ["scan", "baseline", "init", "info", "setup", "skills", "plugin", "hook", "fix", "deps", "history", "status", "export"];
141
166
  /** The command someone most likely meant: the same word without dashes, or one within two typing slips. Pure. */
142
167
  function nearest(word) {
143
168
  const slips = (a, b) => {
@@ -153,53 +178,74 @@ function nearest(word) {
153
178
  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
179
  }
155
180
  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; });
156
- const HELP = `lintsure scan [path] [options]
157
- lintsure baseline [path]
158
- lintsure init [path] Three questions, saved to lintsure.config.yaml
159
- lintsure info [path] Show the settings a scan would use, and where each comes from
160
- lintsure setup [path] Add the Lintsure MCP server to this project's agent configs
161
- (shows the change; --yes writes it; --undo takes it out;
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)
168
- lintsure status [path] Check that this project is ready: Node, config, rules, agents
169
- lintsure export --otlp-json [path] Write .lintsure/activity.jsonl as an OpenTelemetry
170
- traces file (lintsure.otlp.json) for your own observability tool
171
-
172
- scan options:
173
- --framework <ids> Comma list: ${ALL_FRAMEWORKS.join(", ")}
174
- (default: lintsure.config.yaml if present, else all)
175
- --all Also list medium-confidence findings (held back by default)
176
- --diff <base> Only list findings on lines changed since <base>, e.g. origin/main
177
- --json Also write lintsure-report.json
178
- --sarif Also write lintsure.sarif (for GitHub code scanning and editors)
179
- --report Also write lintsure-assessment.html, a multi-page report
180
- to review, print or save as PDF
181
- --project <name> Project name on the assessment cover (default: folder name)
182
- --fail-on <status> Exit 1 if any open finding is "gap" or "partial" (for CI). Held-back
183
- medium-confidence findings count only with --all
184
- --new-only With --fail-on: count only findings that are new since
185
- .lintsure/baseline.json
186
- --github Print GitHub Actions annotations, so findings show on the lines
187
- --pick Ask which folder to check (at a terminal)
188
- --save-record Also save this run's readiness check record to
189
- .lintsure/records/<id>.json, building a dated history (no code inside)
190
-
191
- baseline:
192
- Saves the current open findings to .lintsure/baseline.json in the scanned folder.
193
- Later scans show what is new, fixed or unchanged. The file holds rule ids, file
194
- paths and one-way fingerprints, never code. You decide whether to commit it.
195
-
196
- Accept a finding after review by adding it to .lintsure/accepted.yaml, with the
197
- fingerprint from lintsure-report.json, your reason, your name and the date.
198
-
199
- ${DISCLAIMER}
200
- Lintsure never sends your code anywhere.`;
181
+ const HELP = `lintsure scan [path] [options]
182
+ lintsure baseline [path]
183
+ lintsure init [path] Three questions, saved to lintsure.config.yaml
184
+ lintsure info [path] Show the settings a scan would use, and where each comes from
185
+ lintsure setup [path] Add the Lintsure MCP server to this project's agent configs
186
+ (with no path it asks: --everywhere for every project on this
187
+ machine, --here for this folder;
188
+ shows the change; --yes writes it; --undo takes it out;
189
+ --agents claude,cursor,vscode,gemini,codex;
190
+ --manual for an agent set up in its own settings)
191
+ lintsure skills [path] Add Lintsure's skills to this project: short instruction files that
192
+ tell your agent when to check code and how to handle findings
193
+ (at a terminal you pick which; --yes adds all; --only a,b;
194
+ --undo takes them out)
195
+ lintsure fix [path] [F-001 ...] Apply the change for findings whose rule knows the exact one
196
+ (shows it first; --all includes held-back findings; --yes writes it,
197
+ backs the file up, scans again,
198
+ and puts the file back if the finding is still there; --undo puts back
199
+ what the last fix changed)
200
+ lintsure deps [path] Look up the project's pinned packages for known vulnerabilities.
201
+ The only command that uses the network: it says what it will send
202
+ (package names and versions, never code) and sends it with --yes
203
+ lintsure history [path] List the records saved with scan --save-record, oldest first
204
+ lintsure hook [path] Check the lines you commit: adds a git pre-commit hook that runs
205
+ lintsure scan --staged --fail-on gap (shows it first; --yes writes it;
206
+ --undo removes it; an existing hook of your own is left alone)
207
+ lintsure plugin [path] Install the guards that run while your agent works: the full plugin
208
+ for Claude Code, and hooks files for Cursor, Codex and Gemini CLI
209
+ (shows the plan first; --agents claude,cursor,codex,gemini;
210
+ --yes installs; --undo takes them out)
211
+ lintsure status [path] Check that this project is ready: Node, config, rules, agents
212
+ lintsure export --otlp-json [path] Write .lintsure/activity.jsonl as an OpenTelemetry
213
+ traces file (lintsure.otlp.json) for your own observability tool
214
+
215
+ scan options:
216
+ --framework <ids> Comma list: ${ALL_FRAMEWORKS.join(", ")}
217
+ (default: lintsure.config.yaml if present, else all)
218
+ --all Also list medium-confidence findings (held back by default)
219
+ --diff <base> Only list findings on lines changed since <base>, e.g. origin/main
220
+ --staged Only list findings on lines that are staged for the next commit
221
+ --json Also write lintsure-report.json
222
+ --sarif Also write lintsure.sarif (for GitHub code scanning and editors)
223
+ --report Also write lintsure-assessment.html, a multi-page report
224
+ to review, print or save as PDF
225
+ --project <name> Project name on the assessment cover (default: folder name)
226
+ --fail-on <status> Exit 1 if any open finding is "gap" or "partial" (for CI). Held-back
227
+ medium-confidence findings count only with --all
228
+ --observe With --fail-on: say when the run would have failed, and pass anyway.
229
+ For watching the gate before it blocks anyone
230
+ --new-only With --fail-on: count only findings that are new since
231
+ .lintsure/baseline.json
232
+ --github Print GitHub Actions annotations, so findings show on the lines
233
+ --pick Ask which folder to check (at a terminal)
234
+ --save-record Also save this run's readiness check record to
235
+ .lintsure/records/<id>.json, building a dated history (no code inside)
236
+
237
+ baseline:
238
+ Saves the current open findings to .lintsure/baseline.json in the scanned folder.
239
+ Later scans show what is new, fixed or unchanged. The file holds rule ids, file
240
+ paths and one-way fingerprints, never code. You decide whether to commit it.
241
+
242
+ Accept a finding after review by adding it to .lintsure/accepted.yaml, with the
243
+ fingerprint from lintsure-report.json, your reason, your name and the date.
244
+
245
+ ${DISCLAIMER}
246
+ Lintsure never sends your code anywhere. Only "lintsure deps --yes" uses the network.`;
201
247
  const VALUE_FLAGS = ["--framework", "--fail-on", "--project", "--diff"];
202
- const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all", "--pick"];
248
+ const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all", "--pick", "--staged", "--observe"];
203
249
  /** Changed line numbers per file from `git diff -U0` output. Pure. */
204
250
  export function parseDiff(text) {
205
251
  const out = {};
@@ -219,7 +265,7 @@ export function parseDiff(text) {
219
265
  }
220
266
  return out;
221
267
  }
222
- const FRAMEWORK_NAMES = { "owasp-top10": "OWASP Top 10", "cwe-top25": "CWE Top 25", gdpr: "GDPR", "eu-ai-act": "EU AI Act", "owasp-llm": "OWASP Top 10 for LLM apps", cra: "EU Cyber Resilience Act" };
268
+ const FRAMEWORK_NAMES = { "owasp-top10": "OWASP Top 10", "cwe-top25": "CWE Top 25", gdpr: "GDPR", "eu-ai-act": "EU AI Act", "owasp-llm": "OWASP Top 10 for LLM apps", "owasp-ast": "OWASP Agentic Skills Top 10", "owasp-api": "OWASP API Security Top 10", cra: "EU Cyber Resilience Act" };
223
269
  /** First-run setup: three questions, saved once, never asked in CI. */
224
270
  async function init(path) {
225
271
  const file = join(path, "lintsure.config.yaml");
@@ -243,7 +289,7 @@ async function init(path) {
243
289
  }
244
290
  };
245
291
  console.log("Lintsure setup: 3 questions. Press Enter for the first answer.");
246
- const what = await pick("1. What should Lintsure check?", ["Security only (OWASP Top 10, CWE Top 25)", "Security and privacy (adds GDPR)", "Everything (all six frameworks)", "Let me pick"]);
292
+ const what = await pick("1. What should Lintsure check?", ["Security only (OWASP Top 10, CWE Top 25)", "Security and privacy (adds GDPR)", "Everything (all eight frameworks)", "Let me pick"]);
247
293
  let chosen = what === 1 ? ["owasp-top10", "cwe-top25"] : what === 2 ? ["owasp-top10", "cwe-top25", "gdpr"] : [...ALL_FRAMEWORKS];
248
294
  if (what === 4) {
249
295
  console.log("\nType the numbers you want, separated by commas, or press Enter for all:");
@@ -335,11 +381,302 @@ async function main(argv) {
335
381
  console.log(`Wrote lintsure.otlp.json: ${rows.length} events. Nothing was sent; load the file into your collector or tool (OTLP/JSON).`);
336
382
  return 0;
337
383
  }
384
+ // lintsure fix: applies a change only where the rule knows the exact one (a setting flipped, a line added). Everything
385
+ // else needs judgement and stays a proposal. Shown first; --yes writes; each file is backed up; a change that does not
386
+ // make its finding go away is put back.
387
+ if (cmd === "fix") {
388
+ const bad = raw.find((a) => a.startsWith("--") && !["--yes", "--all", "--undo"].includes(a));
389
+ if (bad) {
390
+ console.error(`Unknown option: ${bad}. Use: lintsure fix [folder] [F-001 ...] [--all] [--yes], or lintsure fix --undo`);
391
+ return 2;
392
+ }
393
+ const words = raw.filter((a) => !a.startsWith("--")), ids = words.filter((a) => /^F-\d+$/i.test(a)).map((a) => a.toUpperCase());
394
+ const root = resolve(words.find((a) => !/^F-\d+$/i.test(a)) ?? ".");
395
+ if (!existsSync(root)) {
396
+ console.error(`No folder at ${root}.`);
397
+ return 2;
398
+ }
399
+ // --undo puts back the files the last fix changed, from the backups it made.
400
+ const last = join(root, ".lintsure", "last-fix.json");
401
+ if (raw.includes("--undo")) {
402
+ const files = existsSync(last) ? JSON.parse(readFileSync(last, "utf8")).files ?? [] : [];
403
+ if (!files.length) {
404
+ console.log("Nothing to undo: no fix has been applied here, or it was already undone.");
405
+ return 0;
406
+ }
407
+ for (const file of files) {
408
+ const path = join(root, file);
409
+ if (!existsSync(path + ".lintsure-backup")) {
410
+ console.log(`left ${file}: its backup is gone, so it was not touched`);
411
+ continue;
412
+ }
413
+ await copyFile(path + ".lintsure-backup", path);
414
+ await rm(path + ".lintsure-backup");
415
+ console.log(`back ${file}`);
416
+ }
417
+ await rm(last);
418
+ return 0;
419
+ }
420
+ const config = await readConfig(root);
421
+ if (config.problems.length) {
422
+ console.error("Problems in lintsure.config.yaml (fix them first):");
423
+ config.problems.forEach((p) => console.error(` ${p}`));
424
+ return 2;
425
+ }
426
+ const frameworks = config.frameworks ?? ALL_FRAMEWORKS;
427
+ // The same list the person saw: --all here when the scan was run with --all, so the finding numbers match.
428
+ const opts = { source: "cli", all: raw.includes("--all") || undefined };
429
+ const before = await scan(root, frameworks, opts);
430
+ const unknown = ids.filter((id) => !before.findings.some((f) => f.id === id));
431
+ if (unknown.length) {
432
+ console.error(`No finding ${unknown.join(", ")} in this scan. Numbers change when the code does: run lintsure scan again.`);
433
+ return 2;
434
+ }
435
+ const wanted = before.findings.filter((f) => isOpen(f) && (!ids.length || ids.includes(f.id)));
436
+ const exact = wanted.filter((f) => f.patch), rest = wanted.length - exact.length;
437
+ for (const f of wanted.filter((x) => !x.patch && ids.includes(x.id)))
438
+ console.log(`${f.id} has no exact change: its fix needs judgement. The proposal is in the report, or hand it to your coding agent.`);
439
+ if (!exact.length) {
440
+ console.log(`No finding here has an exact change Lintsure can apply.${rest ? ` ${rest} need a person or a coding agent: lintsure scan` : ""}`);
441
+ return 0;
442
+ }
443
+ for (const f of exact)
444
+ console.log(`${f.id} ${f.title}\n ${f.file}:${f.patch.line}\n${f.patch.old != null ? ` - ${f.patch.old.trim()}\n` : ""}${f.patch.text.replace(/\n$/, "").split("\n").map((t) => ` + ${t.trim()}`).join("\n")}\n`);
445
+ if (!raw.includes("--yes")) {
446
+ console.log(`Nothing changed yet. To apply ${exact.length === 1 ? "it" : `these ${exact.length}`}, run: lintsure fix${ids.length ? " " + ids.join(" ") : ""}${raw.includes("--all") ? " --all" : ""} --yes\nEach file is backed up first (<file>.lintsure-backup).${rest ? `\n${rest} other finding${rest === 1 ? " needs" : "s need"} a person or a coding agent.` : ""}`);
447
+ if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
448
+ console.log("");
449
+ const ran = await offer([{ text: `${"Apply these changes".padEnd(54)}lintsure fix --yes`, run: ["fix", ...raw, "--yes"] }], !process.env.NO_COLOR && process.env.TERM !== "dumb");
450
+ if (ran !== undefined)
451
+ return ran;
452
+ }
453
+ return 0;
454
+ }
455
+ const byFile = new Map();
456
+ for (const f of exact)
457
+ byFile.set(f.file, [...(byFile.get(f.file) ?? []), f]);
458
+ const originals = new Map(), skipped = [];
459
+ for (const [file, list] of byFile) {
460
+ const path = join(root, file), text = await readFile(path, "utf8"), nl = text.includes("\r\n") ? "\r\n" : "\n", lines = text.split(/\r?\n/);
461
+ // From the bottom up, so an inserted line does not move the ones still to change.
462
+ for (const f of [...list].sort((a, b) => b.patch.line - a.patch.line)) {
463
+ const p = f.patch, at = p.line - 1, add = p.text.replace(/\n$/, "").split("\n");
464
+ if (p.old == null)
465
+ lines.splice(at, 0, ...add);
466
+ else if (lines[at] === p.old)
467
+ lines.splice(at, 1, ...add);
468
+ else
469
+ skipped.push(`${f.id}: ${file}:${p.line} changed since the scan, so it was left alone`);
470
+ }
471
+ const next = lines.join(nl);
472
+ if (next === text)
473
+ continue;
474
+ // The first backup is the user's original: never overwritten by a later run.
475
+ try {
476
+ await copyFile(path, path + ".lintsure-backup", constants.COPYFILE_EXCL);
477
+ }
478
+ catch (e) {
479
+ if (e.code !== "EEXIST") {
480
+ skipped.push(`${file}: could not be backed up, so it was left alone`);
481
+ continue;
482
+ }
483
+ }
484
+ originals.set(file, text);
485
+ await writeFile(path, next);
486
+ }
487
+ // Proof: scan again. A file whose findings from these rules did not go down is put back as it was.
488
+ const after = await scan(root, frameworks, opts);
489
+ const count = (r, ruleId, file) => r.findings.filter((f) => f.ruleId === ruleId && f.file === file).length;
490
+ let fixed = 0;
491
+ for (const [file, text] of originals) {
492
+ const mine = byFile.get(file), worse = mine.some((f) => count(after, f.ruleId, file) >= count(before, f.ruleId, file));
493
+ if (worse) {
494
+ await writeFile(join(root, file), text);
495
+ originals.delete(file);
496
+ skipped.push(`${file}: the change did not clear its finding, so the file was put back`);
497
+ }
498
+ else {
499
+ fixed += mine.length;
500
+ console.log(`fixed ${file} (${mine.map((f) => f.id).join(", ")}; your original is in ${file}.lintsure-backup)`);
501
+ }
502
+ }
503
+ // What --undo will put back.
504
+ if (originals.size) {
505
+ await mkdir(join(root, ".lintsure"), { recursive: true });
506
+ await writeFile(last, JSON.stringify({ files: [...originals.keys()] }) + "\n");
507
+ }
508
+ skipped.forEach((s) => console.log(`left ${s}`));
509
+ console.log(`\n${fixed ? `Done! ${fixed} finding${fixed === 1 ? "" : "s"} fixed and checked again.` : "Nothing was changed."} Look at the change before you commit it: git diff${fixed ? "\nPut it back with: lintsure fix --undo" : ""}`);
510
+ return skipped.length && !fixed ? 1 : 0;
511
+ }
512
+ // lintsure deps: the one command that uses the network, and only after saying what it sends and being told to.
513
+ if (cmd === "deps") {
514
+ const bad = raw.find((a) => a.startsWith("--") && a !== "--yes");
515
+ if (bad) {
516
+ console.error(`Unknown option: ${bad}. Use: lintsure deps [folder] [--yes]`);
517
+ return 2;
518
+ }
519
+ const root = resolve(raw.find((a) => !a.startsWith("--")) ?? ".");
520
+ if (!existsSync(root)) {
521
+ console.error(`No folder at ${root}.`);
522
+ return 2;
523
+ }
524
+ const { found, files } = await pinned(root);
525
+ if (!found.length) {
526
+ console.log("No package-lock.json or pinned requirements.txt at the top of this folder, so there is nothing to look up.");
527
+ return 0;
528
+ }
529
+ console.log(`This asks the public database at api.osv.dev about ${found.length} package${found.length === 1 ? "" : "s"} from ${files.join(" and ")}.\nIt sends package names and versions. It never sends code, file names or anything else from this project.`);
530
+ if (!raw.includes("--yes")) {
531
+ console.log("\nNothing sent yet. To run it: lintsure deps --yes");
532
+ return 0;
533
+ }
534
+ let hits;
535
+ try {
536
+ hits = await advisories(found);
537
+ }
538
+ catch (e) {
539
+ console.error(`\nCouldn't reach api.osv.dev (${e instanceof Error ? e.message : e}). Nothing else was tried.`);
540
+ return 2;
541
+ }
542
+ if (!hits.size) {
543
+ console.log(`\nDone! None of the ${found.length} packages has a known advisory in that database today.`);
544
+ return 0;
545
+ }
546
+ console.log("");
547
+ for (const [p, ids] of [...hits].sort((a, b) => b[1].length - a[1].length || a[0].name.localeCompare(b[0].name)))
548
+ console.log(`${`${p.name}@${p.version}`.padEnd(44)} ${ids.length} known ${ids.slice(0, 3).join(", ")}${ids.length > 3 ? ", ..." : ""}`);
549
+ console.log(`\n${hits.size} of ${found.length} packages have a known advisory. Look one up at https://osv.dev/vulnerability/<id>, then update to a version that fixes it.\nA listed advisory may not affect how you use the package: read it before you decide.`);
550
+ return 0;
551
+ }
552
+ // lintsure history: the records saved by scan --save-record, oldest first, so a trend is visible without a dashboard.
553
+ if (cmd === "history") {
554
+ const root = resolve(raw.find((a) => !a.startsWith("--")) ?? "."), dir = join(root, ".lintsure", "records");
555
+ const rows = (existsSync(dir) ? readdirSync(dir) : []).filter((f) => f.endsWith(".json")).flatMap((f) => { try {
556
+ const r = JSON.parse(readFileSync(join(dir, f), "utf8")).record;
557
+ return r?.createdAt && r.counts ? [r] : [];
558
+ }
559
+ catch {
560
+ return [];
561
+ } })
562
+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
563
+ if (!rows.length) {
564
+ console.log("No saved records in this project yet. Save one with each scan: lintsure scan --save-record");
565
+ return 0;
566
+ }
567
+ console.log(`${"When (UTC)".padEnd(18)}${"Findings".padStart(9)}${"High".padStart(6)}${"Medium".padStart(8)}${"Low".padStart(5)}${"Accepted".padStart(10)}${"Fixed".padStart(7)} Record`);
568
+ for (const r of rows)
569
+ console.log(`${String(r.createdAt).replace("T", " ").slice(0, 16).padEnd(18)}${String(r.counts.findings).padStart(9)}${String(r.counts.byRisk?.high ?? 0).padStart(6)}${String(r.counts.byRisk?.medium ?? 0).padStart(8)}${String(r.counts.byRisk?.low ?? 0).padStart(5)}${String(r.counts.accepted ?? 0).padStart(10)}${String(r.counts.fixedSinceBaseline ?? 0).padStart(7)} ${r.id}`);
570
+ console.log(`\n${rows.length} record${rows.length === 1 ? "" : "s"}. A drop can come from fixes or from a newer Lintsure that raises fewer false alarms: compare records made with the same version.`);
571
+ return 0;
572
+ }
573
+ if (cmd === "hook") {
574
+ const root = resolve(raw.find((a) => !a.startsWith("--")) ?? "."), file = join(root, ".git", "hooks", "pre-commit"), MARK = "# Added by lintsure hook";
575
+ if (!existsSync(join(root, ".git"))) {
576
+ console.error(`No git repository at ${root}. Run this in the folder that has .git.`);
577
+ return 2;
578
+ }
579
+ const now = existsSync(file) ? await readFile(file, "utf8") : null;
580
+ if (raw.includes("--undo")) {
581
+ if (now?.includes(MARK)) {
582
+ await rm(file);
583
+ console.log("Removed the pre-commit hook.");
584
+ }
585
+ else
586
+ console.log(now === null ? "No pre-commit hook here." : "The pre-commit hook here is not Lintsure's, so it was left alone.");
587
+ return 0;
588
+ }
589
+ // Someone else's hook is never overwritten: say what to add to it.
590
+ if (now !== null && !now.includes(MARK)) {
591
+ console.error("This repository already has a pre-commit hook of its own. Add this line to it:\n lintsure scan --staged --fail-on gap");
592
+ return 2;
593
+ }
594
+ console.log(`- pre-commit hook: ${now === null ? "create" : "update"} .git/hooks/pre-commit\n lintsure scan --staged --fail-on gap`);
595
+ if (!raw.includes("--yes")) {
596
+ console.log("\nNothing written yet. To apply, run: lintsure hook --yes");
597
+ return 0;
598
+ }
599
+ await mkdir(join(root, ".git", "hooks"), { recursive: true });
600
+ // Pinned to this version when the command is not installed: a moving version in a hook is what the supply-chain rules warn about.
601
+ await writeFile(file, `#!/bin/sh\n${MARK}. Remove with: lintsure hook --undo\n# Checks only the lines being committed and stops the commit on a clear problem.\nif command -v lintsure >/dev/null 2>&1; then lintsure scan --staged --fail-on gap; else npx --yes lintsure@${RULES_VERSION} scan --staged --fail-on gap; fi\n`, { mode: 0o755 });
602
+ console.log("\nWritten. Each commit now checks the lines being committed.\nSkip it once with: git commit --no-verify\nRemove it with: lintsure hook --undo");
603
+ return 0;
604
+ }
605
+ // lintsure plugin: the guards, for the agents this project uses. Shown first; nothing is downloaded or written before a yes.
606
+ if (cmd === "plugin") {
607
+ const bad = raw.find((a) => a.startsWith("--") && !["--yes", "--undo", "--agents", "--here"].includes(a));
608
+ if (bad) {
609
+ console.error(`Unknown option: ${bad}. Use: lintsure plugin [folder] [--agents ${GUARD_AGENTS.map((a) => a.id).join(",")}] [--yes] [--undo]`);
610
+ return 2;
611
+ }
612
+ const root = resolve(raw.find((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents") ?? ".");
613
+ if (!existsSync(root)) {
614
+ console.error(`No folder at ${root}.`);
615
+ return 2;
616
+ }
617
+ const lost = wrongPlace("plugin", raw, "--agents");
618
+ if (lost) {
619
+ console.error(lost);
620
+ return 2;
621
+ }
622
+ const i = raw.indexOf("--agents"), names = i >= 0 ? (raw[i + 1] ?? "").split(",").map((s) => s.trim()) : undefined;
623
+ const unknown = names?.filter((n) => !GUARD_AGENTS.some((a) => a.id === n));
624
+ if (unknown?.length) {
625
+ console.error(`Unknown agent: ${unknown.join(", ")}. Choose from: ${GUARD_AGENTS.map((a) => a.id).join(", ")}`);
626
+ return 2;
627
+ }
628
+ const used = GUARD_AGENTS.filter((a) => existsSync(join(root, a.marker)));
629
+ let agents = names ? GUARD_AGENTS.filter((a) => names.includes(a.id)) : used.length ? used : [GUARD_AGENTS[0]];
630
+ if (raw.includes("--undo")) {
631
+ const said = await removeGuards(root, names ? agents : GUARD_AGENTS);
632
+ console.log(said.length ? said.map((s) => `- ${s}`).join("\n") : "No Lintsure guards were installed from here.");
633
+ return 0;
634
+ }
635
+ const yes = raw.includes("--yes"), picking = !yes && !names && !!process.stdin.isTTY && !!process.stdout.isTTY;
636
+ console.log("");
637
+ step(tint(BADGE, " Lintsure plugin "), ["The plugin adds guards that run while your agent works. Drift Guard checks each edit against your", "project's rules, Danger Guard asks before a destructive command, and one check runs when a task ends.", "Skills are read when the agent chooses to. Guards run every time."]);
638
+ showFolder("Project", root);
639
+ if (picking) {
640
+ step("Which agents should get the guards?");
641
+ const picked = await chooseMany(GUARD_AGENTS.map((a) => `${a.name.padEnd(14)}${a.file ? `guards through ${a.file}` : "the full plugin, through Claude Code's own installer"}${used.includes(a) ? " used in this project" : ""}`), (n) => (n ? `Install for 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");
642
+ if (!picked?.length) {
643
+ console.log("Nothing installed. Come back any time: lintsure plugin");
644
+ return 0;
645
+ }
646
+ agents = picked.map((n) => GUARD_AGENTS[n]);
647
+ }
648
+ const apply = yes || picking, needsFiles = agents.some((a) => a.file);
649
+ let dir;
650
+ try {
651
+ dir = pluginHome(apply && needsFiles);
652
+ }
653
+ catch (e) {
654
+ console.error(e instanceof Error ? e.message : String(e));
655
+ return 2;
656
+ }
657
+ // Before the download there is nothing to read the hooks from, so the preview names the files and the source.
658
+ const fetched = existsSync(join(dir, "hooks"));
659
+ if (!apply) {
660
+ const lines = fetched ? (await planGuards(root, agents, dir)).map((s) => `${s.agent.name}: ${s.note}`) : agents.map((a) => `${a.name}: ${a.file ? `write the guards' hooks to ${a.file}` : "claude plugin marketplace add lintsure/plugin, then claude plugin install lintsure@lintsure"}`);
661
+ step(`Would install the guards for ${agents.length} agent${agents.length === 1 ? "" : "s"}`, [...lines, ...(needsFiles && !fetched ? [tint("2", `Downloads the plugin ${PLUGIN_TAG} from github.com/lintsure/plugin into your home folder first.`)] : [])]);
662
+ console.log(`Nothing installed yet. To apply, run: lintsure plugin${names ? ` --agents ${names.join(",")}` : ""} --yes`);
663
+ return 0;
664
+ }
665
+ const said = await installGuards(root, await planGuards(root, agents, dir));
666
+ step(tint("32", "Done!"), said.flatMap((s) => s.split("\n")));
667
+ console.log("The guards for Cursor, Codex and Gemini CLI are new: tell us if one misbehaves. Take them out with: lintsure plugin --undo");
668
+ return 0;
669
+ }
338
670
  if (cmd === "skills") {
339
671
  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));
672
+ const bad = raw.find((a) => a.startsWith("--") && !["--yes", "--undo", "--only", "--here"].includes(a));
341
673
  if (bad) {
342
- console.error(`Unknown option: ${bad}. Use --yes, --only <names> or --undo.`);
674
+ console.error(`Unknown option: ${bad}. Use --yes, --only <names>, --here or --undo.`);
675
+ return 2;
676
+ }
677
+ const lost = wrongPlace("skills", raw, "--only");
678
+ if (lost) {
679
+ console.error(lost);
343
680
  return 2;
344
681
  }
345
682
  if (!existsSync(root)) {
@@ -384,6 +721,10 @@ async function main(argv) {
384
721
  }
385
722
  step(tint("32", `Done! Installed ${chosen.length} skill${chosen.length === 1 ? "" : "s"}`), lines);
386
723
  console.log("Restart the agent so it reads them. Take them out any time with: lintsure skills --undo");
724
+ // Renamed in 0.3.16: an older install still has the folder under its first name.
725
+ for (const f of folders)
726
+ if (existsSync(join(root, f, "lintsure-ship")))
727
+ console.log(`${f}/lintsure-ship is the old name of lintsure-prelaunch. Delete that folder so the agent does not load both.`);
387
728
  return 0;
388
729
  }
389
730
  if (cmd === "setup" || cmd === "status") {
@@ -394,6 +735,62 @@ async function main(argv) {
394
735
  console.log(MANUAL());
395
736
  return 0;
396
737
  }
738
+ const everywhere = raw.includes("--everywhere"), folderNamed = raw.some((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents");
739
+ const isProject = looksLikeProject(root), tty = !!process.stdin.isTTY && !!process.stdout.isTTY;
740
+ // With no scope given, ask: every project, or only this one. Typed with --yes inside a project, it is that project, as before.
741
+ if (!everywhere && !folderNamed && !raw.includes("--here") && !raw.includes("--undo") && !(isProject && (raw.includes("--yes") || raw.includes("--agents")))) {
742
+ const one = isProject ? `Only this project (${basename(root)})` : "Only one project";
743
+ if (tty) {
744
+ console.log("");
745
+ step("Where should Lintsure be connected?", isProject ? [] : [`No project found in ${root}.`]);
746
+ return (await offer([
747
+ { text: `${"Every project on this machine".padEnd(54)}lintsure setup --everywhere`, run: ["setup", ...raw, "--everywhere"] },
748
+ isProject ? { text: `${one.padEnd(54)}lintsure setup --here`, run: ["setup", ...raw, "--here"] } : { text: `${one.padEnd(54)}lintsure setup path/to/your/project`, run: async () => console.log("Go to your project's folder and run lintsure setup again, or name the folder: lintsure setup path/to/your/project") },
749
+ ], !process.env.NO_COLOR && process.env.TERM !== "dumb")) ?? 0;
750
+ }
751
+ console.log(`${isProject ? "" : `No project found in ${root}.\n\n`}Lintsure can be connected in two ways. Which one do you want?\n\n 1. Every project on this machine\n Your agent has Lintsure in any project it opens.\n lintsure setup --everywhere\n\n 2. ${one}\n Lintsure is connected in that one folder and nowhere else.\n ${isProject ? "lintsure setup --here" : "lintsure setup path/to/your/project"}\n\nEach command shows what it will write first. Add --yes to apply.\nIf you are an AI agent running this for someone: ask them which of the two they want and wait for the answer. Don't choose for them.`);
752
+ return 0;
753
+ }
754
+ if (everywhere) {
755
+ // The user's own agent settings, in their home folder. Cursor, Gemini CLI and Codex keep them at the same path as in a project.
756
+ const home = homedir(), i = raw.indexOf("--agents"), apply = raw.includes("--yes"), undoIt = raw.includes("--undo");
757
+ const picked = i >= 0 ? await pick(home, raw[i + 1]?.split(",").map((s) => s.trim())) : AGENTS.filter((a) => existsSync(join(home, a.marker)));
758
+ if (typeof picked === "string") {
759
+ console.error(picked);
760
+ return 2;
761
+ }
762
+ if (!picked.length) {
763
+ console.error(`No agent found in ${home}. Name the ones you use: lintsure setup --everywhere --agents ${AGENTS.map((a) => a.id).join(",")}`);
764
+ return 2;
765
+ }
766
+ console.log(`${undoIt ? "Taking Lintsure out of" : "Connecting Lintsure for every project: this changes"} your own agent settings in ${home}.\n`);
767
+ const add = ["mcp", "add", "--scope", "user", "lintsure", "--", "npx", "-y", `@lintsure/mcp@${RULES_VERSION}`];
768
+ for (const a of picked) {
769
+ if (a.id === "vscode")
770
+ console.log(`- ${a.name}: its own settings are set from inside VS Code. Run "MCP: Open User Configuration" there and add the entry shown by: lintsure setup --manual`);
771
+ if (a.id !== "claude")
772
+ continue;
773
+ if (!apply && !undoIt) {
774
+ console.log(`- ${a.name}: claude ${add.join(" ")}`);
775
+ continue;
776
+ }
777
+ try {
778
+ claudeCli(undoIt ? ["mcp", "remove", "--scope", "user", "lintsure"] : add);
779
+ console.log(`- ${a.name}: ${undoIt ? "removed" : "connected"} for every project`);
780
+ }
781
+ catch {
782
+ console.log(`- ${a.name}: the claude command didn't do it. Run it yourself:\n claude ${(undoIt ? ["mcp", "remove", "--scope", "user", "lintsure"] : add).join(" ")}`);
783
+ }
784
+ }
785
+ const files = picked.filter((a) => ["cursor", "gemini", "codex"].includes(a.id));
786
+ if (undoIt)
787
+ return undo(home, files);
788
+ if (files.length)
789
+ return setup(home, files, apply, " --everywhere");
790
+ if (!apply)
791
+ console.log("\nNothing written yet. To apply, run: lintsure setup --everywhere --yes");
792
+ return 0;
793
+ }
397
794
  const named = raw.includes("--agents"), here = named ? [] : await detected(root);
398
795
  // From the menu, ask which agent. Claude Code used to be the silent choice when the project had no agent folder yet.
399
796
  if (viaMenu && !named && !raw.includes("--yes") && !raw.includes("--undo") && process.stdin.isTTY && process.stdout.isTTY) {
@@ -408,7 +805,11 @@ async function main(argv) {
408
805
  return (await offer(rows, !process.env.NO_COLOR && process.env.TERM !== "dumb")) ?? 0;
409
806
  }
410
807
  // 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"))
808
+ const me = callingAgent();
809
+ if (!named && me && !here.includes(me) && !raw.includes("--undo"))
810
+ console.log(`This is running inside ${me.name}, so ${me.name} is connected${here.length ? " too" : ""}.
811
+ `);
812
+ else if (!named && !here.length && !raw.includes("--undo"))
412
813
  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`);
413
814
  const i = raw.indexOf("--agents");
414
815
  const agents = await pick(root, i >= 0 ? raw[i + 1]?.split(",").map((s) => s.trim()) : undefined);
@@ -425,7 +826,7 @@ async function main(argv) {
425
826
  const pending = !raw.includes("--yes") && (await Promise.all(agents.map((a) => plan(root, a)))).some((p) => p.text);
426
827
  const folder = raw.filter((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents").slice(0, 1);
427
828
  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");
829
+ 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] }, { text: `${"Add the guards (the Lintsure plugin)".padEnd(54)}lintsure plugin`, run: ["plugin", ...folder] }], !process.env.NO_COLOR && process.env.TERM !== "dumb");
429
830
  if (ran !== undefined)
430
831
  return ran;
431
832
  }
@@ -517,6 +918,23 @@ async function main(argv) {
517
918
  return 2; // a whole home folder or drive is never what was meant
518
919
  }
519
920
  }
921
+ // A folder that holds several projects is a workspace: one scan would mix their findings together.
922
+ const inside = subProjects(path);
923
+ if (inside.length > 1) {
924
+ if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
925
+ console.log("");
926
+ step(`This folder holds ${inside.length} projects. Which one?`);
927
+ const pick = await choose([...inside, "All of them together", "Back"], HINT, !process.env.NO_COLOR && process.env.TERM !== "dumb");
928
+ if (pick === null || pick > inside.length)
929
+ return 0;
930
+ if (pick < inside.length) {
931
+ const named = rest.find((a, i) => !a.startsWith("--") && !VALUE_FLAGS.includes(rest[i - 1]));
932
+ return main([cmd, join(path, inside[pick]), ...rest.filter((a) => a !== named)]);
933
+ }
934
+ }
935
+ else
936
+ console.error(`This folder holds ${inside.length} projects (${inside.slice(0, 5).join(", ")}${inside.length > 5 ? ", ..." : ""}), so their findings are mixed together below.\nTo check one: lintsure ${cmd} <folder>`);
937
+ }
520
938
  const config = await readConfig(path);
521
939
  // Checked after the config loads its rule packs, so a pack's framework id is accepted.
522
940
  const bad = wanted?.filter((f) => !ALL_FRAMEWORKS.includes(f));
@@ -533,13 +951,17 @@ async function main(argv) {
533
951
  console.log(`Skipping, not checked yet: ${config.skipped.join(", ")}`);
534
952
  const why = wanted ? "Chosen with --framework on the command line." : config.frameworks ? "Listed in lintsure.config.yaml." : undefined;
535
953
  const source = process.env.GITHUB_ACTIONS || process.env.CI ? "ci" : "cli";
536
- const base = flag("--diff");
954
+ const base = flag("--diff"), staged = rest.includes("--staged");
537
955
  let changed;
538
- if (base) {
956
+ if (base || staged) {
539
957
  try {
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 })) };
958
+ changed = { base: base ?? "your last commit (staged changes only)", lines: parseDiff(execFileSync("git", ["-c", "core.quotePath=false", "diff", "-U0", "--no-color", "--no-ext-diff", "--relative", ...(base ? [base] : ["--cached"]), "--"], { cwd: path, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 << 20 })) };
541
959
  }
542
960
  catch {
961
+ if (!base) {
962
+ console.error("--staged needs a git repository, and this folder is not inside one.");
963
+ return 2;
964
+ }
543
965
  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).`);
544
966
  return 2;
545
967
  }
@@ -629,13 +1051,16 @@ async function main(argv) {
629
1051
  }
630
1052
  const status = f.accepted && !f.accepted.expired ? "accepted" : f.status;
631
1053
  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)") : ""}`);
1054
+ console.log(` ${badge} ${paint("2", String(f.line).padStart(5))} ${f.title}${f.change === "new" ? paint("36", " (new)") : ""}${f.confirmed ? paint("32", " (confirmed real)") : ""}`);
633
1055
  }
634
1056
  };
635
1057
  // The first few to fix: gaps before partials, higher risk first, reached code first.
636
1058
  const inCode = open.filter((f) => !isHygiene(f));
637
1059
  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);
1060
+ // Findings in test, example and data files come last, and never set the tone: they are rarely what to fix first.
1061
+ // Agent, skill and MCP findings stay where they are: those rules read tooling folders on purpose.
1062
+ const aside = (f) => !/^(agent|skill|mcp)\./.test(f.ruleId) && (isNonShipping(f.file) || /\.(json|csv)$/i.test(f.file));
1063
+ const ranked = [...inCode].sort((a, b) => order(a) + (aside(a) ? 10 : 0) - order(b) - (aside(b) ? 10 : 0)), first = ranked.slice(0, 3);
639
1064
  const fold = (t, pad) => t.replace(new RegExp(`(.{1,${width - pad.length - 2}})(\\s+|$)`, "g"), `$1\n${pad}`).trimEnd();
640
1065
  const reportFile = resolve("lintsure-report.md");
641
1066
  // A request a person can paste into any coding agent, connected or not: it names the finding and where the proposal is.
@@ -646,7 +1071,7 @@ async function main(argv) {
646
1071
  const gaps = inCode.filter((f) => f.status === "gap");
647
1072
  const headline = !open.length ? paint("1;32", "Done! Nothing found by the current rules.")
648
1073
  : !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.")}`
1074
+ : gaps.some((f) => f.severity === "high" && !aside(f)) ? `${paint(BLUE, "Lintsure")} ${paint("1;31", "found something that needs your attention.")}`
650
1075
  : gaps.length ? `${paint(BLUE, "Lintsure")} ${paint("1;33", "found something interesting.")}`
651
1076
  : inCode.every((f) => f.severity === "low") ? paint("1;33", inCode.length === 1 ? "A minor finding, worth a look." : "Minor findings, worth a look.")
652
1077
  : paint("1;33", "Worth a look.");
@@ -682,6 +1107,7 @@ async function main(argv) {
682
1107
  ...(report.held ? [{ label: `Also show the ${report.held} held-back finding${report.held === 1 ? "" : "s"}`, run: ["scan", ...here, "--all"] }] : []),
683
1108
  ...(open.length && !report.baseline ? [{ label: "Remember these, so later scans show only what is new", run: ["baseline", ...here] }] : []),
684
1109
  ...(rest.includes("--report") ? [] : [{ label: "Write a printable assessment", run: ["scan", ...here, "--report"] }]),
1110
+ ...(open.some((f) => f.patch) ? [{ label: `Apply the ${open.filter((f) => f.patch).length === 1 ? "one exact fix" : `${open.filter((f) => f.patch).length} exact fixes`} Lintsure knows`, run: ["fix", ...here, ...(rest.includes("--all") ? ["--all"] : [])] }] : []),
685
1111
  { label: "Connect your coding agent, then ask it to fix one", run: ["setup", ...here] },
686
1112
  ];
687
1113
  // Menu only: the full proposal for one finding, and a request to paste into a coding agent. Lintsure never edits code.
@@ -716,10 +1142,12 @@ async function main(argv) {
716
1142
  }
717
1143
  const failOn = flag("--fail-on")?.toLowerCase();
718
1144
  const counted = rest.includes("--new-only") && report.baseline ? open.filter((f) => f.change === "new") : open;
719
- if (failOn === "gap" && counted.some((f) => f.status === "gap"))
720
- return 1;
721
- if (failOn === "partial" && counted.length)
722
- return 1;
723
- return 0;
1145
+ const fails = (failOn === "gap" && counted.some((f) => f.status === "gap")) || (failOn === "partial" && counted.length > 0);
1146
+ // Observe mode: say what the gate would have done and let the run pass, so a team can watch it before it blocks anyone.
1147
+ if (fails && rest.includes("--observe")) {
1148
+ console.log(`\nObserve mode: --fail-on ${failOn} would have failed this run. Nothing was blocked.`);
1149
+ return 0;
1150
+ }
1151
+ return fails ? 1 : 0;
724
1152
  }
725
1153
  main(process.argv.slice(2)).then((code) => process.exit(code), (e) => { console.error(e instanceof Error ? e.message : e); process.exit(2); });