lintsure 0.3.14 → 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/README.md +36 -21
- package/dist/src/agents.d.ts +11 -2
- package/dist/src/agents.js +91 -23
- package/dist/src/deps.d.ts +18 -0
- package/dist/src/deps.js +57 -0
- package/dist/src/index.d.ts +6 -0
- package/dist/src/index.js +900 -65
- package/dist/src/menu.d.ts +15 -0
- package/dist/src/menu.js +89 -0
- package/dist/src/plugin.d.ts +28 -0
- package/dist/src/plugin.js +170 -0
- package/dist/src/skills.d.ts +18 -0
- package/dist/src/skills.js +86 -0
- package/package.json +54 -45
- package/skills/lintsure-check/SKILL.md +36 -0
- package/skills/lintsure-fix/SKILL.md +38 -0
- package/skills/lintsure-prelaunch/SKILL.md +37 -0
- package/skills/lintsure-rules/SKILL.md +54 -0
- package/skills/lintsure-rules/agents.mjs +75 -0
- package/skills/lintsure-rules/lib.mjs +60 -0
- package/skills/lintsure-rules/profile.mjs +129 -0
- package/skills/lintsure-rules/rules.mjs +197 -0
- package/skills/lintsure-setup/SKILL.md +34 -0
- package/skills/lintsure-stay-on-track/SKILL.md +39 -0
- package/skills/lintsure-triage/SKILL.md +105 -0
package/dist/src/index.js
CHANGED
|
@@ -1,55 +1,251 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// npx lintsure scan [path] [options] npx lintsure baseline [path]
|
|
3
|
-
// Writes reports into the current folder.
|
|
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 } from "node:fs";
|
|
6
|
-
import {
|
|
6
|
+
import { constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { access, copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
7
9
|
import { basename, dirname, join, resolve } from "node:path";
|
|
8
10
|
import { createInterface } from "node:readline/promises";
|
|
9
|
-
import { status, pick, setup, undo } from "./agents.js";
|
|
11
|
+
import { AGENTS, CONNECT_NOTE, MANUAL, callingAgent, detected, status, pick, plan, setup, undo } from "./agents.js";
|
|
10
12
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
13
|
+
import { ALL_FRAMEWORKS, BASELINE_FILE, DISCLAIMER, RULES_VERSION, classify, isHygiene, isNonShipping, isOpen, nextSteps, readConfig, scan, toAssessmentHtml, toBaseline, toMarkdown, toSarif } from "@lintsure/core";
|
|
14
|
+
import { choose, chooseMany } from "./menu.js";
|
|
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";
|
|
18
|
+
// The old Windows console can't draw block, line or diamond characters reliably, so it gets plain ones.
|
|
19
|
+
const legacy = (env = process.env) => process.platform === "win32" && !env.WT_SESSION && !env.TERM_PROGRAM && !env.ConEmuANSI && !env.FORCE_COLOR;
|
|
20
|
+
// Brand colours: the logo blue for names and choices, gold for the rail that ties the steps of one task together.
|
|
21
|
+
const BLUE = "38;2;98;137;254", GOLD = "38;2;224;176;64";
|
|
22
|
+
// A badge: dark text on the logo blue. Without colour the same words stand as they are.
|
|
23
|
+
const BADGE = "48;2;98;137;254;38;2;16;24;48";
|
|
24
|
+
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);
|
|
25
|
+
/** One step of a task: a marked title, then its lines hung on a rail, so a screen reads as a sequence of steps. */
|
|
26
|
+
const step = (title, body = []) => { const rail = tint(GOLD, legacy() ? "|" : "│"); console.log([`${tint(GOLD, legacy() ? "*" : "◇")} ${title}`, ...body.map((b) => `${rail} ${b}`), rail].join("\n")); };
|
|
27
|
+
/** The Prism in half-block characters, to the proportions of the brand mark: four heavy bands with narrow gaps, a solid
|
|
28
|
+
* tip, and the bottom band split into a long piece and a square. Each character holds two square pixels; `band` and
|
|
29
|
+
* `gap` are heights in those pixels. Pure. */
|
|
30
|
+
function prism(band = 6, gap = 2) {
|
|
31
|
+
const SLOPE = 0.56, height = 4 * band + 3 * gap, half = Math.ceil(SLOPE * height);
|
|
32
|
+
const on = (c, h) => {
|
|
33
|
+
if (h % (band + gap) >= band || Math.abs(c - half) > SLOPE * (h + 1))
|
|
34
|
+
return false; // a gap, or outside the slope
|
|
35
|
+
if (h < 3 * band + 3 * gap)
|
|
36
|
+
return true;
|
|
37
|
+
const at = (c - half + SLOPE * height) / (2 * SLOPE * height); // bottom band: long piece, gap, square
|
|
38
|
+
return at <= 0.6 || (at >= 0.72 && at <= 0.9);
|
|
39
|
+
};
|
|
40
|
+
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(""));
|
|
41
|
+
}
|
|
42
|
+
/** Start screen for a person at a terminal: the Prism in brand green beside the name, version and first commands.
|
|
43
|
+
* NO_COLOR is respected; the old Windows console, which can't draw the blocks, gets the name and version only. */
|
|
44
|
+
function banner(env = process.env) {
|
|
45
|
+
if (legacy(env))
|
|
46
|
+
return `Lintsure ${RULES_VERSION}\n`;
|
|
47
|
+
const color = !env.NO_COLOR && env.TERM !== "dumb";
|
|
48
|
+
const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
49
|
+
const text = [`${paint("38;2;98;137;254", "Lintsure")}${paint("2", ` ${RULES_VERSION}`)}`, "", paint("2", "Everything stays on this machine.")];
|
|
50
|
+
const mark = prism(), width = Math.max(...mark.map((l) => l.length)), top = Math.floor((mark.length - text.length) / 2);
|
|
51
|
+
return "\n" + mark.map((l, i) => (paint("38;2;98;137;254", l.padEnd(width)) + " " + (text[i - top] ?? "")).trimEnd()).join("\n") + "\n";
|
|
52
|
+
}
|
|
53
|
+
// Files and folders that mark the top of a software project, in any of the common stacks.
|
|
54
|
+
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"];
|
|
55
|
+
const isWholeDisk = (dir) => dir === homedir() || dirname(dir) === dir; // the home folder or a drive root
|
|
56
|
+
/** Whether a folder is a software project or sits inside one: a marker file in the folder itself, or a git repository
|
|
57
|
+
* around it. Folders above count only through .git, because a stray package.json in a temp or documents folder is
|
|
58
|
+
* common. The home folder and a drive root never count. */
|
|
59
|
+
export const looksLikeProject = (dir) => projectSign(dir) !== null;
|
|
60
|
+
/** What shows that a folder is a project, in words for a person, or null when nothing does. */
|
|
61
|
+
function projectSign(dir) {
|
|
62
|
+
if (isWholeDisk(dir))
|
|
63
|
+
return null;
|
|
64
|
+
const marker = PROJECT_MARKERS.find((m) => existsSync(join(dir, m)));
|
|
65
|
+
if (marker)
|
|
66
|
+
return marker === ".git" ? "a git repository" : `it has ${marker}`;
|
|
67
|
+
for (let at = dirname(dir); !isWholeDisk(at); at = dirname(at))
|
|
68
|
+
if (existsSync(join(at, ".git")))
|
|
69
|
+
return `inside the git repository ${basename(at)}`;
|
|
70
|
+
return null;
|
|
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
|
+
}
|
|
85
|
+
/** The folder and whether a project was found in it, as one step. */
|
|
86
|
+
function showFolder(title, dir) {
|
|
87
|
+
const sign = projectSign(dir);
|
|
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")]);
|
|
89
|
+
}
|
|
90
|
+
/** Asks a person for their project folder. Returns its full path, "" for Enter alone (use this folder), or null to stop.
|
|
91
|
+
* A pasted path may carry quotes, and ~ stands for the home folder. Only call this at a terminal. */
|
|
92
|
+
async function askFolder(allowHere) {
|
|
93
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
94
|
+
try {
|
|
95
|
+
for (let tries = 0; tries < 3; tries++) {
|
|
96
|
+
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, "");
|
|
97
|
+
if (typed.toLowerCase() === "q")
|
|
98
|
+
return null;
|
|
99
|
+
if (!typed) {
|
|
100
|
+
if (allowHere)
|
|
101
|
+
return "";
|
|
102
|
+
console.log("That would check every file you have. Name one project folder.\n");
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const full = resolve(typed.replace(/^~(?=$|[\\/])/, homedir()));
|
|
106
|
+
if (existsSync(full) && statSync(full).isDirectory()) {
|
|
107
|
+
console.log(`\n${tint("32", "Found")} ${full}${looksLikeProject(full) ? "" : "\nIt doesn't look like a project, so Lintsure checks the folder as it is."}`);
|
|
108
|
+
return full;
|
|
109
|
+
}
|
|
110
|
+
console.log(`${tint(GOLD, "Not found:")} no folder at ${full}. Check the path and try again.\n`);
|
|
111
|
+
}
|
|
112
|
+
console.log("Stopped. When you have the path, run: lintsure scan <folder>");
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
rl.close();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// What the start menu offers, in the order a new user needs them. `run` is the command line it stands for.
|
|
120
|
+
const START = [
|
|
121
|
+
{ label: "Check this folder", run: ["scan"] },
|
|
122
|
+
// `show` is the command to learn; the menu itself asks for the folder with --pick.
|
|
123
|
+
{ label: "Check another folder", run: ["scan", "--pick"], show: "scan <folder>" },
|
|
124
|
+
{ label: "Is everything set up?", run: ["status"] },
|
|
125
|
+
{ label: "Connect your coding agent", run: ["setup"] },
|
|
126
|
+
{ label: "Give your agent skills", run: ["skills"] },
|
|
127
|
+
{ label: "Add the Lintsure plugin", run: ["plugin"] },
|
|
128
|
+
{ label: "Every command and option", run: ["--help"] },
|
|
129
|
+
{ label: "Quit", run: null },
|
|
130
|
+
];
|
|
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
|
+
}
|
|
140
|
+
let viaMenu = false;
|
|
141
|
+
let sawMenu = false; // the command that just ran ended with its own menu
|
|
142
|
+
let wantsMenu = false; // the person chose "Main menu"
|
|
143
|
+
const HINT = " Up and Down to move, Enter to run, q to quit";
|
|
144
|
+
/** The menu a command ends with when it was started from the start menu: what fits next, then the way back.
|
|
145
|
+
* Returns the exit code of the command it ran, or undefined when nothing was run (Main menu or Quit). */
|
|
146
|
+
async function offer(rows, color) {
|
|
147
|
+
sawMenu = true;
|
|
148
|
+
for (;;) {
|
|
149
|
+
const pick = await choose([...rows.map((r) => r.text), "Main menu", "Quit"], HINT, color);
|
|
150
|
+
if (pick === rows.length)
|
|
151
|
+
wantsMenu = true;
|
|
152
|
+
if (pick === null || pick >= rows.length)
|
|
153
|
+
return undefined;
|
|
154
|
+
const run = rows[pick].run;
|
|
155
|
+
// A row that only shows something comes back to this menu afterwards.
|
|
156
|
+
if (typeof run === "function") {
|
|
157
|
+
await run();
|
|
158
|
+
console.log("");
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
sawMenu = false; // the command run next gets its own ending
|
|
162
|
+
return main(run);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const COMMANDS = ["scan", "baseline", "init", "info", "setup", "skills", "plugin", "hook", "fix", "deps", "history", "status", "export"];
|
|
166
|
+
/** The command someone most likely meant: the same word without dashes, or one within two typing slips. Pure. */
|
|
167
|
+
function nearest(word) {
|
|
168
|
+
const slips = (a, b) => {
|
|
169
|
+
let row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
170
|
+
for (let i = 1; i <= a.length; i++) {
|
|
171
|
+
const next = [i];
|
|
172
|
+
for (let j = 1; j <= b.length; j++)
|
|
173
|
+
next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
174
|
+
row = next;
|
|
175
|
+
}
|
|
176
|
+
return row[b.length];
|
|
177
|
+
};
|
|
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];
|
|
179
|
+
}
|
|
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; });
|
|
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.`;
|
|
51
247
|
const VALUE_FLAGS = ["--framework", "--fail-on", "--project", "--diff"];
|
|
52
|
-
const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all"];
|
|
248
|
+
const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all", "--pick", "--staged", "--observe"];
|
|
53
249
|
/** Changed line numbers per file from `git diff -U0` output. Pure. */
|
|
54
250
|
export function parseDiff(text) {
|
|
55
251
|
const out = {};
|
|
@@ -69,7 +265,7 @@ export function parseDiff(text) {
|
|
|
69
265
|
}
|
|
70
266
|
return out;
|
|
71
267
|
}
|
|
72
|
-
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" };
|
|
73
269
|
/** First-run setup: three questions, saved once, never asked in CI. */
|
|
74
270
|
async function init(path) {
|
|
75
271
|
const file = join(path, "lintsure.config.yaml");
|
|
@@ -93,7 +289,7 @@ async function init(path) {
|
|
|
93
289
|
}
|
|
94
290
|
};
|
|
95
291
|
console.log("Lintsure setup: 3 questions. Press Enter for the first answer.");
|
|
96
|
-
const what = await pick("1. What should Lintsure check?", ["Security only (OWASP Top 10, CWE Top 25)", "Security and privacy (adds GDPR)", "Everything (all
|
|
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"]);
|
|
97
293
|
let chosen = what === 1 ? ["owasp-top10", "cwe-top25"] : what === 2 ? ["owasp-top10", "cwe-top25", "gdpr"] : [...ALL_FRAMEWORKS];
|
|
98
294
|
if (what === 4) {
|
|
99
295
|
console.log("\nType the numbers you want, separated by commas, or press Enter for all:");
|
|
@@ -185,23 +381,500 @@ async function main(argv) {
|
|
|
185
381
|
console.log(`Wrote lintsure.otlp.json: ${rows.length} events. Nothing was sent; load the file into your collector or tool (OTLP/JSON).`);
|
|
186
382
|
return 0;
|
|
187
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
|
+
}
|
|
670
|
+
if (cmd === "skills") {
|
|
671
|
+
const root = resolve(raw.find((a, i) => !a.startsWith("--") && raw[i - 1] !== "--only") ?? ".");
|
|
672
|
+
const bad = raw.find((a) => a.startsWith("--") && !["--yes", "--undo", "--only", "--here"].includes(a));
|
|
673
|
+
if (bad) {
|
|
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);
|
|
680
|
+
return 2;
|
|
681
|
+
}
|
|
682
|
+
if (!existsSync(root)) {
|
|
683
|
+
console.error(`No folder at ${root}.`);
|
|
684
|
+
return 2;
|
|
685
|
+
}
|
|
686
|
+
if (raw.includes("--undo")) {
|
|
687
|
+
const said = await removeSkills(root);
|
|
688
|
+
console.log(said.length ? said.join("\n") : "No Lintsure skills in this project.");
|
|
689
|
+
return 0;
|
|
690
|
+
}
|
|
691
|
+
const all = skills(), i = raw.indexOf("--only"), names = i >= 0 ? (raw[i + 1] ?? "").split(",").map((s) => s.trim()) : undefined;
|
|
692
|
+
const unknown = names?.filter((n) => !all.some((s) => s.name === n));
|
|
693
|
+
if (unknown?.length) {
|
|
694
|
+
console.error(`Unknown skill: ${unknown.join(", ")}. Choose from: ${all.map((s) => s.name).join(", ")}`);
|
|
695
|
+
return 2;
|
|
696
|
+
}
|
|
697
|
+
let chosen = names ? all.filter((s) => names.includes(s.name)) : all;
|
|
698
|
+
const folders = skillFolders(root), yes = raw.includes("--yes"), picking = !yes && !names && !!process.stdin.isTTY && !!process.stdout.isTTY;
|
|
699
|
+
console.log("");
|
|
700
|
+
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."]);
|
|
701
|
+
showFolder("Project", root);
|
|
702
|
+
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")}`));
|
|
703
|
+
if (picking) {
|
|
704
|
+
step(`Found ${all.length} skills. Which do you want?`);
|
|
705
|
+
const width = Math.max(...all.map((s) => s.name.length)) + 2;
|
|
706
|
+
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");
|
|
707
|
+
if (!picked?.length) {
|
|
708
|
+
console.log("Nothing installed. Come back any time: lintsure skills");
|
|
709
|
+
return 0;
|
|
710
|
+
}
|
|
711
|
+
chosen = picked.map((n) => all[n]);
|
|
712
|
+
}
|
|
713
|
+
const apply = yes || picking;
|
|
714
|
+
const steps = await installSkills(root, chosen, apply);
|
|
715
|
+
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" };
|
|
716
|
+
const lines = steps.map((s) => `${apply ? `${tint("32", "✓")} ` : ""}${s.folder} ${tint("2", word[s.state])}`);
|
|
717
|
+
if (!apply) {
|
|
718
|
+
step(`Would install ${chosen.length} skill${chosen.length === 1 ? "" : "s"}`, lines);
|
|
719
|
+
console.log(`Nothing written yet. To apply, run: lintsure skills ${names ? `--only ${names.join(",")} ` : ""}--yes`);
|
|
720
|
+
return 0;
|
|
721
|
+
}
|
|
722
|
+
step(tint("32", `Done! Installed ${chosen.length} skill${chosen.length === 1 ? "" : "s"}`), lines);
|
|
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.`);
|
|
728
|
+
return 0;
|
|
729
|
+
}
|
|
188
730
|
if (cmd === "setup" || cmd === "status") {
|
|
189
731
|
const root = resolve(raw.find((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents") ?? ".");
|
|
190
732
|
if (cmd === "status")
|
|
191
733
|
return status(root);
|
|
734
|
+
if (raw.includes("--manual")) {
|
|
735
|
+
console.log(MANUAL());
|
|
736
|
+
return 0;
|
|
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
|
+
}
|
|
794
|
+
const named = raw.includes("--agents"), here = named ? [] : await detected(root);
|
|
795
|
+
// From the menu, ask which agent. Claude Code used to be the silent choice when the project had no agent folder yet.
|
|
796
|
+
if (viaMenu && !named && !raw.includes("--yes") && !raw.includes("--undo") && process.stdin.isTTY && process.stdout.isTTY) {
|
|
797
|
+
console.log("");
|
|
798
|
+
step("Connect your coding agent", CONNECT_NOTE.split("\n"));
|
|
799
|
+
showFolder("Project", root);
|
|
800
|
+
step("Which agent?");
|
|
801
|
+
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] }));
|
|
802
|
+
rows.push({ text: "Another agent (Devin, Windsurf, Zed, ...)", run: ["setup", ...raw, "--manual"] });
|
|
803
|
+
if (here.length > 1)
|
|
804
|
+
rows.unshift({ text: `All ${here.length} used in this project`, run: ["setup", ...raw, "--agents", here.map((a) => a.id).join(",")] });
|
|
805
|
+
return (await offer(rows, !process.env.NO_COLOR && process.env.TERM !== "dumb")) ?? 0;
|
|
806
|
+
}
|
|
807
|
+
// Typed by hand with no agent named and none found here: say which one this is for, and how to pick another.
|
|
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"))
|
|
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`);
|
|
192
814
|
const i = raw.indexOf("--agents");
|
|
193
815
|
const agents = await pick(root, i >= 0 ? raw[i + 1]?.split(",").map((s) => s.trim()) : undefined);
|
|
194
816
|
if (typeof agents === "string") {
|
|
195
817
|
console.error(agents);
|
|
196
818
|
return 2;
|
|
197
819
|
}
|
|
198
|
-
|
|
820
|
+
if (raw.includes("--undo"))
|
|
821
|
+
return undo(root, agents);
|
|
822
|
+
const code = await setup(root, agents, raw.includes("--yes"));
|
|
823
|
+
// From the menu, the preview is followed by the choice to write it, so nobody has to retype the command with --yes.
|
|
824
|
+
// Once the agent is connected, the next thing on offer is the skills that tell it when to use Lintsure.
|
|
825
|
+
if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
|
|
826
|
+
const pending = !raw.includes("--yes") && (await Promise.all(agents.map((a) => plan(root, a)))).some((p) => p.text);
|
|
827
|
+
const folder = raw.filter((a, i) => !a.startsWith("--") && raw[i - 1] !== "--agents").slice(0, 1);
|
|
828
|
+
console.log("");
|
|
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");
|
|
830
|
+
if (ran !== undefined)
|
|
831
|
+
return ran;
|
|
832
|
+
}
|
|
833
|
+
return code;
|
|
199
834
|
}
|
|
200
835
|
if (cmd === "init" || cmd === "info")
|
|
201
836
|
return (cmd === "init" ? init : info)(resolve(raw.find((a) => !a.startsWith("--")) ?? "."));
|
|
837
|
+
// The start screen is for a person at a terminal. Piped output and CI logs stay exactly as they were.
|
|
838
|
+
// With no command, a person at a terminal gets the start screen: a menu when keys can be read, a short list when
|
|
839
|
+
// they can't. Piped output and CI logs get the full help text, exactly as before.
|
|
840
|
+
if (!cmd && (process.stdout.isTTY || process.env.FORCE_COLOR)) {
|
|
841
|
+
console.log(banner());
|
|
842
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
843
|
+
console.log(startRows().slice(0, -1).map((r) => ` ${r}`).join("\n") + "\n");
|
|
844
|
+
return 0;
|
|
845
|
+
}
|
|
846
|
+
// The menu is home. After each command the person can come back here, so no screen is a dead end.
|
|
847
|
+
const color = !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
|
848
|
+
for (let code = 0;;) {
|
|
849
|
+
showFolder("You are in", process.cwd());
|
|
850
|
+
const pick = await choose(startRows(), HINT, color);
|
|
851
|
+
const run = pick === null ? null : START[pick].run;
|
|
852
|
+
if (!run)
|
|
853
|
+
return code;
|
|
854
|
+
viaMenu = true;
|
|
855
|
+
sawMenu = false;
|
|
856
|
+
wantsMenu = false;
|
|
857
|
+
code = await main(run);
|
|
858
|
+
if (!sawMenu)
|
|
859
|
+
await offer([], color); // a command with no menu of its own still ends with the way back
|
|
860
|
+
if (!wantsMenu)
|
|
861
|
+
return code;
|
|
862
|
+
console.log(`\n${tint(BLUE, "Lintsure")} ${RULES_VERSION}\n`);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (cmd === "--version" || cmd === "-v") {
|
|
866
|
+
console.log(RULES_VERSION);
|
|
867
|
+
return 0;
|
|
868
|
+
}
|
|
202
869
|
if (cmd !== "scan" && cmd !== "baseline") {
|
|
203
|
-
|
|
204
|
-
|
|
870
|
+
if (!cmd || ["--help", "-h", "help"].includes(cmd)) {
|
|
871
|
+
console.log(HELP);
|
|
872
|
+
return 0;
|
|
873
|
+
}
|
|
874
|
+
// A command typed with dashes (lintsure --scan) or misspelt: say what was meant, not the whole manual.
|
|
875
|
+
const guess = nearest(cmd.replace(/^-+/, ""));
|
|
876
|
+
console.error(`Unknown command: ${cmd}${guess ? `\nDid you mean: lintsure ${guess}` : ""}\nRun lintsure --help for every command and option.`);
|
|
877
|
+
return 2;
|
|
205
878
|
}
|
|
206
879
|
const parsed = parseArgs(raw);
|
|
207
880
|
if ("error" in parsed) {
|
|
@@ -216,11 +889,57 @@ async function main(argv) {
|
|
|
216
889
|
console.error(`No folder at ${path}. Pass the project folder to scan, for example: lintsure scan .`);
|
|
217
890
|
return 2;
|
|
218
891
|
}
|
|
892
|
+
// No folder was named and this one isn't a project. Lintsure can't guess where the project is: at a terminal it asks,
|
|
893
|
+
// elsewhere it says how to name it. A named folder is taken at its word.
|
|
894
|
+
const namedFolder = rest.some((a, i) => !a.startsWith("--") && !VALUE_FLAGS.includes(rest[i - 1]));
|
|
895
|
+
// --pick: ask for the folder. It is what "Check another folder" in the menu runs.
|
|
896
|
+
if (rest.includes("--pick")) {
|
|
897
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
898
|
+
console.error(`--pick asks a question, so it needs a terminal. Name the folder: lintsure ${cmd} <folder>`);
|
|
899
|
+
return 2;
|
|
900
|
+
}
|
|
901
|
+
console.log("");
|
|
902
|
+
const where = await askFolder(false);
|
|
903
|
+
return where ? main([cmd, where, ...rest.filter((a) => a !== "--pick")]) : 0;
|
|
904
|
+
}
|
|
905
|
+
if (!namedFolder && !looksLikeProject(path)) {
|
|
906
|
+
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.`;
|
|
907
|
+
if (process.stdin.isTTY && process.stdout.isTTY) {
|
|
908
|
+
console.log(`\n${why}\n`);
|
|
909
|
+
const where = await askFolder(!isWholeDisk(path));
|
|
910
|
+
if (where === null)
|
|
911
|
+
return 0;
|
|
912
|
+
if (where)
|
|
913
|
+
return main([cmd, where, ...rest]);
|
|
914
|
+
}
|
|
915
|
+
else {
|
|
916
|
+
console.error(`${why}\nGo to your project folder first, or name it: lintsure ${cmd} <folder>`);
|
|
917
|
+
if (isWholeDisk(path))
|
|
918
|
+
return 2; // a whole home folder or drive is never what was meant
|
|
919
|
+
}
|
|
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
|
+
}
|
|
219
938
|
const config = await readConfig(path);
|
|
220
939
|
// Checked after the config loads its rule packs, so a pack's framework id is accepted.
|
|
221
940
|
const bad = wanted?.filter((f) => !ALL_FRAMEWORKS.includes(f));
|
|
222
941
|
if (bad?.length) {
|
|
223
|
-
console.error(`Unknown framework: ${bad.join(", ")}`);
|
|
942
|
+
console.error(`Unknown framework: ${bad.join(", ")}\nChoose from: ${ALL_FRAMEWORKS.join(", ")}`);
|
|
224
943
|
return 2;
|
|
225
944
|
}
|
|
226
945
|
if (config.problems.length) {
|
|
@@ -232,14 +951,18 @@ async function main(argv) {
|
|
|
232
951
|
console.log(`Skipping, not checked yet: ${config.skipped.join(", ")}`);
|
|
233
952
|
const why = wanted ? "Chosen with --framework on the command line." : config.frameworks ? "Listed in lintsure.config.yaml." : undefined;
|
|
234
953
|
const source = process.env.GITHUB_ACTIONS || process.env.CI ? "ci" : "cli";
|
|
235
|
-
const base = flag("--diff");
|
|
954
|
+
const base = flag("--diff"), staged = rest.includes("--staged");
|
|
236
955
|
let changed;
|
|
237
|
-
if (base) {
|
|
956
|
+
if (base || staged) {
|
|
238
957
|
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 })) };
|
|
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 })) };
|
|
240
959
|
}
|
|
241
960
|
catch {
|
|
242
|
-
|
|
961
|
+
if (!base) {
|
|
962
|
+
console.error("--staged needs a git repository, and this folder is not inside one.");
|
|
963
|
+
return 2;
|
|
964
|
+
}
|
|
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).`);
|
|
243
966
|
return 2;
|
|
244
967
|
}
|
|
245
968
|
}
|
|
@@ -256,6 +979,11 @@ async function main(argv) {
|
|
|
256
979
|
process.exit(2);
|
|
257
980
|
}
|
|
258
981
|
}
|
|
982
|
+
// A large project takes a few seconds: say that work has started, so the screen isn't blank.
|
|
983
|
+
if (process.stdout.isTTY) {
|
|
984
|
+
console.log("");
|
|
985
|
+
showFolder(`${tint(BLUE, "Lintsure")} is checking`, path);
|
|
986
|
+
}
|
|
259
987
|
const report = await scan(path, wanted ?? config.frameworks ?? ALL_FRAMEWORKS, { why, source, all: rest.includes("--all") || undefined, changed, workspaceRules });
|
|
260
988
|
const date = new Date().toISOString().slice(0, 10);
|
|
261
989
|
if (cmd === "baseline") {
|
|
@@ -283,36 +1011,143 @@ async function main(argv) {
|
|
|
283
1011
|
const open = report.findings.filter(isOpen);
|
|
284
1012
|
const n = (s) => open.filter((f) => f.status === s).length;
|
|
285
1013
|
const accepted = report.findings.length - open.length;
|
|
1014
|
+
const hygiene = open.filter(isHygiene).length;
|
|
286
1015
|
if (report.record)
|
|
287
1016
|
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
1017
|
// 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`);
|
|
1018
|
+
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
1019
|
console.log(` Read ${report.filesChecked} file${report.filesChecked === 1 ? "" : "s"}${report.filesSkipped ? `, skipped ${report.filesSkipped} (over 1 MB, binary or unreadable)` : ""}`);
|
|
291
1020
|
if (report.diffBase)
|
|
292
1021
|
console.log(` Only lines changed since ${report.diffBase}`);
|
|
1022
|
+
{
|
|
1023
|
+
const far = open.filter((f) => f.reach?.status === "unreachable" && !isHygiene(f)).length;
|
|
1024
|
+
if (far)
|
|
1025
|
+
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)`);
|
|
1026
|
+
}
|
|
293
1027
|
if (report.held)
|
|
294
1028
|
console.log(` ${report.held} more at medium confidence: run with --all to see ${report.held === 1 ? "it" : "them"}`);
|
|
295
1029
|
if (report.baseline)
|
|
296
1030
|
console.log(` Since the baseline of ${report.baseline.created}: ${report.baseline.newCount} new, ${report.baseline.fixed.length} fixed, ${report.baseline.unchangedCount} unchanged`);
|
|
297
|
-
|
|
298
|
-
|
|
1031
|
+
// Findings in the code first; repo hygiene under its own label (sort is stable, so file order holds within each group).
|
|
1032
|
+
const listed = [...report.findings].sort((a, b) => +isHygiene(a) - +isHygiene(b));
|
|
1033
|
+
// For a person at a terminal the findings stand apart from the summary and the notes: a ruled heading per group, each
|
|
1034
|
+
// file on its own line, and the status in colour. Piped output keeps one line per finding, which other tools read.
|
|
1035
|
+
const pretty = (process.stdout.isTTY || !!process.env.FORCE_COLOR) && !rest.includes("--github");
|
|
1036
|
+
const color = pretty && !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
|
1037
|
+
const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
1038
|
+
const width = Math.min(process.stdout.columns || 100, 100);
|
|
1039
|
+
// The old Windows console can't draw line characters reliably, so it gets plain dashes.
|
|
1040
|
+
const dash = legacy() ? "-" : "─";
|
|
1041
|
+
const ruled = (title) => `\n${paint("38;2;98;137;254", `${dash}${dash} ${title} `)}${paint("2", dash.repeat(Math.max(3, width - title.length - 4)))}`;
|
|
1042
|
+
const group = (title, items) => {
|
|
1043
|
+
if (!items.length)
|
|
1044
|
+
return;
|
|
1045
|
+
console.log(ruled(`${title} (${items.length})`));
|
|
1046
|
+
let file = "";
|
|
1047
|
+
for (const f of items) {
|
|
1048
|
+
if (f.file !== file) {
|
|
1049
|
+
file = f.file;
|
|
1050
|
+
console.log(`\n ${paint("38;2;98;137;254", file)}`);
|
|
1051
|
+
}
|
|
1052
|
+
const status = f.accepted && !f.accepted.expired ? "accepted" : f.status;
|
|
1053
|
+
const badge = status === "gap" ? paint("1;31", "GAP ") : status === "partial" ? paint("33", "PARTIAL ") : paint("2", "ACCEPTED");
|
|
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)") : ""}`);
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
// The first few to fix: gaps before partials, higher risk first, reached code first.
|
|
1058
|
+
const inCode = open.filter((f) => !isHygiene(f));
|
|
1059
|
+
const order = (f) => (f.status === "gap" ? 0 : 3) + { high: 0, medium: 1, low: 2 }[f.severity] + (f.reach?.status === "unreachable" ? 0.5 : 0);
|
|
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);
|
|
1064
|
+
const fold = (t, pad) => t.replace(new RegExp(`(.{1,${width - pad.length - 2}})(\\s+|$)`, "g"), `$1\n${pad}`).trimEnd();
|
|
1065
|
+
const reportFile = resolve("lintsure-report.md");
|
|
1066
|
+
// A request a person can paste into any coding agent, connected or not: it names the finding and where the proposal is.
|
|
1067
|
+
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.`;
|
|
1068
|
+
if (pretty) {
|
|
1069
|
+
// One line that fits the outcome, so the result is clear before any detail. It reports what the rules found and
|
|
1070
|
+
// never calls a project safe: "nothing found" is said in those words.
|
|
1071
|
+
const gaps = inCode.filter((f) => f.status === "gap");
|
|
1072
|
+
const headline = !open.length ? paint("1;32", "Done! Nothing found by the current rules.")
|
|
1073
|
+
: !inCode.length ? paint("1;32", "Done! Nothing in the code. Only housekeeping is left.")
|
|
1074
|
+
: gaps.some((f) => f.severity === "high" && !aside(f)) ? `${paint(BLUE, "Lintsure")} ${paint("1;31", "found something that needs your attention.")}`
|
|
1075
|
+
: gaps.length ? `${paint(BLUE, "Lintsure")} ${paint("1;33", "found something interesting.")}`
|
|
1076
|
+
: inCode.every((f) => f.severity === "low") ? paint("1;33", inCode.length === 1 ? "A minor finding, worth a look." : "Minor findings, worth a look.")
|
|
1077
|
+
: paint("1;33", "Worth a look.");
|
|
1078
|
+
console.log(`\n${headline}`);
|
|
1079
|
+
group("Findings in the code", listed.filter((f) => !isHygiene(f)));
|
|
1080
|
+
group("Repo hygiene: housekeeping, not flaws in the code", listed.filter(isHygiene));
|
|
1081
|
+
if (first.length) {
|
|
1082
|
+
console.log(ruled(`Start here (${first.length} of ${inCode.length})`));
|
|
1083
|
+
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, " ")}`));
|
|
1084
|
+
if (inCode.length > first.length)
|
|
1085
|
+
console.log(`\n ${paint("2", `The fix for every finding is in ${resolve("lintsure-report.md")}`)}`);
|
|
1086
|
+
}
|
|
1087
|
+
console.log(ruled("What next") + "\n");
|
|
1088
|
+
}
|
|
1089
|
+
else
|
|
1090
|
+
for (const f of listed)
|
|
1091
|
+
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
1092
|
if (rest.includes("--github"))
|
|
300
1093
|
for (const f of open) {
|
|
301
1094
|
const msg = `${f.title}. Proposed change, needs your approval: ${f.proposal.what}`.replace(/%/g, "%25").replace(/\r?\n/g, " ");
|
|
302
1095
|
console.log(`::${f.status === "gap" ? "error" : "warning"} file=${f.file},line=${f.line},title=Lintsure ${f.ruleId}::${msg}`);
|
|
303
1096
|
}
|
|
304
|
-
console.log(
|
|
1097
|
+
console.log(`Report saved to ${pretty ? resolve("lintsure-report.md") : "lintsure-report.md"}`);
|
|
305
1098
|
if (rest.includes("--report"))
|
|
306
1099
|
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
1100
|
console.log("\nNext steps:");
|
|
308
1101
|
nextSteps(report).forEach((x, i) => console.log(` ${i + 1}. ${x}`));
|
|
309
|
-
|
|
1102
|
+
// The steps above say what to decide. These are the commands that act on this scan, written out so they can be
|
|
1103
|
+
// copied; only the ones that apply are listed.
|
|
1104
|
+
const given = rest.find((a, i) => !a.startsWith("--") && !VALUE_FLAGS.includes(rest[i - 1]));
|
|
1105
|
+
const here = given ? [given] : [];
|
|
1106
|
+
const follow = [
|
|
1107
|
+
...(report.held ? [{ label: `Also show the ${report.held} held-back finding${report.held === 1 ? "" : "s"}`, run: ["scan", ...here, "--all"] }] : []),
|
|
1108
|
+
...(open.length && !report.baseline ? [{ label: "Remember these, so later scans show only what is new", run: ["baseline", ...here] }] : []),
|
|
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"] : [])] }] : []),
|
|
1111
|
+
{ label: "Connect your coding agent, then ask it to fix one", run: ["setup", ...here] },
|
|
1112
|
+
];
|
|
1113
|
+
// Menu only: the full proposal for one finding, and a request to paste into a coding agent. Lintsure never edits code.
|
|
1114
|
+
const showFix = async () => {
|
|
1115
|
+
const list = [...ranked, ...open.filter(isHygiene)].slice(0, 15);
|
|
1116
|
+
console.log(`\nWhich finding?${open.length > list.length ? ` (the first ${list.length} of ${open.length}; the rest are in the report)` : ""}`);
|
|
1117
|
+
const pick = await choose([...list.map((f) => `${f.id} ${f.title} ${f.file}:${f.line}`.slice(0, width - 6)), "Back"], HINT, color);
|
|
1118
|
+
if (pick === null || pick >= list.length)
|
|
1119
|
+
return;
|
|
1120
|
+
const f = list[pick], row = (name, text) => console.log(` ${paint(GOLD, name.padEnd(8))}${fold(text, " ")}`);
|
|
1121
|
+
console.log(ruled(`${f.id} ${f.title}`) + "\n");
|
|
1122
|
+
row("Where", f.proposal.where);
|
|
1123
|
+
row("Change", f.proposal.what);
|
|
1124
|
+
row("Why", f.proposal.why);
|
|
1125
|
+
row("Gain", f.proposal.benefit);
|
|
1126
|
+
console.log(`\n ${paint("2", "Nothing was changed. To hand it over, paste this into your coding agent:")}\n\n ${fold(request([f]), " ")}`);
|
|
1127
|
+
};
|
|
1128
|
+
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), " ")}`) }] : [])] : [];
|
|
1129
|
+
// A folder with a space in its name is quoted, so the line can be pasted as it is.
|
|
1130
|
+
const followRows = follow.map((f) => `${f.label.padEnd(54)}lintsure ${f.run.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(" ")}`);
|
|
1131
|
+
const asMenu = viaMenu && !!process.stdin.isTTY && !!process.stdout.isTTY;
|
|
1132
|
+
if (pretty && !asMenu)
|
|
1133
|
+
console.log(`\nRun next:\n${followRows.map((r) => ` ${r}`).join("\n")}`);
|
|
1134
|
+
// In a terminal the closing note is dimmed and wrapped at word ends, so it reads as a footnote and never splits a word.
|
|
1135
|
+
const wrap = (t) => t.split("\n").map((p) => p.replace(new RegExp(`(.{1,${width - 2}})(\\s+|$)`, "g"), "$1\n").trimEnd()).join("\n");
|
|
1136
|
+
console.log(`\n${pretty ? paint("2", wrap(DISCLAIMER)) : DISCLAIMER}`);
|
|
1137
|
+
if (asMenu) {
|
|
1138
|
+
console.log("\nRun next:");
|
|
1139
|
+
const ran = await offer([...fixRows, ...follow.map((f, i) => ({ text: followRows[i], run: f.run }))], color);
|
|
1140
|
+
if (ran !== undefined)
|
|
1141
|
+
return ran;
|
|
1142
|
+
}
|
|
310
1143
|
const failOn = flag("--fail-on")?.toLowerCase();
|
|
311
1144
|
const counted = rest.includes("--new-only") && report.baseline ? open.filter((f) => f.change === "new") : open;
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
if (
|
|
315
|
-
|
|
316
|
-
|
|
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;
|
|
317
1152
|
}
|
|
318
1153
|
main(process.argv.slice(2)).then((code) => process.exit(code), (e) => { console.error(e instanceof Error ? e.message : e); process.exit(2); });
|