lintsure 0.3.19 → 0.3.21
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 +2 -0
- package/dist/src/agents.d.ts +3 -0
- package/dist/src/agents.js +27 -1
- package/dist/src/index.js +94 -17
- package/dist/src/menu.d.ts +3 -0
- package/dist/src/menu.js +3 -0
- package/dist/src/plugin.d.ts +1 -1
- package/dist/src/plugin.js +1 -1
- package/dist/src/send.js +1 -1
- package/dist/src/skills.d.ts +4 -0
- package/dist/src/skills.js +24 -0
- package/package.json +69 -54
- package/skills/lintsure-rules/SKILL.md +57 -55
- package/skills/lintsure-rules/agents.mjs +64 -19
- package/skills/lintsure-rules/lib.mjs +2 -1
- package/skills/lintsure-rules/rules.mjs +217 -215
|
@@ -1,215 +1,217 @@
|
|
|
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, grok, copilot,
|
|
10
|
-
// claude; comma separated). Default: AGENTS.md and Grok Build, 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
|
-
|
|
78
|
-
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
text
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
parentPort.postMessage({
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
w.on("
|
|
121
|
-
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
return { ok: true, kind: "
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
else if (r.kind === "
|
|
156
|
-
else lines.push(` -
|
|
157
|
-
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const
|
|
163
|
-
if (
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
let
|
|
168
|
-
|
|
169
|
-
let
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
console.log(
|
|
204
|
-
|
|
205
|
-
console.log(
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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, grok, copilot,
|
|
10
|
+
// claude; comma separated). Default: AGENTS.md and Grok Build, 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
|
+
const skillRecord = existsSync(join(root, ".lintsure/skills.json")); // the reviewed fingerprints of the skill files
|
|
78
|
+
if (setters.length || claudeDir || skillRecord) s.push({ id: "protect-rule-files", kind: "protect", paths: [...setters.flatMap((n) => [n, `**/${n}`]), ...(claudeDir ? [".claude/**"] : []), ...(skillRecord ? [".lintsure/skills.json"] : [])].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/"] : []), ...(skillRecord ? [".lintsure/skills.json"] : [])].join(", ")}. A change there changes what every later check looks for.` });
|
|
79
|
+
// Rules the project already wrote down for one agent, offered so that every agent follows them. Only plain
|
|
80
|
+
// do and don't lines from the top-level files; a line that steers an agent against its user is never passed on.
|
|
81
|
+
const said = [];
|
|
82
|
+
for (const f of ["CLAUDE.md", "AGENTS.md", "REVIEW.md"]) {
|
|
83
|
+
let text; try { text = readFileSync(join(root, f), "utf8"); } catch { continue; }
|
|
84
|
+
text.split(/\r?\n/).forEach((line, i) => {
|
|
85
|
+
const t = line.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "").replace(/[*_`]/g, "").replace(/\s+/g, " ").trim();
|
|
86
|
+
if (said.length >= 5 || t.length < 12 || t.length > 160) return;
|
|
87
|
+
if (!/^(never|always|don'?t|do not|must|only|avoid|use)\b/i.test(t)) return;
|
|
88
|
+
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;
|
|
89
|
+
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}.` });
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
s.push(...said);
|
|
93
|
+
const gen = has(/(^|\/)(generated|__generated__)\/|\.gen\.[jt]s$/);
|
|
94
|
+
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.` });
|
|
95
|
+
const env = has(/(^|\/)\.env(\.example|\.sample)?$/);
|
|
96
|
+
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." });
|
|
97
|
+
|
|
98
|
+
// Drop what the rules file already has.
|
|
99
|
+
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);
|
|
100
|
+
return s.filter((x) => !have.some((h) => same(h, x))).slice(0, 10);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Dry run: what a rule would match in this repo today, before it is written. Matched text is shown cut short, so a key
|
|
104
|
+
* the code already holds isn't copied in full into the conversation. Pure apart from reading files. */
|
|
105
|
+
// The scan runs in a worker that is stopped after 3 seconds, so even a pattern that is slow on a single line ends.
|
|
106
|
+
const SCAN = `
|
|
107
|
+
const { parentPort, workerData: w } = require("node:worker_threads");
|
|
108
|
+
const re = new RegExp(w.pattern, "i");
|
|
109
|
+
for (const f of w.files) {
|
|
110
|
+
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] }); });
|
|
111
|
+
parentPort.postMessage({ file: true });
|
|
112
|
+
}
|
|
113
|
+
parentPort.postMessage({ done: true });`;
|
|
114
|
+
function scanInWorker(pattern, list, ms = 3000) {
|
|
115
|
+
return new Promise((resolve) => {
|
|
116
|
+
const hits = []; let scanned = 0, w, timer;
|
|
117
|
+
const end = (partial) => { clearTimeout(timer); w?.terminate().catch(() => {}); resolve({ hits, scanned, partial }); };
|
|
118
|
+
try { w = new Worker(SCAN, { eval: true, workerData: { pattern, files: list, max: MAX_LINE } }); } catch { return resolve({ hits, scanned, partial: true }); }
|
|
119
|
+
timer = setTimeout(() => end(true), ms);
|
|
120
|
+
w.on("message", (m) => { if (m.done) end(false); else if (m.file) scanned++; else hits.push(m); });
|
|
121
|
+
w.on("error", () => end(true));
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
async function tryRule(r) {
|
|
125
|
+
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);
|
|
126
|
+
if (r.kind === "avoid") {
|
|
127
|
+
const safe = safePattern(r.pattern, "i");
|
|
128
|
+
if (safe.error) return { ok: false, says: safe.error };
|
|
129
|
+
const list = []; let tooBig = 0;
|
|
130
|
+
for (const f of all) {
|
|
131
|
+
const p = rel(f);
|
|
132
|
+
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;
|
|
133
|
+
try { if (statSync(f).size > 300_000) { tooBig++; continue; } list.push({ p, text: readFileSync(f, "utf8") }); } catch { tooBig++; }
|
|
134
|
+
}
|
|
135
|
+
const { hits, scanned, partial } = await scanInWorker(r.pattern, list);
|
|
136
|
+
const notRead = tooBig ? ` ${tooBig} file${tooBig > 1 ? "s were" : " was"} not read (over 300 KB or unreadable), so no match there means not checked.` : "";
|
|
137
|
+
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.` : "";
|
|
138
|
+
return { ok: true, kind: "avoid", scanned, notRead: tooBig, partial, hits: hits.length, sample: hits.slice(0, 12),
|
|
139
|
+
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 };
|
|
140
|
+
}
|
|
141
|
+
if (r.kind === "protect") {
|
|
142
|
+
const hit = all.map(rel).filter(inScope).filter((p) => !out(p));
|
|
143
|
+
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." };
|
|
144
|
+
}
|
|
145
|
+
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." };
|
|
146
|
+
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." };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// YAML writing: append to the end of the rules: block, keep everything else exactly as it is.
|
|
150
|
+
const q = (v) => JSON.stringify(String(v));
|
|
151
|
+
function item(r) {
|
|
152
|
+
const lines = [];
|
|
153
|
+
const ex = r.except ? [` except: ${q(r.except)}`] : [];
|
|
154
|
+
if (r.kind === "avoid") lines.push(` - avoid: ${q(r.pattern)}`, ` say: ${q(r.text)}`, ...(r.in ? [` in: ${q(r.in)}`] : []), ...ex);
|
|
155
|
+
else if (r.kind === "protect") lines.push(` - protect: ${q(r.paths)}`, ` say: ${q(r.text)}`, ...ex);
|
|
156
|
+
else if (r.kind === "deps") lines.push(` - deps: ask`, ` say: ${q(r.text)}`);
|
|
157
|
+
else lines.push(` - note: ${q(r.text)}`, ...(r.when ? [` when: ${q(r.when)}`] : []));
|
|
158
|
+
if (r.agents) lines.push(` agents: ${q([].concat(r.agents).join(", "))}`);
|
|
159
|
+
return lines;
|
|
160
|
+
}
|
|
161
|
+
function write(list) {
|
|
162
|
+
const ok = list.filter((r) => ["avoid", "protect", "deps", "note"].includes(r.kind) && r.text && (r.kind !== "avoid" || r.pattern) && (r.kind !== "protect" || r.paths));
|
|
163
|
+
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; } }
|
|
164
|
+
const add = ok.filter((r) => !r.skip);
|
|
165
|
+
if (!add.length) { console.log("Nothing to add."); return; }
|
|
166
|
+
const before = fileRules(root).length;
|
|
167
|
+
let src = existsSync(FILE) ? readFileSync(FILE, "utf8") : "# Project rules for AI agents. Lintsure Drift Guard holds every agent to these.\nrules:\n";
|
|
168
|
+
const lines = src.replace(/\r\n/g, "\n").split("\n");
|
|
169
|
+
let start = lines.findIndex((l) => /^rules:\s*$/.test(l));
|
|
170
|
+
if (start < 0) { if (lines.at(-1) === "") lines.pop(); lines.push("rules:"); start = lines.length - 1; }
|
|
171
|
+
let end = start + 1;
|
|
172
|
+
while (end < lines.length && !/^\S/.test(lines[end])) end++;
|
|
173
|
+
while (end - 1 > start && lines[end - 1].trim() === "") end--; // keep blank lines after the block
|
|
174
|
+
lines.splice(end, 0, ...add.flatMap(item));
|
|
175
|
+
mkdirSync(join(root, ".lintsure"), { recursive: true });
|
|
176
|
+
writeFileSync(FILE, lines.join("\n").replace(/\n*$/, "\n"));
|
|
177
|
+
const after = fileRules(root);
|
|
178
|
+
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; }
|
|
179
|
+
console.log(`Added ${add.length} rule${add.length > 1 ? "s" : ""} to .lintsure/rules.yml:`);
|
|
180
|
+
for (const r of add) console.log(`- ${r.text}`);
|
|
181
|
+
// Files that already carry the rules stay in step; nothing new is created without "sync".
|
|
182
|
+
const keep = synced(root);
|
|
183
|
+
if (keep.length) { const r = sync(root, keep); console.log(`Updated the rules in: ${r.written.join(", ")}.`); }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const [cmd, rawArg] = process.argv.slice(2);
|
|
187
|
+
// JSON can come from a file (@rule.json): some shells eat the backslashes in a pattern passed inline.
|
|
188
|
+
const arg = rawArg?.startsWith("@") ? readFileSync(rawArg.slice(1), "utf8") : rawArg;
|
|
189
|
+
/** A pattern with control characters lost its backslashes on the way in (\b became a backspace). */
|
|
190
|
+
const mangled = (r) => r.kind === "avoid" && /[\x00-\x1f]/.test(r.pattern || "");
|
|
191
|
+
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.";
|
|
192
|
+
if (cmd === "suggest") {
|
|
193
|
+
const s = suggest();
|
|
194
|
+
if (!s.length) console.log("No suggestions: the rules file already covers what Lintsure can see in this project.");
|
|
195
|
+
else { s.forEach((x, i) => console.log(`${i + 1}. ${x.text}\n ${x.why}`)); console.log(`\nJSON: ${JSON.stringify(s)}`); }
|
|
196
|
+
} else if (cmd === "write") {
|
|
197
|
+
let list; try { list = JSON.parse(arg || "[]"); } catch { console.log("Pass the rules as one JSON array."); process.exit(1); }
|
|
198
|
+
list = Array.isArray(list) ? list : [list];
|
|
199
|
+
if (list.some(mangled)) { console.log(MANGLED); process.exit(1); }
|
|
200
|
+
write(list);
|
|
201
|
+
} else if (cmd === "try") {
|
|
202
|
+
let r; try { r = JSON.parse(arg || "{}"); } catch { console.log("Pass one rule as JSON: {kind, text, pattern?, in?, paths?, except?}"); process.exit(1); }
|
|
203
|
+
if (mangled(r)) { console.log(MANGLED); process.exit(1); }
|
|
204
|
+
const t = await tryRule(r);
|
|
205
|
+
console.log(t.says);
|
|
206
|
+
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` : ""));
|
|
207
|
+
console.log(`\nJSON: ${JSON.stringify(t)}`);
|
|
208
|
+
} else if (cmd === "list") {
|
|
209
|
+
const r = fileRules(root);
|
|
210
|
+
console.log(r.length ? r.map((x) => `- ${x.text}${x.kind === "protect" ? ` (protects ${x.paths})` : ""}${x.agents ? ` (only for ${x.agents.join(", ")})` : ""}`).join("\n") : "No rules file yet.");
|
|
211
|
+
} else if (cmd === "sync") {
|
|
212
|
+
const r = sync(root, arg ? arg.split(",").map((x) => x.trim()) : null);
|
|
213
|
+
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.`);
|
|
214
|
+
} else if (cmd === "unsync") {
|
|
215
|
+
const d = unsync(root);
|
|
216
|
+
console.log(d.length ? `Took the Lintsure rules out of: ${d.join(", ")}.` : "No Lintsure rules found in other agents' files.");
|
|
217
|
+
} else console.log("Use: suggest | try '<json>' | write '<json>' | list | sync [targets] | unsync");
|