lintsure 0.3.16 → 0.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/index.js CHANGED
@@ -121,10 +121,14 @@ const START = [
121
121
  { label: "Check this folder", run: ["scan"] },
122
122
  // `show` is the command to learn; the menu itself asks for the folder with --pick.
123
123
  { label: "Check another folder", run: ["scan", "--pick"], show: "scan <folder>" },
124
- { label: "Is everything set up?", run: ["status"] },
124
+ { label: "Check what I'm committing", run: ["scan", "--staged"] },
125
+ { label: "Apply the sure fixes", run: ["fix"] },
126
+ { label: "Check before every commit", run: ["hook"] },
127
+ { label: "Look up my packages", run: ["deps"] },
125
128
  { label: "Connect your coding agent", run: ["setup"] },
126
129
  { label: "Give your agent skills", run: ["skills"] },
127
130
  { label: "Add the Lintsure plugin", run: ["plugin"] },
131
+ { label: "Is everything set up?", run: ["status"] },
128
132
  { label: "Every command and option", run: ["--help"] },
129
133
  { label: "Quit", run: null },
130
134
  ];
@@ -178,71 +182,71 @@ function nearest(word) {
178
182
  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
183
  }
180
184
  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}
185
+ const HELP = `lintsure scan [path] [options]
186
+ lintsure baseline [path]
187
+ lintsure init [path] Three questions, saved to lintsure.config.yaml
188
+ lintsure info [path] Show the settings a scan would use, and where each comes from
189
+ lintsure setup [path] Add the Lintsure MCP server to this project's agent configs
190
+ (with no path it asks: --everywhere for every project on this
191
+ machine, --here for this folder;
192
+ shows the change; --yes writes it; --undo takes it out;
193
+ --agents claude,cursor,vscode,gemini,codex;
194
+ --manual for an agent set up in its own settings)
195
+ lintsure skills [path] Add Lintsure's skills to this project: short instruction files that
196
+ tell your agent when to check code and how to handle findings
197
+ (at a terminal you pick which; --yes adds all; --only a,b;
198
+ --undo takes them out)
199
+ lintsure fix [path] [F-001 ...] Apply the change for findings whose rule knows the exact one
200
+ (shows it first; --all includes held-back findings; --yes writes it,
201
+ backs the file up, scans again,
202
+ and puts the file back if the finding is still there; --undo puts back
203
+ what the last fix changed)
204
+ lintsure deps [path] Look up the project's pinned packages for known vulnerabilities.
205
+ The only command that uses the network: it says what it will send
206
+ (package names and versions, never code) and sends it with --yes
207
+ lintsure history [path] List the records saved with scan --save-record, oldest first
208
+ lintsure hook [path] Check the lines you commit: adds a git pre-commit hook that runs
209
+ lintsure scan --staged --fail-on gap (shows it first; --yes writes it;
210
+ --undo removes it; an existing hook of your own is left alone)
211
+ lintsure plugin [path] Install the guards that run while your agent works: the full plugin
212
+ for Claude Code, and hooks files for Cursor, Codex and Gemini CLI
213
+ (shows the plan first; --agents claude,cursor,codex,gemini;
214
+ --yes installs; --undo takes them out)
215
+ lintsure status [path] Check that this project is ready: Node, config, rules, agents
216
+ lintsure export --otlp-json [path] Write .lintsure/activity.jsonl as an OpenTelemetry
217
+ traces file (lintsure.otlp.json) for your own observability tool
218
+
219
+ scan options:
220
+ --framework <ids> Comma list: ${ALL_FRAMEWORKS.join(", ")}
221
+ (default: lintsure.config.yaml if present, else all)
222
+ --all Also list medium-confidence findings (held back by default)
223
+ --diff <base> Only list findings on lines changed since <base>, e.g. origin/main
224
+ --staged Only list findings on lines that are staged for the next commit
225
+ --json Also write lintsure-report.json
226
+ --sarif Also write lintsure.sarif (for GitHub code scanning and editors)
227
+ --report Also write lintsure-assessment.html, a multi-page report
228
+ to review, print or save as PDF
229
+ --project <name> Project name on the assessment cover (default: folder name)
230
+ --fail-on <status> Exit 1 if any open finding is "gap" or "partial" (for CI). Held-back
231
+ medium-confidence findings count only with --all
232
+ --observe With --fail-on: say when the run would have failed, and pass anyway.
233
+ For watching the gate before it blocks anyone
234
+ --new-only With --fail-on: count only findings that are new since
235
+ .lintsure/baseline.json
236
+ --github Print GitHub Actions annotations, so findings show on the lines
237
+ --pick Ask which folder to check (at a terminal)
238
+ --save-record Also save this run's readiness check record to
239
+ .lintsure/records/<id>.json, building a dated history (no code inside)
240
+
241
+ baseline:
242
+ Saves the current open findings to .lintsure/baseline.json in the scanned folder.
243
+ Later scans show what is new, fixed or unchanged. The file holds rule ids, file
244
+ paths and one-way fingerprints, never code. You decide whether to commit it.
245
+
246
+ Accept a finding after review by adding it to .lintsure/accepted.yaml, with the
247
+ fingerprint from lintsure-report.json, your reason, your name and the date.
248
+
249
+ ${DISCLAIMER}
246
250
  Lintsure never sends your code anywhere. Only "lintsure deps --yes" uses the network.`;
