diff --git a/scanners/rules-validator.mjs b/scanners/rules-validator.mjs index 3bd358f..e277132 100644 --- a/scanners/rules-validator.mjs +++ b/scanners/rules-validator.mjs @@ -10,7 +10,7 @@ import { SEVERITY } from './lib/severity.mjs'; import { parseFrontmatter } from './lib/yaml-parser.mjs'; import { lineCount, truncate } from './lib/string-utils.mjs'; import { readdir, stat } from 'node:fs/promises'; -import { join, resolve, relative } from 'node:path'; +import { join, resolve, relative, sep } from 'node:path'; const SCANNER = 'RUL'; @@ -30,8 +30,16 @@ export async function scan(targetPath, discovery) { return scannerResult(SCANNER, 'skipped', [], 0, Date.now() - start); } - // Collect all real files in the project for glob matching - const projectFiles = await collectProjectFiles(targetPath); + // Rule path patterns scope relative to the rule's OWN project root (the dir + // containing its .claude/), not the outer scan root. Resolve + cache per root. + const home = process.env.HOME || process.env.USERPROFILE || ''; + const projectFilesByRoot = new Map(); + async function projectFilesFor(root) { + if (!projectFilesByRoot.has(root)) { + projectFilesByRoot.set(root, await collectProjectFiles(root)); + } + return projectFilesByRoot.get(root); + } for (const file of ruleFiles) { const content = await readTextFile(file.absPath); @@ -74,22 +82,32 @@ export async function scan(targetPath, discovery) { if (paths) { const patterns = Array.isArray(paths) ? paths : [paths]; - for (const pattern of patterns) { - if (typeof pattern !== 'string') continue; + // A rule scopes relative to its own project root (parent of its .claude/), + // not the scan root. User-global rules (root === HOME) match against the + // active project at runtime, so "matches no files here" is not meaningful. + const projectRoot = deriveProjectRoot(file.absPath) || targetPath; + const isUserGlobal = home && projectRoot === home; - // Check if pattern matches any real files - const matchCount = countGlobMatches(pattern, projectFiles, targetPath); - if (matchCount === 0) { - findings.push(finding({ - scanner: SCANNER, - severity: SEVERITY.high, - title: 'Rule path pattern matches no files', - description: `${file.relPath}: pattern "${pattern}" matches 0 files. This rule will never activate.`, - file: file.absPath, - evidence: `paths: "${pattern}"`, - recommendation: 'Check the glob pattern. Common issues: wrong directory name, missing **, incorrect extension.', - autoFixable: false, - })); + if (!isUserGlobal) { + const projectFiles = await projectFilesFor(projectRoot); + + for (const pattern of patterns) { + if (typeof pattern !== 'string') continue; + + // Check if pattern matches any real files (relative to the rule's root) + const matchCount = countGlobMatches(pattern, projectFiles, projectRoot); + if (matchCount === 0) { + findings.push(finding({ + scanner: SCANNER, + severity: SEVERITY.high, + title: 'Rule path pattern matches no files', + description: `${file.relPath}: pattern "${pattern}" matches 0 files. This rule will never activate.`, + file: file.absPath, + evidence: `paths: "${pattern}"`, + recommendation: 'Check the glob pattern. Common issues: wrong directory name, missing **, incorrect extension.', + autoFixable: false, + })); + } } } } @@ -195,6 +213,18 @@ async function collectProjectFiles(targetPath, depth = 0) { * @param {string} basePath * @returns {number} */ +/** + * Resolve the project root a rule scopes against: the directory containing the + * `.claude/` dir the rule lives under. `/a/b/.claude/rules/x.md` → `/a/b`. + * Returns null if the path has no `.claude` segment. + */ +function deriveProjectRoot(ruleAbsPath) { + const parts = ruleAbsPath.split(sep); + const idx = parts.lastIndexOf('.claude'); + if (idx <= 0) return null; + return parts.slice(0, idx).join(sep); +} + function countGlobMatches(pattern, files, basePath) { try { const regex = globToRegex(pattern); diff --git a/tests/scanners/rules-validator.test.mjs b/tests/scanners/rules-validator.test.mjs index c3fedab..4cf9390 100644 --- a/tests/scanners/rules-validator.test.mjs +++ b/tests/scanners/rules-validator.test.mjs @@ -200,3 +200,94 @@ describe('RUL — block-sequence-scoped rule is correctly scoped (parser regress assert.equal(f.severity, 'low'); }); }); + +describe('RUL — nested-repo rule glob resolves to its own project root (M-BUG-9)', () => { + // A rule living in a NESTED repo's .claude/rules/ scopes its paths: pattern + // relative to that nested repo's root — NOT relative to the outer scan root. + // Before the fix, countGlobMatches globbed against the scan root and + // collectProjectFiles' depth>4 cutoff never reached the deep matching files, + // so a live rule was wrongly flagged "matches no files / never activates". + // (Real-machine surface: ~/.claude/plugins/marketplaces/ktg-privat/.claude/rules/.) + let tmpRoot; + let result; + + async function writeNestedRepo(scanRoot) { + // Nested repo sits 3 dirs below the scan root → its matching files land + // past the old depth>4 cutoff when walked from the scan root. + const nested = join(scanRoot, 'level1', 'level2', 'nested-repo'); + await mkdir(join(nested, '.claude', 'rules'), { recursive: true }); + await mkdir(join(nested, 'plugins', 'app'), { recursive: true }); + await mkdir(join(nested, 'plugins', 'app', 'hooks'), { recursive: true }); + // Files that the rule patterns match — relative to the NESTED repo root. + await writeFile(join(nested, 'plugins', 'app', 'CLAUDE.md'), '# App\n', 'utf8'); + await writeFile(join(nested, 'plugins', 'app', 'hooks', 'hooks.json'), '{}\n', 'utf8'); + // Two rules mirroring the real ktg-privat ones. + await writeFile( + join(nested, '.claude', 'rules', 'plugin-convention.md'), + '---\npaths: "plugins/*/CLAUDE.md"\n---\n\n# Convention\nbody\n', + 'utf8', + ); + await writeFile( + join(nested, '.claude', 'rules', 'hook-format.md'), + '---\npaths: "**/hooks/hooks.json"\n---\n\n# Hook format\nbody\n', + 'utf8', + ); + } + + beforeEach(async () => { + resetCounter(); + tmpRoot = await mkdtemp(join(tmpdir(), 'ca-rul-nested-')); + await writeNestedRepo(tmpRoot); + const discovery = await discoverConfigFiles(tmpRoot); + result = await scan(tmpRoot, discovery); + }); + + afterEach(async () => { + if (tmpRoot) await rm(tmpRoot, { recursive: true, force: true }); + }); + + it('does NOT flag the nested rules as "matches no files"', () => { + const dead = result.findings.filter(f => f.title.includes('matches no files')); + assert.equal( + dead.length, + 0, + `nested-repo rules matched real files but were flagged dead: ${dead.map(f => f.evidence).join(' | ')}`, + ); + }); +}); + +describe('RUL — user-global rule is not flagged "matches no files" (M-BUG-9 guard)', () => { + // A user-global ~/.claude/rules/ rule scopes against whatever project is + // active at runtime, not a fixed tree — so "matches 0 files here" is not a + // meaningful dead-rule signal and must not be flagged (and must not trigger a + // HOME-wide file walk). + let tmpHome; + let savedHome; + let result; + + beforeEach(async () => { + resetCounter(); + tmpHome = await mkdtemp(join(tmpdir(), 'ca-rul-home-')); + savedHome = process.env.HOME; + process.env.HOME = tmpHome; + await mkdir(join(tmpHome, '.claude', 'rules'), { recursive: true }); + await writeFile( + join(tmpHome, '.claude', 'rules', 'global.md'), + '---\npaths: "src/**/*.rs"\n---\n\n# Global rust rule\nbody\n', + 'utf8', + ); + // Scan from HOME so the rule is discovered AND its derived project root === HOME. + const discovery = await discoverConfigFiles(tmpHome); + result = await scan(tmpHome, discovery); + }); + + afterEach(async () => { + process.env.HOME = savedHome; + if (tmpHome) await rm(tmpHome, { recursive: true, force: true }); + }); + + it('does NOT flag a user-global rule as "matches no files"', () => { + const dead = result.findings.filter(f => f.title.includes('matches no files')); + assert.equal(dead.length, 0, `user-global rule wrongly flagged dead: ${dead.map(f => f.evidence).join(' | ')}`); + }); +});