@cmodjs/rulebook 0.0.0-stage → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +53 -4
- package/src/agent.ts +146 -0
- package/src/api.ts +59 -0
- package/src/check.ts +304 -0
- package/src/claude-md.ts +160 -0
- package/src/config.ts +243 -0
- package/src/edit.ts +66 -0
- package/src/files.ts +103 -0
- package/src/linters.ts +338 -0
- package/src/lsp.ts +105 -0
- package/src/main.ts +106 -0
- package/src/modules.ts +20 -0
- package/src/questions.ts +98 -0
- package/src/report.ts +71 -0
- package/src/rules.ts +225 -0
- package/src/serve.ts +117 -0
- package/src/worker.ts +33 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cmodjs/rulebook",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.2",
|
|
4
|
+
"description": "Checks every file, reply, and tool call a Claude Code agent writes against your rules and linters before it lands.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/heyJordanParker/rulebook.git",
|
|
10
|
+
"directory": "cli"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"bin": {
|
|
16
|
+
"rulebook": "src/main.ts"
|
|
17
|
+
},
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/api.ts"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "bun build.ts",
|
|
26
|
+
"check": "tsc --noEmit",
|
|
27
|
+
"test": "bun test"
|
|
28
|
+
},
|
|
29
|
+
"cmod": {
|
|
30
|
+
"build": "bun run build",
|
|
31
|
+
"output": "dist"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/bun": "^1.2.21",
|
|
35
|
+
"@types/picomatch": "4.0.3",
|
|
36
|
+
"typescript": "^5.9.2"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@ast-grep/lang-bash": "0.0.8",
|
|
40
|
+
"@ast-grep/lang-json": "0.0.7",
|
|
41
|
+
"@ast-grep/lang-lua": "0.0.7",
|
|
42
|
+
"@ast-grep/lang-markdown": "0.0.6",
|
|
43
|
+
"@ast-grep/lang-php": "0.0.7",
|
|
44
|
+
"@ast-grep/lang-python": "0.0.6",
|
|
45
|
+
"@ast-grep/lang-toml": "0.0.9",
|
|
46
|
+
"@ast-grep/lang-yaml": "0.0.6",
|
|
47
|
+
"@ast-grep/napi": "0.51.1",
|
|
48
|
+
"@biomejs/biome": "2.6.4",
|
|
49
|
+
"diff": "9.0.0",
|
|
50
|
+
"marked": "15.0.0",
|
|
51
|
+
"oxlint": "1.86.0",
|
|
52
|
+
"picomatch": "4.0.7",
|
|
53
|
+
"stylelint": "17.15.0"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/agent.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { tmpdir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import type { Finding, PromptFile } from './api.ts'
|
|
5
|
+
import { isRecord } from './config.ts'
|
|
6
|
+
import type { AgenticRule } from './rules.ts'
|
|
7
|
+
|
|
8
|
+
const PLUGIN = 'rulebook-rule'
|
|
9
|
+
const SKILL = 'check'
|
|
10
|
+
|
|
11
|
+
const SCHEMA = {
|
|
12
|
+
type: 'object',
|
|
13
|
+
properties: {
|
|
14
|
+
findings: {
|
|
15
|
+
type: 'array',
|
|
16
|
+
items: {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: { line: { type: 'integer' }, message: { type: 'string' } },
|
|
19
|
+
required: ['line', 'message'],
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
required: ['findings'],
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const WRITE_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
|
|
27
|
+
|
|
28
|
+
function claudeProgram(): string {
|
|
29
|
+
const program = Bun.which('claude', { PATH: process.env.PATH ?? '' })
|
|
30
|
+
if (!program) throw new Error('rulebook runs agentic rules with Claude Code, and finds no claude on PATH.')
|
|
31
|
+
return program
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sessionArguments(plugin: string): string[] {
|
|
35
|
+
return [
|
|
36
|
+
'-p',
|
|
37
|
+
'--output-format', 'stream-json',
|
|
38
|
+
'--verbose',
|
|
39
|
+
'--json-schema', JSON.stringify(SCHEMA),
|
|
40
|
+
'--no-session-persistence',
|
|
41
|
+
'--permission-prompts', 'none',
|
|
42
|
+
'--settings', JSON.stringify({ disableAllHooks: true }),
|
|
43
|
+
'--plugin-dir', plugin,
|
|
44
|
+
'--model', 'haiku',
|
|
45
|
+
'--disallowedTools', ...WRITE_TOOLS,
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function ruleSkill(rule: AgenticRule, file: PromptFile, changed: readonly number[] | undefined): string {
|
|
50
|
+
const list = (tools: string | readonly string[] | undefined): string[] => (tools === undefined ? [] : typeof tools === 'string' ? tools.split(/[\s,]+/).filter((tool) => tool !== '') : [...tools])
|
|
51
|
+
const allowed = list(rule.allowedTools)
|
|
52
|
+
const frontmatter = {
|
|
53
|
+
name: SKILL,
|
|
54
|
+
description: rule.description,
|
|
55
|
+
context: 'fork',
|
|
56
|
+
...(rule.agent === undefined ? {} : { agent: rule.agent }),
|
|
57
|
+
...(rule.model === undefined ? {} : { model: rule.model }),
|
|
58
|
+
...(rule.effort === undefined ? {} : { effort: rule.effort }),
|
|
59
|
+
...(allowed.length === 0 ? {} : { 'allowed-tools': allowed }),
|
|
60
|
+
'disallowed-tools': [...WRITE_TOOLS, ...list(rule.disallowedTools)],
|
|
61
|
+
}
|
|
62
|
+
const width = String(file.lines.length).length
|
|
63
|
+
const numbered = file.lines.map((line, index) => `${String(index + 1).padStart(width)} | ${line}`).join('\n')
|
|
64
|
+
const edit = changed === undefined ? '' : `\n\nThis is the file as an edit will leave it. The edit wrote lines ${changed.length === 0 ? '(none, it only removed lines)' : changed.join(', ')}.`
|
|
65
|
+
return `---
|
|
66
|
+
${JSON.stringify(frontmatter)}
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
${rule.body}
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
Check the file \`${file.path}\` against the rule above. Its lines, numbered:
|
|
74
|
+
|
|
75
|
+
${numbered}${edit}
|
|
76
|
+
|
|
77
|
+
Answer only with a JSON object of the form {"findings": [{"line": <number>, "message": "<what the author changes>"}]}: one finding per line that breaks the rule. A line that follows the rule gets no finding, so never write a finding that says a line is fine. When every line follows the rule, answer {"findings": []}. Change no file.`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function runAgentic(rule: AgenticRule, file: PromptFile, root: string, changed: readonly number[] | undefined, deadline: AbortSignal): Promise<readonly Finding[]> {
|
|
81
|
+
const plugin = mkdtempSync(join(tmpdir(), 'rulebook-rule-'))
|
|
82
|
+
try {
|
|
83
|
+
mkdirSync(join(plugin, '.claude-plugin'))
|
|
84
|
+
writeFileSync(join(plugin, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: PLUGIN, version: '0.0.0', description: `Runs ${rule.id} for rulebook.` }))
|
|
85
|
+
mkdirSync(join(plugin, 'skills', SKILL), { recursive: true })
|
|
86
|
+
writeFileSync(join(plugin, 'skills', SKILL, 'SKILL.md'), ruleSkill(rule, file, changed))
|
|
87
|
+
return await runSession(plugin, root, deadline)
|
|
88
|
+
} finally {
|
|
89
|
+
rmSync(plugin, { recursive: true, force: true })
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function runSession(plugin: string, root: string, deadline: AbortSignal): Promise<readonly Finding[]> {
|
|
94
|
+
deadline.throwIfAborted()
|
|
95
|
+
const child = Bun.spawn([claudeProgram(), ...sessionArguments(plugin)], {
|
|
96
|
+
cwd: root,
|
|
97
|
+
env: process.env,
|
|
98
|
+
stdin: new Blob([`/${PLUGIN}:${SKILL}`]),
|
|
99
|
+
stdout: 'pipe',
|
|
100
|
+
stderr: 'pipe',
|
|
101
|
+
signal: deadline,
|
|
102
|
+
})
|
|
103
|
+
const passed = new Promise<never>((_, reject) => deadline.addEventListener('abort', () => reject(deadline.reason), { once: true }))
|
|
104
|
+
const finished = Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
|
|
105
|
+
const [stdout, stderr, exitCode] = await Promise.race([finished, passed])
|
|
106
|
+
if (exitCode !== 0 && stdout.trim() === '') throw new Error(`claude exited ${exitCode}: ${lastLine(stderr)}`)
|
|
107
|
+
return findingsOf(stdout)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function findingsOf(stdout: string): readonly Finding[] {
|
|
111
|
+
const events: unknown[] = stdout.trim().split('\n').map((line) => JSON.parse(line))
|
|
112
|
+
const answer = events.at(-1)
|
|
113
|
+
if (!isRecord(answer) || answer.type !== 'result') throw new Error('claude answered no result event')
|
|
114
|
+
if (answer.is_error === true) throw new Error(`claude failed: ${String(answer.result ?? answer.subtype ?? 'no reason')}`)
|
|
115
|
+
const structured = structuredOutputOf(events) ?? parsedResult(answer.result)
|
|
116
|
+
if (!isRecord(structured) || !Array.isArray(structured.findings)) throw new Error(`claude answered no findings: ${String(answer.result ?? '').slice(0, 200)}`)
|
|
117
|
+
return structured.findings.map((finding: unknown) => {
|
|
118
|
+
if (!isRecord(finding) || !Number.isInteger(finding.line) || typeof finding.message !== 'string') throw new Error(`claude answered a finding without a line and a message: ${JSON.stringify(finding)}`)
|
|
119
|
+
return { line: finding.line as number, message: finding.message }
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function structuredOutputOf(events: readonly unknown[]): unknown {
|
|
124
|
+
const answers = events.flatMap((event) => {
|
|
125
|
+
if (!isRecord(event)) return []
|
|
126
|
+
if (event.type === 'result' && isRecord(event.structured_output)) return [event.structured_output]
|
|
127
|
+
const content = isRecord(event.message) && Array.isArray(event.message.content) ? event.message.content : []
|
|
128
|
+
return content.filter((block: unknown) => isRecord(block) && block.type === 'tool_use' && block.name === 'StructuredOutput').map((block: Record<string, unknown>) => block.input)
|
|
129
|
+
})
|
|
130
|
+
return answers.at(-1)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function parsedResult(result: unknown): unknown {
|
|
134
|
+
if (typeof result !== 'string') return undefined
|
|
135
|
+
const json = /\{[\s\S]*\}/.exec(result)?.[0]
|
|
136
|
+
if (json === undefined) return undefined
|
|
137
|
+
try {
|
|
138
|
+
return JSON.parse(json)
|
|
139
|
+
} catch {
|
|
140
|
+
return undefined
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function lastLine(text: string): string {
|
|
145
|
+
return text.trim().split('\n').at(-1) ?? ''
|
|
146
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export type Level = 'error' | 'warning'
|
|
2
|
+
|
|
3
|
+
export type Runs = 'always' | 'manual'
|
|
4
|
+
|
|
5
|
+
export type PromptFile = {
|
|
6
|
+
readonly path: string
|
|
7
|
+
readonly text: string
|
|
8
|
+
readonly lines: readonly string[]
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type Finding = {
|
|
12
|
+
readonly line: number
|
|
13
|
+
readonly message?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type Rule = {
|
|
17
|
+
readonly description: string
|
|
18
|
+
readonly level?: Level
|
|
19
|
+
readonly runs?: Runs
|
|
20
|
+
readonly paths?: readonly string[]
|
|
21
|
+
check(file: PromptFile): readonly Finding[] | Promise<readonly Finding[]>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type RuleSettings = {
|
|
25
|
+
readonly level?: Level | 'off'
|
|
26
|
+
readonly runs?: Runs
|
|
27
|
+
readonly paths?: readonly string[]
|
|
28
|
+
readonly timeout?: number
|
|
29
|
+
readonly agent?: string
|
|
30
|
+
readonly model?: string
|
|
31
|
+
readonly effort?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type LinterName = 'mago' | 'oxlint' | 'biome' | 'stylelint' | 'ruff' | 'selene' | 'shellcheck'
|
|
35
|
+
|
|
36
|
+
export type Config = {
|
|
37
|
+
readonly extends?: readonly (string | Config)[]
|
|
38
|
+
readonly plugins?: Readonly<Record<string, string>>
|
|
39
|
+
readonly paths?: readonly string[]
|
|
40
|
+
readonly probes?: readonly string[]
|
|
41
|
+
readonly timeout?: number
|
|
42
|
+
readonly existingErrors?: Level
|
|
43
|
+
readonly rules?: Readonly<Record<string, Level | 'off' | RuleSettings>>
|
|
44
|
+
readonly linters?: readonly LinterName[]
|
|
45
|
+
readonly messages?: Readonly<Record<string, { readonly tools?: readonly string[]; readonly folder?: string }>>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function defineRule(rule: Rule): Rule {
|
|
49
|
+
return rule
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function defineConfig(config: Config): Config {
|
|
53
|
+
return config
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const recommended = defineConfig({
|
|
57
|
+
paths: ['**/{CLAUDE,Claude}.md', '**/{CLAUDE,Claude}.local.md', '**/AGENTS.md', '**/.claude/{rules,agents,commands,skills}/**/*.md'],
|
|
58
|
+
rules: { 'rulebook/imports': 'error' },
|
|
59
|
+
})
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
2
|
+
import { relative } from 'node:path'
|
|
3
|
+
import { diffArrays } from 'diff'
|
|
4
|
+
import picomatch from 'picomatch/posix'
|
|
5
|
+
import type { Finding, Level, LinterName, PromptFile } from './api.ts'
|
|
6
|
+
import { runAgentic } from './agent.ts'
|
|
7
|
+
import { importedFile, isClaudeMd, readClaudeMd } from './claude-md.ts'
|
|
8
|
+
import { isInside, type Settings } from './config.ts'
|
|
9
|
+
import { coveringLinters, LINTERS, lintFolder, lintText, projectLinters, type Covering, type ProjectLinter } from './linters.ts'
|
|
10
|
+
import { seconds } from './lsp.ts'
|
|
11
|
+
import type { LoadedRule, StaticRule } from './rules.ts'
|
|
12
|
+
|
|
13
|
+
type Scope = 'edit' | 'all' | 'static'
|
|
14
|
+
|
|
15
|
+
export type Reported = {
|
|
16
|
+
readonly rule: string
|
|
17
|
+
readonly line: number
|
|
18
|
+
readonly level: Level
|
|
19
|
+
readonly message: string
|
|
20
|
+
readonly quote: string
|
|
21
|
+
readonly isExisting: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
type Failure = { readonly rule: string; readonly reason: string }
|
|
25
|
+
|
|
26
|
+
export type FileReport = {
|
|
27
|
+
readonly path: string
|
|
28
|
+
readonly findings: readonly Reported[]
|
|
29
|
+
readonly failures: readonly Failure[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type CheckOptions = {
|
|
33
|
+
readonly scope: Scope
|
|
34
|
+
readonly previous?: string | undefined
|
|
35
|
+
readonly imported: () => Promise<ReadonlySet<string>>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const PIN = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
|
|
39
|
+
const MAX_EDIT_LENGTH = 1_000
|
|
40
|
+
|
|
41
|
+
function matches(globs: readonly string[], path: string): boolean {
|
|
42
|
+
return globs.some((glob) => globRegExp(glob).test(path))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const regExps = new Map<string, RegExp>()
|
|
46
|
+
|
|
47
|
+
export function globRegExp(glob: string): RegExp {
|
|
48
|
+
const known = regExps.get(glob)
|
|
49
|
+
if (known !== undefined) return known
|
|
50
|
+
const { source, flags } = picomatch.makeRe(glob, { dot: true, posix: true, strictSlashes: true })
|
|
51
|
+
const regExp = new RegExp(`${glob.startsWith('@') ? '(?=@)' : '(?!@)'}${source}`, flags)
|
|
52
|
+
regExps.set(glob, regExp)
|
|
53
|
+
return regExp
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function displayPath(settings: Settings, file: string): string {
|
|
57
|
+
if (file.startsWith('@')) return file
|
|
58
|
+
for (const [name, { folder }] of Object.entries(settings.messages)) {
|
|
59
|
+
if (folder !== undefined && isInside(folder, file)) return `@${name}/${relative(folder, file)}`
|
|
60
|
+
}
|
|
61
|
+
return isInside(settings.root, file) ? relative(settings.root, file) : file
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function isCovered(settings: Settings, rules: readonly LoadedRule[], file: string): boolean {
|
|
65
|
+
const path = displayPath(settings, file)
|
|
66
|
+
return rules.some((rule) => covers(rule, path, false))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isProbe(settings: Settings, file: string): boolean {
|
|
70
|
+
return settings.configs.some((config) => isInside(config.dir, file) && matches(config.probes, relative(config.dir, file)))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function isPrompt(settings: Settings, file: string): boolean {
|
|
74
|
+
return isInside(settings.root, file) && matches(settings.paths, relative(settings.root, file))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function checkFile(settings: Settings, rules: readonly LoadedRule[], file: string, text: string, options: CheckOptions): Promise<FileReport | undefined> {
|
|
78
|
+
const path = displayPath(settings, file)
|
|
79
|
+
const isMessage = path.startsWith('@')
|
|
80
|
+
const probe = !isMessage && isProbe(settings, file)
|
|
81
|
+
const configured = probe || (!isMessage && isPrompt(settings, file))
|
|
82
|
+
const isMemory = !isMessage && isClaudeMd(file)
|
|
83
|
+
const imported = !isMessage && !(configured && isMemory) && existsSync(file) && (await options.imported()).has(realpathSync(file))
|
|
84
|
+
const covered = rules.filter((rule) => inScope(rule, options.scope) && covers(rule, path, configured || imported))
|
|
85
|
+
const linted = !isMessage && !probe ? coveringLinters(settings.linters, file, text, settings.root) : []
|
|
86
|
+
if (!configured && !imported && covered.length === 0 && linted.length === 0) return undefined
|
|
87
|
+
const written = text.split('\n')
|
|
88
|
+
const isDoc = imported || isMemory
|
|
89
|
+
const mayPin = text.includes('rulebook-expect')
|
|
90
|
+
const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
|
|
91
|
+
const memory = isDoc ? claudeMd : undefined
|
|
92
|
+
const prompt: PromptFile = memory === undefined ? { path, text, lines: written } : { path, text: memory.lines.join('\n'), lines: memory.lines }
|
|
93
|
+
const doc = memory === undefined ? undefined : { file, imports: memory.imports }
|
|
94
|
+
const pins = mayPin ? pinsOf(written, claudeMd?.lines ?? []) : []
|
|
95
|
+
const pinned = new Set(pins.map(({ rule }) => rule))
|
|
96
|
+
const chosen = probe ? rules.filter((rule) => inScope(rule, options.scope) && pinned.has(rule.id)) : covered
|
|
97
|
+
const wrote = options.previous === undefined ? undefined : linesWritten(options.previous, written)
|
|
98
|
+
const changed = wrote === undefined ? undefined : [...wrote].filter((line) => written[line - 1]?.trim() !== '')
|
|
99
|
+
|
|
100
|
+
const linting = Promise.all((options.scope === 'edit' ? linted : []).map((linter) => linterFlags(linter, file, text, settings.timeout)))
|
|
101
|
+
const longest = Math.max(0, ...chosen.flatMap((rule) => (rule.kind === 'agentic' ? [rule.timeout] : [])))
|
|
102
|
+
const deadline = new AbortController()
|
|
103
|
+
const timer = longest === 0 ? undefined : setTimeout(() => deadline.abort(new Error(`it ran past ${seconds(longest)}`)), longest)
|
|
104
|
+
const runs = await Promise.all(chosen.map(async (rule) => {
|
|
105
|
+
try {
|
|
106
|
+
const found = rule.kind === 'static' ? await rule.check(prompt, doc) : await runAgentic(rule, prompt, settings.root, changed, deadline.signal)
|
|
107
|
+
return { rule, found: validFindings(rule.id, prompt, found) }
|
|
108
|
+
} catch (error) {
|
|
109
|
+
return { rule, failure: error instanceof Error ? error.message : String(error) }
|
|
110
|
+
}
|
|
111
|
+
})).finally(() => clearTimeout(timer))
|
|
112
|
+
|
|
113
|
+
const lints = await linting
|
|
114
|
+
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
115
|
+
const found = [...runs.flatMap((run) => ('found' in run ? run.found.map(({ line, message }) => ({ line, message: message ?? run.rule.description, rule: run.rule.id, level: run.rule.level === 'off' ? 'error' as const : run.rule.level })) : [])), ...lints.flatMap((lint) => lint.flags)]
|
|
116
|
+
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options.scope)).map(({ id }) => id))
|
|
117
|
+
const flagged = probe ? probeFindings(found, pins.filter(({ rule }) => !unscoped.has(rule))) : [...found, ...pins.map((pin) => ({ rule: 'rulebook/pins', line: pin.line, level: 'error' as const, message: 'A rulebook-expect pin works only in a probe file. Remove it.' }))]
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
path,
|
|
121
|
+
failures,
|
|
122
|
+
findings: flagged
|
|
123
|
+
.map((finding) => {
|
|
124
|
+
const quote = written[finding.line - 1] ?? ''
|
|
125
|
+
const isExisting = wrote !== undefined && !wrote.has(finding.line)
|
|
126
|
+
return { ...finding, quote, isExisting, level: isExisting && finding.level === 'error' ? settings.existingErrors : finding.level }
|
|
127
|
+
})
|
|
128
|
+
.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)),
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function lintProject(groups: ReadonlyMap<Settings, readonly string[]>, reports: readonly FileReport[], only?: readonly string[]): Promise<readonly FileReport[]> {
|
|
133
|
+
const linters = new Map<string, { readonly linter: ProjectLinter; readonly settings: Settings; readonly timeout: number }>()
|
|
134
|
+
for (const [settings, files] of groups) {
|
|
135
|
+
for (const linter of projectLinters(settings.linters, files, settings.root)) {
|
|
136
|
+
const key = `${linter.name}\0${linter.config ?? ''}`
|
|
137
|
+
const known = linters.get(key)
|
|
138
|
+
linters.set(key, known === undefined ? { linter, settings, timeout: settings.timeout } : { ...known, linter: { ...known.linter, files: [...known.linter.files, ...linter.files] }, timeout: Math.max(known.timeout, settings.timeout) })
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const runs = await Promise.all([...linters.values()].map(async ({ linter, settings, timeout }) => {
|
|
142
|
+
try {
|
|
143
|
+
return { linter, settings, found: await lintFolder(linter, timeout) }
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return { linter, settings, failure: error instanceof Error ? error.message : String(error) }
|
|
146
|
+
}
|
|
147
|
+
}))
|
|
148
|
+
const merged = new Map(reports.map(({ path, findings, failures }) => [path, { path, findings: [...findings], failures: [...failures] }]))
|
|
149
|
+
const reportOf = (path: string): { path: string; findings: Reported[]; failures: Failure[] } => {
|
|
150
|
+
const report = merged.get(path) ?? { path, findings: [], failures: [] }
|
|
151
|
+
merged.set(path, report)
|
|
152
|
+
return report
|
|
153
|
+
}
|
|
154
|
+
const lines = new Map<string, readonly string[]>()
|
|
155
|
+
for (const run of runs) {
|
|
156
|
+
if ('failure' in run) {
|
|
157
|
+
reportOf(displayPath(run.settings, run.linter.config ?? run.linter.folder) || '.').failures.push({ rule: run.linter.name, reason: run.failure })
|
|
158
|
+
continue
|
|
159
|
+
}
|
|
160
|
+
const linted = new Set(run.linter.files)
|
|
161
|
+
for (const { file, line, level, rule, message } of run.found) {
|
|
162
|
+
if (!linted.has(file) || (only !== undefined && !only.includes(file))) continue
|
|
163
|
+
const path = displayPath(run.settings, file)
|
|
164
|
+
if (!lines.has(file)) lines.set(file, existsSync(file) ? readFileSync(file, 'utf8').split('\n') : [])
|
|
165
|
+
reportOf(path).findings.push({ rule, line, message, level, quote: lines.get(file)?.[line - 1] ?? '', isExisting: false })
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return [...merged.values()].map((report) => ({ ...report, findings: report.findings.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)) }))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function linterFlags(linter: Covering, file: string, text: string, timeout: number): Promise<{ readonly flags: readonly Flag[]; readonly failures: readonly Failure[] }> {
|
|
172
|
+
try {
|
|
173
|
+
const found = await lintText(linter, file, text, timeout)
|
|
174
|
+
return { flags: found.map(({ line, level, rule, message }) => ({ line, rule, message, level })), failures: [] }
|
|
175
|
+
} catch (error) {
|
|
176
|
+
return { flags: [], failures: [{ rule: linter.name, reason: error instanceof Error ? error.message : String(error) }] }
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function covers(rule: LoadedRule, path: string, isPrompt: boolean): boolean {
|
|
181
|
+
return rule.level !== 'off' && (rule.paths === undefined ? isPrompt : matches(rule.paths, path))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function inScope(rule: LoadedRule, scope: Scope): boolean {
|
|
185
|
+
if (scope === 'all') return true
|
|
186
|
+
if (scope === 'static') return rule.kind === 'static'
|
|
187
|
+
return rule.runs === 'always'
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
type Pin = { readonly rule: string; readonly line: number; readonly target: number }
|
|
191
|
+
|
|
192
|
+
function pinsOf(written: readonly string[], shown: readonly string[]): readonly Pin[] {
|
|
193
|
+
const pins: Pin[] = []
|
|
194
|
+
const waiting: { rule: string; line: number }[] = []
|
|
195
|
+
written.forEach((text, index) => {
|
|
196
|
+
const rule = PIN.test(shown[index] ?? '') ? undefined : PIN.exec(text)?.[1]
|
|
197
|
+
if (rule !== undefined) waiting.push({ rule, line: index + 1 })
|
|
198
|
+
else for (const pin of waiting.splice(0)) pins.push({ ...pin, target: index + 1 })
|
|
199
|
+
})
|
|
200
|
+
return [...pins, ...waiting.map((pin) => ({ ...pin, target: written.length + 1 }))]
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function linesWritten(previous: string, written: readonly string[]): ReadonlySet<number> {
|
|
204
|
+
const before = withoutFinalBlank(previous.split('\n'))
|
|
205
|
+
const after = withoutFinalBlank(written)
|
|
206
|
+
let start = 0
|
|
207
|
+
while (start < before.length && start < after.length && before[start] === after[start]) start += 1
|
|
208
|
+
let end = 0
|
|
209
|
+
while (end < before.length - start && end < after.length - start && before[before.length - 1 - end] === after[after.length - 1 - end]) end += 1
|
|
210
|
+
const oldMiddle = before.slice(start, before.length - end)
|
|
211
|
+
const newMiddle = after.slice(start, after.length - end)
|
|
212
|
+
const parts = unmatchedLines(oldMiddle, newMiddle) > MAX_EDIT_LENGTH ? undefined : diffArrays(oldMiddle, newMiddle, { maxEditLength: MAX_EDIT_LENGTH })
|
|
213
|
+
if (parts === undefined) return new Set(written.map((_, index) => index + 1))
|
|
214
|
+
const lines = new Set<number>()
|
|
215
|
+
let line = start + 1
|
|
216
|
+
for (const { added, removed, count } of parts) {
|
|
217
|
+
if (removed) continue
|
|
218
|
+
if (added) for (let each = line; each < line + count; each += 1) lines.add(each)
|
|
219
|
+
line += count
|
|
220
|
+
}
|
|
221
|
+
return lines
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function withoutFinalBlank(lines: readonly string[]): readonly string[] {
|
|
225
|
+
return lines.at(-1) === '' ? lines.slice(0, -1) : lines
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function unmatchedLines(before: readonly string[], after: readonly string[]): number {
|
|
229
|
+
const unpaired = new Map<string, number>()
|
|
230
|
+
for (const line of before) unpaired.set(line, (unpaired.get(line) ?? 0) + 1)
|
|
231
|
+
let paired = 0
|
|
232
|
+
for (const line of after) {
|
|
233
|
+
const count = unpaired.get(line) ?? 0
|
|
234
|
+
if (count === 0) continue
|
|
235
|
+
unpaired.set(line, count - 1)
|
|
236
|
+
paired += 1
|
|
237
|
+
}
|
|
238
|
+
return before.length + after.length - 2 * paired
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function importsRule(settings: Settings): StaticRule {
|
|
242
|
+
return {
|
|
243
|
+
id: 'rulebook/imports',
|
|
244
|
+
source: 'rulebook',
|
|
245
|
+
kind: 'static',
|
|
246
|
+
description: 'Import only files that exist.',
|
|
247
|
+
level: 'off',
|
|
248
|
+
runs: 'always',
|
|
249
|
+
paths: undefined,
|
|
250
|
+
check: (_, doc) => (doc === undefined ? [] : doc.imports.flatMap(({ path, line }) => {
|
|
251
|
+
const target = importedFile(doc.file, path)
|
|
252
|
+
if (target === undefined || statSync(target, { throwIfNoEntry: false })?.isFile() === true) return []
|
|
253
|
+
return [{ line, message: `The import names ${displayPath(settings, target)}, which is not a file. Fix the path or remove the import.` }]
|
|
254
|
+
})),
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const SUPPRESSIONS: Readonly<Record<LinterName, RegExp>> = {
|
|
259
|
+
mago: /(?:\/\/|#|\*)\s*@mago-(?:expect|ignore)\b/,
|
|
260
|
+
oxlint: /(?:\/\/|\/\*)\s*(?:oxlint|eslint)-disable\b/,
|
|
261
|
+
biome: /(?:\/\/|\/\*)\s*biome-ignore(?:-all|-start)?(?![\w-])/,
|
|
262
|
+
stylelint: /(?:\/\/|\/\*)\s*stylelint-disable\b/,
|
|
263
|
+
ruff: /#\s*(?:(?:ruff|flake8):\s*)?noqa\b|#\s*ruff:\s*(?:ignore|disable|file-ignore)\[/i,
|
|
264
|
+
selene: /--#?\s*selene:\s*allow\(/,
|
|
265
|
+
shellcheck: /#\s*shellcheck\s.*\bdisable=/,
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export const noSuppressionsRule: StaticRule = {
|
|
269
|
+
id: 'rulebook/no-suppressions',
|
|
270
|
+
source: 'rulebook',
|
|
271
|
+
kind: 'static',
|
|
272
|
+
description: 'Fix the code instead of suppressing the rule.',
|
|
273
|
+
level: 'off',
|
|
274
|
+
runs: 'always',
|
|
275
|
+
paths: [`**/*.{${[...new Set(Object.values(LINTERS).flatMap(({ extensions }) => extensions.map((extension) => extension.slice(1))))].join(',')}}`, '**/!(*.*)'],
|
|
276
|
+
check: ({ lines }) => lines.flatMap((text, index) => {
|
|
277
|
+
const linter = Object.entries(SUPPRESSIONS).find(([, suppression]) => suppression.test(text))?.[0]
|
|
278
|
+
return linter === undefined ? [] : [{ line: index + 1, message: `This comment suppresses ${linter}. Fix the code ${linter} flags, and remove the comment.` }]
|
|
279
|
+
}),
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
type Flag = Omit<Reported, 'isExisting' | 'quote'>
|
|
283
|
+
|
|
284
|
+
function probeFindings(found: readonly Flag[], pins: readonly Pin[]): readonly Flag[] {
|
|
285
|
+
const open = [...pins]
|
|
286
|
+
const unexpected = found.filter((finding) => {
|
|
287
|
+
const index = open.findIndex((pin) => pin.rule === finding.rule && pin.target === finding.line)
|
|
288
|
+
if (index === -1) return true
|
|
289
|
+
open.splice(index, 1)
|
|
290
|
+
return false
|
|
291
|
+
})
|
|
292
|
+
return [
|
|
293
|
+
...unexpected.map((finding) => ({ ...finding, level: 'error' as const, message: `${finding.message} (no pin expects this flag)` })),
|
|
294
|
+
...open.map((pin) => ({ rule: pin.rule, line: pin.line, level: 'error' as const, message: `The pin expects ${pin.rule} to flag line ${pin.target}, and it does not.` })),
|
|
295
|
+
]
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function validFindings(rule: string, file: PromptFile, found: readonly Finding[]): readonly Finding[] {
|
|
299
|
+
for (const finding of found) {
|
|
300
|
+
if (!Number.isInteger(finding.line) || finding.line < 1 || finding.line > file.lines.length) throw new Error(`${rule} flagged line ${finding.line}, which ${file.path} does not have`)
|
|
301
|
+
if (finding.message !== undefined && (typeof finding.message !== 'string' || finding.message.trim() === '')) throw new Error(`${rule} flagged line ${finding.line} with a blank message. Write the message, or leave it out to show the rule's description`)
|
|
302
|
+
}
|
|
303
|
+
return found
|
|
304
|
+
}
|