247
251
  const VALUE_FLAGS = ["--framework", "--fail-on", "--project", "--diff"];
248
252
  const BOOL_FLAGS = ["--json", "--sarif", "--report", "--new-only", "--github", "--save-record", "--all", "--pick", "--staged", "--observe"];
@@ -529,6 +533,12 @@ async function main(argv) {
529
533
  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
534
  if (!raw.includes("--yes")) {
531
535
  console.log("\nNothing sent yet. To run it: lintsure deps --yes");
536
+ if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
537
+ console.log("");
538
+ 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");
539
+ if (ran !== undefined)
540
+ return ran;
541
+ }
532
542
  return 0;
533
543
  }
534
544
  let hits;
@@ -594,12 +604,18 @@ async function main(argv) {
594
604
  console.log(`- pre-commit hook: ${now === null ? "create" : "update"} .git/hooks/pre-commit\n lintsure scan --staged --fail-on gap`);
595
605
  if (!raw.includes("--yes")) {
596
606
  console.log("\nNothing written yet. To apply, run: lintsure hook --yes");
607
+ if (viaMenu && process.stdin.isTTY && process.stdout.isTTY) {
608
+ console.log("");
609
+ 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");
610
+ if (ran !== undefined)
611
+ return ran;
612
+ }
597
613
  return 0;
598
614
  }
599
615
  await mkdir(join(root, ".git", "hooks"), { recursive: true });
600
616
  // 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
617
  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");
618
+ 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
619
  return 0;
604
620
  }
605
621
  // lintsure plugin: the guards, for the agents this project uses. Shown first; nothing is downloaded or written before a yes.
