memfresh 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,90 @@
1
+ import { finding } from '../context.js';
2
+ import { normalise } from '../text.js';
3
+
4
+ function lcsRatio(a, b) {
5
+ let prev = new Array(b.length + 1).fill(0);
6
+ for (let i = 1; i <= a.length; i++) {
7
+ const cur = [0];
8
+ for (let j = 1; j <= b.length; j++) cur[j] = a[i - 1] === b[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
9
+ prev = cur;
10
+ }
11
+ return (2 * prev[b.length]) / (a.length + b.length);
12
+ }
13
+
14
+ /** duplicate: near-identical instruction lines in different files (info). */
15
+ export function checkDuplicates(ctx) {
16
+ const cand = [];
17
+ for (const src of ctx.sources) {
18
+ if (src.kind === 'codex-memory') continue;
19
+ for (let i = src.bodyStart; i < src.lines.length; i++) {
20
+ const raw = src.lines[i];
21
+ if (src.fence[i] || /^\s*(#|\||>|<!--|-{3,}|={3,})/.test(raw)) continue;
22
+ const norm = normalise(raw);
23
+ const tokens = norm.split(' ');
24
+ if (tokens.length < 5 || norm.length < 30) continue;
25
+ if (/^@\S+$/.test(norm)) continue;
26
+ cand.push({ src, line: i + 1, norm, tokens, raw: raw.trim() });
27
+ }
28
+ }
29
+ const MAX = 20000;
30
+ const capped = cand.slice(0, MAX);
31
+ if (cand.length > MAX) ctx.notes.push(`duplicate check looked at the first ${MAX} of ${cand.length} candidate lines`);
32
+ const parent = capped.map((_, i) => i);
33
+ const find = (x) => (parent[x] === x ? x : (parent[x] = find(parent[x])));
34
+ const union = (a, b) => {
35
+ parent[find(a)] = find(b);
36
+ };
37
+ // exact (normalised) matches
38
+ const exact = new Map();
39
+ capped.forEach((c, i) => {
40
+ if (exact.has(c.norm)) union(i, exact.get(c.norm));
41
+ else exact.set(c.norm, i);
42
+ });
43
+ // near matches: only compare lines that share rare tokens (document frequency <= RARE).
44
+ const RARE = 30;
45
+ const uniq = [...exact.values()];
46
+ const df = new Map();
47
+ for (const i of uniq) for (const t of new Set(capped[i].tokens)) df.set(t, (df.get(t) || 0) + 1);
48
+ const postings = new Map();
49
+ for (const i of uniq) {
50
+ for (const t of new Set(capped[i].tokens)) {
51
+ if (df.get(t) <= RARE) {
52
+ if (!postings.has(t)) postings.set(t, []);
53
+ postings.get(t).push(i);
54
+ }
55
+ }
56
+ }
57
+ for (const i of uniq) {
58
+ const a = capped[i];
59
+ const rare = [...new Set(a.tokens)].filter((t) => df.get(t) <= RARE);
60
+ const shared = new Map();
61
+ for (const t of rare) for (const j of postings.get(t)) if (j > i) shared.set(j, (shared.get(j) || 0) + 1);
62
+ for (const [j, n] of shared) {
63
+ const b = capped[j];
64
+ if (a.src === b.src) continue;
65
+ if (n < Math.min(2, rare.length)) continue;
66
+ const la = a.tokens.length;
67
+ const lb = b.tokens.length;
68
+ if (Math.min(la, lb) / Math.max(la, lb) < ctx.config.duplicateThreshold - 0.1) continue;
69
+ if (lcsRatio(a.tokens, b.tokens) >= ctx.config.duplicateThreshold) union(i, j);
70
+ }
71
+ }
72
+ const clusters = new Map();
73
+ capped.forEach((c, i) => {
74
+ const r = find(i);
75
+ if (!clusters.has(r)) clusters.set(r, []);
76
+ clusters.get(r).push(c);
77
+ });
78
+ const out = [];
79
+ for (const members of clusters.values()) {
80
+ if (new Set(members.map((m) => m.src)).size < 2) continue;
81
+ members.sort((a, b) => (a.src.display === b.src.display ? a.line - b.line : a.src.display < b.src.display ? -1 : 1));
82
+ const [first, ...rest] = members;
83
+ const snippet = first.raw.length > 70 ? `${first.raw.slice(0, 67)}...` : first.raw;
84
+ out.push(finding('duplicate', 'info', first.src, first.line,
85
+ `"${snippet}" also appears in ${rest.map((m) => `${m.src.display}:${m.line}`).join(', ')}`,
86
+ 'Keep it in one file and import or link it from the others (for example `@AGENTS.md` from CLAUDE.md).',
87
+ rest.map((m) => ({ file: m.src.display, line: m.line }))));
88
+ }
89
+ return out;
90
+ }
@@ -0,0 +1,60 @@
1
+ import path from 'node:path';
2
+ import { finding } from '../context.js';
3
+ import { posix } from '../util.js';
4
+
5
+ /** broken-import: `@path` imports that do not resolve, are too deep, or loop. */
6
+ export function checkImports(ctx, maxDepth) {
7
+ const out = [];
8
+ for (const src of ctx.sources) {
9
+ for (const imp of src.imports) {
10
+ const shown = imp.resolved.startsWith(ctx.root) ? posix(path.relative(ctx.root, imp.resolved)) : imp.resolved;
11
+ if (imp.status === 'missing') {
12
+ const clear = /^(\.{1,2}\/|~\/|\/)/.test(imp.raw.slice(1)) || imp.atLineStart;
13
+ // `@/lib` in the middle of a sentence is almost always a bundler path alias (Next.js, Vite).
14
+ if (/^@\/[\w-]+(?:\/[\w-]+)*$/.test(imp.raw) && !imp.atLineStart) {
15
+ out.push(finding('broken-import', 'info', src, imp.line, `\`${imp.raw}\` looks like a path alias, but Claude Code reads \`@path\` as an import and would look for ${shown}`,
16
+ `Put it in backticks (\`${imp.raw}\`) so it is not treated as an import.`));
17
+ continue;
18
+ }
19
+ out.push(finding('broken-import', clear ? 'error' : 'warn', src, imp.line, `import \`${imp.raw}\` does not resolve (looked for ${shown})`,
20
+ 'Fix the path (relative paths resolve from the importing file) or delete the import.'));
21
+ } else if (imp.status === 'too-deep') {
22
+ out.push(finding('broken-import', 'warn', src, imp.line, `import \`${imp.raw}\` is more than ${maxDepth} hops deep, so Claude Code does not load it`,
23
+ 'Flatten the import chain or import this file from a shallower file.'));
24
+ } else if (imp.status === 'external') {
25
+ out.push(finding('broken-import', 'info', src, imp.line, `import \`${imp.raw}\` points outside the project; Claude Code asks for approval before loading it and memfresh does not read it`,
26
+ 'Nothing to fix unless the import is unintended.'));
27
+ } else if (imp.status === 'cycle') {
28
+ out.push(finding('broken-import', 'info', src, imp.line, `import \`${imp.raw}\` points back into its own import chain`, 'Remove the circular import.'));
29
+ }
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+
35
+ /**
36
+ * agents-not-loaded: documented Claude Code behaviour is to read CLAUDE.md files OR AGENTS.md,
37
+ * not both, unless a CLAUDE.md imports AGENTS.md.
38
+ * https://code.claude.com/docs/en/memory#agents-md
39
+ */
40
+ export function checkAgentsNotLoaded(ctx) {
41
+ const out = [];
42
+ const claudeDirs = ctx.sources
43
+ .filter((s) => s.scope === 'project' && (s.kind === 'claude-md' || s.kind === 'claude-local') && s.importedFrom === null)
44
+ .map((s) => path.dirname(s.abs).replace(/\/\.claude$/, ''));
45
+ if (!claudeDirs.length) return out;
46
+ const imported = new Set();
47
+ for (const s of ctx.sources) for (const i of s.imports) if (i.status === 'ok' && i.target) imported.add(i.target.realpath);
48
+ for (const src of ctx.sources) {
49
+ if (src.scope !== 'project' || src.kind !== 'agents-md' || src.importedFrom || src.bytes === 0) continue;
50
+ const dir = path.dirname(src.abs);
51
+ // Claude Code uses AGENTS.md only when no CLAUDE.md exists in the working dir or above it.
52
+ const shadowed = claudeDirs.some((c) => dir === c || dir.startsWith(c + path.sep));
53
+ if (shadowed && !imported.has(src.realpath)) {
54
+ out.push(finding('agents-not-loaded', 'info', src, 1,
55
+ 'Claude Code reads CLAUDE.md instead of AGENTS.md when a CLAUDE.md exists in the working directory or above it, and none of them imports this file, so these instructions are not loaded by Claude Code',
56
+ 'Add `@AGENTS.md` to a CLAUDE.md in the same directory (or one above), or set Claude Code\'s project-instructions mode to claude-md-and-agents-md.'));
57
+ }
58
+ }
59
+ return out;
60
+ }
@@ -0,0 +1,132 @@
1
+ import { finding } from '../context.js';
2
+ import { globToRegExp } from '../glob.js';
3
+ import { ignoreDirectives } from '../text.js';
4
+ import { checkBudget } from './budget.js';
5
+ import { checkContradictions } from './contradiction.js';
6
+ import { checkDuplicates } from './duplicate.js';
7
+ import { checkAgentsNotLoaded, checkImports } from './imports.js';
8
+ import { checkPaths } from './paths.js';
9
+ import { checkScripts } from './scripts.js';
10
+ import { checkSecrets } from './secrets.js';
11
+ import { checkStaleAge } from './stale.js';
12
+
13
+ export const CHECK_IDS = [
14
+ 'missing-path', 'missing-script', 'stale-reference', 'stale-age', 'contradiction',
15
+ 'duplicate', 'budget', 'secret-like', 'broken-import', 'agents-not-loaded', 'internal-error',
16
+ ];
17
+ const SEV_ORDER = { error: 0, warn: 1, info: 2 };
18
+
19
+ /**
20
+ * Config ignore rule: `id`, or `id:path` where path is a substring of the file path or, when it
21
+ * contains * ? [ or {, a glob (a pattern without a slash matches at any depth). `*` as the id
22
+ * matches every check.
23
+ */
24
+ function ignoredByConfig(rule, f) {
25
+ const [id, ...rest] = rule.split(':');
26
+ if (id !== '*' && id !== f.id) return false;
27
+ if (!rest.length) return true;
28
+ const target = rest.join(':');
29
+ const test = (file) => (/[*?[{]/.test(target) ? globToRegExp(target).test(file || '') : (file || '').includes(target));
30
+ // a two-location finding (a contradiction, a duplicate) is silenced by a rule for either file
31
+ return test(f.file) || (f.related || []).some((r) => test(r.file));
32
+ }
33
+
34
+ const CHECKS = [
35
+ (ctx) => checkPaths(ctx), // must run first: it records referenced paths for stale-age
36
+ (ctx) => checkScripts(ctx),
37
+ (ctx) => checkStaleAge(ctx),
38
+ (ctx) => checkContradictions(ctx),
39
+ (ctx) => checkDuplicates(ctx),
40
+ (ctx) => checkBudget(ctx),
41
+ (ctx) => checkSecrets(ctx),
42
+ (ctx, o) => checkImports(ctx, o.maxImportDepth),
43
+ (ctx) => checkAgentsNotLoaded(ctx),
44
+ ];
45
+
46
+ /**
47
+ * Safety net. If a check throws, find the file(s) that make it throw (by running it on each file
48
+ * alone), report each as an `internal-error` info finding, and run the check again without them,
49
+ * so one odd file never costs the user the whole report. `onInternalError(error, source, index)`
50
+ * lets the CLI show the stack under --debug.
51
+ */
52
+ function runGuarded(fn, ctx, opts) {
53
+ try {
54
+ return fn(ctx, opts);
55
+ } catch (error) {
56
+ const all = ctx.sources;
57
+ const culprits = [];
58
+ for (const s of all) {
59
+ ctx.sources = [s];
60
+ try {
61
+ fn(ctx, opts);
62
+ } catch (e) {
63
+ culprits.push({ s, e });
64
+ }
65
+ }
66
+ ctx.sources = all.filter((s) => !culprits.some((c) => c.s === s));
67
+ let out = [];
68
+ try {
69
+ out = fn(ctx, opts);
70
+ } catch {
71
+ out = [];
72
+ if (!culprits.length) culprits.push({ s: all[0], e: error });
73
+ }
74
+ ctx.sources = all;
75
+ if (!culprits.length) culprits.push({ s: all[0] || null, e: error });
76
+ for (const { s, e } of culprits) {
77
+ if (opts.onInternalError) opts.onInternalError(e, s);
78
+ out.push(finding('internal-error', 'info', s, 1,
79
+ `memfresh hit an internal error while checking this file (${e && e.message ? e.message : e}); some checks were skipped for it`,
80
+ 'Run with --debug for the stack trace and please report it with the file (or a cut-down copy) at https://github.com/boscofoulsham/memfresh/issues.'));
81
+ }
82
+ return out;
83
+ }
84
+ }
85
+
86
+ /** Run every check and return sorted, de-ignored findings. */
87
+ export function runChecks(ctx, { maxImportDepth = 4, onInternalError, onNote } = {}) {
88
+ const opts = { maxImportDepth, onInternalError };
89
+ let findings = CHECKS.flatMap((fn) => runGuarded(fn, ctx, opts));
90
+ const directives = new Map(ctx.sources.map((s) => {
91
+ try {
92
+ return [s.display, ignoreDirectives(s.lines, s.fence)];
93
+ } catch {
94
+ return [s.display, new Map()];
95
+ }
96
+ }));
97
+ if (onNote) {
98
+ for (const s of ctx.sources) {
99
+ const d = directives.get(s.display);
100
+ const unknown = d && d.mentioned ? [...d.mentioned].filter((id) => !CHECK_IDS.includes(id)) : [];
101
+ if (unknown.length) onNote(`${s.display}: memfresh-ignore names unknown check id${unknown.length > 1 ? 's' : ''} ${unknown.map((u) => `"${u}"`).join(', ')} (check ids: ${CHECK_IDS.join(', ')}); the directive does nothing for ${unknown.length > 1 ? 'them' : 'it'}`);
102
+ }
103
+ }
104
+ // A directive on either side of a two-location finding (a contradiction, a duplicate) silences it.
105
+ const silenced = (file, line, id) => {
106
+ const d = directives.get(file);
107
+ if (!d) return false;
108
+ if (d.fileIds !== undefined && (d.fileIds === null || d.fileIds.has(id))) return true;
109
+ if (line && d.has(line)) {
110
+ const ids = d.get(line);
111
+ if (ids === null || ids.has(id)) return true;
112
+ }
113
+ return false;
114
+ };
115
+ findings = findings.filter((f) => {
116
+ if (silenced(f.file, f.line, f.id) || (f.related || []).some((r) => silenced(r.file, r.line, f.id))) return false;
117
+ return !ctx.config.ignore.some((rule) => ignoredByConfig(String(rule), f));
118
+ });
119
+ const key = (f) => [f.file === null ? 1 : 0, f.file, String(f.line ?? 0).padStart(8, '0'), SEV_ORDER[f.severity], f.id, f.message].join('\u0000');
120
+ findings.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
121
+ return findings;
122
+ }
123
+
124
+ export function summarise(findings) {
125
+ const s = { errors: 0, warnings: 0, info: 0, total: findings.length };
126
+ for (const f of findings) {
127
+ if (f.severity === 'error') s.errors++;
128
+ else if (f.severity === 'warn') s.warnings++;
129
+ else s.info++;
130
+ }
131
+ return s;
132
+ }
@@ -0,0 +1,237 @@
1
+ import path from 'node:path';
2
+ import { COMMON_DIRS, scanPaths } from '../refs.js';
3
+ import { finding } from '../context.js';
4
+ import { splitPatterns } from '../glob.js';
5
+ import { IGNORED_DIRS, KNOWN_EXT, extOf, exists, globMatchesAny, isDir, posix } from '../util.js';
6
+ import { blankSpans, codeSpans } from '../text.js';
7
+
8
+ const GENERATED = /^(\.env(\..*)?|.*\.log|.*\.tmp)$/;
9
+
10
+ /** Directory holding the .claude / .cursor folder a rule lives in ('' for the repo root). */
11
+ export function ruleBase(src) {
12
+ const m = /^(.*?)\/?\.(?:claude|cursor)\/rules\//.exec(src.display);
13
+ return m ? m[1] : '';
14
+ }
15
+
16
+ /** Does this source's relative references make sense to verify against the repo? */
17
+ export function checkable(src) {
18
+ if (src.scope === 'project') return true;
19
+ return src.kind === 'claude-memory-index' || src.kind === 'claude-memory-topic';
20
+ }
21
+
22
+ /**
23
+ * Directories named by the nearest preceding heading, or by an earlier backticked directory on
24
+ * the same line. Monorepo instruction files often say "## packages/db" and then use paths
25
+ * relative to that package.
26
+ */
27
+ function contextBases(ctx, src, line) {
28
+ if (!line) return [];
29
+ const root = ctx.baseRoot(src);
30
+ const found = [];
31
+ const addFrom = (text) => {
32
+ for (const tok of text.match(/[\w@.][\w@./-]*/g) || []) {
33
+ const t = tok.replace(/\/+$/, '');
34
+ if (t.includes('/') || COMMON_DIRS.has(t) || isDir(path.join(root, t))) {
35
+ const abs = path.join(root, t);
36
+ if (isDir(abs) && !found.includes(abs)) found.push(abs);
37
+ }
38
+ }
39
+ };
40
+ for (const s2 of codeSpans(src.lines[line - 1]).slice(0, 4)) addFrom(s2.text);
41
+ // nearest heading above the line (computed once per file: this runs for every path mention)
42
+ if (!src.headingAbove) {
43
+ src.headingAbove = new Int32Array(src.lines.length).fill(-1);
44
+ let cur = -1;
45
+ for (let i = 0; i < src.lines.length; i++) {
46
+ if (!src.fence[i] && /^#{1,6}\s/.test(src.lines[i])) cur = i;
47
+ src.headingAbove[i] = cur;
48
+ }
49
+ }
50
+ const h = src.headingAbove[line - 1];
51
+ if (h >= 0) addFrom(blankSpans(src.lines[h]) + ' ' + codeSpans(src.lines[h]).map((x) => x.text).join(' '));
52
+ return found;
53
+ }
54
+
55
+ function resolve(ctx, src, rel, line) {
56
+ const bases = [ctx.baseRoot(src)];
57
+ bases.push(path.dirname(src.abs));
58
+ bases.push(...contextBases(ctx, src, line));
59
+ for (const b of bases) {
60
+ const p = path.join(b, rel);
61
+ if (exists(p)) return p;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ function anchored(ctx, src, c, line) {
67
+ const segs = c.path.split('/');
68
+ if (c.explicitRel) return true;
69
+ if (segs.length === 1 && !c.isDir) return true;
70
+ const first = segs[0];
71
+ if (first.startsWith('.') || COMMON_DIRS.has(first)) return true;
72
+ return Boolean(resolve(ctx, src, first, line));
73
+ }
74
+
75
+ /** Resolve a missing path through git history. */
76
+ function staleInfo(ctx, src, cand) {
77
+ const git = ctx.git;
78
+ if (!git.available) return null;
79
+ const hist = git.history();
80
+ if (!hist.size) return null;
81
+ const bases = [ctx.baseRoot(src)];
82
+ if (src.scope === 'project') bases.push(path.dirname(src.abs));
83
+ const toRoot = (gitRel) => posix(path.relative(ctx.root, path.join(git.top, gitRel)));
84
+ for (const b of bases) {
85
+ const key = git.rel(path.join(b, cand.path));
86
+ if (key === null || key.startsWith('..')) continue;
87
+ let ev = hist.get(key);
88
+ if (ev) {
89
+ let to = ev.to;
90
+ for (let i = 0; i < 20 && to && !exists(path.join(git.top, to)) && hist.has(to); i++) {
91
+ const next = hist.get(to);
92
+ if (next.kind === 'deleted') {
93
+ ev = { ...next, from: ev };
94
+ to = null;
95
+ break;
96
+ }
97
+ to = next.to;
98
+ }
99
+ const target = to && exists(path.join(git.top, to)) ? toRoot(to) : null;
100
+ return { kind: target ? 'renamed' : 'deleted', hash: ev.hash, date: ev.date, target };
101
+ }
102
+ if (cand.isDir || !path.extname(cand.path)) {
103
+ const prefix = `${key}/`;
104
+ for (const [old, e] of hist) {
105
+ if (!old.startsWith(prefix)) continue;
106
+ if (e.kind === 'renamed') {
107
+ const suffix = old.slice(key.length);
108
+ if (e.to.endsWith(suffix)) {
109
+ const newDir = e.to.slice(0, e.to.length - suffix.length);
110
+ if (exists(path.join(git.top, newDir))) return { kind: 'renamed', hash: e.hash, date: e.date, target: `${toRoot(newDir)}/` };
111
+ }
112
+ }
113
+ return { kind: 'deleted', hash: e.hash, date: e.date, target: null };
114
+ }
115
+ }
116
+ }
117
+ return null;
118
+ }
119
+
120
+ /** Other places below the root where the missing path exists (monorepo packages). */
121
+ function elsewhereHits(ctx, cand) {
122
+ const hits = new Set();
123
+ if (!(cand.path.includes('/') || path.extname(cand.path))) return hits;
124
+ const tail = `/${cand.path.replace(/\/$/, '')}`;
125
+ const dirLike = cand.isDir || !path.extname(cand.path);
126
+ for (const f of ctx.files) {
127
+ const i = dirLike ? f.indexOf(`${tail}/`) : f.endsWith(tail) ? f.length - tail.length : -1;
128
+ if (i > 0) hits.add(dirLike ? f.slice(0, i + tail.length) : f);
129
+ }
130
+ return hits;
131
+ }
132
+
133
+ /**
134
+ * missing-path + stale-reference. Also records referenced, existing paths on `src.referenced`
135
+ * (used by stale-age).
136
+ */
137
+ export function checkPaths(ctx) {
138
+ const out = [];
139
+ const pending = [];
140
+ for (const src of ctx.sources) {
141
+ src.referenced = [];
142
+ if (!checkable(src)) continue;
143
+ for (const { cand, line, history } of scanPaths(src)) {
144
+ const first = cand.path.split('/')[0];
145
+ if (IGNORED_DIRS.has(first) || GENERATED.test(cand.path.split('/').pop())) continue;
146
+ if (cand.isGlob) {
147
+ if (!globMatchesAny(cand.path, ctx.files) && anchored(ctx, src, cand, line) && ctx.files.length) {
148
+ // A bare basename pattern (`*.test.ts`) is a naming convention, not a location: info only.
149
+ pending.push({ src, line, cand, glob: true, soft: !cand.path.includes('/') });
150
+ }
151
+ continue;
152
+ }
153
+ const hit = resolve(ctx, src, cand.path, line);
154
+ if (hit) {
155
+ src.referenced.push(posix(path.relative(ctx.root, hit)));
156
+ continue;
157
+ }
158
+ if (!anchored(ctx, src, cand, line)) continue;
159
+ // `.test.ts`, `_test.go`, `-spec.rb`, `.module.css`: file-suffix naming conventions, not files.
160
+ if (/^[._-][\w-]*(?:\.[\w-]+)*$/.test(cand.path) && KNOWN_EXT.has(extOf(cand.path))) continue;
161
+ if (!cand.path.includes('/') && ctx.basenames.has(cand.path.split('/').pop())) continue;
162
+ // A bare directory name (`tests/`) that exists nested somewhere is a generic reference.
163
+ if (cand.isDir && !cand.path.includes('/') && ctx.files.some((f) => f.includes(`/${cand.path}/`))) continue;
164
+ pending.push({ src, line, cand, glob: false, history });
165
+ }
166
+ // Cursor/Claude rule globs that match nothing. A nested rule's patterns are relative to the
167
+ // directory that holds its .claude/.cursor folder (Claude Code docs, "path-specific rules").
168
+ // Root-relative matching is accepted too, so this never claims a miss the tool would not.
169
+ const key = src.frontmatter.globs ? 'globs' : 'paths';
170
+ const globs = splitPatterns([].concat(src.frontmatter[key] || []).filter((g) => typeof g === 'string' && g))
171
+ .filter((g) => !g.startsWith('!'));
172
+ const baseDir = ruleBase(src);
173
+ const scoped = baseDir ? ctx.files.filter((f) => f.startsWith(`${baseDir}/`)).map((f) => f.slice(baseDir.length + 1)) : ctx.files;
174
+ const missing = globs.filter((g) => ctx.files.length && !globMatchesAny(g, scoped) && !globMatchesAny(g, ctx.files));
175
+ for (const g of missing) {
176
+ out.push(finding('missing-path', 'warn', src, src.frontmatterKeyLines[key] || 1,
177
+ missing.length === globs.length
178
+ ? `${key} pattern \`${g}\` matches no files${baseDir ? ` under ${baseDir}/` : ' in the repo'}, so this rule never applies`
179
+ : `${key} pattern \`${g}\` matches no files${baseDir ? ` under ${baseDir}/` : ' in the repo'} (the other patterns do match)`,
180
+ 'Fix the pattern or delete it.'));
181
+ }
182
+ }
183
+ // gitignored paths are legitimately absent in a fresh clone
184
+ const ignored = ctx.git.ignored(
185
+ pending.filter((p) => !p.glob).flatMap((p) => {
186
+ const rel = ctx.git.rel(path.join(ctx.baseRoot(p.src), p.cand.path));
187
+ // a directory-only ignore pattern (`public/`) matches only when the path ends in a slash
188
+ return p.cand.isDir && rel ? [rel, `${rel}/`] : [rel];
189
+ }).filter((x) => x && !x.startsWith('..')),
190
+ );
191
+ for (const p of pending) {
192
+ const { src, line, cand } = p;
193
+ const shown = `${cand.path}${cand.isDir && !cand.path.endsWith('/') ? '/' : ''}`;
194
+ if (p.glob) {
195
+ out.push(finding('missing-path', p.soft ? 'info' : 'warn', src, line, `glob \`${cand.path}\` matches no files in the repo`, 'Update the pattern or remove the reference.'));
196
+ continue;
197
+ }
198
+ const rel = ctx.git.rel(path.join(ctx.baseRoot(src), cand.path));
199
+ if (rel && (ignored.has(rel) || ignored.has(`${rel}/`))) continue;
200
+ const text = src.lines[line - 1] || '';
201
+ // Exists below some other directory (typically a monorepo package): probably package-relative.
202
+ // Checked before history, so a repo that became a monorepo with `git mv` is not told its
203
+ // "every package has src/index.ts" line is stale.
204
+ const elsewhere = elsewhereHits(ctx, cand);
205
+ if (elsewhere.size === 1) {
206
+ out.push(finding('missing-path', 'info', src, line, `\`${shown}\` does not exist at the repo root, but \`${[...elsewhere][0]}\` does; if this is relative to that package, ignore this`,
207
+ `Write the full path (\`${[...elsewhere][0]}\`) so it works from any directory.`));
208
+ continue;
209
+ }
210
+ if (elsewhere.size > 1) {
211
+ out.push(finding('missing-path', 'info', src, line, `\`${shown}\` does not exist at the repo root, but it exists in ${elsewhere.size} other places (for example \`${[...elsewhere].sort()[0]}\`); if this describes every package, ignore this`,
212
+ 'Name the package directory if you mean one of them.'));
213
+ continue;
214
+ }
215
+ const st = staleInfo(ctx, src, cand);
216
+ if (st) {
217
+ // The line already names where the file went: a historical note, not a stale fact.
218
+ if (st.target) {
219
+ const tgt = st.target.replace(/\/+$/, '');
220
+ if (text.includes(tgt)) continue;
221
+ }
222
+ const old = p.history;
223
+ const when = `in ${st.hash} (${st.date})`;
224
+ out.push(finding('stale-reference', old ? 'info' : 'warn', src, line,
225
+ st.kind === 'renamed' ? `\`${shown}\` was renamed to \`${st.target}\` ${when}` : `\`${shown}\` was deleted ${when}`,
226
+ st.kind === 'renamed' ? `Replace the reference with \`${st.target}\`.` : 'Remove the reference or point it at the replacement.'));
227
+ continue;
228
+ }
229
+ let fix = 'Update the path or remove the line.';
230
+ if (!cand.path.includes('/') || path.extname(cand.path)) {
231
+ const alts = ctx.basenames.get(cand.path.split('/').pop()) || [];
232
+ if (alts.length === 1) fix = `Did you mean \`${alts[0]}\`?`;
233
+ }
234
+ out.push(finding('missing-path', p.history ? 'info' : 'warn', src, line, `\`${shown}\` does not exist${p.history ? ' (the line reads as history, so this is only a note)' : ''}`, fix));
235
+ }
236
+ return out;
237
+ }
@@ -0,0 +1,87 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { allWorkspaceScripts, finding, justRecipes, makeTargets, packageScripts } from '../context.js';
4
+ import { scanCommands } from '../refs.js';
5
+ import { checkable } from './paths.js';
6
+
7
+ // Binary names that differ from the package that provides them.
8
+ const BIN_ALIASES = { tsc: 'typescript', tsserver: 'typescript', changeset: '@changesets/cli', biome: '@biomejs/biome', nest: '@nestjs/cli', ng: '@angular/cli', vue: '@vue/cli', next: 'next', tsx: 'tsx', rollup: 'rollup', turbo: 'turbo', nx: 'nx', playwright: '@playwright/test', cypress: 'cypress', storybook: 'storybook', wrangler: 'wrangler', drizzle: 'drizzle-kit', 'drizzle-kit': 'drizzle-kit' };
9
+
10
+ /** Is `name` plausibly a binary of a declared dependency (or present in node_modules/.bin)? */
11
+ function isDependencyBin(ctx, dirAbs, name) {
12
+ const dirs = new Set([dirAbs, ctx.root]);
13
+ let cur = dirAbs;
14
+ for (let i = 0; i < 30 && cur !== ctx.root && path.dirname(cur) !== cur; i++) {
15
+ cur = path.dirname(cur);
16
+ dirs.add(cur);
17
+ }
18
+ const deps = new Set();
19
+ for (const d of dirs) {
20
+ if (fs.existsSync(path.join(d, 'node_modules', '.bin', name))) return true;
21
+ const pj = fs.existsSync(path.join(d, 'package.json')) ? ctx.readJson(path.join(d, 'package.json')) : null;
22
+ for (const k of Object.keys({ ...(pj?.dependencies || {}), ...(pj?.devDependencies || {}), ...(pj?.optionalDependencies || {}) })) deps.add(k);
23
+ }
24
+ for (const f of ctx.files) {
25
+ if (f.endsWith('/package.json') && f.split('/').length <= 4) {
26
+ const pj = ctx.readJson(path.join(ctx.root, f));
27
+ for (const k of Object.keys({ ...(pj?.dependencies || {}), ...(pj?.devDependencies || {}) })) deps.add(k);
28
+ }
29
+ }
30
+ if (deps.has(name) || (BIN_ALIASES[name] && deps.has(BIN_ALIASES[name]))) return true;
31
+ for (const d of deps) {
32
+ const bare = d.replace(/^@[^/]+\//, '');
33
+ const scope = d.startsWith('@') ? d.slice(1, d.indexOf('/')) : '';
34
+ if (bare === name || bare.startsWith(`${name}-`) || bare.startsWith(`${name}.`) || scope === name || scope.replace(/s$/, '') === name || bare.replace(/-cli$/, '') === name) return true;
35
+ }
36
+ return false;
37
+ }
38
+
39
+ /** missing-script: npm/pnpm/yarn/bun scripts, make targets, just recipes that do not exist. */
40
+ export function checkScripts(ctx) {
41
+ const out = [];
42
+ for (const src of ctx.sources) {
43
+ if (!checkable(src)) continue;
44
+ const baseDir = src.scope === 'project' ? path.dirname(src.abs) : ctx.baseRoot(src);
45
+ const seen = new Set();
46
+ for (const c of scanCommands(src)) {
47
+ const key = `${c.line}:${c.tool}:${c.name}`;
48
+ if (seen.has(key)) continue;
49
+ seen.add(key);
50
+ if (c.kind === 'script') {
51
+ const dir = c.cwd ? path.resolve(baseDir, c.cwd) : baseDir;
52
+ const info = packageScripts(ctx, dir);
53
+ if (!info) continue; // no package.json anywhere: cannot verify
54
+ if (info.names.has(c.name)) continue;
55
+ if (info.workspaces && allWorkspaceScripts(ctx).has(c.name)) continue;
56
+ // pnpm X / yarn X / yarn run X fall back to dependency binaries, which is how most
57
+ // pnpm and yarn instruction files are written.
58
+ // A name with a colon (`test:unit`, `db:seed`) is a script name by convention, not a binary.
59
+ const mayBeBin = (c.bare || c.runForm) && !c.name.includes(':');
60
+ if (mayBeBin && isDependencyBin(ctx, dir, c.name)) continue;
61
+ const elsewhere = allWorkspaceScripts(ctx).has(c.name);
62
+ const soft = mayBeBin || elsewhere;
63
+ const near = [...info.names].filter((n) => n.startsWith(c.name.split(':')[0]) || c.name.startsWith(n.split(':')[0]));
64
+ out.push(finding('missing-script', soft ? 'info' : 'error', src, c.line,
65
+ `\`${c.tool} ${c.tool === 'yarn' || c.tool === 'pnpm' ? '' : 'run '}${c.name}\` refers to a script that is not in package.json${mayBeBin ? ' and does not match a dependency binary I can see (it may still be one)' : elsewhere ? ' here (another package.json defines it)' : ''}`.replace(' ', ' '),
66
+ near.length ? `package.json has: ${near.slice(0, 4).join(', ')}. Use one of those or remove the line.` : 'Add the script to package.json or remove the line.'));
67
+ } else if (c.kind === 'target') {
68
+ const m = makeTargets(ctx, c.cwd);
69
+ if (m.includes) continue;
70
+ if (!m.found) {
71
+ out.push(finding('missing-script', 'warn', src, c.line, `\`make ${c.name}\` is referenced but the repo has no Makefile`, 'Add a Makefile or remove the line.'));
72
+ } else if (!m.has(c.name)) {
73
+ out.push(finding('missing-script', 'error', src, c.line, `\`make ${c.name}\`: the Makefile has no target "${c.name}"`, 'Add the target or remove the line.'));
74
+ }
75
+ } else if (c.kind === 'recipe') {
76
+ const j = justRecipes(ctx);
77
+ if (j.imports) continue;
78
+ if (!j.found) {
79
+ out.push(finding('missing-script', 'warn', src, c.line, `\`just ${c.name}\` is referenced but the repo has no justfile`, 'Add a justfile or remove the line.'));
80
+ } else if (!j.recipes.has(c.name)) {
81
+ out.push(finding('missing-script', 'error', src, c.line, `\`just ${c.name}\`: the justfile has no recipe "${c.name}"`, 'Add the recipe or remove the line.'));
82
+ }
83
+ }
84
+ }
85
+ }
86
+ return out;
87
+ }