lintsure 0.3.15 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,75 +1,75 @@
1
- // One rules file for every agent: writes the rules from .lintsure/rules.yml into the instruction files other agents
2
- // read (AGENTS.md for Codex and many others, Cursor's rules folder, GitHub Copilot, CLAUDE.md). Lintsure owns only its
3
- // own marked block in shared files, so the user's text around it is never touched.
4
- import { readFileSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from "node:fs";
5
- import { join, dirname } from "node:path";
6
- import { fileRules } from "./lib.mjs";
7
-
8
- const START = "<!-- lintsure:rules:start -->", END = "<!-- lintsure:rules:end -->";
9
- export const TARGETS = {
10
- agents: { file: "AGENTS.md", shared: true, label: "AGENTS.md (Codex, Jules, Amp, Zed and other agents)" },
11
- cursor: { file: ".cursor/rules/lintsure.mdc", shared: false, label: "Cursor (.cursor/rules/lintsure.mdc)" },
12
- copilot: { file: ".github/copilot-instructions.md", shared: true, label: "GitHub Copilot (.github/copilot-instructions.md)" },
13
- claude: { file: "CLAUDE.md", shared: true, label: "CLAUDE.md (Claude Code without the plugin)" },
14
- };
15
-
16
- /** The rules as plain instructions. Says honestly where they're checked. */
17
- export function block(root) {
18
- const rules = fileRules(root);
19
- if (!rules.length) return null;
20
- const line = (r) => r.kind === "protect" ? `- ${r.text} (Files: ${r.paths})` : r.kind === "avoid" && r.paths ? `- ${r.text} (In: ${r.paths})` : `- ${r.text}`;
21
- return [
22
- "## Project rules (from Lintsure)",
23
- "",
24
- "Keep to these in every change. They come from `.lintsure/rules.yml`; change them there, not here.",
25
- "",
26
- ...rules.map(line),
27
- "",
28
- "If the user asks for something that goes against one of these, do it and say which rule it changes in one line. Lintsure checks these rules automatically in Claude Code with the Lintsure plugin.",
29
- ].join("\n");
30
- }
31
-
32
- function put(path, text, shared) {
33
- mkdirSync(dirname(path), { recursive: true });
34
- if (!shared) {
35
- writeFileSync(path, `---\ndescription: Project rules from Lintsure (.lintsure/rules.yml)\nalwaysApply: true\n---\n\n${text}\n`);
36
- return;
37
- }
38
- const marked = `${START}\n${text}\n${END}`;
39
- const cur = existsSync(path) ? readFileSync(path, "utf8") : "";
40
- const i = cur.indexOf(START), j = cur.indexOf(END);
41
- const next = i >= 0 && j > i ? cur.slice(0, i) + marked + cur.slice(j + END.length) : cur ? `${cur.replace(/\s*$/, "")}\n\n${marked}\n` : `${marked}\n`;
42
- if (next !== cur) writeFileSync(path, next);
43
- }
44
-
45
- /** Which targets already carry Lintsure's rules, so a rules change keeps exactly those in step. */
46
- export function synced(root) {
47
- return Object.entries(TARGETS).filter(([, t]) => {
48
- const p = join(root, t.file);
49
- if (!existsSync(p)) return false;
50
- return !t.shared || readFileSync(p, "utf8").includes(START);
51
- }).map(([k]) => k);
52
- }
53
-
54
- /** Writes the rules to the chosen targets. Default: AGENTS.md and Cursor, plus Copilot and CLAUDE.md when those files exist. */
55
- export function sync(root, want) {
56
- const text = block(root);
57
- if (!text) return { written: [], note: "No rules in .lintsure/rules.yml yet." };
58
- const keys = want?.length ? want.filter((k) => TARGETS[k]) : ["agents", "cursor", ...["copilot", "claude"].filter((k) => existsSync(join(root, TARGETS[k].file)))];
59
- for (const k of keys) put(join(root, TARGETS[k].file), text, TARGETS[k].shared);
60
- return { written: keys.map((k) => TARGETS[k].label) };
61
- }
62
-
63
- /** Takes Lintsure's block out again (the user's own text stays). */
64
- export function unsync(root) {
65
- const done = [];
66
- for (const [k, t] of Object.entries(TARGETS)) {
67
- const p = join(root, t.file);
68
- if (!existsSync(p)) continue;
69
- const cur = readFileSync(p, "utf8");
70
- if (!t.shared) { if (cur.includes("Project rules from Lintsure")) { unlinkSync(p); done.push(t.label); } continue; }
71
- const i = cur.indexOf(START), j = cur.indexOf(END);
72
- if (i >= 0 && j > i) { writeFileSync(p, (cur.slice(0, i) + cur.slice(j + END.length)).replace(/\n{3,}/g, "\n\n")); done.push(t.label); }
73
- }
74
- return done;
75
- }
1
+ // One rules file for every agent: writes the rules from .lintsure/rules.yml into the instruction files other agents
2
+ // read (AGENTS.md for Codex and many others, Cursor's rules folder, GitHub Copilot, CLAUDE.md). Lintsure owns only its
3
+ // own marked block in shared files, so the user's text around it is never touched.
4
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from "node:fs";
5
+ import { join, dirname } from "node:path";
6
+ import { fileRules } from "./lib.mjs";
7
+
8
+ const START = "<!-- lintsure:rules:start -->", END = "<!-- lintsure:rules:end -->";
9
+ export const TARGETS = {
10
+ agents: { file: "AGENTS.md", shared: true, label: "AGENTS.md (Codex, Jules, Amp, Zed and other agents)" },
11
+ cursor: { file: ".cursor/rules/lintsure.mdc", shared: false, label: "Cursor (.cursor/rules/lintsure.mdc)" },
12
+ copilot: { file: ".github/copilot-instructions.md", shared: true, label: "GitHub Copilot (.github/copilot-instructions.md)" },
13
+ claude: { file: "CLAUDE.md", shared: true, label: "CLAUDE.md (Claude Code without the plugin)" },
14
+ };
15
+
16
+ /** The rules as plain instructions. Says honestly where they're checked. */
17
+ export function block(root) {
18
+ const rules = fileRules(root);
19
+ if (!rules.length) return null;
20
+ const line = (r) => r.kind === "protect" ? `- ${r.text} (Files: ${r.paths})` : r.kind === "avoid" && r.paths ? `- ${r.text} (In: ${r.paths})` : `- ${r.text}`;
21
+ return [
22
+ "## Project rules (from Lintsure)",
23
+ "",
24
+ "Keep to these in every change. They come from `.lintsure/rules.yml`; change them there, not here.",
25
+ "",
26
+ ...rules.map(line),
27
+ "",
28
+ "If the user asks for something that goes against one of these, do it and say which rule it changes in one line. Lintsure checks these rules automatically in Claude Code with the Lintsure plugin.",
29
+ ].join("\n");
30
+ }
31
+
32
+ function put(path, text, shared) {
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ if (!shared) {
35
+ writeFileSync(path, `---\ndescription: Project rules from Lintsure (.lintsure/rules.yml)\nalwaysApply: true\n---\n\n${text}\n`);
36
+ return;
37
+ }
38
+ const marked = `${START}\n${text}\n${END}`;
39
+ const cur = existsSync(path) ? readFileSync(path, "utf8") : "";
40
+ const i = cur.indexOf(START), j = cur.indexOf(END);
41
+ const next = i >= 0 && j > i ? cur.slice(0, i) + marked + cur.slice(j + END.length) : cur ? `${cur.replace(/\s*$/, "")}\n\n${marked}\n` : `${marked}\n`;
42
+ if (next !== cur) writeFileSync(path, next);
43
+ }
44
+
45
+ /** Which targets already carry Lintsure's rules, so a rules change keeps exactly those in step. */
46
+ export function synced(root) {
47
+ return Object.entries(TARGETS).filter(([, t]) => {
48
+ const p = join(root, t.file);
49
+ if (!existsSync(p)) return false;
50
+ return !t.shared || readFileSync(p, "utf8").includes(START);
51
+ }).map(([k]) => k);
52
+ }
53
+
54
+ /** Writes the rules to the chosen targets. Default: AGENTS.md and Cursor, plus Copilot and CLAUDE.md when those files exist. */
55
+ export function sync(root, want) {
56
+ const text = block(root);
57
+ if (!text) return { written: [], note: "No rules in .lintsure/rules.yml yet." };
58
+ const keys = want?.length ? want.filter((k) => TARGETS[k]) : ["agents", "cursor", ...["copilot", "claude"].filter((k) => existsSync(join(root, TARGETS[k].file)))];
59
+ for (const k of keys) put(join(root, TARGETS[k].file), text, TARGETS[k].shared);
60
+ return { written: keys.map((k) => TARGETS[k].label) };
61
+ }
62
+
63
+ /** Takes Lintsure's block out again (the user's own text stays). */
64
+ export function unsync(root) {
65
+ const done = [];
66
+ for (const [k, t] of Object.entries(TARGETS)) {
67
+ const p = join(root, t.file);
68
+ if (!existsSync(p)) continue;
69
+ const cur = readFileSync(p, "utf8");
70
+ if (!t.shared) { if (cur.includes("Project rules from Lintsure")) { unlinkSync(p); done.push(t.label); } continue; }
71
+ const i = cur.indexOf(START), j = cur.indexOf(END);
72
+ if (i >= 0 && j > i) { writeFileSync(p, (cur.slice(0, i) + cur.slice(j + END.length)).replace(/\n{3,}/g, "\n\n")); done.push(t.label); }
73
+ }
74
+ return done;
75
+ }
@@ -1,60 +1,60 @@
1
- // What the rules helper needs to read and check .lintsure/rules.yml. Local files only: nothing here uses the network.
2
- import { readFileSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- /** Rules from .lintsure/rules.yml in the repo. A small YAML subset: a "rules:" list of items with one kind key
6
- * (avoid, protect, deps, note) plus optional "say" and "in". Anything it can't read is skipped, never fatal. */
7
- export function fileRules(root) {
8
- let src; try { src = readFileSync(join(root, ".lintsure", "rules.yml"), "utf8"); } catch { return []; }
9
- const val = (v) => { v = v.trim(); if (/^".*"$/.test(v)) { try { return JSON.parse(v); } catch { return v.slice(1, -1); } } if (/^'.*'$/.test(v)) return v.slice(1, -1).replace(/''/g, "'"); return v.replace(/\s+#.*$/, ""); };
10
- const items = []; let inRules = false, cur = null;
11
- for (const raw of src.split(/\r?\n/)) {
12
- if (/^\s*(#|$)/.test(raw)) continue;
13
- const top = raw.match(/^mode:\s*(quiet|guide|strict)\b/i);
14
- if (top) { items.mode = top[1].toLowerCase(); continue; }
15
- if (/^\S/.test(raw)) { inRules = /^rules:\s*$/.test(raw); cur = null; continue; }
16
- if (!inRules) continue;
17
- const m = raw.match(/^\s*(-\s+)?([a-z]+):\s*(.*)$/i);
18
- if (!m) continue;
19
- if (m[1]) { cur = {}; items.push(cur); }
20
- if (cur) cur[m[2].toLowerCase()] = val(m[3]);
21
- }
22
- const out = items.map((it, i) => {
23
- const kind = ["avoid", "protect", "deps", "note"].find((k) => k in it);
24
- if (!kind) return null;
25
- const v = it[kind], say = it.say || (kind === "note" ? v : ""), except = it.except || null;
26
- if (kind === "avoid") return { id: `file:${i}`, kind, pattern: v, paths: it.when || it.in || null, except, text: say || `Don't add code matching ${v}.` };
27
- if (kind === "protect") return { id: `file:${i}`, kind, paths: v, except, text: say || `Don't edit ${v}.` };
28
- if (kind === "deps") return { id: `file:${i}`, kind, except, text: say || "Don't add new dependencies without asking." };
29
- // A note with "when:" (or "in:") globs applies only to those files: it's shown when the agent edits one, not in Memory.
30
- return { id: `file:${i}`, kind, paths: it.when || it.in || null, text: say };
31
- }).filter((r) => r && r.text);
32
- out.mode = items.mode;
33
- return out;
34
- }
35
-
36
- /** Small glob: ** any path, * one segment, a bare folder name matches everything under it. */
37
- export function globMatch(path, globs) {
38
- return String(globs || "").split(",").map((g) => g.trim().replace(/^\.\//, "")).filter(Boolean).some((g) => {
39
- if (!/[*?]/.test(g)) return path === g || path.startsWith(g.replace(/\/$/, "") + "/");
40
- // Runs of "**" and "*" collapse to one ".*", so a glob like **/**/** can't build a slow regex.
41
- const re = g.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "\u0000").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/(?:\u0000|\[\^\/\]\*)*\u0000(?:\u0000|\[\^\/\]\*)*/g, "\u0000").replace(/\u0000/g, ".*");
42
- return new RegExp(`^${re}$`).test(path);
43
- });
44
- }
45
-
46
- // Rule patterns come from people and from repos (a cloned project's .lintsure/rules.yml), so a pattern is checked before
47
- // it runs: a repeated group that repeats inside, like (a+)+ or (\w*)*, can take minutes on one line, so it's refused.
48
- // Patterns stay under 500 characters and run on lines cut to 2,000, so even an unusual pattern finishes fast.
49
- export const MAX_PATTERN = 500, MAX_LINE = 2000;
50
- // A repeated group that repeats inside, (a+)+, or that offers overlapping choices, (a|aa)*: both can take exponential time,
51
- // and cutting the line doesn't save an exponential pattern, so both shapes are refused. A character class, [ab]+, is fine.
52
- const NESTED = /\((?:[^()\\]|\\.)*(?:[+*]|\{\d*,\d*\}|\|)(?:[^()\\]|\\.)*\)(?:[+*]|\{\d*,)/;
53
- /** A rule's pattern as a regex, or the reason it can't be used. Pure. */
54
- export function safePattern(src, flags = "") {
55
- const p = String(src ?? "");
56
- if (!p) return { error: "The pattern is empty." };
57
- if (p.length > MAX_PATTERN) return { error: `The pattern is longer than ${MAX_PATTERN} characters.` };
58
- if (NESTED.test(p)) return { error: "The pattern repeats a group that repeats inside or offers choices, like (a+)+ or (a|b)*, which can take minutes on a single line. Write it without the repeated group, for example with a character class like [ab]+." };
59
- try { return { re: new RegExp(p, flags) }; } catch (e) { return { error: `The pattern isn't a valid regular expression: ${e.message}` }; }
60
- }
1
+ // What the rules helper needs to read and check .lintsure/rules.yml. Local files only: nothing here uses the network.
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /** Rules from .lintsure/rules.yml in the repo. A small YAML subset: a "rules:" list of items with one kind key
6
+ * (avoid, protect, deps, note) plus optional "say" and "in". Anything it can't read is skipped, never fatal. */
7
+ export function fileRules(root) {
8
+ let src; try { src = readFileSync(join(root, ".lintsure", "rules.yml"), "utf8"); } catch { return []; }
9
+ const val = (v) => { v = v.trim(); if (/^".*"$/.test(v)) { try { return JSON.parse(v); } catch { return v.slice(1, -1); } } if (/^'.*'$/.test(v)) return v.slice(1, -1).replace(/''/g, "'"); return v.replace(/\s+#.*$/, ""); };
10
+ const items = []; let inRules = false, cur = null;
11
+ for (const raw of src.split(/\r?\n/)) {
12
+ if (/^\s*(#|$)/.test(raw)) continue;
13
+ const top = raw.match(/^mode:\s*(quiet|guide|strict)\b/i);
14
+ if (top) { items.mode = top[1].toLowerCase(); continue; }
15
+ if (/^\S/.test(raw)) { inRules = /^rules:\s*$/.test(raw); cur = null; continue; }
16
+ if (!inRules) continue;
17
+ const m = raw.match(/^\s*(-\s+)?([a-z]+):\s*(.*)$/i);
18
+ if (!m) continue;
19
+ if (m[1]) { cur = {}; items.push(cur); }
20
+ if (cur) cur[m[2].toLowerCase()] = val(m[3]);
21
+ }
22
+ const out = items.map((it, i) => {
23
+ const kind = ["avoid", "protect", "deps", "note"].find((k) => k in it);
24
+ if (!kind) return null;
25
+ const v = it[kind], say = it.say || (kind === "note" ? v : ""), except = it.except || null;
26
+ if (kind === "avoid") return { id: `file:${i}`, kind, pattern: v, paths: it.when || it.in || null, except, text: say || `Don't add code matching ${v}.` };
27
+ if (kind === "protect") return { id: `file:${i}`, kind, paths: v, except, text: say || `Don't edit ${v}.` };
28
+ if (kind === "deps") return { id: `file:${i}`, kind, except, text: say || "Don't add new dependencies without asking." };
29
+ // A note with "when:" (or "in:") globs applies only to those files: it's shown when the agent edits one, not in Memory.
30
+ return { id: `file:${i}`, kind, paths: it.when || it.in || null, text: say };
31
+ }).filter((r) => r && r.text);
32
+ out.mode = items.mode;
33
+ return out;
34
+ }
35
+
36
+ /** Small glob: ** any path, * one segment, a bare folder name matches everything under it. */
37
+ export function globMatch(path, globs) {
38
+ return String(globs || "").split(",").map((g) => g.trim().replace(/^\.\//, "")).filter(Boolean).some((g) => {
39
+ if (!/[*?]/.test(g)) return path === g || path.startsWith(g.replace(/\/$/, "") + "/");
40
+ // Runs of "**" and "*" collapse to one ".*", so a glob like **/**/** can't build a slow regex.
41
+ const re = g.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "\u0000").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/(?:\u0000|\[\^\/\]\*)*\u0000(?:\u0000|\[\^\/\]\*)*/g, "\u0000").replace(/\u0000/g, ".*");
42
+ return new RegExp(`^${re}$`).test(path);
43
+ });
44
+ }
45
+
46
+ // Rule patterns come from people and from repos (a cloned project's .lintsure/rules.yml), so a pattern is checked before
47
+ // it runs: a repeated group that repeats inside, like (a+)+ or (\w*)*, can take minutes on one line, so it's refused.
48
+ // Patterns stay under 500 characters and run on lines cut to 2,000, so even an unusual pattern finishes fast.
49
+ export const MAX_PATTERN = 500, MAX_LINE = 2000;
50
+ // A repeated group that repeats inside, (a+)+, or that offers overlapping choices, (a|aa)*: both can take exponential time,
51
+ // and cutting the line doesn't save an exponential pattern, so both shapes are refused. A character class, [ab]+, is fine.
52
+ const NESTED = /\((?:[^()\\]|\\.)*(?:[+*]|\{\d*,\d*\}|\|)(?:[^()\\]|\\.)*\)(?:[+*]|\{\d*,)/;
53
+ /** A rule's pattern as a regex, or the reason it can't be used. Pure. */
54
+ export function safePattern(src, flags = "") {
55
+ const p = String(src ?? "");
56
+ if (!p) return { error: "The pattern is empty." };
57
+ if (p.length > MAX_PATTERN) return { error: `The pattern is longer than ${MAX_PATTERN} characters.` };
58
+ if (NESTED.test(p)) return { error: "The pattern repeats a group that repeats inside or offers choices, like (a+)+ or (a|b)*, which can take minutes on a single line. Write it without the repeated group, for example with a character class like [ab]+." };
59
+ try { return { re: new RegExp(p, flags) }; } catch (e) { return { error: `The pattern isn't a valid regular expression: ${e.message}` }; }
60
+ }
@@ -1,129 +1,129 @@
1
- // Lintsure project profile: what the project already has, read on this machine and never sent anywhere.
2
- // - Brand: colours defined as CSS custom properties or in a Tailwind config, and font families.
3
- // - Building blocks: components by name. Content: where quotes and copy live (paths only). Pages, and the stack.
4
- // Cached in the temp folder and rebuilt when the key files change, so checks after each edit stay fast.
5
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from "node:fs";
6
- import { tmpdir } from "node:os";
7
- import { join, basename, extname, relative } from "node:path";
8
- import { createHash } from "node:crypto";
9
- import { globMatch } from "./lib.mjs";
10
-
11
- const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".astro", ".output", "coverage", ".turbo", ".vercel", ".wrangler", "vendor", "out"]);
12
- const STYLE = /\.(css|scss|sass|less|pcss)$/i;
13
- const UI = /\.(astro|tsx|jsx|vue|svelte|html)$/i;
14
- const GENERIC = new Set(["serif", "sans-serif", "monospace", "system-ui", "ui-sans-serif", "ui-serif", "ui-monospace", "inherit", "initial", "cursive", "fantasy", "emoji", "math", "-apple-system", "blinkmacsystemfont", "segoe ui", "roboto", "helvetica", "arial", "helvetica neue", "apple color emoji", "segoe ui emoji", "noto sans", "var"]);
15
- // A file marked lintsure:private reads as empty, so nothing from it reaches Memory.
16
- const read = (f, max = 200_000) => { try { const st = statSync(f); const t = st.size > max ? "" : readFileSync(f, "utf8"); return /lintsure:private/.test(t.slice(0, 2000)) ? "" : t; } catch { return ""; } };
17
- const hex6 = (h) => { h = h.toLowerCase().replace("#", ""); if (h.length === 3 || h.length === 4) h = h.slice(0, 3).split("").map((c) => c + c).join(""); return h.length >= 6 ? `#${h.slice(0, 6)}` : null; };
18
-
19
- function walk(root, max = 4000) {
20
- const files = [];
21
- const go = (d, depth) => {
22
- if (files.length >= max || depth > 8) return;
23
- let ents = []; try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
24
- for (const e of ents) {
25
- if (e.name.startsWith(".") && e.name !== ".lintsure") { if (e.isDirectory()) continue; }
26
- const p = join(d, e.name);
27
- if (e.isDirectory()) { if (!SKIP.has(e.name)) go(p, depth + 1); } else files.push(p);
28
- }
29
- };
30
- go(root, 0);
31
- return files;
32
- }
33
-
34
- function build(root, files) {
35
- const rel = (f) => relative(root, f).replace(/\\/g, "/");
36
- const colors = {}, used = {}, fonts = new Set(), components = {}, content = [], pages = [];
37
- for (const f of files) {
38
- const r = rel(f), name = basename(f);
39
- if (STYLE.test(f) || /tailwind\.config\.[cm]?[jt]s$/.test(name) || (/\.astro$/.test(f) && /layouts?\//.test(r))) {
40
- const src = read(f);
41
- // Colours the project names: --brand-green: #0B6E4F; and Tailwind-style green: '#0B6E4F'
42
- for (const m of src.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-f]{3,8})\b/gi)) { const h = hex6(m[2]); if (h) colors[h] ||= m[1]; }
43
- if (/tailwind\.config/.test(name)) for (const m of src.matchAll(/['"]?([\w-]+)['"]?\s*:\s*['"](#[0-9a-f]{3,8})['"]/gi)) { const h = hex6(m[2]); if (h) colors[h] ||= m[1]; }
44
- for (const m of src.matchAll(/font-family\s*:\s*([^;}\n]+)|--font[\w-]*\s*:\s*([^;}\n]+)|fontFamily\s*:\s*\{([^}]+)\}/gi)) {
45
- for (const fam of String(m[1] || m[2] || m[3]).matchAll(/['"]?([A-Za-z][\w .-]+?)['"]?\s*(?:,|$|\])/g)) { const n = fam[1].trim().toLowerCase(); if (n && !GENERIC.has(n) && !n.startsWith("var(")) fonts.add(n); }
46
- }
47
- }
48
- // Colours already used anywhere in the UI count as the project's: only brand-new ones get flagged.
49
- if (STYLE.test(f) || UI.test(f)) for (const m of read(f).matchAll(/#[0-9a-f]{3,8}\b/gi)) { const h = hex6(m[0]); if (h) { const u = (used[h] ||= []); if (u.length < 3 && !u.includes(r)) u.push(r); } }
50
- if (UI.test(f) && /(^|\/)components?\//.test(r)) components[name.replace(/\.[^.]+$/, "")] = r;
51
- if (/(^|\/)(content|data|copy|i18n|locales)\//.test(r) && /\.(md|mdx|json|ya?ml|ts|js)$/.test(f) || /(quote|testimonial|copy|slogan|tagline)/i.test(name)) content.push(r);
52
- const pg = r.match(/^(?:src\/)?pages\/(.+)\.(astro|tsx|jsx|md|mdx|vue|svelte)$/) || r.match(/^(?:src\/)?app\/(?:(.+)\/)?page\.(tsx|jsx|ts|js)$/);
53
- if (pg) pages.push("/" + String(pg[1] ?? "").replace(/(^|\/)index$/, "").replace(/\/$/, ""));
54
- }
55
- // DESIGN.md (the open format for describing a brand to agents): its tokens are the brand, named as it names them.
56
- const design = read(join(root, "DESIGN.md")).replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
57
- if (design) {
58
- for (const m of design[1].matchAll(/^\s+([\w-]+):\s*["']?(#[0-9a-f]{3,8})\b/gim)) { const h = hex6(m[2]); if (h) colors[h] = `DESIGN.md ${m[1]}`; }
59
- for (const m of design[1].matchAll(/fontFamily:\s*["']?([^"'\n]+)/g)) fonts.add(m[1].trim().toLowerCase());
60
- }
61
- let stack = [];
62
- try {
63
- const pk = JSON.parse(read(join(root, "package.json")) || "{}"), deps = { ...pk.dependencies, ...pk.devDependencies };
64
- stack = ["astro", "next", "react", "vue", "svelte", "@sveltejs/kit", "nuxt", "remix", "tailwindcss", "express", "fastify", "hono", "prisma", "drizzle-orm"].filter((n) => n in deps);
65
- } catch { /* no package.json */ }
66
- return { colors, used, fonts: [...fonts].slice(0, 12), components, content: content.slice(0, 20), pages: [...new Set(pages)].sort().slice(0, 40), stack };
67
- }
68
-
69
- /** The profile for this project, from cache when nothing important changed. */
70
- export function profile(root) {
71
- const files = walk(root);
72
- const keys = files.filter((f) => STYLE.test(f) || /DESIGN\.md$|tailwind\.config|package\.json$|(^|[\\/])components?[\\/]|(^|[\\/])pages[\\/]|(^|[\\/])content[\\/]/.test(f));
73
- const stamp = createHash("sha256").update(keys.map((f) => { try { return `${f}:${statSync(f).mtimeMs}`; } catch { return f; } }).join("|")).digest("hex").slice(0, 16);
74
- const dir = join(tmpdir(), "lintsure-drift"), cache = join(dir, `profile-${createHash("sha256").update(root).digest("hex").slice(0, 12)}.json`);
75
- try { const c = JSON.parse(readFileSync(cache, "utf8")); if (c.stamp === stamp) return c.profile; } catch { /* rebuild */ }
76
- const p = build(root, files);
77
- try { mkdirSync(dir, { recursive: true }); writeFileSync(cache, JSON.stringify({ stamp, profile: p })); } catch { /* fine */ }
78
- return p;
79
- }
80
-
81
- /** At most about 15 lines for the agent. */
82
- export function summary(p) {
83
- const out = [], cols = Object.entries(p.colors);
84
- if (p.stack.length) out.push(`- Stack: ${p.stack.join(", ")}`);
85
- if (cols.length) out.push(`- Brand colours: ${cols.slice(0, 10).map(([h, n]) => `${n} ${h}`).join(", ")}. Use these, not new colours.`);
86
- if (p.fonts.length) out.push(`- Fonts: ${p.fonts.slice(0, 5).join(", ")}`);
87
- const comps = Object.keys(p.components);
88
- if (comps.length) out.push(`- Existing components (reuse them): ${comps.slice(0, 25).join(", ")}${comps.length > 25 ? ` and ${comps.length - 25} more` : ""}`);
89
- if (p.content.length) out.push(`- Real content and copy lives in: ${p.content.slice(0, 6).join(", ")}. Use it; don't invent quotes, names or claims.`);
90
- if (p.pages.length) out.push(`- Pages: ${p.pages.slice(0, 15).join(", ")}${p.pages.length > 15 ? " ..." : ""}`);
91
- return out;
92
- }
93
-
94
- const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
95
- const dist = (a, b) => { const x = rgb(a), y = rgb(b); return Math.hypot(x[0] - y[0], x[1] - y[1], x[2] - y[2]); };
96
-
97
- /** Checks after an edit: colours and fonts outside the brand, and new components that copy an existing one. */
98
- export function profileChecks(root, rel, text, whole, exceptFiles = "") {
99
- // A colour that only appears in files with an agreed exception is still off brand everywhere else.
100
- const normal = (f) => f !== rel && !(exceptFiles && globMatch(f, exceptFiles));
101
- let p; try { p = profile(root); } catch { return []; }
102
- const out = [], palette = Object.keys(p.colors), lineOf = (s) => { const i = whole.indexOf(s); return i < 0 ? 0 : whole.slice(0, i).split("\n").length; };
103
- if ((STYLE.test(rel) || UI.test(rel)) && palette.length >= 2) {
104
- const seen = new Set();
105
- for (const line of text.split("\n")) {
106
- if (/^\s*--[\w-]+\s*:/.test(line)) continue; // defining a brand token is how a palette grows
107
- for (const m of line.matchAll(/#[0-9a-f]{3,8}\b/gi)) {
108
- const h = hex6(m[0]); if (!h || p.colors[h] || (p.used?.[h] || []).some(normal) || seen.has(h)) continue;
109
- if (/^#(fff|ffffff|000|000000)$/i.test(m[0])) continue;
110
- seen.add(h);
111
- const near = palette.reduce((a, b) => (dist(h, a) <= dist(h, b) ? a : b));
112
- out.push({ kind: "off_brand", line: lineOf(m[0]), detail: `Uses the colour ${m[0]}, which isn't in the project's palette. Closest brand colour: ${p.colors[near]} (${near}). Prefer it unless the user asked for this colour.` });
113
- }
114
- }
115
- }
116
- if (p.fonts.length && (STYLE.test(rel) || UI.test(rel))) {
117
- for (const m of text.matchAll(/font-family\s*:\s*['"]?([A-Za-z][\w .-]+)/gi)) {
118
- const n = m[1].trim().toLowerCase();
119
- if (!GENERIC.has(n) && !p.fonts.includes(n) && !n.startsWith("var")) out.push({ kind: "off_brand", line: lineOf(m[0]), detail: `Uses the font "${m[1].trim()}", which isn't one of the project's fonts (${p.fonts.slice(0, 3).join(", ")}).` });
120
- }
121
- }
122
- if (UI.test(rel) && /(^|\/)components?\//.test(rel)) {
123
- const name = basename(rel).replace(/\.[^.]+$/, ""), norm = (n) => n.toLowerCase().replace(/(new|copy|v?\d+|alt|2)$/g, "").replace(/[-_]/g, "");
124
- // The profile may already include this new file, so compare against every other component, not just older ones.
125
- const twin = Object.entries(p.components).find(([n, r]) => r !== rel && n !== name && norm(n) === norm(name));
126
- if (twin) out.push({ kind: "duplicate", line: 0, detail: `${name} looks like a copy of ${twin[0]} in ${twin[1]}. Reuse or extend it instead of making a copy.` });
127
- }
128
- return out;
129
- }
1
+ // Lintsure project profile: what the project already has, read on this machine and never sent anywhere.
2
+ // - Brand: colours defined as CSS custom properties or in a Tailwind config, and font families.
3
+ // - Building blocks: components by name. Content: where quotes and copy live (paths only). Pages, and the stack.
4
+ // Cached in the temp folder and rebuilt when the key files change, so checks after each edit stay fast.
5
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join, basename, extname, relative } from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { globMatch } from "./lib.mjs";
10
+
11
+ const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".astro", ".output", "coverage", ".turbo", ".vercel", ".wrangler", "vendor", "out"]);
12
+ const STYLE = /\.(css|scss|sass|less|pcss)$/i;
13
+ const UI = /\.(astro|tsx|jsx|vue|svelte|html)$/i;
14
+ const GENERIC = new Set(["serif", "sans-serif", "monospace", "system-ui", "ui-sans-serif", "ui-serif", "ui-monospace", "inherit", "initial", "cursive", "fantasy", "emoji", "math", "-apple-system", "blinkmacsystemfont", "segoe ui", "roboto", "helvetica", "arial", "helvetica neue", "apple color emoji", "segoe ui emoji", "noto sans", "var"]);
15
+ // A file marked lintsure:private reads as empty, so nothing from it reaches Memory.
16
+ const read = (f, max = 200_000) => { try { const st = statSync(f); const t = st.size > max ? "" : readFileSync(f, "utf8"); return /lintsure:private/.test(t.slice(0, 2000)) ? "" : t; } catch { return ""; } };
17
+ const hex6 = (h) => { h = h.toLowerCase().replace("#", ""); if (h.length === 3 || h.length === 4) h = h.slice(0, 3).split("").map((c) => c + c).join(""); return h.length >= 6 ? `#${h.slice(0, 6)}` : null; };
18
+
19
+ function walk(root, max = 4000) {
20
+ const files = [];
21
+ const go = (d, depth) => {
22
+ if (files.length >= max || depth > 8) return;
23
+ let ents = []; try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
24
+ for (const e of ents) {
25
+ if (e.name.startsWith(".") && e.name !== ".lintsure") { if (e.isDirectory()) continue; }
26
+ const p = join(d, e.name);
27
+ if (e.isDirectory()) { if (!SKIP.has(e.name)) go(p, depth + 1); } else files.push(p);
28
+ }
29
+ };
30
+ go(root, 0);
31
+ return files;
32
+ }
33
+
34
+ function build(root, files) {
35
+ const rel = (f) => relative(root, f).replace(/\\/g, "/");
36
+ const colors = {}, used = {}, fonts = new Set(), components = {}, content = [], pages = [];
37
+ for (const f of files) {
38
+ const r = rel(f), name = basename(f);
39
+ if (STYLE.test(f) || /tailwind\.config\.[cm]?[jt]s$/.test(name) || (/\.astro$/.test(f) && /layouts?\//.test(r))) {
40
+ const src = read(f);
41
+ // Colours the project names: --brand-green: #0B6E4F; and Tailwind-style green: '#0B6E4F'
42
+ for (const m of src.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-f]{3,8})\b/gi)) { const h = hex6(m[2]); if (h) colors[h] ||= m[1]; }
43
+ if (/tailwind\.config/.test(name)) for (const m of src.matchAll(/['"]?([\w-]+)['"]?\s*:\s*['"](#[0-9a-f]{3,8})['"]/gi)) { const h = hex6(m[2]); if (h) colors[h] ||= m[1]; }
44
+ for (const m of src.matchAll(/font-family\s*:\s*([^;}\n]+)|--font[\w-]*\s*:\s*([^;}\n]+)|fontFamily\s*:\s*\{([^}]+)\}/gi)) {
45
+ for (const fam of String(m[1] || m[2] || m[3]).matchAll(/['"]?([A-Za-z][\w .-]+?)['"]?\s*(?:,|$|\])/g)) { const n = fam[1].trim().toLowerCase(); if (n && !GENERIC.has(n) && !n.startsWith("var(")) fonts.add(n); }
46
+ }
47
+ }
48
+ // Colours already used anywhere in the UI count as the project's: only brand-new ones get flagged.
49
+ if (STYLE.test(f) || UI.test(f)) for (const m of read(f).matchAll(/#[0-9a-f]{3,8}\b/gi)) { const h = hex6(m[0]); if (h) { const u = (used[h] ||= []); if (u.length < 3 && !u.includes(r)) u.push(r); } }
50
+ if (UI.test(f) && /(^|\/)components?\//.test(r)) components[name.replace(/\.[^.]+$/, "")] = r;
51
+ if (/(^|\/)(content|data|copy|i18n|locales)\//.test(r) && /\.(md|mdx|json|ya?ml|ts|js)$/.test(f) || /(quote|testimonial|copy|slogan|tagline)/i.test(name)) content.push(r);
52
+ const pg = r.match(/^(?:src\/)?pages\/(.+)\.(astro|tsx|jsx|md|mdx|vue|svelte)$/) || r.match(/^(?:src\/)?app\/(?:(.+)\/)?page\.(tsx|jsx|ts|js)$/);
53
+ if (pg) pages.push("/" + String(pg[1] ?? "").replace(/(^|\/)index$/, "").replace(/\/$/, ""));
54
+ }
55
+ // DESIGN.md (the open format for describing a brand to agents): its tokens are the brand, named as it names them.
56
+ const design = read(join(root, "DESIGN.md")).replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
57
+ if (design) {
58
+ for (const m of design[1].matchAll(/^\s+([\w-]+):\s*["']?(#[0-9a-f]{3,8})\b/gim)) { const h = hex6(m[2]); if (h) colors[h] = `DESIGN.md ${m[1]}`; }
59
+ for (const m of design[1].matchAll(/fontFamily:\s*["']?([^"'\n]+)/g)) fonts.add(m[1].trim().toLowerCase());
60
+ }
61
+ let stack = [];
62
+ try {
63
+ const pk = JSON.parse(read(join(root, "package.json")) || "{}"), deps = { ...pk.dependencies, ...pk.devDependencies };
64
+ stack = ["astro", "next", "react", "vue", "svelte", "@sveltejs/kit", "nuxt", "remix", "tailwindcss", "express", "fastify", "hono", "prisma", "drizzle-orm"].filter((n) => n in deps);
65
+ } catch { /* no package.json */ }
66
+ return { colors, used, fonts: [...fonts].slice(0, 12), components, content: content.slice(0, 20), pages: [...new Set(pages)].sort().slice(0, 40), stack };
67
+ }
68
+
69
+ /** The profile for this project, from cache when nothing important changed. */
70
+ export function profile(root) {
71
+ const files = walk(root);
72
+ const keys = files.filter((f) => STYLE.test(f) || /DESIGN\.md$|tailwind\.config|package\.json$|(^|[\\/])components?[\\/]|(^|[\\/])pages[\\/]|(^|[\\/])content[\\/]/.test(f));
73
+ const stamp = createHash("sha256").update(keys.map((f) => { try { return `${f}:${statSync(f).mtimeMs}`; } catch { return f; } }).join("|")).digest("hex").slice(0, 16);
74
+ const dir = join(tmpdir(), "lintsure-drift"), cache = join(dir, `profile-${createHash("sha256").update(root).digest("hex").slice(0, 12)}.json`);
75
+ try { const c = JSON.parse(readFileSync(cache, "utf8")); if (c.stamp === stamp) return c.profile; } catch { /* rebuild */ }
76
+ const p = build(root, files);
77
+ try { mkdirSync(dir, { recursive: true }); writeFileSync(cache, JSON.stringify({ stamp, profile: p })); } catch { /* fine */ }
78
+ return p;
79
+ }
80
+
81
+ /** At most about 15 lines for the agent. */
82
+ export function summary(p) {
83
+ const out = [], cols = Object.entries(p.colors);
84
+ if (p.stack.length) out.push(`- Stack: ${p.stack.join(", ")}`);
85
+ if (cols.length) out.push(`- Brand colours: ${cols.slice(0, 10).map(([h, n]) => `${n} ${h}`).join(", ")}. Use these, not new colours.`);
86
+ if (p.fonts.length) out.push(`- Fonts: ${p.fonts.slice(0, 5).join(", ")}`);
87
+ const comps = Object.keys(p.components);
88
+ if (comps.length) out.push(`- Existing components (reuse them): ${comps.slice(0, 25).join(", ")}${comps.length > 25 ? ` and ${comps.length - 25} more` : ""}`);
89
+ if (p.content.length) out.push(`- Real content and copy lives in: ${p.content.slice(0, 6).join(", ")}. Use it; don't invent quotes, names or claims.`);
90
+ if (p.pages.length) out.push(`- Pages: ${p.pages.slice(0, 15).join(", ")}${p.pages.length > 15 ? " ..." : ""}`);
91
+ return out;
92
+ }
93
+
94
+ const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
95
+ const dist = (a, b) => { const x = rgb(a), y = rgb(b); return Math.hypot(x[0] - y[0], x[1] - y[1], x[2] - y[2]); };
96
+
97
+ /** Checks after an edit: colours and fonts outside the brand, and new components that copy an existing one. */
98
+ export function profileChecks(root, rel, text, whole, exceptFiles = "") {
99
+ // A colour that only appears in files with an agreed exception is still off brand everywhere else.
100
+ const normal = (f) => f !== rel && !(exceptFiles && globMatch(f, exceptFiles));
101
+ let p; try { p = profile(root); } catch { return []; }
102
+ const out = [], palette = Object.keys(p.colors), lineOf = (s) => { const i = whole.indexOf(s); return i < 0 ? 0 : whole.slice(0, i).split("\n").length; };
103
+ if ((STYLE.test(rel) || UI.test(rel)) && palette.length >= 2) {
104
+ const seen = new Set();
105
+ for (const line of text.split("\n")) {
106
+ if (/^\s*--[\w-]+\s*:/.test(line)) continue; // defining a brand token is how a palette grows
107
+ for (const m of line.matchAll(/#[0-9a-f]{3,8}\b/gi)) {
108
+ const h = hex6(m[0]); if (!h || p.colors[h] || (p.used?.[h] || []).some(normal) || seen.has(h)) continue;
109
+ if (/^#(fff|ffffff|000|000000)$/i.test(m[0])) continue;
110
+ seen.add(h);
111
+ const near = palette.reduce((a, b) => (dist(h, a) <= dist(h, b) ? a : b));
112
+ out.push({ kind: "off_brand", line: lineOf(m[0]), detail: `Uses the colour ${m[0]}, which isn't in the project's palette. Closest brand colour: ${p.colors[near]} (${near}). Prefer it unless the user asked for this colour.` });
113
+ }
114
+ }
115
+ }
116
+ if (p.fonts.length && (STYLE.test(rel) || UI.test(rel))) {
117
+ for (const m of text.matchAll(/font-family\s*:\s*['"]?([A-Za-z][\w .-]+)/gi)) {
118
+ const n = m[1].trim().toLowerCase();
119
+ if (!GENERIC.has(n) && !p.fonts.includes(n) && !n.startsWith("var")) out.push({ kind: "off_brand", line: lineOf(m[0]), detail: `Uses the font "${m[1].trim()}", which isn't one of the project's fonts (${p.fonts.slice(0, 3).join(", ")}).` });
120
+ }
121
+ }
122
+ if (UI.test(rel) && /(^|\/)components?\//.test(rel)) {
123
+ const name = basename(rel).replace(/\.[^.]+$/, ""), norm = (n) => n.toLowerCase().replace(/(new|copy|v?\d+|alt|2)$/g, "").replace(/[-_]/g, "");
124
+ // The profile may already include this new file, so compare against every other component, not just older ones.
125
+ const twin = Object.entries(p.components).find(([n, r]) => r !== rel && n !== name && norm(n) === norm(name));
126
+ if (twin) out.push({ kind: "duplicate", line: 0, detail: `${name} looks like a copy of ${twin[0]} in ${twin[1]}. Reuse or extend it instead of making a copy.` });
127
+ }
128
+ return out;
129
+ }