@@ -807,7 +823,7 @@ async function main(argv) {
807
823
  // Typed by hand with no agent named and none found here: say which one this is for, and how to pick another.
808
824
  const me = callingAgent();
809
825
  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" : ""}.
826
+ console.log(`This is running inside ${me.name}, so ${me.name} is connected${here.length ? " too" : ""}.
811
827
  `);
812
828
  else if (!named && !here.length && !raw.includes("--undo"))
813
829
  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`);
@@ -1,4 +1,4 @@
1
- export declare const PLUGIN_TAG = "v0.3.5";
1
+ export declare const PLUGIN_TAG = "v0.3.7";
2
2
  export interface GuardAgent {
3
3
  id: string;
4
4
  name: string;
@@ -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.5";
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" },
package/package.json CHANGED
@@ -1,54 +1,54 @@
1
- {
2
- "name": "lintsure",
3
- "version": "0.3.16",
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.16"
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.17",
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.17"
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: 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.
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: 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.
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
- const gen = has(/(^|\/)(generated|__generated__)\/|\.gen\.[jt]s$/);
75
- 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.` });
76
- const env = has(/(^|\/)\.env(\.example|\.sample)?$/);
77
- 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." });
78
-
79
- // Drop what the rules file already has.
80
- 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);
81
- return s.filter((x) => !have.some((h) => same(h, x))).slice(0, 10);
82
- }
83
-
84
- /** Dry run: what a rule would match in this repo today, before it is written. Matched text is shown cut short, so a key
85
- * the code already holds isn't copied in full into the conversation. Pure apart from reading files. */
86
- // The scan runs in a worker that is stopped after 3 seconds, so even a pattern that is slow on a single line ends.
87
- const SCAN = `
88
- const { parentPort, workerData: w } = require("node:worker_threads");
89
- const re = new RegExp(w.pattern, "i");
90
- for (const f of w.files) {
91
- 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] }); });
92
- parentPort.postMessage({ file: true });
93
- }
94
- parentPort.postMessage({ done: true });`;
95
- function scanInWorker(pattern, list, ms = 3000) {
96
- return new Promise((resolve) => {
97
- const hits = []; let scanned = 0, w, timer;
98
- const end = (partial) => { clearTimeout(timer); w?.terminate().catch(() => {}); resolve({ hits, scanned, partial }); };
99
- try { w = new Worker(SCAN, { eval: true, workerData: { pattern, files: list, max: MAX_LINE } }); } catch { return resolve({ hits, scanned, partial: true }); }
100
- timer = setTimeout(() => end(true), ms);
101
- w.on("message", (m) => { if (m.done) end(false); else if (m.file) scanned++; else hits.push(m); });
102
- w.on("error", () => end(true));
103
- });
104
- }
105
- async function tryRule(r) {
106
- 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);
107
- if (r.kind === "avoid") {
108
- const safe = safePattern(r.pattern, "i");
109
- if (safe.error) return { ok: false, says: safe.error };
110
- const list = []; let tooBig = 0;
111
- for (const f of all) {
112
- const p = rel(f);
113
- 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;
114
- try { if (statSync(f).size > 300_000) { tooBig++; continue; } list.push({ p, text: readFileSync(f, "utf8") }); } catch { tooBig++; }
115
- }
116
- const { hits, scanned, partial } = await scanInWorker(r.pattern, list);
117
- const notRead = tooBig ? ` ${tooBig} file${tooBig > 1 ? "s were" : " was"} not read (over 300 KB or unreadable), so no match there means not checked.` : "";
118
- 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.` : "";
119
- return { ok: true, kind: "avoid", scanned, notRead: tooBig, partial, hits: hits.length, sample: hits.slice(0, 12),
120
- 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 };
121
- }
122
- if (r.kind === "protect") {
123
- const hit = all.map(rel).filter(inScope).filter((p) => !out(p));
124
- 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." };
125
- }
126
- 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." };
127
- 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." };
128
- }
129
-
130
- // YAML writing: append to the end of the rules: block, keep everything else exactly as it is.
131
- const q = (v) => JSON.stringify(String(v));
132
- function item(r) {
133
- const lines = [];
134
- const ex = r.except ? [` except: ${q(r.except)}`] : [];
135
- if (r.kind === "avoid") lines.push(` - avoid: ${q(r.pattern)}`, ` say: ${q(r.text)}`, ...(r.in ? [` in: ${q(r.in)}`] : []), ...ex);
136
- else if (r.kind === "protect") lines.push(` - protect: ${q(r.paths)}`, ` say: ${q(r.text)}`, ...ex);
137
- else if (r.kind === "deps") lines.push(` - deps: ask`, ` say: ${q(r.text)}`);
138
- else lines.push(` - note: ${q(r.text)}`, ...(r.when ? [` when: ${q(r.when)}`] : []));
139
- return lines;
140
- }
141
- function write(list) {
142
- const ok = list.filter((r) => ["avoid", "protect", "deps", "note"].includes(r.kind) && r.text && (r.kind !== "avoid" || r.pattern) && (r.kind !== "protect" || r.paths));
143
- 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; } }
144
- const add = ok.filter((r) => !r.skip);
145
- if (!add.length) { console.log("Nothing to add."); return; }
146
- const before = fileRules(root).length;
147
- let src = existsSync(FILE) ? readFileSync(FILE, "utf8") : "# Project rules for AI agents. Lintsure Drift Guard holds every agent to these.\nrules:\n";
148
- const lines = src.replace(/\r\n/g, "\n").split("\n");
149
- let start = lines.findIndex((l) => /^rules:\s*$/.test(l));
150
- if (start < 0) { if (lines.at(-1) === "") lines.pop(); lines.push("rules:"); start = lines.length - 1; }
151
- let end = start + 1;
152
- while (end < lines.length && !/^\S/.test(lines[end])) end++;
153
- while (end - 1 > start && lines[end - 1].trim() === "") end--; // keep blank lines after the block
154
- lines.splice(end, 0, ...add.flatMap(item));
155
- mkdirSync(join(root, ".lintsure"), { recursive: true });
156
- writeFileSync(FILE, lines.join("\n").replace(/\n*$/, "\n"));
157
- const after = fileRules(root);
158
- 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; }
159
- console.log(`Added ${add.length} rule${add.length > 1 ? "s" : ""} to .lintsure/rules.yml:`);
160
- for (const r of add) console.log(`- ${r.text}`);
161
- // Files that already carry the rules stay in step; nothing new is created without "sync".
162
- const keep = synced(root);
163
- if (keep.length) { const r = sync(root, keep); console.log(`Updated the rules in: ${r.written.join(", ")}.`); }
164
- }
165
-
166
- const [cmd, rawArg] = process.argv.slice(2);
167
- // JSON can come from a file (@rule.json): some shells eat the backslashes in a pattern passed inline.
168
- const arg = rawArg?.startsWith("@") ? readFileSync(rawArg.slice(1), "utf8") : rawArg;
169
- /** A pattern with control characters lost its backslashes on the way in (\b became a backspace). */
170
- const mangled = (r) => r.kind === "avoid" && /[\x00-\x1f]/.test(r.pattern || "");
171
- 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.";
172
- if (cmd === "suggest") {
173
- const s = suggest();
174
- if (!s.length) console.log("No suggestions: the rules file already covers what Lintsure can see in this project.");
175
- else { s.forEach((x, i) => console.log(`${i + 1}. ${x.text}\n ${x.why}`)); console.log(`\nJSON: ${JSON.stringify(s)}`); }
176
- } else if (cmd === "write") {
177
- let list; try { list = JSON.parse(arg || "[]"); } catch { console.log("Pass the rules as one JSON array."); process.exit(1); }
178
- list = Array.isArray(list) ? list : [list];
179
- if (list.some(mangled)) { console.log(MANGLED); process.exit(1); }
180
- write(list);
181
- } else if (cmd === "try") {
182
- let r; try { r = JSON.parse(arg || "{}"); } catch { console.log("Pass one rule as JSON: {kind, text, pattern?, in?, paths?, except?}"); process.exit(1); }
183
- if (mangled(r)) { console.log(MANGLED); process.exit(1); }
184
- const t = await tryRule(r);
185
- console.log(t.says);
186
- 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` : ""));
187
- console.log(`\nJSON: ${JSON.stringify(t)}`);
188
- } else if (cmd === "list") {
189
- const r = fileRules(root);
190
- console.log(r.length ? r.map((x) => `- ${x.text}${x.kind === "protect" ? ` (protects ${x.paths})` : ""}`).join("\n") : "No rules file yet.");
191
- } else if (cmd === "sync") {
192
- const r = sync(root, arg ? arg.split(",").map((x) => x.trim()) : null);
193
- 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.`);
194
- } else if (cmd === "unsync") {
195
- const d = unsync(root);
196
- console.log(d.length ? `Took the Lintsure rules out of: ${d.join(", ")}.` : "No Lintsure rules found in other agents' files.");
197
- } else console.log("Use: suggest | try '<json>' | write '<json>' | list | sync [targets] | unsync");
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");