lintsure 0.3.16 → 0.3.18
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 +31 -5
- package/dist/src/plugin.d.ts +1 -1
- package/dist/src/plugin.js +1 -1
- package/dist/src/send.d.ts +42 -0
- package/dist/src/send.js +49 -0
- package/package.json +54 -54
- package/skills/lintsure-check/SKILL.md +2 -1
- package/skills/lintsure-rules/SKILL.md +2 -1
- package/skills/lintsure-rules/rules.mjs +215 -197
package/dist/src/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { basename, dirname, join, resolve } from "node:path";
|
|
|
10
10
|
import { createInterface } from "node:readline/promises";
|
|
11
11
|
import { AGENTS, CONNECT_NOTE, MANUAL, callingAgent, detected, status, pick, plan, setup, undo } from "./agents.js";
|
|
12
12
|
import { parseActivity, toOtlp } from "./otel.js";
|
|
13
|
+
import { sendRun } from "./send.js";
|
|
13
14
|
import { ALL_FRAMEWORKS, BASELINE_FILE, DISCLAIMER, RULES_VERSION, classify, isHygiene, isNonShipping, isOpen, nextSteps, readConfig, scan, toAssessmentHtml, toBaseline, toMarkdown, toSarif } from "@lintsure/core";
|
|
14
15
|
import { choose, chooseMany } from "./menu.js";
|
|
15
16
|
import { installSkills, removeSkills, skillFolders, skills } from "./skills.js";
|
|
@@ -121,10 +122,14 @@ const START = [
|
|
|
121
122
|
{ label: "Check this folder", run: ["scan"] },
|
|
122
123
|
// `show` is the command to learn; the menu itself asks for the folder with --pick.
|
|
123
124
|
{ label: "Check another folder", run: ["scan", "--pick"], show: "scan <folder>" },
|
|
124
|
-
{ label: "
|
|
125
|
+
{ label: "Check what I'm committing", run: ["scan", "--staged"] },
|
|
126
|
+
{ label: "Apply the sure fixes", run: ["fix"] },
|
|
127
|
+
{ label: "Check before every commit", run: ["hook"] },
|
|
128
|
+
{ label: "Look up my packages", run: ["deps"] },
|
|
125
129
|
{ label: "Connect your coding agent", run: ["setup"] },
|
|
126
130
|
{ label: "Give your agent skills", run: ["skills"] },
|
|
127
131
|
{ label: "Add the Lintsure plugin", run: ["plugin"] },
|
|
132
|
+
{ label: "Is everything set up?", run: ["status"] },
|
|
128
133
|
{ label: "Every command and option", run: ["--help"] },
|
|
129
134
|
{ label: "Quit", run: null },
|
|
130
135
|
];
|
|
@@ -222,7 +227,11 @@ scan options:
|
|
|
222
227
|
--sarif Also write lintsure.sarif (for GitHub code scanning and editors)
|
|
223
228
|
--report Also write lintsure-assessment.html, a multi-page report
|
|
224
229
|
to review, print or save as PDF
|
|
225
|
-
--
|
|
230
|
+
--send Send this run's summary to your Lintsure workspace, so it shows on the
|
|
231
|
+
dashboard. Needs LINTSURE_API_KEY. Sends rule ids, file paths, lines,
|
|
232
|
+
severity and counts, never code
|
|
233
|
+
--project <name> Project name on the assessment cover and in the workspace
|
|
234
|
+
(default: folder name)
|
|
226
235
|
--fail-on <status> Exit 1 if any open finding is "gap" or "partial" (for CI). Held-back
|
|
227
236
|
medium-confidence findings count only with --all
|
|
228
237
|
--observe With --fail-on: say when the run would have failed, and pass anyway.
|
|
@@ -243,9 +252,10 @@ Accept a finding after review by adding it to .lintsure/accepted.yaml, with the
|
|
|
243
252
|
fingerprint from lintsure-report.json, your reason, your name and the date.
|
|
244
253
|
|
|
245
254
|
${DISCLAIMER}
|
|
246
|
-
Lintsure never sends your code anywhere. Only "lintsure deps --yes"
|
|
255
|
+
Lintsure never sends your code anywhere. Only "lintsure deps --yes" and "scan --send"
|
|
256
|
+
(a summary with no code, to your own workspace) use the network.`;
|
|
247
257
|
const VALUE_FLAGS = ["--framework", "--fail-on", "--project", "--diff"];
|
|
248
|
-
const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all", "--pick", "--staged", "--observe"];
|
|
258
|
+
const BOOL_FLAGS = ["--json", "--sarif", "--report", "--send", "--new-only", "--github", "--save-record", "--all", "--pick", "--staged", "--observe"];
|
|
249
259
|
/** Changed line numbers per file from `git diff -U0` output. Pure. */
|
|
250
260
|
export function parseDiff(text) {
|
|
251
261
|
const out = {};
|
|
@@ -529,6 +539,12 @@ async function main(argv) {
|
|
|
529
539
|
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
540
|
if (!raw.includes("--yes")) {
|
|
531
541
|
console.log("\nNothing sent yet. To run it: lintsure deps --yes");
|
|
542
|
+
if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
|
|
543
|
+
console.log("");
|
|
544
|
+
const ran = await offer([{ text: `${"Send the names and look them up".padEnd(54)}lintsure deps --yes`, run: ["deps", ...raw, "--yes"] }], !process.env.NO_COLOR && process.env.TERM !== "dumb");
|
|
545
|
+
if (ran !== undefined)
|
|
546
|
+
return ran;
|
|
547
|
+
}
|
|
532
548
|
return 0;
|
|
533
549
|
}
|
|
534
550
|
let hits;
|
|
@@ -594,12 +610,18 @@ async function main(argv) {
|
|
|
594
610
|
console.log(`- pre-commit hook: ${now === null ? "create" : "update"} .git/hooks/pre-commit\n lintsure scan --staged --fail-on gap`);
|
|
595
611
|
if (!raw.includes("--yes")) {
|
|
596
612
|
console.log("\nNothing written yet. To apply, run: lintsure hook --yes");
|
|
613
|
+
if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
|
|
614
|
+
console.log("");
|
|
615
|
+
const ran = await offer([{ text: `${"Add this hook".padEnd(54)}lintsure hook --yes`, run: ["hook", ...raw, "--yes"] }], !process.env.NO_COLOR && process.env.TERM !== "dumb");
|
|
616
|
+
if (ran !== undefined)
|
|
617
|
+
return ran;
|
|
618
|
+
}
|
|
597
619
|
return 0;
|
|
598
620
|
}
|
|
599
621
|
await mkdir(join(root, ".git", "hooks"), { recursive: true });
|
|
600
622
|
// 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
623
|
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");
|
|
624
|
+
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\nAn agent that commits for you may skip git hooks, so keep the check in CI too: lintsure/action");
|
|
603
625
|
return 0;
|
|
604
626
|
}
|
|
605
627
|
// lintsure plugin: the guards, for the agents this project uses. Shown first; nothing is downloaded or written before a yes.
|
|
@@ -1008,6 +1030,10 @@ async function main(argv) {
|
|
|
1008
1030
|
}
|
|
1009
1031
|
if (rest.includes("--report"))
|
|
1010
1032
|
await writeFile("lintsure-assessment.html", toAssessmentHtml(report, { project: flag("--project") ?? basename(path), date }));
|
|
1033
|
+
if (rest.includes("--send")) {
|
|
1034
|
+
const sent = await sendRun(report, path, flag("--project"));
|
|
1035
|
+
(sent.ok ? console.log : console.error)(sent.say);
|
|
1036
|
+
}
|
|
1011
1037
|
const open = report.findings.filter(isOpen);
|
|
1012
1038
|
const n = (s) => open.filter((f) => f.status === s).length;
|
|
1013
1039
|
const accepted = report.findings.length - open.length;
|
package/dist/src/plugin.d.ts
CHANGED
package/dist/src/plugin.js
CHANGED
|
@@ -12,7 +12,7 @@ import { homedir } from "node:os";
|
|
|
12
12
|
import { dirname, join } from "node:path";
|
|
13
13
|
import { writeJson } from "./agents.js";
|
|
14
14
|
// The plugin release that pairs with this engine. Pinned: a moving branch here would be what the supply-chain rules flag.
|
|
15
|
-
export const PLUGIN_TAG = "v0.3.
|
|
15
|
+
export const PLUGIN_TAG = "v0.3.7";
|
|
16
16
|
const REPO = "https://github.com/lintsure/plugin.git";
|
|
17
17
|
export const GUARD_AGENTS = [
|
|
18
18
|
{ id: "claude", name: "Claude Code", marker: ".claude" },
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type Report } from "@lintsure/core";
|
|
2
|
+
/** The body POST /api/v1/runs takes. Pure, so the smoke test can check that no code is in it. */
|
|
3
|
+
export declare function runPayload(report: Report, o: {
|
|
4
|
+
project: string;
|
|
5
|
+
source: "ci" | "agent";
|
|
6
|
+
commit?: string;
|
|
7
|
+
branch?: string;
|
|
8
|
+
}): {
|
|
9
|
+
checks: string[];
|
|
10
|
+
filesChecked: number;
|
|
11
|
+
held: number;
|
|
12
|
+
findings: {
|
|
13
|
+
ruleId: string;
|
|
14
|
+
title: string;
|
|
15
|
+
severity: import("@lintsure/core").Severity;
|
|
16
|
+
status: import("@lintsure/core").Status;
|
|
17
|
+
file: string;
|
|
18
|
+
line: number;
|
|
19
|
+
fix: string;
|
|
20
|
+
why: string;
|
|
21
|
+
controls: import("@lintsure/core").Control[];
|
|
22
|
+
}[];
|
|
23
|
+
scope: {
|
|
24
|
+
diffBase?: string | undefined;
|
|
25
|
+
notCovered: string[];
|
|
26
|
+
rulesOff: string[];
|
|
27
|
+
skipped: {
|
|
28
|
+
why: string;
|
|
29
|
+
n: number;
|
|
30
|
+
}[];
|
|
31
|
+
};
|
|
32
|
+
branch?: string | undefined;
|
|
33
|
+
commit?: string | undefined;
|
|
34
|
+
project: string;
|
|
35
|
+
source: "agent" | "ci";
|
|
36
|
+
version: string;
|
|
37
|
+
};
|
|
38
|
+
/** Sends the summary. Returns a line to print; never throws, so a network problem can't fail a CI job on its own. */
|
|
39
|
+
export declare function sendRun(report: Report, path: string, project?: string): Promise<{
|
|
40
|
+
ok: boolean;
|
|
41
|
+
say: string;
|
|
42
|
+
}>;
|
package/dist/src/send.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// `lintsure scan --send`: send this run's summary to your Lintsure workspace, so CI and agents other than Claude Code
|
|
2
|
+
// show up on the dashboard. Off unless you pass --send AND set LINTSURE_API_KEY. What is sent: the project name,
|
|
3
|
+
// commit and branch, rule ids, titles, file paths and line numbers, severity, the fix text and counts. Never code.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { basename } from "node:path";
|
|
6
|
+
import { isOpen, RULES_VERSION } from "@lintsure/core";
|
|
7
|
+
/** The body POST /api/v1/runs takes. Pure, so the smoke test can check that no code is in it. */
|
|
8
|
+
export function runPayload(report, o) {
|
|
9
|
+
const open = report.findings.filter(isOpen);
|
|
10
|
+
return {
|
|
11
|
+
project: o.project, source: o.source, version: RULES_VERSION,
|
|
12
|
+
...(o.commit && /^[0-9a-f]{7,64}$/i.test(o.commit) ? { commit: o.commit } : {}), ...(o.branch ? { branch: o.branch } : {}),
|
|
13
|
+
checks: [...new Set([...report.met.map((m) => m.ruleId), ...report.findings.map((f) => f.ruleId)])],
|
|
14
|
+
filesChecked: report.filesChecked, held: report.held ?? 0,
|
|
15
|
+
findings: open.map((f) => ({ ruleId: f.ruleId, title: f.title, severity: f.severity, status: f.status, file: f.file, line: f.line, fix: f.fix, why: f.proposal?.why?.slice(0, 300), controls: f.controls })),
|
|
16
|
+
scope: {
|
|
17
|
+
notCovered: report.notCovered ?? [], rulesOff: report.rulesOff ?? [],
|
|
18
|
+
skipped: report.filesSkipped ? [{ why: "over 1 MB, binary or unreadable", n: report.filesSkipped }] : [],
|
|
19
|
+
...(report.diffBase ? { diffBase: report.diffBase } : {}),
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const git = (cwd, args) => { try {
|
|
24
|
+
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return "";
|
|
28
|
+
} };
|
|
29
|
+
/** Sends the summary. Returns a line to print; never throws, so a network problem can't fail a CI job on its own. */
|
|
30
|
+
export async function sendRun(report, path, project) {
|
|
31
|
+
const key = process.env.LINTSURE_API_KEY, api = (process.env.LINTSURE_URL || "https://lintsure.com").replace(/\/$/, "");
|
|
32
|
+
if (!key)
|
|
33
|
+
return { ok: false, say: "--send needs LINTSURE_API_KEY (a key from Settings, API keys in your Lintsure workspace). Nothing was sent." };
|
|
34
|
+
const ci = !!(process.env.GITHUB_ACTIONS || process.env.CI);
|
|
35
|
+
const branch = process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME || git(path, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
36
|
+
const body = runPayload(report, { project: project || basename(path), source: ci ? "ci" : "agent", commit: process.env.GITHUB_SHA || git(path, ["rev-parse", "HEAD"]), branch: branch === "HEAD" ? "" : branch });
|
|
37
|
+
try {
|
|
38
|
+
const r = await fetch(`${api}/api/v1/runs`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json", "user-agent": `lintsure-cli/${RULES_VERSION}` }, body: JSON.stringify(body), signal: AbortSignal.timeout(15000) });
|
|
39
|
+
if (r.status === 401)
|
|
40
|
+
return { ok: false, say: "Lintsure didn't accept that API key. Nothing was sent." };
|
|
41
|
+
if (!r.ok)
|
|
42
|
+
return { ok: false, say: `Couldn't send the summary to Lintsure (HTTP ${r.status}). The scan itself is unaffected.` };
|
|
43
|
+
const d = await r.json().catch(() => ({}));
|
|
44
|
+
return { ok: true, say: d.unchanged ? "Same as the last run sent for this commit, so Lintsure kept that one." : `Sent the summary (${body.findings.length} open finding${body.findings.length === 1 ? "" : "s"}, no code) to your Lintsure workspace.` };
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return { ok: false, say: "Couldn't reach Lintsure to send the summary. The scan itself is unaffected." };
|
|
48
|
+
}
|
|
49
|
+
}
|
package/package.json
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "lintsure",
|
|
3
|
-
"version": "0.3.
|
|
4
|
-
"description": "Keep your AI coding agents on track: checks the code Claude Code, Cursor and Codex write for secrets, open databases and unsafe patterns, mapped to OWASP, GDPR and the EU AI Act. Runs locally. Not an audit or legal advice.",
|
|
5
|
-
"license": "Apache-2.0",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"bin": {
|
|
8
|
-
"lintsure": "dist/src/index.js"
|
|
9
|
-
},
|
|
10
|
-
"files": [
|
|
11
|
-
"dist/src",
|
|
12
|
-
"skills",
|
|
13
|
-
"README.md",
|
|
14
|
-
"LICENSE"
|
|
15
|
-
],
|
|
16
|
-
"dependencies": {
|
|
17
|
-
"@lintsure/core": "0.3.
|
|
18
|
-
},
|
|
19
|
-
"author": "Lintsure <hello@lintsure.com>",
|
|
20
|
-
"homepage": "https://lintsure.com/docs",
|
|
21
|
-
"repository": {
|
|
22
|
-
"type": "git",
|
|
23
|
-
"url": "git+https://github.com/lintsure/lintsure.git"
|
|
24
|
-
},
|
|
25
|
-
"bugs": {
|
|
26
|
-
"url": "https://github.com/lintsure/lintsure/issues",
|
|
27
|
-
"email": "support@lintsure.com"
|
|
28
|
-
},
|
|
29
|
-
"engines": {
|
|
30
|
-
"node": ">=22"
|
|
31
|
-
},
|
|
32
|
-
"publishConfig": {
|
|
33
|
-
"access": "public"
|
|
34
|
-
},
|
|
35
|
-
"keywords": [
|
|
36
|
-
"ai-agents",
|
|
37
|
-
"claude-code",
|
|
38
|
-
"cursor",
|
|
39
|
-
"codex",
|
|
40
|
-
"coding-agent",
|
|
41
|
-
"guardrails",
|
|
42
|
-
"security",
|
|
43
|
-
"secrets",
|
|
44
|
-
"supabase",
|
|
45
|
-
"owasp",
|
|
46
|
-
"gdpr",
|
|
47
|
-
"eu-ai-act",
|
|
48
|
-
"mcp",
|
|
49
|
-
"static-analysis"
|
|
50
|
-
],
|
|
51
|
-
"scripts": {
|
|
52
|
-
"prepublishOnly": "cd ../.. && npm test"
|
|
53
|
-
}
|
|
54
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "lintsure",
|
|
3
|
+
"version": "0.3.18",
|
|
4
|
+
"description": "Keep your AI coding agents on track: checks the code Claude Code, Cursor and Codex write for secrets, open databases and unsafe patterns, mapped to OWASP, GDPR and the EU AI Act. Runs locally. Not an audit or legal advice.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"lintsure": "dist/src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/src",
|
|
12
|
+
"skills",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@lintsure/core": "0.3.18"
|
|
18
|
+
},
|
|
19
|
+
"author": "Lintsure <hello@lintsure.com>",
|
|
20
|
+
"homepage": "https://lintsure.com/docs",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/lintsure/lintsure.git"
|
|
24
|
+
},
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/lintsure/lintsure/issues",
|
|
27
|
+
"email": "support@lintsure.com"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"ai-agents",
|
|
37
|
+
"claude-code",
|
|
38
|
+
"cursor",
|
|
39
|
+
"codex",
|
|
40
|
+
"coding-agent",
|
|
41
|
+
"guardrails",
|
|
42
|
+
"security",
|
|
43
|
+
"secrets",
|
|
44
|
+
"supabase",
|
|
45
|
+
"owasp",
|
|
46
|
+
"gdpr",
|
|
47
|
+
"eu-ai-act",
|
|
48
|
+
"mcp",
|
|
49
|
+
"static-analysis"
|
|
50
|
+
],
|
|
51
|
+
"scripts": {
|
|
52
|
+
"prepublishOnly": "cd ../.. && npm test"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: lintsure-check
|
|
3
|
-
description:
|
|
3
|
+
description: >-
|
|
4
|
+
Use when code has just been written, changed or pasted into the chat and the user asks whether it is fine, safe or ready to commit, or when you yourself just wrote or changed such code, and it touches any of these: secrets or API keys, login, passwords, sessions or cookies, database migrations or row-level security, logging of user data, calls to an AI model, file uploads, webhooks, or CI workflows. Also use when the user asks to have code checked against security, GDPR or EU AI Act rules. Checks the code with Lintsure and reports what its checks find; it does not say whether something is secure or compliant. Runs locally; quick; silent when nothing is found.
|
|
4
5
|
---
|
|
5
6
|
|
|
6
7
|
# Lintsure check
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: lintsure-rules
|
|
3
|
-
description:
|
|
3
|
+
description: >-
|
|
4
|
+
Use whenever a message starts with "Lintsure:" followed by a rule in plain words ("Lintsure: never let it touch the payment code", "Lintsure: always use our logger"), and whenever the user states a standing rule for how agents must work in this project (never, always, don't, only, ask before). Also use when the user wants to set up, suggest, add or see Lintsure rules ("Lintsure, suggest rules", "what rules do we have"), or share them with other agents ("make Cursor follow these too"). Turns the words into one rule, tries it, and writes it to .lintsure/rules.yml only after the user agrees.
|
|
4
5
|
---
|
|
5
6
|
|
|
6
7
|
# Lintsure rules
|
|
@@ -1,197 +1,215 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Lintsure rules helper for the lintsure-rules skill. Runs on this machine; nothing is sent anywhere.
|
|
3
|
-
// node rules.mjs suggest Suggest rules from what the project already has, each with its reason.
|
|
4
|
-
// node rules.mjs write '<json>' Add rules to .lintsure/rules.yml. <json> is an array of
|
|
5
|
-
// {kind, text, pattern?, paths?, in?} (kind: avoid, protect, deps, note).
|
|
6
|
-
// node rules.mjs try '<json>' Dry run one rule on the repo before writing it: what it matches today.
|
|
7
|
-
// Either command also takes @file.json, safer for patterns with backslashes.
|
|
8
|
-
// node rules.mjs list Show the rules the file holds now, in plain words.
|
|
9
|
-
// node rules.mjs sync [targets] Write the rules into other agents' instruction files (agents, cursor, copilot,
|
|
10
|
-
// claude; comma separated). Default: AGENTS.md and Cursor, plus the others if present.
|
|
11
|
-
// node rules.mjs unsync Take Lintsure's block out of those files again.
|
|
12
|
-
// Suggestions are guesses from files that exist, never claims about what the code does. The user decides.
|
|
13
|
-
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from "node:fs";
|
|
14
|
-
import { join, relative, basename } from "node:path";
|
|
15
|
-
import { fileRules, globMatch, safePattern, MAX_LINE } from "./lib.mjs";
|
|
16
|
-
import { Worker } from "node:worker_threads";
|
|
17
|
-
import { profile } from "./profile.mjs";
|
|
18
|
-
import { sync, synced, unsync } from "./agents.mjs";
|
|
19
|
-
|
|
20
|
-
const root = process.cwd(), FILE = join(root, ".lintsure", "rules.yml");
|
|
21
|
-
const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".astro", ".output", "coverage", ".wrangler", "vendor", "out"]);
|
|
22
|
-
const rel = (f) => relative(root, f).replace(/\\/g, "/");
|
|
23
|
-
|
|
24
|
-
function files(max = 5000) {
|
|
25
|
-
const out = [];
|
|
26
|
-
const go = (d, depth) => {
|
|
27
|
-
if (out.length >= max || depth > 8) return;
|
|
28
|
-
let ents = []; try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
29
|
-
for (const e of ents) {
|
|
30
|
-
if (e.isDirectory()) { if (!SKIP.has(e.name) && (!e.name.startsWith(".") || e.name === ".github")) go(join(d, e.name), depth + 1); }
|
|
31
|
-
else out.push(join(d, e.name));
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
go(root, 0);
|
|
35
|
-
return out;
|
|
36
|
-
}
|
|
37
|
-
/** How many lines in source files already match, so a rule the code breaks everywhere isn't suggested blindly. */
|
|
38
|
-
function uses(all, re, only) {
|
|
39
|
-
let n = 0;
|
|
40
|
-
for (const f of all) {
|
|
41
|
-
if (!/\.(m?[jt]sx?|cjs|astro|vue|svelte)$/.test(f) || (only && !only.test(rel(f)))) continue;
|
|
42
|
-
try { if (statSync(f).size > 300_000) continue; for (const line of readFileSync(f, "utf8").split("\n")) if (re.test(line)) n++; } catch { /* skip */ }
|
|
43
|
-
}
|
|
44
|
-
return n;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function suggest() {
|
|
48
|
-
const all = files(), paths = all.map(rel), p = profile(root), s = [];
|
|
49
|
-
const has = (re) => paths.find((x) => re.test(x));
|
|
50
|
-
const dirOf = (x) => x.split("/").slice(0, -1).join("/");
|
|
51
|
-
|
|
52
|
-
const mig = has(/(^|\/)(migrations?|db\/migrate|prisma\/migrations)\/[^/]+\.(sql|[jt]s|rb|py)$/);
|
|
53
|
-
if (mig) s.push({ id: "protect-migrations", kind: "protect", paths: `${dirOf(mig)}/**`, text: "Don't change database migrations that already exist. Add a new one instead.", why: `Suggested because ${dirOf(mig)}/ holds migrations. New files there are still allowed.` });
|
|
54
|
-
|
|
55
|
-
const test = has(/(\.test|\.spec)\.[jt]sx?$|(^|\/)tests?\//);
|
|
56
|
-
if (test) {
|
|
57
|
-
const n = uses(all, /\.(skip|only)\(|\bxit\(|\bxdescribe\(/);
|
|
58
|
-
s.push({ id: "no-skip-tests", kind: "avoid", pattern: "\\.(skip|only)\\(|\\bxit\\(|\\bxdescribe\\(", text: "Never skip or disable tests to make them pass.", why: `Suggested because the project has tests (${test}).${n ? ` Note: ${n} skipped or focused test${n > 1 ? "s" : ""} already exist.` : ""}` });
|
|
59
|
-
}
|
|
60
|
-
if (existsSync(join(root, "package.json"))) s.push({ id: "ask-deps", kind: "deps", text: "Ask me before adding a new package.", why: "Suggested because the project has a package.json. Agents often add packages, or invent ones that don't exist." });
|
|
61
|
-
|
|
62
|
-
const logger = has(/(^|\/)(lib|utils?|src)\/(log|logger|logging)\.[jt]s$/);
|
|
63
|
-
if (logger) {
|
|
64
|
-
const n = uses(all, /console\.log\(/, /^(src|app|lib)\//);
|
|
65
|
-
if (n < 5) s.push({ id: "use-logger", kind: "avoid", pattern: "console\\.log\\(", in: "src/**, app/**, lib/**", text: `Use the logger in ${logger}, not console.log.`, why: `Suggested because ${logger} exists${n ? ` (console.log is used ${n} time${n > 1 ? "s" : ""} today)` : ""}.` });
|
|
66
|
-
}
|
|
67
|
-
const cols = Object.entries(p.colors);
|
|
68
|
-
if (cols.length >= 2) s.push({ id: "brand-colours", kind: "note", text: `Use the brand colours (${cols.slice(0, 6).map(([h, n]) => `${n} ${h}`).join(", ")}), not new ones.`, why: "Suggested because the project defines these colours. Drift Guard already flags brand-new colours." });
|
|
69
|
-
const comps = Object.keys(p.components);
|
|
70
|
-
if (comps.length >= 2) s.push({ id: "reuse-components", kind: "note", text: `Reuse the existing components (${comps.slice(0, 8).join(", ")}${comps.length > 8 ? " and more" : ""}) instead of making new ones that do the same thing.`, why: `Suggested because the project has ${comps.length} components.` });
|
|
71
|
-
if (p.content.length) s.push({ id: "real-copy", kind: "note", text: `Use the real quotes, names and copy from ${p.content.slice(0, 3).join(", ")}. Never invent them.`, why: "Suggested because the project keeps content in these files." });
|
|
72
|
-
const wf = has(/^\.github\/workflows\/[^/]+\.ya?ml$/);
|
|
73
|
-
if (wf) s.push({ id: "protect-ci", kind: "protect", paths: ".github/workflows/**", text: "Don't change the CI workflows unless I ask.", why: "Suggested because the project has GitHub workflows. Changes there can leak secrets or skip checks." });
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
if (
|
|
78
|
-
|
|
79
|
-
//
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const { hits, scanned, partial }
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
lines.
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const
|
|
163
|
-
if (
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
} else if (cmd === "
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Lintsure rules helper for the lintsure-rules skill. Runs on this machine; nothing is sent anywhere.
|
|
3
|
+
// node rules.mjs suggest Suggest rules from what the project already has, each with its reason.
|
|
4
|
+
// node rules.mjs write '<json>' Add rules to .lintsure/rules.yml. <json> is an array of
|
|
5
|
+
// {kind, text, pattern?, paths?, in?} (kind: avoid, protect, deps, note).
|
|
6
|
+
// node rules.mjs try '<json>' Dry run one rule on the repo before writing it: what it matches today.
|
|
7
|
+
// Either command also takes @file.json, safer for patterns with backslashes.
|
|
8
|
+
// node rules.mjs list Show the rules the file holds now, in plain words.
|
|
9
|
+
// node rules.mjs sync [targets] Write the rules into other agents' instruction files (agents, cursor, copilot,
|
|
10
|
+
// claude; comma separated). Default: AGENTS.md and Cursor, plus the others if present.
|
|
11
|
+
// node rules.mjs unsync Take Lintsure's block out of those files again.
|
|
12
|
+
// Suggestions are guesses from files that exist, never claims about what the code does. The user decides.
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from "node:fs";
|
|
14
|
+
import { join, relative, basename } from "node:path";
|
|
15
|
+
import { fileRules, globMatch, safePattern, MAX_LINE } from "./lib.mjs";
|
|
16
|
+
import { Worker } from "node:worker_threads";
|
|
17
|
+
import { profile } from "./profile.mjs";
|
|
18
|
+
import { sync, synced, unsync } from "./agents.mjs";
|
|
19
|
+
|
|
20
|
+
const root = process.cwd(), FILE = join(root, ".lintsure", "rules.yml");
|
|
21
|
+
const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".astro", ".output", "coverage", ".wrangler", "vendor", "out"]);
|
|
22
|
+
const rel = (f) => relative(root, f).replace(/\\/g, "/");
|
|
23
|
+
|
|
24
|
+
function files(max = 5000) {
|
|
25
|
+
const out = [];
|
|
26
|
+
const go = (d, depth) => {
|
|
27
|
+
if (out.length >= max || depth > 8) return;
|
|
28
|
+
let ents = []; try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
29
|
+
for (const e of ents) {
|
|
30
|
+
if (e.isDirectory()) { if (!SKIP.has(e.name) && (!e.name.startsWith(".") || e.name === ".github")) go(join(d, e.name), depth + 1); }
|
|
31
|
+
else out.push(join(d, e.name));
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
go(root, 0);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** How many lines in source files already match, so a rule the code breaks everywhere isn't suggested blindly. */
|
|
38
|
+
function uses(all, re, only) {
|
|
39
|
+
let n = 0;
|
|
40
|
+
for (const f of all) {
|
|
41
|
+
if (!/\.(m?[jt]sx?|cjs|astro|vue|svelte)$/.test(f) || (only && !only.test(rel(f)))) continue;
|
|
42
|
+
try { if (statSync(f).size > 300_000) continue; for (const line of readFileSync(f, "utf8").split("\n")) if (re.test(line)) n++; } catch { /* skip */ }
|
|
43
|
+
}
|
|
44
|
+
return n;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function suggest() {
|
|
48
|
+
const all = files(), paths = all.map(rel), p = profile(root), s = [];
|
|
49
|
+
const has = (re) => paths.find((x) => re.test(x));
|
|
50
|
+
const dirOf = (x) => x.split("/").slice(0, -1).join("/");
|
|
51
|
+
|
|
52
|
+
const mig = has(/(^|\/)(migrations?|db\/migrate|prisma\/migrations)\/[^/]+\.(sql|[jt]s|rb|py)$/);
|
|
53
|
+
if (mig) s.push({ id: "protect-migrations", kind: "protect", paths: `${dirOf(mig)}/**`, text: "Don't change database migrations that already exist. Add a new one instead.", why: `Suggested because ${dirOf(mig)}/ holds migrations. New files there are still allowed.` });
|
|
54
|
+
|
|
55
|
+
const test = has(/(\.test|\.spec)\.[jt]sx?$|(^|\/)tests?\//);
|
|
56
|
+
if (test) {
|
|
57
|
+
const n = uses(all, /\.(skip|only)\(|\bxit\(|\bxdescribe\(/);
|
|
58
|
+
s.push({ id: "no-skip-tests", kind: "avoid", pattern: "\\.(skip|only)\\(|\\bxit\\(|\\bxdescribe\\(", text: "Never skip or disable tests to make them pass.", why: `Suggested because the project has tests (${test}).${n ? ` Note: ${n} skipped or focused test${n > 1 ? "s" : ""} already exist.` : ""}` });
|
|
59
|
+
}
|
|
60
|
+
if (existsSync(join(root, "package.json"))) s.push({ id: "ask-deps", kind: "deps", text: "Ask me before adding a new package.", why: "Suggested because the project has a package.json. Agents often add packages, or invent ones that don't exist." });
|
|
61
|
+
|
|
62
|
+
const logger = has(/(^|\/)(lib|utils?|src)\/(log|logger|logging)\.[jt]s$/);
|
|
63
|
+
if (logger) {
|
|
64
|
+
const n = uses(all, /console\.log\(/, /^(src|app|lib)\//);
|
|
65
|
+
if (n < 5) s.push({ id: "use-logger", kind: "avoid", pattern: "console\\.log\\(", in: "src/**, app/**, lib/**", text: `Use the logger in ${logger}, not console.log.`, why: `Suggested because ${logger} exists${n ? ` (console.log is used ${n} time${n > 1 ? "s" : ""} today)` : ""}.` });
|
|
66
|
+
}
|
|
67
|
+
const cols = Object.entries(p.colors);
|
|
68
|
+
if (cols.length >= 2) s.push({ id: "brand-colours", kind: "note", text: `Use the brand colours (${cols.slice(0, 6).map(([h, n]) => `${n} ${h}`).join(", ")}), not new ones.`, why: "Suggested because the project defines these colours. Drift Guard already flags brand-new colours." });
|
|
69
|
+
const comps = Object.keys(p.components);
|
|
70
|
+
if (comps.length >= 2) s.push({ id: "reuse-components", kind: "note", text: `Reuse the existing components (${comps.slice(0, 8).join(", ")}${comps.length > 8 ? " and more" : ""}) instead of making new ones that do the same thing.`, why: `Suggested because the project has ${comps.length} components.` });
|
|
71
|
+
if (p.content.length) s.push({ id: "real-copy", kind: "note", text: `Use the real quotes, names and copy from ${p.content.slice(0, 3).join(", ")}. Never invent them.`, why: "Suggested because the project keeps content in these files." });
|
|
72
|
+
const wf = has(/^\.github\/workflows\/[^/]+\.ya?ml$/);
|
|
73
|
+
if (wf) s.push({ id: "protect-ci", kind: "protect", paths: ".github/workflows/**", text: "Don't change the CI workflows unless I ask.", why: "Suggested because the project has GitHub workflows. Changes there can leak secrets or skip checks." });
|
|
74
|
+
// The files that tell agents and reviewers what to do. A change there changes what every later check looks for.
|
|
75
|
+
const setters = [["CLAUDE.md", /(^|\/)CLAUDE\.md$/], ["AGENTS.md", /(^|\/)AGENTS\.md$/], ["REVIEW.md", /(^|\/)REVIEW\.md$/], ["CODEOWNERS", /(^|\/)CODEOWNERS$/]].filter(([, re]) => has(re)).map(([n]) => n);
|
|
76
|
+
const claudeDir = existsSync(join(root, ".claude")); // dot folders are not in the file list
|
|
77
|
+
if (setters.length || claudeDir) s.push({ id: "protect-rule-files", kind: "protect", paths: [...setters.flatMap((n) => [n, `**/${n}`]), ...(claudeDir ? [".claude/**"] : [])].join(", "), text: "Don't change the files that set the rules for agents and reviews unless I ask.", why: `Suggested because the project has ${[...setters, ...(claudeDir ? [".claude/"] : [])].join(", ")}. A change there changes what every later check looks for.` });
|
|
78
|
+
// Rules the project already wrote down for one agent, offered so that every agent follows them. Only plain
|
|
79
|
+
// do and don't lines from the top-level files; a line that steers an agent against its user is never passed on.
|
|
80
|
+
const said = [];
|
|
81
|
+
for (const f of ["CLAUDE.md", "AGENTS.md", "REVIEW.md"]) {
|
|
82
|
+
let text; try { text = readFileSync(join(root, f), "utf8"); } catch { continue; }
|
|
83
|
+
text.split(/\r?\n/).forEach((line, i) => {
|
|
84
|
+
const t = line.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "").replace(/[*_`]/g, "").replace(/\s+/g, " ").trim();
|
|
85
|
+
if (said.length >= 5 || t.length < 12 || t.length > 160) return;
|
|
86
|
+
if (!/^(never|always|don'?t|do not|must|only|avoid|use)\b/i.test(t)) return;
|
|
87
|
+
if (/\b(ignore|disregard|override|forget)\b.*\b(instructions|rules|prompts?)\b|\b(tell|inform|mention|show)\b.*\bthe user\b|https?:\/\/|\bcurl\b|\bwget\b/i.test(t)) return;
|
|
88
|
+
said.push({ id: `from-${f.toLowerCase().replace(/\W/g, "-")}-${i + 1}`, kind: "note", text: t, why: `Suggested because ${f} line ${i + 1} says so. As a Lintsure rule every agent follows it, not only the one that reads ${f}.` });
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
s.push(...said);
|
|
92
|
+
const gen = has(/(^|\/)(generated|__generated__)\/|\.gen\.[jt]s$/);
|
|
93
|
+
if (gen) s.push({ id: "protect-generated", kind: "protect", paths: gen.includes("generated/") ? `${gen.slice(0, gen.indexOf("generated/") + 10)}**` : "**/*.gen.*", text: "Don't edit generated files by hand. Change the source and regenerate.", why: `Suggested because ${gen} looks generated.` });
|
|
94
|
+
const env = has(/(^|\/)\.env(\.example|\.sample)?$/);
|
|
95
|
+
if (env || paths.some((x) => /\.env/.test(x))) s.push({ id: "no-secrets", kind: "avoid", pattern: "(sk_live_|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY)", text: "Never put keys or passwords in the code. Read them from environment variables.", why: "Suggested because the project uses environment files." });
|
|
96
|
+
|
|
97
|
+
// Drop what the rules file already has.
|
|
98
|
+
const have = fileRules(root), same = (a, b) => a.kind === b.kind && (a.pattern || "") === (b.pattern || "") && (a.paths || "") === (b.paths || "") && (a.kind !== "note" || a.text === b.text);
|
|
99
|
+
return s.filter((x) => !have.some((h) => same(h, x))).slice(0, 10);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Dry run: what a rule would match in this repo today, before it is written. Matched text is shown cut short, so a key
|
|
103
|
+
* the code already holds isn't copied in full into the conversation. Pure apart from reading files. */
|
|
104
|
+
// The scan runs in a worker that is stopped after 3 seconds, so even a pattern that is slow on a single line ends.
|
|
105
|
+
const SCAN = `
|
|
106
|
+
const { parentPort, workerData: w } = require("node:worker_threads");
|
|
107
|
+
const re = new RegExp(w.pattern, "i");
|
|
108
|
+
for (const f of w.files) {
|
|
109
|
+
f.text.split("\\n").forEach((line, i) => { const m = line.slice(0, w.max).match(re); if (m) parentPort.postMessage({ at: f.p + ":" + (i + 1), match: m[0].length > 12 ? m[0].slice(0, 6) + "…" : m[0] }); });
|
|
110
|
+
parentPort.postMessage({ file: true });
|
|
111
|
+
}
|
|
112
|
+
parentPort.postMessage({ done: true });`;
|
|
113
|
+
function scanInWorker(pattern, list, ms = 3000) {
|
|
114
|
+
return new Promise((resolve) => {
|
|
115
|
+
const hits = []; let scanned = 0, w, timer;
|
|
116
|
+
const end = (partial) => { clearTimeout(timer); w?.terminate().catch(() => {}); resolve({ hits, scanned, partial }); };
|
|
117
|
+
try { w = new Worker(SCAN, { eval: true, workerData: { pattern, files: list, max: MAX_LINE } }); } catch { return resolve({ hits, scanned, partial: true }); }
|
|
118
|
+
timer = setTimeout(() => end(true), ms);
|
|
119
|
+
w.on("message", (m) => { if (m.done) end(false); else if (m.file) scanned++; else hits.push(m); });
|
|
120
|
+
w.on("error", () => end(true));
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
async function tryRule(r) {
|
|
124
|
+
const all = files(), inScope = (p) => (!r.in && !r.paths) || globMatch(p, r.kind === "protect" ? r.paths : r.in), out = (p) => !!r.except && globMatch(p, r.except);
|
|
125
|
+
if (r.kind === "avoid") {
|
|
126
|
+
const safe = safePattern(r.pattern, "i");
|
|
127
|
+
if (safe.error) return { ok: false, says: safe.error };
|
|
128
|
+
const list = []; let tooBig = 0;
|
|
129
|
+
for (const f of all) {
|
|
130
|
+
const p = rel(f);
|
|
131
|
+
if (!/\.(m?[jt]sx?|cjs|astro|vue|svelte|py|rb|go|java|kt|php|html|ya?ml|json|toml|env|sh|sql|md)$|(^|\/)\.env/.test(p) || !inScope(p) || out(p)) continue;
|
|
132
|
+
try { if (statSync(f).size > 300_000) { tooBig++; continue; } list.push({ p, text: readFileSync(f, "utf8") }); } catch { tooBig++; }
|
|
133
|
+
}
|
|
134
|
+
const { hits, scanned, partial } = await scanInWorker(r.pattern, list);
|
|
135
|
+
const notRead = tooBig ? ` ${tooBig} file${tooBig > 1 ? "s were" : " was"} not read (over 300 KB or unreadable), so no match there means not checked.` : "";
|
|
136
|
+
const more = partial ? ` It stopped after 3 seconds (${scanned} of ${list.length} files read), so there may be more. If that's on a small repo, the pattern is too slow: simplify it.` : "";
|
|
137
|
+
return { ok: true, kind: "avoid", scanned, notRead: tooBig, partial, hits: hits.length, sample: hits.slice(0, 12),
|
|
138
|
+
says: (hits.length ? `Matches ${hits.length} line${hits.length > 1 ? "s" : ""} in ${scanned} files already. The guard checks new edits, so these won't be flagged, but if this list is long the pattern is probably too broad.` : `Matches nothing in the ${scanned} files it covers today. New code that matches will be flagged.`) + more + notRead };
|
|
139
|
+
}
|
|
140
|
+
if (r.kind === "protect") {
|
|
141
|
+
const hit = all.map(rel).filter(inScope).filter((p) => !out(p));
|
|
142
|
+
return { ok: true, kind: "protect", files: hit.length, sample: hit.slice(0, 12), says: hit.length ? `Protects ${hit.length} existing file${hit.length > 1 ? "s" : ""}. New files there are still allowed.` : "No files match these paths yet. Check the paths are right." };
|
|
143
|
+
}
|
|
144
|
+
if (r.kind === "deps") return { ok: true, kind: "deps", says: existsSync(join(root, "package.json")) || existsSync(join(root, "requirements.txt")) || existsSync(join(root, "pyproject.toml")) ? "Will ask before a new package is added." : "This project has no package file yet, so there's nothing to check until it does." };
|
|
145
|
+
return { ok: true, kind: "note", says: "A note can't be tried: nothing in the code shows whether it was followed. The agent sees it as a reminder." };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// YAML writing: append to the end of the rules: block, keep everything else exactly as it is.
|
|
149
|
+
const q = (v) => JSON.stringify(String(v));
|
|
150
|
+
function item(r) {
|
|
151
|
+
const lines = [];
|
|
152
|
+
const ex = r.except ? [` except: ${q(r.except)}`] : [];
|
|
153
|
+
if (r.kind === "avoid") lines.push(` - avoid: ${q(r.pattern)}`, ` say: ${q(r.text)}`, ...(r.in ? [` in: ${q(r.in)}`] : []), ...ex);
|
|
154
|
+
else if (r.kind === "protect") lines.push(` - protect: ${q(r.paths)}`, ` say: ${q(r.text)}`, ...ex);
|
|
155
|
+
else if (r.kind === "deps") lines.push(` - deps: ask`, ` say: ${q(r.text)}`);
|
|
156
|
+
else lines.push(` - note: ${q(r.text)}`, ...(r.when ? [` when: ${q(r.when)}`] : []));
|
|
157
|
+
return lines;
|
|
158
|
+
}
|
|
159
|
+
function write(list) {
|
|
160
|
+
const ok = list.filter((r) => ["avoid", "protect", "deps", "note"].includes(r.kind) && r.text && (r.kind !== "avoid" || r.pattern) && (r.kind !== "protect" || r.paths));
|
|
161
|
+
for (const r of ok) if (r.kind === "avoid") { const s = safePattern(r.pattern); if (s.error) { console.log(`Skipped "${r.text}": ${s.error}`); r.skip = true; } }
|
|
162
|
+
const add = ok.filter((r) => !r.skip);
|
|
163
|
+
if (!add.length) { console.log("Nothing to add."); return; }
|
|
164
|
+
const before = fileRules(root).length;
|
|
165
|
+
let src = existsSync(FILE) ? readFileSync(FILE, "utf8") : "# Project rules for AI agents. Lintsure Drift Guard holds every agent to these.\nrules:\n";
|
|
166
|
+
const lines = src.replace(/\r\n/g, "\n").split("\n");
|
|
167
|
+
let start = lines.findIndex((l) => /^rules:\s*$/.test(l));
|
|
168
|
+
if (start < 0) { if (lines.at(-1) === "") lines.pop(); lines.push("rules:"); start = lines.length - 1; }
|
|
169
|
+
let end = start + 1;
|
|
170
|
+
while (end < lines.length && !/^\S/.test(lines[end])) end++;
|
|
171
|
+
while (end - 1 > start && lines[end - 1].trim() === "") end--; // keep blank lines after the block
|
|
172
|
+
lines.splice(end, 0, ...add.flatMap(item));
|
|
173
|
+
mkdirSync(join(root, ".lintsure"), { recursive: true });
|
|
174
|
+
writeFileSync(FILE, lines.join("\n").replace(/\n*$/, "\n"));
|
|
175
|
+
const after = fileRules(root);
|
|
176
|
+
if (after.length !== before + add.length) { writeFileSync(FILE, src); console.log("Couldn't add the rules safely, so the file was left as it was."); process.exitCode = 1; return; }
|
|
177
|
+
console.log(`Added ${add.length} rule${add.length > 1 ? "s" : ""} to .lintsure/rules.yml:`);
|
|
178
|
+
for (const r of add) console.log(`- ${r.text}`);
|
|
179
|
+
// Files that already carry the rules stay in step; nothing new is created without "sync".
|
|
180
|
+
const keep = synced(root);
|
|
181
|
+
if (keep.length) { const r = sync(root, keep); console.log(`Updated the rules in: ${r.written.join(", ")}.`); }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const [cmd, rawArg] = process.argv.slice(2);
|
|
185
|
+
// JSON can come from a file (@rule.json): some shells eat the backslashes in a pattern passed inline.
|
|
186
|
+
const arg = rawArg?.startsWith("@") ? readFileSync(rawArg.slice(1), "utf8") : rawArg;
|
|
187
|
+
/** A pattern with control characters lost its backslashes on the way in (\b became a backspace). */
|
|
188
|
+
const mangled = (r) => r.kind === "avoid" && /[\x00-\x1f]/.test(r.pattern || "");
|
|
189
|
+
const MANGLED = "The pattern arrived with control characters, so the shell ate its backslashes (\\b turned into a backspace). Write the JSON to a file and pass it as @file.json.";
|
|
190
|
+
if (cmd === "suggest") {
|
|
191
|
+
const s = suggest();
|
|
192
|
+
if (!s.length) console.log("No suggestions: the rules file already covers what Lintsure can see in this project.");
|
|
193
|
+
else { s.forEach((x, i) => console.log(`${i + 1}. ${x.text}\n ${x.why}`)); console.log(`\nJSON: ${JSON.stringify(s)}`); }
|
|
194
|
+
} else if (cmd === "write") {
|
|
195
|
+
let list; try { list = JSON.parse(arg || "[]"); } catch { console.log("Pass the rules as one JSON array."); process.exit(1); }
|
|
196
|
+
list = Array.isArray(list) ? list : [list];
|
|
197
|
+
if (list.some(mangled)) { console.log(MANGLED); process.exit(1); }
|
|
198
|
+
write(list);
|
|
199
|
+
} else if (cmd === "try") {
|
|
200
|
+
let r; try { r = JSON.parse(arg || "{}"); } catch { console.log("Pass one rule as JSON: {kind, text, pattern?, in?, paths?, except?}"); process.exit(1); }
|
|
201
|
+
if (mangled(r)) { console.log(MANGLED); process.exit(1); }
|
|
202
|
+
const t = await tryRule(r);
|
|
203
|
+
console.log(t.says);
|
|
204
|
+
if (t.sample?.length) console.log(t.sample.map((s) => `- ${typeof s === "string" ? s : `${s.at} ${s.match}`}`).join("\n") + ((t.hits ?? t.files) > t.sample.length ? `\n- and ${(t.hits ?? t.files) - t.sample.length} more` : ""));
|
|
205
|
+
console.log(`\nJSON: ${JSON.stringify(t)}`);
|
|
206
|
+
} else if (cmd === "list") {
|
|
207
|
+
const r = fileRules(root);
|
|
208
|
+
console.log(r.length ? r.map((x) => `- ${x.text}${x.kind === "protect" ? ` (protects ${x.paths})` : ""}`).join("\n") : "No rules file yet.");
|
|
209
|
+
} else if (cmd === "sync") {
|
|
210
|
+
const r = sync(root, arg ? arg.split(",").map((x) => x.trim()) : null);
|
|
211
|
+
console.log(r.note ?? `Wrote the project rules to:\n${r.written.map((w) => `- ${w}`).join("\n")}\nYour own text in those files was left as it was.`);
|
|
212
|
+
} else if (cmd === "unsync") {
|
|
213
|
+
const d = unsync(root);
|
|
214
|
+
console.log(d.length ? `Took the Lintsure rules out of: ${d.join(", ")}.` : "No Lintsure rules found in other agents' files.");
|
|
215
|
+
} else console.log("Use: suggest | try '<json>' | write '<json>' | list | sync [targets] | unsync");
|