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,619 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { blankSpans, codeSpans } from '../text.js';
4
+ import { finding } from '../context.js';
5
+ import { splitPatterns } from '../glob.js';
6
+ import { exists, posix } from '../util.js';
7
+
8
+ // High precision over recall. Each detector extracts "claims" from instruction lines; claims only
9
+ // conflict when they share a topic key: same directory group, same rule scope (globs/paths
10
+ // frontmatter), and same qualifier (language/ecosystem words, scope words, a path in backticks).
11
+
12
+ const NEG = String.raw`(?:not|never|no|than|over|instead of|rather than|don'?t use|do not use|don'?t|do not|avoid|stop using|without)`;
13
+ const PM_LIST = ['npm', 'pnpm', 'yarn', 'bun'];
14
+ const SCOPE_WORDS = /\b(frontend|front-end|backend|back-end|api|server|client|web|ui|e2e|end-to-end|integration|unit|mobile|cli|docs|legacy)\b/gi;
15
+ const LANG_WORDS = /\b(python|javascript|typescript|js|ts|rust|go|golang|java|kotlin|swift|ruby|php|css|html|c\+\+|c#)\b/gi;
16
+ // "go" is also a verb ("where things go"): only the capitalised language name counts.
17
+ const isGoVerb = (m, plain) => m[1] === 'go' || (m[1] === 'Go' && /^\s+(?:to|through|back|ahead|here|there|into|over|on|and|for)\b/i.test(plain.slice(m.index + 2)));
18
+ const SKIP_CONTEXT = /\b(migrat\w*|switch\w*|moving|used to|previously|formerly|deprecated|no longer|dropp\w*|eol|end of life|legacy|was|were)\b/i;
19
+
20
+ // File kinds and tools that make a rule specific to some files ("Makefiles use tabs", "YAML uses 2
21
+ // spaces", "SQL keywords are upper case"). A rule that names one is scoped and never contradicts a
22
+ // general rule.
23
+ const KIND_WORDS = /\b(makefiles?|gnumakefiles?|dockerfiles?|yaml|yml|toml|json|jsonc|markdown|sql|shell|bash|zsh|sh|ini|xml|csv|proto|protobuf|graphql|terraform|hcl|nix|lua|cmake|gradle|ruby|erb|haml|scss|sass|svelte|vue|jsx|tsx|mdx|rst|tex|html)\b/gi;
24
+ const PURPOSE_AFTER = /^\s+(?:parsing|parsers?|serialis\w*|serializ\w*|encoding|decoding|handling|responses?|payloads?|requests?|bodies|body|data|output|input)\b/i;
25
+ // Words that, in "The X uses Y", name the whole project rather than a part of it.
26
+ const GENERIC_SUBJECT = new Set(['project', 'repo', 'repository', 'codebase', 'code', 'tests', 'test', 'suite', 'monorepo', 'workspace', 'app', 'application', 'package', 'library', 'lib', 'source', 'team', 'we', 'it', 'this', 'that', 'default', 'rule', 'rules', 'build', 'ci', 'style', 'formatter', 'linter', 'repo’s']);
27
+ const SUBJECT_NOUN = '(?:app|apps|package|packages|service|services|worker|workers|module|modules|crate|crates|library|plugin|extension|site|backend|frontend|dashboard|server|client|cli|sdk|api|lambda|function)';
28
+
29
+ /** Qualifier text for a line: languages, file kinds, scope words, named packages and paths, sorted. */
30
+ function qualifierOf(line) {
31
+ const words = new Set();
32
+ const plain = blankSpans(line).replace(/\b[\w-]+\.js\b/gi, ' ');
33
+ for (const m of plain.matchAll(LANG_WORDS)) if (!isGoVerb(m, plain)) words.add(m[1].toLowerCase().replace('golang', 'go').replace(/^js$/, 'javascript').replace(/^ts$/, 'typescript'));
34
+ for (const m of plain.matchAll(SCOPE_WORDS)) words.add(m[1].toLowerCase());
35
+ for (const m of plain.matchAll(KIND_WORDS)) {
36
+ // "Always use Gson for JSON parsing": a purpose ("for <kind> parsing"), not a rule about JSON files
37
+ if (/\bfor\s+(?:the\s+)?$/i.test(plain.slice(0, m.index)) && PURPOSE_AFTER.test(plain.slice(m.index + m[0].length))) continue;
38
+ words.add(`kind:${m[1].toLowerCase().replace(/^(gnu)?makefiles?$/, 'makefile').replace(/^yml$/, 'yaml').replace(/s$/, '')}`);
39
+ }
40
+ const spans = codeSpans(line);
41
+ for (const s of spans) {
42
+ const t = s.text.trim();
43
+ if (/^[\w.@-]+\/[\w./*@-]*$/.test(t)) {
44
+ // an example after a colon or "e.g." says where something lives; it does not scope the rule
45
+ if (!/(?::|e\.g\.|for example|such as|see|like)\s*$/i.test(line.slice(0, s.start))) words.add(`path:${t}`);
46
+ }
47
+ // a bare file name or extension: `Makefile`, `Dockerfile`, `*.sql`, `.yml`
48
+ else if (/^(?:makefile|dockerfile|gnumakefile|justfile)$/i.test(t)) words.add(`kind:${t.toLowerCase()}`.replace('gnumakefile', 'makefile'));
49
+ else if (/^\*?\.[a-z0-9]{1,6}$/i.test(t)) words.add(`kind:${t.replace(/^\*?\./, '').toLowerCase()}`);
50
+ // inside a command: `pnpm -F @acme/worker test`, `yarn workspace web test`, `cd apps/web && ...`
51
+ for (const m of t.matchAll(/(?:^|\s)(?:-F|--filter|-w|--workspace|--prefix|-C|--cwd|--dir|workspace|cd)[\s=]+(?:\.\/)?([@\w./-]+)/g)) {
52
+ if (m[1] && m[1] !== '.' && m[1] !== '..') words.add(`pkg:${m[1].replace(/\/+$/, '')}`);
53
+ }
54
+ for (const m of t.matchAll(/(?:^|\s)(@[\w-]+\/[\w-]+)(?=\s|$)/g)) words.add(`pkg:${m[1]}`);
55
+ }
56
+ // prose subject naming a part of the project: "The worker uses Jest", "the web app runs ..."
57
+ const subj = new RegExp(`^\\W*(?:the|our)\\s+([\\w-]+)(?:\\s+${SUBJECT_NOUN})?\\s+(?:uses?|runs?|is|are|has|needs|requires|relies|tests?|builds?|keeps?|follows?|must|should)\\b`, 'i').exec(plain.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, ''));
58
+ if (subj && !GENERIC_SUBJECT.has(subj[1].toLowerCase()) && !/^(?:\d|use|run)/i.test(subj[1])) words.add(`subject:${subj[1].toLowerCase()}`);
59
+ const noun = new RegExp(`\\b([\\w-]+)\\s+${SUBJECT_NOUN}\\b`, 'i').exec(plain);
60
+ if (noun && !GENERIC_SUBJECT.has(noun[1].toLowerCase()) && !/^(?:the|our|a|an|this|each|every|all|any|your|that|these|those|per|and|or|of|in|for|to|new|existing|shared|other)$/i.test(noun[1])) words.add(`subject:${noun[1].toLowerCase()}`);
61
+ return [...words].sort().join(',');
62
+ }
63
+
64
+ const mergeQuals = (...qs) => [...new Set(qs.flatMap((q) => (q ? q.split(',') : [])))].sort().join(',');
65
+
66
+ /** Split a line into clauses at ";" and sentence ends, never inside a code span. */
67
+ function clausesOf(line) {
68
+ const masked = line.replace(/`[^`]*`/g, (m) => 'x'.repeat(m.length));
69
+ const cuts = [];
70
+ for (const m of masked.matchAll(/;\s+|[.!?]\s+(?=[A-Z`])/g)) cuts.push(m.index + m[0].length);
71
+ if (!cuts.length) return [line];
72
+ const out = [];
73
+ let from = 0;
74
+ for (const c of [...cuts, line.length]) {
75
+ const part = line.slice(from, c).trim();
76
+ if (part) out.push(part);
77
+ from = c;
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /** Qualifier of the headings above each line: a rule under "## Python" is a Python rule. */
83
+ function headingQualifiers(src) {
84
+ const out = new Array(src.lines.length).fill('');
85
+ // A heading scopes the rules under it only when the file is partitioned by such headings (at
86
+ // least two different scoped headings: "## Python" and "## TypeScript"). A lone "# Java" title
87
+ // does not turn the whole file into a niche.
88
+ const distinct = new Set();
89
+ for (let i = src.bodyStart; i < src.lines.length; i++) {
90
+ const m = !src.fence[i] && /^#{1,6}\s+(.*?)\s*#*\s*$/.exec(src.lines[i]);
91
+ const q = m && qualifierOf(m[1]);
92
+ if (q) distinct.add(q);
93
+ }
94
+ if (distinct.size < 2) return out;
95
+ const stack = [];
96
+ for (let i = src.bodyStart; i < src.lines.length; i++) {
97
+ const m = !src.fence[i] && /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(src.lines[i]);
98
+ if (m) {
99
+ const level = m[1].length;
100
+ while (stack.length && stack[stack.length - 1].level >= level) stack.pop();
101
+ stack.push({ level, qual: qualifierOf(m[2]) });
102
+ }
103
+ out[i] = mergeQuals(...stack.map((h) => h.qual));
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /**
109
+ * Cursor rules that are not always on (no globs, alwaysApply not true) apply only when the agent
110
+ * picks them from their description, or when invoked by hand. They are scoped: they get their own
111
+ * scope token plus whatever the description and file name say.
112
+ */
113
+ function ruleQualifier(src) {
114
+ if (src.kind !== 'cursor-rule') return '';
115
+ const fm = src.frontmatter || {};
116
+ if (splitPatterns([].concat(fm.globs || [], fm.paths || [])).length) return '';
117
+ if (String(fm.alwaysApply).toLowerCase() === 'true') return '';
118
+ const stem = posix(src.display).split('/').pop().replace(/\.mdc$/, '');
119
+ return mergeQuals(`rule:${src.display}`, qualifierOf(`${fm.description || ''} ${stem.replace(/[-_]/g, ' ')}`));
120
+ }
121
+
122
+ function negBefore(text, idx) {
123
+ return new RegExp(`${NEG}\\s+(?:use\\s+|using\\s+)?(?:\\d+[\\s-]*)?$`, 'i').test(text.slice(Math.max(0, idx - 30), idx).replace(/`/g, ''));
124
+ }
125
+
126
+ /** Directory group a source applies to (so nested configs are not compared with root ones). */
127
+ function groupOf(src) {
128
+ if (src.importedFrom) return groupOf(src.importedFrom);
129
+ if (src.scope === 'user') return '';
130
+ let dir = posix(path.dirname(src.display));
131
+ if (dir === '.') dir = '';
132
+ dir = dir.replace(/(^|\/)(\.claude\/rules|\.claude|\.cursor\/rules|\.github|\.clinerules)$/, '');
133
+ return dir;
134
+ }
135
+
136
+ function scopeKeyOf(src) {
137
+ const fm = src.frontmatter || {};
138
+ const g = splitPatterns([].concat(fm.globs || [], fm.paths || [])).sort();
139
+ return g.join('|');
140
+ }
141
+
142
+ // ------------------------------------------------------------------ detectors
143
+ const PM_CMD = new RegExp(String.raw`\b(npm|pnpm|yarn|bun)\s+(install|i|ci|add|remove|rm|run|test|t|start|dev|build|lint|exec)\b(?![^\n\`]*\s(?:-g|--global)\b)(?:\s+([^\s\`]+))?`, 'gi');
144
+ const PM_PROSE = /\b(?:use|using|uses|prefer|package manager(?: is|:)?|managed (?:with|by)|installed? (?:with|using|via)|always use|run with)\s+(?:`)?(npm|pnpm|yarn|bun)\b/gi;
145
+
146
+ function pmClaims(line) {
147
+ const pos = new Set();
148
+ const neg = new Set();
149
+ for (const re of [PM_CMD, PM_PROSE]) {
150
+ re.lastIndex = 0;
151
+ for (const m of line.matchAll(re)) {
152
+ // Bun is also a script runtime, test runner and bundler: `bun run scripts/x.ts`, `bun test`,
153
+ // `bun build` say nothing about the package manager. Only install/add/remove/ci and
154
+ // `bun run <script-name>` count.
155
+ if (re === PM_PROSE && m[1].toLowerCase() === 'bun' && /^\s+(?:test|build|x|pm|run\s+[\w./-]+\.\w)/i.test(line.slice(m.index + m[0].length))) continue;
156
+ if (re === PM_PROSE && m[1].toLowerCase() === 'bun' && /\bbunx?\s+(?:run\s+)?[\w./-]+\.(?:[cm]?[jt]sx?)\b/i.test(line)) continue;
157
+ if (re === PM_CMD && m[1].toLowerCase() === 'bun') {
158
+ const verb = m[2].toLowerCase();
159
+ if (!['install', 'i', 'ci', 'add', 'remove', 'rm', 'run'].includes(verb)) continue;
160
+ if (verb === 'run' && (!m[3] || /[/\\]|\.[a-z]{1,4}$/i.test(m[3]))) continue;
161
+ }
162
+ (negBefore(line, m.index) ? neg : pos).add(m[1].toLowerCase());
163
+ }
164
+ }
165
+ for (const pm of PM_LIST) {
166
+ for (const m of line.matchAll(new RegExp(`\\b${NEG}\\s+(?:use\\s+|using\\s+)?\`?${pm}\\b`, 'gi'))) {
167
+ void m;
168
+ neg.add(pm);
169
+ }
170
+ if (new RegExp(`\\binstead of\\s+\`?${pm}\\b|,\\s*not\\s+\`?${pm}\\b`, 'i').test(line)) neg.add(pm);
171
+ }
172
+ for (const n of neg) pos.delete(n);
173
+ return pos.size === 1 ? [{ value: [...pos][0] }] : [];
174
+ }
175
+
176
+ const JS_RUNNERS = ['jest', 'vitest', 'mocha', 'node:test', 'karma'];
177
+ const PY_RUNNERS = ['pytest', 'unittest'];
178
+ const RUN_RE = /(?:(?:npx|pnpm exec|pnpm dlx|yarn|bunx|npm exec --)\s+|^\s*(?:[$>]\s+)?|`)(jest|vitest|mocha|pytest|karma|jasmine)(?![\w-]|\.\w)/gi;
179
+ const RUN_PROSE = /\b(?:use|using|uses|run|runs|test runner(?: is|:)?|testing framework(?: is|:)?|tests? (?:with|using|via)|tests? (?:are|is) (?:written|run) (?:in|with|using))\s+(?:the\s+)?`?(jest|vitest|mocha|pytest|unittest|node:test|karma|jasmine)(?![\w-]|\.\w)/gi;
180
+ // "Unit tests (Karma + Jasmine)", as written in tables
181
+ const RUN_PAREN = /\btests?\s*\(\s*(?:the\s+)?(jest|vitest|mocha|pytest|unittest|karma|jasmine)\b/gi;
182
+
183
+ // "`npm test` - Vitest unit tests", "`yarn test` (Jest, via Turbo)": the runner named right after the command
184
+ const RUN_AFTER_CMD = /`(?:npm|pnpm|yarn|bun)(?:\s+run)?\s+test[^`]*`\s*(?:[-\u2013\u2014:]\s+|\(\s*)(?:the\s+)?(jest|vitest|mocha|pytest|karma|jasmine)(?![\w-]|\.\w)/gi;
185
+
186
+ function testClaims(line) {
187
+ if (SKIP_CONTEXT.test(line)) return [];
188
+ const pos = new Set();
189
+ const neg = new Set();
190
+ const add = (re) => {
191
+ re.lastIndex = 0;
192
+ // Jasmine is the assertion half of Karma + Jasmine: one runner setup, not two claims.
193
+ for (const m of line.matchAll(re)) (negBefore(line, m.index + (m[0].length - m[1].length)) ? neg : pos).add(m[1].toLowerCase().replace(/^jasmine$/, 'karma'));
194
+ };
195
+ add(RUN_RE);
196
+ add(RUN_PROSE);
197
+ add(RUN_PAREN);
198
+ add(RUN_AFTER_CMD);
199
+ if (/\bnode\s+--test\b/.test(line)) pos.add('node:test');
200
+ if (/\bpython3?\s+-m\s+unittest(?![\w-]|\.\w)/.test(line)) pos.add('unittest');
201
+ if (/\bnode:test\b/.test(line)) pos.add('node:test');
202
+ for (const r of [...JS_RUNNERS, ...PY_RUNNERS]) {
203
+ if (new RegExp(`\\b${NEG}\\s+(?:use\\s+|using\\s+)?\`?${r}\\b|,\\s*not\\s+\`?${r}\\b`, 'i').test(line)) neg.add(r);
204
+ }
205
+ for (const n of neg) pos.delete(n);
206
+ if (pos.size !== 1) return [];
207
+ const v = [...pos][0];
208
+ return [{ value: v, eco: JS_RUNNERS.includes(v) ? 'js-tests' : 'py-tests' }];
209
+ }
210
+
211
+ const NUMBER_WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, eight: 8 };
212
+ function indentClaims(line) {
213
+ if (!/\b(indent\w*|format\w*|style|tabs?|spaces?|code)\b/i.test(line)) return [];
214
+ if (SKIP_CONTEXT.test(line)) return [];
215
+ const pos = new Set();
216
+ for (const m of line.matchAll(/\b(\d+|one|two|three|four|five|six|eight)[\s-]*spaces?\b/gi)) {
217
+ if (!negBefore(line, m.index) && /\b(indent\w*|format\w*|style|tabs?)\b/i.test(line)) pos.add(`spaces:${NUMBER_WORDS[m[1].toLowerCase()] ?? m[1]}`);
218
+ }
219
+ for (const m of line.matchAll(/(?<!\b(?:browser|editor|open|terminal|new|split)\s)\btabs?\b/gi)) {
220
+ // "Prettier: tabs, single quotes", "gofmt (tabs)": a formatter or style word is enough context
221
+ if (!/\b(indent\w*|spaces?|prettier|gofmt|biome|dprint|rustfmt|editorconfig|formatt\w*)\b/i.test(line)) continue;
222
+ const trailingNeg = negBefore(line, m.index);
223
+ if (trailingNeg) pos.add('spaces');
224
+ else pos.add('tabs');
225
+ }
226
+ if (/\bspaces?\b/i.test(line) && !pos.size && /\bindent/i.test(line) && !/\d/.test(line)) {
227
+ const m = /\bspaces?\b/i.exec(line);
228
+ if (!negBefore(line, m.index)) pos.add('spaces');
229
+ }
230
+ // "tabs, not spaces" => tabs only; "spaces, not tabs" handled by trailingNeg above.
231
+ if (/\btabs?\b[^.]*(?:,|\s)(?:not|never|instead of|rather than)\s+(?:\d+[\s-]*)?spaces?\b/i.test(line)) {
232
+ pos.clear();
233
+ pos.add('tabs');
234
+ }
235
+ return pos.size === 1 ? [{ value: [...pos][0] }] : [];
236
+ }
237
+
238
+ const QUOTE_SKIP = /\b(json|yaml|yml|toml|shell|bash|sql|html|attributes?|jsx|css|markdown|docstrings?|commit messages?|csv|interpolation|template)\b/i;
239
+ function quoteClaims(line) {
240
+ if (QUOTE_SKIP.test(line) || SKIP_CONTEXT.test(line)) return [];
241
+ const pos = new Set();
242
+ for (const m of line.matchAll(/\b(single|double)[\s-]quotes?\b/gi)) {
243
+ const v = m[1].toLowerCase();
244
+ if (!/\b(use|prefer|always|quote style|strings?|quotes? for|require)\b/i.test(line) && !negBefore(line, m.index)) continue;
245
+ const opp = v === 'single' ? 'double' : 'single';
246
+ if (negBefore(line, m.index) || /,\s*not\s*$/i.test(line.slice(0, m.index))) pos.add(opp);
247
+ else pos.add(v);
248
+ }
249
+ return pos.size === 1 ? [{ value: [...pos][0] }] : [];
250
+ }
251
+
252
+ function formatterClaims(line) {
253
+ if (SKIP_CONTEXT.test(line)) return [];
254
+ const pos = new Set();
255
+ const neg = new Set();
256
+ const re = /(?:(?:npx|pnpm exec|pnpm dlx|yarn|bunx|npm exec --)\s+|`|^\s*|\b(?:use|using|run|format(?:ted)? with|formatter is|formatting:)\s+`?)(prettier|biome)\b/gi;
257
+ for (const m of line.matchAll(re)) (negBefore(line, m.index + (m[0].length - m[1].length)) ? neg : pos).add(m[1].toLowerCase());
258
+ for (const f of ['prettier', 'biome']) {
259
+ if (new RegExp(`\\b${NEG}\\s+(?:use\\s+)?\`?${f}\\b|,\\s*not\\s+\`?${f}\\b`, 'i').test(line)) neg.add(f);
260
+ }
261
+ for (const n of neg) pos.delete(n);
262
+ return pos.size === 1 ? [{ value: [...pos][0] }] : [];
263
+ }
264
+
265
+ const AFTER_VERSION = String.raw`(?:\.(?:x|\*))?(?:\s+(?:LTS|\(LTS\)))?(\+|\s*(?:\(?or (?:newer|higher|later|above|greater|more recent)\)?|and (?:up|above|newer|later)|\u2192|\bLTS or (?:newer|later)))?`;
266
+ // "minimum Node 20", "requires Node 20", "at least Node 20" are lower bounds even without "or later".
267
+ const MIN_BEFORE = /(?:minimum|min\.?|at least|requires?|required|needs?|>=|\u2265)\s*(?:version\s+)?(?:of\s+)?$/i;
268
+ const isMinBefore = (line, idx, end) => MIN_BEFORE.test(line.slice(Math.max(0, idx - 24), idx)) || (end !== undefined && /^\W*(?:is |are )?(?:required|needed|the minimum|at least)\b/i.test(line.slice(end)));
269
+ function nodeClaims(line) {
270
+ if (SKIP_CONTEXT.test(line) || /\bmatrix\b/i.test(line)) return [];
271
+ const found = [];
272
+ for (const m of line.matchAll(new RegExp(String.raw`\bnode(?:\.?js)?\s*(?:version\s*)?(>=|≥|v|@|=)?\s*(\d{1,2})(?:\.\d+)*${AFTER_VERSION}`, 'gi'))) {
273
+ const min = m[1] === '>=' || m[1] === '≥' || Boolean(m[3]) || isMinBefore(line, m.index, m.index + m[0].length);
274
+ found.push({ value: `node ${min ? '>=' : ''}${m[2]}`, ver: { op: min ? 'min' : 'exact', n: [Number(m[2])] }, topic: 'node' });
275
+ }
276
+ return new Set(found.map((f) => f.value)).size === 1 ? [found[0]] : [];
277
+ }
278
+ function pythonClaims(line) {
279
+ if (SKIP_CONTEXT.test(line) || /\bmatrix\b/i.test(line)) return [];
280
+ const found = [];
281
+ for (const m of line.matchAll(new RegExp(String.raw`\bpython\s*(>=|≥|v|=)?\s*(3)\.(\d{1,2})(?:\.\d+)*${AFTER_VERSION}`, 'gi'))) {
282
+ const min = m[1] === '>=' || m[1] === '≥' || Boolean(m[4]) || isMinBefore(line, m.index, m.index + m[0].length);
283
+ found.push({ value: `python ${min ? '>=' : ''}3.${m[3]}`, ver: { op: min ? 'min' : 'exact', n: [3, Number(m[3])] }, topic: 'python' });
284
+ }
285
+ return new Set(found.map((f) => f.value)).size === 1 ? [found[0]] : [];
286
+ }
287
+
288
+ const STOP = new Set(['the', 'a', 'an', 'any', 'your', 'our', 'this', 'that', 'these', 'those', 'please', 'ever', 'also', 'to']);
289
+ function alwaysNever(line) {
290
+ const m = /\b(always|never|do not ever|don'?t ever)\s+(.+?)\s*[.!]?\s*$/i.exec(blankSpansKeep(line));
291
+ if (!m) return [];
292
+ const polarity = m[1].toLowerCase() === 'always' ? 'always' : 'never';
293
+ const x = m[2].toLowerCase().replace(/[^a-z0-9:@./\s-]/g, ' ').split(/\s+/).filter((w) => w && !STOP.has(w)).join(' ');
294
+ if (x.split(' ').length < 2 && x.length < 4) return [];
295
+ // "Always use default exports for screens" meets "Never use default exports": compare the object
296
+ // without its trailing "for/in ..." scope. Two different scopes ("tabs for alignment" vs "tabs
297
+ // for indentation") do not conflict.
298
+ const sm = /^(.*?)\s+(?:for|in|on|within|inside)\s+(.+)$/.exec(x);
299
+ return [{ value: sm ? sm[1] : x, polarity, topic: 'rule', forq: sm ? sm[2] : '' }];
300
+ }
301
+ function blankSpansKeep(line) {
302
+ return line.replace(/`/g, '');
303
+ }
304
+ const DOES_NOT_ALWAYS = /\b(not always|almost always|nearly always|as always|not never)\b/i;
305
+
306
+ // ------------------------------------------------------------------ version evidence
307
+ function parseVerExpr(expr, depth) {
308
+ const e = String(expr).trim();
309
+ let m = /^v?(\d+)(?:\.(\d+|x|\*))?(?:\.[\dx*]+)?$/.exec(e);
310
+ if (m) return { op: 'exact', n: depth === 2 ? [Number(m[1]), m[2] && /^\d+$/.test(m[2]) ? Number(m[2]) : 0] : [Number(m[1])] };
311
+ m = /^\^v?(\d+)/.exec(e);
312
+ if (m && depth === 1) return { op: 'exact', n: [Number(m[1])] };
313
+ m = /^>=\s*v?(\d+)(?:\.(\d+))?(?:\.\d+)?$/.exec(e);
314
+ if (m) return { op: 'min', n: depth === 2 ? [Number(m[1]), Number(m[2] || 0)] : [Number(m[1])] };
315
+ return null;
316
+ }
317
+
318
+ function geq(a, b) {
319
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
320
+ const x = a[i] ?? 0;
321
+ const y = b[i] ?? 0;
322
+ if (x !== y) return x > y;
323
+ }
324
+ return true;
325
+ }
326
+ function eq(a, b) {
327
+ const l = Math.min(a.length, b.length);
328
+ return a.slice(0, l).every((x, i) => x === b[i]);
329
+ }
330
+ function versionsConflict(a, b) {
331
+ if (a.op === 'exact' && b.op === 'exact') return !eq(a.n, b.n);
332
+ if (a.op === 'exact' && b.op === 'min') return !geq(a.n, b.n);
333
+ if (a.op === 'min' && b.op === 'exact') return !geq(b.n, a.n);
334
+ return false;
335
+ }
336
+
337
+ function readFirstLine(abs) {
338
+ try {
339
+ return (readFileSyncSafe(abs).split(/\r?\n/)[0] || '').trim();
340
+ } catch {
341
+ return '';
342
+ }
343
+ }
344
+ function readFileSyncSafe(abs) {
345
+ return fs.readFileSync(abs, 'utf8');
346
+ }
347
+
348
+ /** Facts about the project that claims can be checked against, for a directory group. */
349
+ function evidenceFor(ctx, group) {
350
+ const key = `evidence:${group}`;
351
+ if (ctx.cache.has(key)) return ctx.cache.get(key);
352
+ const ev = { lockfiles: [], packageManager: null, node: [], python: [], formatter: [], indent: null };
353
+ const dirs = [];
354
+ let cur = group;
355
+ for (;;) {
356
+ dirs.push(cur);
357
+ if (!cur) break;
358
+ cur = cur.includes('/') ? cur.slice(0, cur.lastIndexOf('/')) : '';
359
+ }
360
+ const rel = (d, f) => (d ? `${d}/${f}` : f);
361
+ const abs = (d, f) => path.join(ctx.root, rel(d, f));
362
+ // nearest ancestor that has any lockfile / package.json decides
363
+ const locks = { 'package-lock.json': 'npm', 'npm-shrinkwrap.json': 'npm', 'pnpm-lock.yaml': 'pnpm', 'yarn.lock': 'yarn', 'bun.lock': 'bun', 'bun.lockb': 'bun' };
364
+ for (const d of dirs) {
365
+ const here = Object.keys(locks).filter((f) => exists(abs(d, f)));
366
+ if (here.length) {
367
+ ev.lockfiles = here.map((f) => ({ file: rel(d, f), pm: locks[f] }));
368
+ break;
369
+ }
370
+ }
371
+ for (const d of dirs) {
372
+ const pj = exists(abs(d, 'package.json')) ? ctx.readJson(abs(d, 'package.json')) : null;
373
+ if (pj && pj.packageManager && !ev.packageManager) {
374
+ const m = /^(npm|pnpm|yarn|bun)@/.exec(pj.packageManager);
375
+ if (m) ev.packageManager = { file: rel(d, 'package.json'), pm: m[1] };
376
+ }
377
+ if (pj && pj.engines && pj.engines.node && !ev.node.length) {
378
+ const v = parseVerExpr(pj.engines.node, 1);
379
+ if (v) ev.node.push({ file: rel(d, 'package.json'), ver: v, label: `engines.node ${pj.engines.node}` });
380
+ }
381
+ if (pj && !ev.formatter.length) {
382
+ const deps = { ...(pj.dependencies || {}), ...(pj.devDependencies || {}) };
383
+ const f = new Set();
384
+ if (deps.prettier) f.add('prettier');
385
+ if (deps['@biomejs/biome']) f.add('biome');
386
+ if (f.size) ev.formatter.push({ file: rel(d, 'package.json'), set: f });
387
+ }
388
+ for (const f of ['.nvmrc', '.node-version']) {
389
+ if (exists(abs(d, f)) && !ev.node.length) {
390
+ const v = parseVerExpr(readFirstLine(abs(d, f)), 1);
391
+ if (v) ev.node.push({ file: rel(d, f), ver: v, label: `${f} ${readFirstLine(abs(d, f))}` });
392
+ }
393
+ }
394
+ if (exists(abs(d, '.tool-versions'))) {
395
+ for (const l of readFileSyncSafe(abs(d, '.tool-versions')).split('\n')) {
396
+ const m = /^(nodejs|node|python)\s+(\S+)/.exec(l.trim());
397
+ if (!m) continue;
398
+ const isNode = m[1] !== 'python';
399
+ const v = parseVerExpr(m[2], isNode ? 1 : 2);
400
+ const list = isNode ? ev.node : ev.python;
401
+ if (v && !list.length) list.push({ file: rel(d, '.tool-versions'), ver: v, label: `.tool-versions ${l.trim()}` });
402
+ }
403
+ }
404
+ if (exists(abs(d, 'pyproject.toml')) && !ev.python.length) {
405
+ const m = /^\s*requires-python\s*=\s*["']([^"']+)["']/m.exec(readFileSyncSafe(abs(d, 'pyproject.toml')));
406
+ const v = m && parseVerExpr(m[1].replace(/\s+/g, ''), 2);
407
+ if (v) ev.python.push({ file: rel(d, 'pyproject.toml'), ver: v, label: `requires-python ${m[1]}` });
408
+ }
409
+ if (exists(abs(d, '.python-version')) && !ev.python.length) {
410
+ const v = parseVerExpr(readFirstLine(abs(d, '.python-version')), 2);
411
+ if (v) ev.python.push({ file: rel(d, '.python-version'), ver: v, label: `.python-version ${readFirstLine(abs(d, '.python-version'))}` });
412
+ }
413
+ const hasPrettier = ['.prettierrc', '.prettierrc.json', '.prettierrc.yml', '.prettierrc.yaml', '.prettierrc.js', '.prettierrc.cjs', '.prettierrc.mjs', 'prettier.config.js', 'prettier.config.mjs', 'prettier.config.cjs'].find((f) => exists(abs(d, f)));
414
+ if (!ev.indent) ev.indent = indentEvidence(ctx, d, rel, abs, pj);
415
+ const hasBiome = ['biome.json', 'biome.jsonc'].find((f) => exists(abs(d, f)));
416
+ if ((hasPrettier || hasBiome) && !ev.formatter.length) {
417
+ const set = new Set();
418
+ if (hasPrettier) set.add('prettier');
419
+ if (hasBiome) set.add('biome');
420
+ ev.formatter.push({ file: rel(d, hasPrettier || hasBiome), set });
421
+ }
422
+ }
423
+ ctx.cache.set(key, ev);
424
+ return ev;
425
+ }
426
+
427
+ /**
428
+ * Indentation the tooling enforces: Prettier `useTabs`, Biome `indentStyle`, and `indent_style` in the
429
+ * `[*]` section of .editorconfig. Returns { file, style: 'tabs' | 'spaces' } or null.
430
+ * https://prettier.io/docs/options#tabs https://biomejs.dev/reference/configuration/#formatterindentstyle
431
+ * https://spec.editorconfig.org/#supported-pairs
432
+ */
433
+ function indentEvidence(ctx, d, rel, abs, pj) {
434
+ const fromBool = (file, v) => (v === true || v === 'true' ? { file, style: 'tabs' } : v === false || v === 'false' ? { file, style: 'spaces' } : null);
435
+ for (const f of ['.prettierrc', '.prettierrc.json', '.prettierrc.yml', '.prettierrc.yaml']) {
436
+ if (!exists(abs(d, f))) continue;
437
+ const text = readFileSyncSafe(abs(d, f));
438
+ let v;
439
+ try {
440
+ v = JSON.parse(text).useTabs;
441
+ } catch {
442
+ v = /^useTabs\s*:\s*(true|false)\b/m.exec(text)?.[1];
443
+ }
444
+ const e = fromBool(rel(d, f), v);
445
+ if (e) return e;
446
+ }
447
+ if (pj && pj.prettier && typeof pj.prettier === 'object') {
448
+ const e = fromBool(rel(d, 'package.json'), pj.prettier.useTabs);
449
+ if (e) return e;
450
+ }
451
+ for (const f of ['biome.json', 'biome.jsonc']) {
452
+ if (!exists(abs(d, f))) continue;
453
+ const m = /"indentStyle"\s*:\s*"(tab|space)"/.exec(readFileSyncSafe(abs(d, f)));
454
+ if (m) return { file: rel(d, f), style: m[1] === 'tab' ? 'tabs' : 'spaces' };
455
+ }
456
+ if (exists(abs(d, '.editorconfig'))) {
457
+ let inStar = true;
458
+ for (const l of readFileSyncSafe(abs(d, '.editorconfig')).split(/\r?\n/)) {
459
+ const sec = /^\s*\[(.*)\]\s*$/.exec(l);
460
+ if (sec) inStar = sec[1] === '*';
461
+ const m = inStar && /^\s*indent_style\s*=\s*(tab|space)\s*(?:[#;].*)?$/i.exec(l);
462
+ if (m) return { file: rel(d, '.editorconfig'), style: m[1].toLowerCase() === 'tab' ? 'tabs' : 'spaces' };
463
+ }
464
+ }
465
+ return null;
466
+ }
467
+
468
+ // ------------------------------------------------------------------ driver
469
+ const LINE_DETECTORS = [
470
+ { id: 'package-manager', label: 'package manager', fn: pmClaims, fenceOk: true },
471
+ { id: 'test-runner', label: 'test runner', fn: testClaims, fenceOk: true },
472
+ { id: 'indentation', label: 'indentation', fn: indentClaims },
473
+ { id: 'quotes', label: 'quote style', fn: quoteClaims },
474
+ { id: 'formatter', label: 'formatter', fn: formatterClaims, fenceOk: true },
475
+ { id: 'node-version', label: 'Node version', fn: nodeClaims },
476
+ { id: 'python-version', label: 'Python version', fn: pythonClaims },
477
+ { id: 'always-never', label: 'always/never rule', fn: (l) => (DOES_NOT_ALWAYS.test(l) ? [] : alwaysNever(l)) },
478
+ ];
479
+
480
+ const loc = (c) => `${c.src.display}:${c.line}`;
481
+
482
+ /** contradiction: rule-based detectors across all files. */
483
+ export function checkContradictions(ctx) {
484
+ /** @type {Map<string, any[]>} */
485
+ const topics = new Map();
486
+ for (const src of ctx.sources) {
487
+ if (src.kind === 'codex-memory') continue;
488
+ const group = groupOf(src);
489
+ const scopeKey = scopeKeyOf(src);
490
+ const ruleQual = ruleQualifier(src);
491
+ const headings = headingQualifiers(src);
492
+ for (let i = src.bodyStart; i < src.lines.length; i++) {
493
+ const raw = src.lines[i];
494
+ const inFence = src.fence[i];
495
+ if (inFence && /^ {0,3}[`~]{3,}/.test(raw)) continue;
496
+ let line = raw.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, '');
497
+ // Table rows ("| Unit tests (Karma + Jasmine) | `npm test` |") are read for test runners only.
498
+ const tableRow = /^\s*\|/.test(line) && !/^\s*\|[\s:|-]*$/.test(line);
499
+ if (tableRow) line = line.replace(/^\s*\||\|\s*$/g, '').split('|').join('; ');
500
+ if (!line.trim() || (!tableRow && /^\s*(#|\||>)/.test(line) && !/^\s*>\s*\S/.test(line))) continue;
501
+ // Compound lines are judged clause by clause ("Unit tests use Vitest; they sit in `app/x.ts`").
502
+ for (const clause of clausesOf(line)) {
503
+ const fullQual = mergeQuals(qualifierOf(clause), headings[i], ruleQual);
504
+ for (const det of LINE_DETECTORS) {
505
+ // "Unit tests use Vitest" and "Tests use Jest" are about the same thing: unit tests are what
506
+ // an unqualified "tests" rule means, so "unit" does not scope a test-runner claim.
507
+ const lineQual = det.id === 'test-runner' ? fullQual.split(',').filter((w) => w !== 'unit').join(',') : fullQual;
508
+ if (inFence && !det.fenceOk) continue;
509
+ if (tableRow && det.id !== 'test-runner') continue;
510
+ for (const claim of det.fn(clause)) {
511
+ // "Python 3.9+ (`requires-python` in libs/core/pyproject.toml)": a path that only says where
512
+ // the version comes from does not make the claim about that path.
513
+ const dq = det.id === 'node-version' || det.id === 'python-version' ? lineQual.split(',').filter((w) => !w.startsWith('path:')).join(',') : lineQual;
514
+ const qual = [claim.eco, dq].filter(Boolean).join(';');
515
+ const key = [det.id, claim.topic || '', group, scopeKey, qual, det.id === 'always-never' ? claim.value : ''].join('\u0000');
516
+ if (!topics.has(key)) topics.set(key, []);
517
+ topics.get(key).push({ ...claim, src, line: i + 1, det, group, qual });
518
+ }
519
+ }
520
+ }
521
+ }
522
+ }
523
+ const out = [];
524
+ for (const claims of topics.values()) {
525
+ const det = claims[0].det;
526
+ claims.sort((a, b) => (a.src.display === b.src.display ? a.line - b.line : a.src.display < b.src.display ? -1 : 1));
527
+ const group = claims[0].group;
528
+ const evidence = [];
529
+ let conflicting = [];
530
+ let note = '';
531
+ const firstPer = (arr, keyFn) => {
532
+ const m = new Map();
533
+ for (const c of arr) if (!m.has(keyFn(c))) m.set(keyFn(c), c);
534
+ return [...m.values()];
535
+ };
536
+ if (det.id === 'always-never') {
537
+ const pair = [];
538
+ for (const a of claims.filter((c) => c.polarity === 'always')) {
539
+ for (const b of claims.filter((c) => c.polarity === 'never')) if (!pair.length && !(a.forq && b.forq && a.forq !== b.forq)) pair.push(a, b);
540
+ }
541
+ conflicting = pair.sort((x, y) => claims.indexOf(x) - claims.indexOf(y));
542
+ } else if (det.id === 'node-version' || det.id === 'python-version') {
543
+ const ev = evidenceFor(ctx, group);
544
+ const evs = det.id === 'node-version' ? ev.node : ev.python;
545
+ const bad = new Set();
546
+ for (let a = 0; a < claims.length; a++) {
547
+ for (let b = a + 1; b < claims.length; b++) if (versionsConflict(claims[a].ver, claims[b].ver)) { bad.add(claims[a]); bad.add(claims[b]); }
548
+ for (const e of evs) if (versionsConflict(claims[a].ver, e.ver)) { bad.add(claims[a]); evidence.push(e); }
549
+ }
550
+ conflicting = firstPer([...bad].sort((x, y) => claims.indexOf(x) - claims.indexOf(y)), (c) => c.value);
551
+ if (evidence.length) note = ` (${evidence[0].label} in ${evidence[0].file})`;
552
+ } else if (det.id === 'indentation') {
553
+ const bad = new Set();
554
+ for (let a = 0; a < claims.length; a++) for (let b = a + 1; b < claims.length; b++) {
555
+ const x = claims[a].value;
556
+ const y = claims[b].value;
557
+ const conflict = (x === 'tabs') !== (y === 'tabs') || (x.startsWith('spaces:') && y.startsWith('spaces:') && x !== y);
558
+ if (x !== y && conflict) { bad.add(claims[a]); bad.add(claims[b]); }
559
+ }
560
+ conflicting = firstPer([...bad], (c) => c.value);
561
+ // An unqualified project rule against what the formatter config enforces.
562
+ const ind = evidenceFor(ctx, group).indent;
563
+ if (!conflicting.length && ind) {
564
+ const off = claims.filter((c) => !c.qual && c.src.scope !== 'user' && (c.value === 'tabs') !== (ind.style === 'tabs'));
565
+ if (off.length) {
566
+ conflicting = firstPer(off, (c) => c.value);
567
+ note = ` (${ind.file} sets ${ind.style === 'tabs' ? 'tabs' : 'spaces'})`;
568
+ evidence.push({ file: ind.file });
569
+ }
570
+ }
571
+ } else {
572
+ const values = new Set(claims.map((c) => c.value));
573
+ if (values.size > 1) conflicting = firstPer(claims, (c) => c.value);
574
+ if (det.id === 'package-manager') {
575
+ const ev = evidenceFor(ctx, group);
576
+ const lockPms = new Set(ev.lockfiles.map((l) => l.pm));
577
+ const authority = ev.packageManager ? ev.packageManager.pm : lockPms.size === 1 ? [...lockPms][0] : null;
578
+ if (authority) {
579
+ const off = claims.filter((c) => c.value !== authority);
580
+ if (conflicting.length === 0 && off.length) conflicting = firstPer(off, (c) => c.value);
581
+ const file = ev.packageManager ? ev.packageManager.file : ev.lockfiles[0].file;
582
+ if (conflicting.length) {
583
+ note = ev.packageManager ? ` (package.json packageManager says ${authority})` : ` (${file} is present, which is ${authority}'s lockfile)`;
584
+ evidence.push({ file });
585
+ }
586
+ }
587
+ } else if (det.id === 'formatter') {
588
+ const ev = evidenceFor(ctx, group);
589
+ const e = ev.formatter[0];
590
+ if (e && e.set.size === 1) {
591
+ const only = [...e.set][0];
592
+ const off = claims.filter((c) => c.value !== only);
593
+ if (conflicting.length === 0 && off.length) conflicting = firstPer(off, (c) => c.value);
594
+ if (conflicting.length) {
595
+ note = ` (${e.file} only configures ${only})`;
596
+ evidence.push({ file: e.file });
597
+ }
598
+ }
599
+ }
600
+ }
601
+ if (!conflicting.length) continue;
602
+ const crossScope = new Set(conflicting.map((c) => c.src.scope)).size > 1;
603
+ const first = conflicting[0];
604
+ // Two claims from one line ("Node 18 or newer; CI runs Node 20") agree with each other: show them
605
+ // together, so the message does not say they conflict.
606
+ const byLoc = new Map();
607
+ for (const c of conflicting) {
608
+ const label = det.id === 'always-never' ? `"${c.polarity} ${c.value}"` : c.value;
609
+ byLoc.set(loc(c), [...(byLoc.get(loc(c)) || []), label]);
610
+ }
611
+ const desc = [...byLoc].map(([where, labels]) => `${labels.join(' / ')} (${where})`).join(' vs ');
612
+ const topic = det.id === 'always-never' ? `${det.label} conflict` : `conflicting ${det.label}`;
613
+ out.push(finding('contradiction', crossScope ? 'info' : 'warn', first.src, first.line,
614
+ `${topic}: ${desc}${note}${crossScope ? ' [user scope vs project: the project may be meant to override]' : ''}`,
615
+ det.id === 'always-never' ? 'Keep one of the two rules and delete or reword the other.' : 'Decide which is right, then update every file to say the same thing (ideally keep it in one file and import it).',
616
+ [...new Map(conflicting.slice(1).map((c) => [loc(c), { file: c.src.display, line: c.line }])).entries()].filter(([where]) => where !== loc(first)).map(([, r]) => r).concat(evidence.map((e) => ({ file: e.file, line: null })))));
617
+ }
618
+ return out;
619
+ }