@cmodjs/rulebook 0.3.0 → 0.5.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.
- package/package.json +2 -2
- package/src/agent.ts +3 -3
- package/src/api.ts +7 -4
- package/src/check.ts +20 -11
- package/src/commit.ts +140 -0
- package/src/config.ts +10 -3
- package/src/edit.ts +16 -15
- package/src/jev.ts +2 -2
- package/src/linters.ts +164 -38
- package/src/main.ts +79 -27
- package/src/questions.ts +28 -8
- package/src/report.ts +13 -2
- package/src/rules.ts +8 -4
- package/src/serve.ts +3 -3
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cmodjs/rulebook",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Checks every file, reply,
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Checks every file, reply, tool call, and commit against your rules and linters before it lands.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
package/src/agent.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { tmpdir } from 'node:os'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
|
-
import type { Finding,
|
|
4
|
+
import type { Finding, CheckedFile } from './api.ts'
|
|
5
5
|
import { isRecord } from './config.ts'
|
|
6
6
|
import type { AgenticRule } from './rules.ts'
|
|
7
7
|
|
|
@@ -46,7 +46,7 @@ function sessionArguments(plugin: string): string[] {
|
|
|
46
46
|
]
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
function ruleSkill(rule: AgenticRule, file:
|
|
49
|
+
function ruleSkill(rule: AgenticRule, file: CheckedFile, changed: readonly number[] | undefined): string {
|
|
50
50
|
const list = (tools: string | readonly string[] | undefined): string[] => (tools === undefined ? [] : typeof tools === 'string' ? tools.split(/[\s,]+/).filter((tool) => tool !== '') : [...tools])
|
|
51
51
|
const allowed = list(rule.allowedTools)
|
|
52
52
|
const frontmatter = {
|
|
@@ -77,7 +77,7 @@ ${numbered}${edit}
|
|
|
77
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
78
|
}
|
|
79
79
|
|
|
80
|
-
export async function runAgentic(rule: AgenticRule, file:
|
|
80
|
+
export async function runAgentic(rule: AgenticRule, file: CheckedFile, root: string, changed: readonly number[] | undefined, deadline: AbortSignal): Promise<readonly Finding[]> {
|
|
81
81
|
const plugin = mkdtempSync(join(tmpdir(), 'rulebook-rule-'))
|
|
82
82
|
try {
|
|
83
83
|
mkdirSync(join(plugin, '.claude-plugin'))
|
package/src/api.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
export type Level = 'error' | 'warning'
|
|
2
2
|
|
|
3
|
-
export type Runs = 'always' | 'manual'
|
|
3
|
+
export type Runs = 'always' | 'commit' | 'manual'
|
|
4
4
|
|
|
5
|
-
export type
|
|
5
|
+
export type CheckedFile = {
|
|
6
|
+
readonly root: string
|
|
6
7
|
readonly path: string
|
|
7
8
|
readonly text: string
|
|
8
9
|
readonly lines: readonly string[]
|
|
10
|
+
readonly input?: Readonly<Record<string, unknown>>
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export type Finding = {
|
|
@@ -18,7 +20,7 @@ export type Rule = {
|
|
|
18
20
|
readonly level?: Level
|
|
19
21
|
readonly runs?: Runs
|
|
20
22
|
readonly paths?: readonly string[]
|
|
21
|
-
check(file:
|
|
23
|
+
check(file: CheckedFile): readonly Finding[] | Promise<readonly Finding[]>
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
export type RuleSettings = {
|
|
@@ -32,7 +34,7 @@ export type RuleSettings = {
|
|
|
32
34
|
readonly threshold?: number
|
|
33
35
|
}
|
|
34
36
|
|
|
35
|
-
export type LinterName = 'mago' | 'oxlint' | 'biome' | 'stylelint' | 'ruff' | 'selene' | 'shellcheck'
|
|
37
|
+
export type LinterName = 'mago' | 'oxlint' | 'biome' | 'stylelint' | 'ruff' | 'selene' | 'shellcheck' | 'pint' | 'tsc'
|
|
36
38
|
|
|
37
39
|
export type Config = {
|
|
38
40
|
readonly extends?: readonly (string | Config)[]
|
|
@@ -43,6 +45,7 @@ export type Config = {
|
|
|
43
45
|
readonly existingErrors?: Level
|
|
44
46
|
readonly rules?: Readonly<Record<string, Level | 'off' | RuleSettings>>
|
|
45
47
|
readonly linters?: readonly LinterName[]
|
|
48
|
+
readonly programs?: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
|
46
49
|
readonly messages?: Readonly<Record<string, { readonly tools?: readonly string[]; readonly folder?: string }>>
|
|
47
50
|
}
|
|
48
51
|
|
package/src/check.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
|
2
2
|
import { relative } from 'node:path'
|
|
3
3
|
import { diffArrays } from 'diff'
|
|
4
4
|
import picomatch from 'picomatch/posix'
|
|
5
|
-
import type { Finding, Level, LinterName,
|
|
5
|
+
import type { Finding, Level, LinterName, CheckedFile } from './api.ts'
|
|
6
6
|
import { runAgentic } from './agent.ts'
|
|
7
7
|
import { importedFile, isClaudeMd, readClaudeMd } from './claude-md.ts'
|
|
8
8
|
import { isInside, type Settings } from './config.ts'
|
|
@@ -11,7 +11,7 @@ import { coveringLinters, LINTERS, lintFolder, lintText, projectLinters, type Co
|
|
|
11
11
|
import { seconds } from './lsp.ts'
|
|
12
12
|
import type { LoadedRule, StaticRule } from './rules.ts'
|
|
13
13
|
|
|
14
|
-
type Scope = 'edit' | '
|
|
14
|
+
type Scope = 'edit' | 'commit' | 'all'
|
|
15
15
|
|
|
16
16
|
export type Reported = {
|
|
17
17
|
readonly rule: string
|
|
@@ -34,6 +34,8 @@ type CheckOptions = {
|
|
|
34
34
|
readonly scope: Scope
|
|
35
35
|
readonly previous?: string | undefined
|
|
36
36
|
readonly imported: () => Promise<ReadonlySet<string>>
|
|
37
|
+
readonly input?: Readonly<Record<string, unknown>>
|
|
38
|
+
readonly skip?: readonly string[]
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
const PIN = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
|
|
@@ -82,19 +84,19 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
82
84
|
const configured = probe || (!isMessage && isPrompt(settings, file))
|
|
83
85
|
const isMemory = !isMessage && isClaudeMd(file)
|
|
84
86
|
const imported = !isMessage && !(configured && isMemory) && existsSync(file) && (await options.imported()).has(realpathSync(file))
|
|
85
|
-
const covered = rules.filter((rule) => inScope(rule, options
|
|
86
|
-
const linted = !isMessage && !probe ? coveringLinters(settings.linters, file, text, settings.root) : []
|
|
87
|
+
const covered = rules.filter((rule) => inScope(rule, options) && covers(rule, path, configured || imported))
|
|
88
|
+
const linted = !isMessage && !probe ? coveringLinters(settings.linters.filter((name) => !isSkipped(options.skip, name)), settings.programs, file, text, settings.root) : []
|
|
87
89
|
if (!configured && !imported && covered.length === 0 && linted.length === 0) return undefined
|
|
88
90
|
const written = text.split('\n')
|
|
89
91
|
const isDoc = imported || isMemory
|
|
90
92
|
const mayPin = text.includes('rulebook-expect')
|
|
91
93
|
const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
|
|
92
94
|
const memory = isDoc ? claudeMd : undefined
|
|
93
|
-
const prompt:
|
|
95
|
+
const prompt: CheckedFile = { root: settings.root, path, ...(memory === undefined ? { text, lines: written } : { text: memory.lines.join('\n'), lines: memory.lines }), ...(options.input === undefined ? {} : { input: options.input }) }
|
|
94
96
|
const doc = memory === undefined ? undefined : { file, imports: memory.imports }
|
|
95
97
|
const pins = mayPin ? pinsOf(written, claudeMd?.lines ?? []) : []
|
|
96
98
|
const pinned = new Set(pins.map(({ rule }) => rule))
|
|
97
|
-
const chosen = probe ? rules.filter((rule) => inScope(rule, options
|
|
99
|
+
const chosen = probe ? rules.filter((rule) => inScope(rule, options) && pinned.has(rule.id)) : covered
|
|
98
100
|
const wrote = options.previous === undefined ? undefined : linesWritten(options.previous, written)
|
|
99
101
|
const changed = wrote === undefined ? undefined : [...wrote].filter((line) => written[line - 1]?.trim() !== '')
|
|
100
102
|
|
|
@@ -114,7 +116,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
114
116
|
const lints = await linting
|
|
115
117
|
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
116
118
|
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)]
|
|
117
|
-
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options
|
|
119
|
+
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
|
|
118
120
|
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.' }))]
|
|
119
121
|
|
|
120
122
|
return {
|
|
@@ -133,7 +135,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
133
135
|
export async function lintProject(groups: ReadonlyMap<Settings, readonly string[]>, reports: readonly FileReport[], only?: readonly string[]): Promise<readonly FileReport[]> {
|
|
134
136
|
const linters = new Map<string, { readonly linter: ProjectLinter; readonly settings: Settings; readonly timeout: number }>()
|
|
135
137
|
for (const [settings, files] of groups) {
|
|
136
|
-
for (const linter of projectLinters(settings.linters, files, settings.root)) {
|
|
138
|
+
for (const linter of projectLinters(settings.linters, settings.programs, files, settings.root)) {
|
|
137
139
|
const key = `${linter.name}\0${linter.config ?? ''}`
|
|
138
140
|
const known = linters.get(key)
|
|
139
141
|
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) })
|
|
@@ -182,12 +184,17 @@ function covers(rule: LoadedRule, path: string, isPrompt: boolean): boolean {
|
|
|
182
184
|
return rule.level !== 'off' && (rule.paths === undefined ? isPrompt : matches(rule.paths, path))
|
|
183
185
|
}
|
|
184
186
|
|
|
185
|
-
function inScope(rule: LoadedRule, scope:
|
|
187
|
+
function inScope(rule: LoadedRule, { scope, skip }: CheckOptions): boolean {
|
|
188
|
+
if (isSkipped(skip, rule.id) || (rule.kind === 'agentic' && isSkipped(skip, 'agentic'))) return false
|
|
186
189
|
if (scope === 'all') return true
|
|
187
|
-
if (scope === '
|
|
190
|
+
if (scope === 'commit') return rule.runs !== 'manual'
|
|
188
191
|
return rule.runs === 'always'
|
|
189
192
|
}
|
|
190
193
|
|
|
194
|
+
export function isSkipped(skip: readonly string[] | undefined, name: string): boolean {
|
|
195
|
+
return skip?.some((skipped) => name === skipped || name.startsWith(`${skipped}/`)) ?? false
|
|
196
|
+
}
|
|
197
|
+
|
|
191
198
|
type Pin = { readonly rule: string; readonly line: number; readonly target: number }
|
|
192
199
|
|
|
193
200
|
function pinsOf(written: readonly string[], shown: readonly string[]): readonly Pin[] {
|
|
@@ -264,6 +271,8 @@ const SUPPRESSIONS: Readonly<Record<LinterName, RegExp>> = {
|
|
|
264
271
|
ruff: /#\s*(?:(?:ruff|flake8):\s*)?noqa\b|#\s*ruff:\s*(?:ignore|disable|file-ignore)\[/i,
|
|
265
272
|
selene: /--#?\s*selene:\s*allow\(/,
|
|
266
273
|
shellcheck: /#\s*shellcheck\s.*\bdisable=/,
|
|
274
|
+
pint: /(?:\/\/|\*)\s*@php-cs-fixer-ignore\b/,
|
|
275
|
+
tsc: /(?:\/\/|\/\*)\s*@ts-(?:expect-error|ignore|nocheck)\b/,
|
|
267
276
|
}
|
|
268
277
|
|
|
269
278
|
export const noSuppressionsRule: StaticRule = {
|
|
@@ -296,7 +305,7 @@ function probeFindings(found: readonly Flag[], pins: readonly Pin[]): readonly F
|
|
|
296
305
|
]
|
|
297
306
|
}
|
|
298
307
|
|
|
299
|
-
function validFindings(rule: string, file:
|
|
308
|
+
function validFindings(rule: string, file: CheckedFile, found: readonly Finding[]): readonly Finding[] {
|
|
300
309
|
for (const finding of found) {
|
|
301
310
|
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`)
|
|
302
311
|
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`)
|
package/src/commit.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
|
|
2
|
+
import { constants, tmpdir } from 'node:os'
|
|
3
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
4
|
+
import type { LinterName } from './api.ts'
|
|
5
|
+
import { checkFile, isSkipped, lintProject, type FileReport, type Reported } from './check.ts'
|
|
6
|
+
import { isInside, loadSettings } from './config.ts'
|
|
7
|
+
import { filesBySettings, loadImportedFiles } from './files.ts'
|
|
8
|
+
import { isLinterInput, LINTERS, projectLinters } from './linters.ts'
|
|
9
|
+
import { loadRules } from './rules.ts'
|
|
10
|
+
|
|
11
|
+
export type CommitReport = { readonly reports: readonly FileReport[]; readonly failures: readonly string[] }
|
|
12
|
+
|
|
13
|
+
const DEPENDENCIES = new Set(Object.values(LINTERS).flatMap(({ copies }) => copies.map((copy) => copy.split('/')[0] ?? copy)))
|
|
14
|
+
const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
|
|
15
|
+
|
|
16
|
+
export async function checkStaged(root: string, skip: readonly string[]): Promise<CommitReport> {
|
|
17
|
+
const unloaded = new Set<string>()
|
|
18
|
+
const staged = await gitPaths(root, ['diff', '--cached', '--name-only', '-z', '--diff-filter=ACMR'])
|
|
19
|
+
const deleted = await gitPaths(root, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--diff-filter=D'])
|
|
20
|
+
const renamed = await renamedFrom(root)
|
|
21
|
+
const checked = await Promise.all(staged.map(async (path) => {
|
|
22
|
+
const text = await git(root, ['show', `:${path}`])
|
|
23
|
+
if (text.slice(0, 8000).includes('\0')) return undefined
|
|
24
|
+
const file = join(root, path)
|
|
25
|
+
const settings = await loadSettings(dirname(file), root)
|
|
26
|
+
const { rules, failures } = await loadRules(settings)
|
|
27
|
+
for (const failure of failures) unloaded.add(failure)
|
|
28
|
+
return checkFile(settings, rules, file, text, { scope: 'commit', previous: await committed(root, renamed.get(path) ?? path), imported: () => loadImportedFiles(root), skip })
|
|
29
|
+
}))
|
|
30
|
+
const reports = checked.filter((report) => report !== undefined)
|
|
31
|
+
const linters = new Set((await Promise.all([...staged, ...deleted].map((path) => lintersCovering(root, path)))).flat().filter((name) => !isSkipped(skip, name)))
|
|
32
|
+
return { reports: linters.size === 0 ? reports : withAddedErrors(reports, await addedErrors(root, linters, renamed)), failures: [...unloaded] }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function renamedFrom(root: string): Promise<ReadonlyMap<string, string>> {
|
|
36
|
+
const fields = await gitPaths(root, ['diff', '--cached', '-z', '--name-status', '--diff-filter=R'])
|
|
37
|
+
return new Map(fields.flatMap((field, index) => (index % 3 === 2 ? [[field, fields[index - 1] ?? field] as const] : [])))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function lintersCovering(root: string, path: string): Promise<readonly LinterName[]> {
|
|
41
|
+
const file = join(root, path)
|
|
42
|
+
const { linters, programs } = await loadSettings(dirname(file), root)
|
|
43
|
+
return [...projectLinters(linters, programs, [file], root).map(({ name }) => name), ...linters.filter((name) => isLinterInput(name, file, root))]
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function addedErrors(root: string, linters: ReadonlySet<LinterName>, renamed: ReadonlyMap<string, string>): Promise<readonly FileReport[]> {
|
|
47
|
+
const copies = realpathSync(mkdtempSync(join(tmpdir(), 'rulebook-commit-')))
|
|
48
|
+
const stop = (signal: (typeof SIGNALS)[number]): void => {
|
|
49
|
+
rmSync(copies, { recursive: true, force: true })
|
|
50
|
+
process.exit(128 + constants.signals[signal])
|
|
51
|
+
}
|
|
52
|
+
for (const signal of SIGNALS) process.once(signal, stop)
|
|
53
|
+
try {
|
|
54
|
+
const ignored = (await gitPaths(root, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory'])).map((path) => path.replace(/\/$/, ''))
|
|
55
|
+
const tree = (await git(root, ['write-tree'])).trim()
|
|
56
|
+
const after = await lintTree(root, tree, join(copies, 'commit'), linters, ignored)
|
|
57
|
+
const hasErrors = after.some(({ findings }) => findings.some(({ level }) => level === 'error'))
|
|
58
|
+
const before = hasErrors && (await hasHead(root)) ? await lintTree(root, 'HEAD', join(copies, 'head'), linters, ignored) : []
|
|
59
|
+
const failed = new Set(before.flatMap(({ failures }) => failures.map(({ rule }) => rule)))
|
|
60
|
+
const renamedTo = new Map([...renamed].map(([path, old]) => [old, path]))
|
|
61
|
+
const known = new Map<string, number>()
|
|
62
|
+
const keyOf = (path: string, { rule, message }: Reported): string => `${path}\0${rule}\0${message}`
|
|
63
|
+
for (const { path, findings } of before) {
|
|
64
|
+
for (const finding of findings.filter(({ level }) => level === 'error')) {
|
|
65
|
+
const key = keyOf(renamedTo.get(path) ?? path, finding)
|
|
66
|
+
known.set(key, (known.get(key) ?? 0) + 1)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const added = after.map(({ path, findings, failures }) => ({
|
|
70
|
+
path,
|
|
71
|
+
failures,
|
|
72
|
+
findings: findings.flatMap((finding) => {
|
|
73
|
+
if (finding.level !== 'error') return []
|
|
74
|
+
if (failed.has(finding.rule.split('/')[0] ?? '')) return [{ ...finding, level: 'warning' as const }]
|
|
75
|
+
const remaining = known.get(keyOf(path, finding)) ?? 0
|
|
76
|
+
known.set(keyOf(path, finding), remaining - 1)
|
|
77
|
+
return remaining <= 0 ? [finding] : []
|
|
78
|
+
}),
|
|
79
|
+
}))
|
|
80
|
+
return [...added.filter(({ findings, failures }) => findings.length > 0 || failures.length > 0), ...before.flatMap(({ path, failures }) => (failures.length === 0 ? [] : [{ path: path === '.' ? 'HEAD' : `HEAD:${path}`, findings: [], failures }]))]
|
|
81
|
+
} finally {
|
|
82
|
+
rmSync(copies, { recursive: true, force: true })
|
|
83
|
+
for (const signal of SIGNALS) process.off(signal, stop)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function lintTree(root: string, tree: string, copy: string, linters: ReadonlySet<LinterName>, ignored: readonly string[]): Promise<readonly FileReport[]> {
|
|
88
|
+
mkdirSync(copy)
|
|
89
|
+
const archive = Bun.spawn(['git', 'archive', tree], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'pipe' })
|
|
90
|
+
const extract = Bun.spawn(['tar', '-x', '-C', copy], { env: process.env, stdin: archive.stdout, stdout: 'ignore', stderr: 'pipe' })
|
|
91
|
+
const [archived, extracted, archiveError, extractError] = await Promise.all([archive.exited, extract.exited, new Response(archive.stderr).text(), new Response(extract.stderr).text()])
|
|
92
|
+
if (archived !== 0 || extracted !== 0) throw new Error(`git archive ${tree} | tar -x failed: ${`${archiveError}${extractError}`.trim()}`)
|
|
93
|
+
const paths = await gitPaths(root, ['ls-tree', '-r', '-z', '--name-only', tree])
|
|
94
|
+
const included = paths.flatMap((path) => [...linters].flatMap((name) => {
|
|
95
|
+
const { configs, includes } = LINTERS[name]
|
|
96
|
+
return includes !== undefined && configs.includes(basename(path)) ? includes(readFileSync(join(copy, path), 'utf8')).map((include) => join(dirname(path), include)) : []
|
|
97
|
+
}))
|
|
98
|
+
const isInclude = (path: string): boolean => included.some((include) => isInside(include, path) || isInside(path, include))
|
|
99
|
+
for (const path of ignored.filter((path) => DEPENDENCIES.has(basename(path)) || isInclude(path))) {
|
|
100
|
+
const link = join(copy, path)
|
|
101
|
+
if (existsSync(link)) continue
|
|
102
|
+
mkdirSync(dirname(link), { recursive: true })
|
|
103
|
+
symlinkSync(join(root, path), link)
|
|
104
|
+
}
|
|
105
|
+
const groups = await filesBySettings(root, paths.map((path) => join(root, path)))
|
|
106
|
+
const reports = await lintProject(new Map([...groups].map(([settings, files]) => [{ ...settings, root: copy, linters: settings.linters.filter((name) => linters.has(name)) }, files.map((file) => join(copy, relative(root, file)))])), [])
|
|
107
|
+
const bare = (text: string): string => text.replaceAll(`${copy}/`, '')
|
|
108
|
+
return reports.map(({ path, findings, failures }) => ({ path, findings: findings.map((finding) => ({ ...finding, message: bare(finding.message) })), failures: failures.map((failure) => ({ ...failure, reason: bare(failure.reason) })) }))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function withAddedErrors(reports: readonly FileReport[], added: readonly FileReport[]): readonly FileReport[] {
|
|
112
|
+
const merged = new Map(reports.map((report) => [report.path, report]))
|
|
113
|
+
for (const { path, findings, failures } of added) {
|
|
114
|
+
const report = merged.get(path) ?? { path, findings: [], failures: [] }
|
|
115
|
+
merged.set(path, { path, failures: [...report.failures, ...failures], findings: [...report.findings, ...findings].sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)) })
|
|
116
|
+
}
|
|
117
|
+
return [...merged.values()]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function committed(root: string, path: string): Promise<string> {
|
|
121
|
+
const show = Bun.spawn(['git', 'show', `HEAD:${path}`], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'ignore' })
|
|
122
|
+
const [text, code] = await Promise.all([new Response(show.stdout).text(), show.exited])
|
|
123
|
+
return code === 0 ? text : ''
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function hasHead(root: string): Promise<boolean> {
|
|
127
|
+
const head = Bun.spawn(['git', 'rev-parse', '--verify', '--quiet', 'HEAD'], { cwd: root, env: process.env, stdout: 'ignore', stderr: 'ignore' })
|
|
128
|
+
return (await head.exited) === 0
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function gitPaths(root: string, args: readonly string[]): Promise<readonly string[]> {
|
|
132
|
+
return (await git(root, args)).split('\0').filter((path) => path !== '')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function git(root: string, args: readonly string[]): Promise<string> {
|
|
136
|
+
const run = Bun.spawn(['git', ...args], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'pipe' })
|
|
137
|
+
const [text, error, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited])
|
|
138
|
+
if (code !== 0) throw new Error(`git ${args.join(' ')} failed: ${error.trim()}`)
|
|
139
|
+
return text
|
|
140
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -30,10 +30,11 @@ export type Settings = {
|
|
|
30
30
|
readonly existingErrors: Level
|
|
31
31
|
readonly rules: Readonly<Record<string, RuleSettings>>
|
|
32
32
|
readonly linters: readonly LinterName[]
|
|
33
|
+
readonly programs: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
|
33
34
|
readonly messages: Readonly<Record<string, MessageSource>>
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
const KEYS = new Set(['extends', 'plugins', 'paths', 'probes', 'timeout', 'existingErrors', 'rules', 'linters', 'messages'])
|
|
37
|
+
const KEYS = new Set(['extends', 'plugins', 'paths', 'probes', 'timeout', 'existingErrors', 'rules', 'linters', 'programs', 'messages'])
|
|
37
38
|
const RULE_KEYS = new Set(['level', 'runs', 'paths', 'timeout', 'agent', 'model', 'effort', 'threshold'])
|
|
38
39
|
const MESSAGE_KEYS = new Set(['tools', 'folder'])
|
|
39
40
|
const BUILT_IN: Pick<LoadedConfig, 'file' | 'plugins' | 'messages'> = { file: 'rulebook', plugins: {}, messages: { reply: { tools: [], folder: undefined } } }
|
|
@@ -111,6 +112,7 @@ async function settingsOf(root: string, file: string | undefined): Promise<Setti
|
|
|
111
112
|
existingErrors: latest.find(({ existingErrors }) => existingErrors !== undefined)?.existingErrors ?? 'warning',
|
|
112
113
|
rules: overrides(configs.map(({ loaded, config }) => rootRelativeRules(loaded.basePath, config.rules ?? {}))),
|
|
113
114
|
linters: [...new Set(configs.flatMap(({ config }) => config.linters ?? []))],
|
|
115
|
+
programs: Object.assign({}, ...configs.map(({ config }) => config.programs ?? {})),
|
|
114
116
|
messages: Object.assign({}, ...sources.map(({ messages }) => messages)),
|
|
115
117
|
}
|
|
116
118
|
}
|
|
@@ -183,6 +185,11 @@ function validConfig(file: string, value: unknown): Config {
|
|
|
183
185
|
for (const [id, override] of Object.entries(isRecord(value.rules) ? value.rules : {})) validOverride(file, id, override)
|
|
184
186
|
if (value.linters !== undefined && !isStrings(value.linters)) fail(`linters is a list of the linters to run, such as ['oxlint', 'biome']. The linters are ${Object.keys(LINTERS).join(', ')}.`)
|
|
185
187
|
for (const name of isStrings(value.linters) ? value.linters : []) if (!Object.hasOwn(LINTERS, name)) fail(`linters names "${name}", which is not a linter rulebook runs. The linters are ${Object.keys(LINTERS).join(', ')}.`)
|
|
188
|
+
if (value.programs !== undefined && !isRecord(value.programs)) fail("programs maps each linter to the command that runs it, such as { mago: ['bun', 'scripts/mago.ts'] }.")
|
|
189
|
+
for (const [name, command] of Object.entries(isRecord(value.programs) ? value.programs : {})) {
|
|
190
|
+
if (!Object.hasOwn(LINTERS, name)) fail(`programs names "${name}", which is not a linter rulebook runs. The linters are ${Object.keys(LINTERS).join(', ')}.`)
|
|
191
|
+
if (!isStrings(command) || command.length === 0) fail(`programs["${name}"] is the command that runs ${name}, a list of words such as ['bun', 'scripts/${name}.ts'].`)
|
|
192
|
+
}
|
|
186
193
|
if (value.messages !== undefined && !isRecord(value.messages)) fail('messages maps each message name, such as "inbox", to the tools and the folder its text comes from.')
|
|
187
194
|
for (const [name, message] of Object.entries(isRecord(value.messages) ? value.messages : {})) validMessage(file, name, message)
|
|
188
195
|
return value as Config
|
|
@@ -207,7 +214,7 @@ function validOverride(file: string, id: string, override: unknown): void {
|
|
|
207
214
|
if (!isRecord(override)) return fail('is "error", "warning", "off", or an object of rule settings.')
|
|
208
215
|
for (const key of Object.keys(override)) if (!RULE_KEYS.has(key)) fail(`sets "${key}", which no rule has. A rule's settings are ${[...RULE_KEYS].join(', ')}.`)
|
|
209
216
|
if (override.level !== undefined && override.level !== 'off' && !isLevel(override.level)) fail('level is "error", "warning", or "off".')
|
|
210
|
-
if (override.runs !== undefined && !isRuns(override.runs)) fail('runs is "always" or "manual".')
|
|
217
|
+
if (override.runs !== undefined && !isRuns(override.runs)) fail('runs is "always", "commit", or "manual".')
|
|
211
218
|
if (override.paths !== undefined && !isStrings(override.paths)) fail('paths is a list of globs.')
|
|
212
219
|
if (override.timeout !== undefined && !isTimeout(override.timeout)) fail('timeout is a whole number of milliseconds above 0.')
|
|
213
220
|
if (override.threshold !== undefined && !isThreshold(override.threshold)) fail('threshold is a probability above 0 and at most 1.')
|
|
@@ -236,7 +243,7 @@ export function isLevel(value: unknown): value is Level {
|
|
|
236
243
|
}
|
|
237
244
|
|
|
238
245
|
export function isRuns(value: unknown): value is Runs {
|
|
239
|
-
return value === 'always' || value === 'manual'
|
|
246
|
+
return value === 'always' || value === 'commit' || value === 'manual'
|
|
240
247
|
}
|
|
241
248
|
|
|
242
249
|
export function isTimeout(value: unknown): value is number {
|
package/src/edit.ts
CHANGED
|
@@ -16,15 +16,25 @@ export type ToolCall = {
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
export function editRoot(call: ToolCall): string {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
const path = call.tool_input.file_path
|
|
20
|
+
return typeof path === 'string' ? fileRoot(realFile(path, call.cwd), call.cwd) : projectRoot(call.cwd, call.cwd)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function realFile(path: string, cwd: string): string {
|
|
24
|
+
const file = isAbsolute(path) ? path : resolve(cwd, path)
|
|
25
|
+
const nearest = existingFolder(file)
|
|
26
|
+
return join(realpathSync(nearest), relative(nearest, file))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function fileRoot(file: string, cwd: string): string {
|
|
30
|
+
const folder = existingFolder(dirname(file))
|
|
31
|
+
return projectRoot(folder, file.startsWith(`${realpathSync(cwd)}/`) ? cwd : folder)
|
|
22
32
|
}
|
|
23
33
|
|
|
24
34
|
export async function checkEdit(call: ToolCall, root: string): Promise<EditAnswer> {
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
-
const
|
|
35
|
+
const path = call.tool_input.file_path
|
|
36
|
+
if (typeof path !== 'string') return editAnswer(undefined)
|
|
37
|
+
const file = realFile(path, call.cwd)
|
|
28
38
|
const previous = existsSync(file) ? await Bun.file(file).text() : undefined
|
|
29
39
|
const next = editedText(call.tool_name, call.tool_input, previous)
|
|
30
40
|
if (next === undefined) return editAnswer(undefined)
|
|
@@ -35,15 +45,6 @@ export async function checkEdit(call: ToolCall, root: string): Promise<EditAnswe
|
|
|
35
45
|
return editAnswer(report)
|
|
36
46
|
}
|
|
37
47
|
|
|
38
|
-
function editedFile(call: ToolCall): { readonly file: string; readonly folder: string } | undefined {
|
|
39
|
-
const path = call.tool_input.file_path
|
|
40
|
-
if (typeof path !== 'string') return undefined
|
|
41
|
-
const file = isAbsolute(path) ? path : resolve(call.cwd, path)
|
|
42
|
-
const nearest = existingFolder(file)
|
|
43
|
-
const real = join(realpathSync(nearest), relative(nearest, file))
|
|
44
|
-
return { file: real, folder: existingFolder(dirname(real)) }
|
|
45
|
-
}
|
|
46
|
-
|
|
47
48
|
function editedText(tool: string, input: Readonly<Record<string, unknown>>, previous: string | undefined): string | undefined {
|
|
48
49
|
if (tool === 'Write') return typeof input.content === 'string' ? input.content : undefined
|
|
49
50
|
if (previous === undefined) return undefined
|
package/src/jev.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { join } from 'node:path'
|
|
2
|
-
import type { Finding,
|
|
2
|
+
import type { Finding, CheckedFile } from './api.ts'
|
|
3
3
|
import { isRecord } from './config.ts'
|
|
4
4
|
import type { AgenticRule } from './rules.ts'
|
|
5
5
|
|
|
@@ -14,7 +14,7 @@ export function isJev(model: unknown): boolean {
|
|
|
14
14
|
return model === 'jev'
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
export async function runJev(rule: AgenticRule, file:
|
|
17
|
+
export async function runJev(rule: AgenticRule, file: CheckedFile, deadline: AbortSignal): Promise<readonly Finding[]> {
|
|
18
18
|
const key = await jevKey()
|
|
19
19
|
if (key === '') throw new Error(`${rule.id} runs on Jev, and rulebook has no Jev key. Store your TypeSafe API key with \`cmod secret store rulebook jev\`, which reads it on stdin.`)
|
|
20
20
|
const width = String(file.lines.length).length
|
package/src/linters.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync } from 'node:fs'
|
|
1
|
+
import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { homedir, tmpdir } from 'node:os'
|
|
3
3
|
import { basename, dirname, extname, join, relative, resolve } from 'node:path'
|
|
4
4
|
import packageJson from '../package.json' with { type: 'json' }
|
|
5
5
|
import type { Level, LinterName } from './api.ts'
|
|
6
|
-
import { existingFolder } from './config.ts'
|
|
6
|
+
import { existingFolder, isStrings } from './config.ts'
|
|
7
7
|
import { oneLine, openedDiagnostics, seconds, type Diagnostic, type Server } from './lsp.ts'
|
|
8
8
|
|
|
9
9
|
type LinterFinding = { readonly file: string; readonly line: number; readonly level: Level; readonly rule: string; readonly message: string }
|
|
10
10
|
|
|
11
|
-
export type Covering = { readonly name: LinterName; readonly folder: string; readonly config: string | undefined }
|
|
11
|
+
export type Covering = { readonly name: LinterName; readonly folder: string; readonly config: string | undefined; readonly command?: readonly string[] | undefined }
|
|
12
12
|
|
|
13
13
|
export type ProjectLinter = Covering & { readonly files: readonly string[] }
|
|
14
14
|
|
|
@@ -18,18 +18,22 @@ type StylelintResult = { readonly source?: string; readonly warnings: readonly {
|
|
|
18
18
|
|
|
19
19
|
type Linter = {
|
|
20
20
|
readonly extensions: readonly string[]
|
|
21
|
+
readonly configExtensions?: (config: string) => readonly string[] | undefined
|
|
21
22
|
readonly shebang?: RegExp
|
|
22
23
|
readonly configs: readonly string[]
|
|
23
24
|
readonly copies: readonly string[]
|
|
25
|
+
readonly includes?: (config: string) => readonly string[]
|
|
26
|
+
readonly inputs?: (config: string) => readonly string[]
|
|
24
27
|
readonly isBuiltIn?: boolean
|
|
25
28
|
readonly runsOnBun?: boolean
|
|
26
29
|
readonly program: string
|
|
27
|
-
lintText(program: Program, folder: string, file: string, text: string, timeout: number)
|
|
30
|
+
readonly lintText?: (program: Program, folder: string, file: string, text: string, timeout: number) => Promise<readonly LinterFinding[]>
|
|
28
31
|
lintFolder(program: Program, folder: string, files: readonly string[], timeout: number): Promise<readonly LinterFinding[]>
|
|
29
32
|
}
|
|
30
33
|
|
|
31
34
|
const SCRIPTS = ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts']
|
|
32
35
|
const MAGO_REPORT = ['--reporting-format', 'json']
|
|
36
|
+
const MAGO_LEVELS = ['note', 'help', 'warning', 'error']
|
|
33
37
|
const SHELLCHECK_REPORT = ['--format', 'json1']
|
|
34
38
|
const SELENE_REPORT = ['--display-style', 'json2', '--no-summary']
|
|
35
39
|
const STYLELINT_CONFIGS = ['.stylelintrc', ...['json', 'yaml', 'yml', 'js', 'mjs', 'cjs', 'ts', 'mts', 'cts'].map((extension) => `.stylelintrc.${extension}`), ...['js', 'mjs', 'cjs', 'ts', 'mts', 'cts'].map((extension) => `stylelint.config.${extension}`)]
|
|
@@ -40,13 +44,22 @@ export const LINTERS: Readonly<Record<LinterName, Linter>> = {
|
|
|
40
44
|
extensions: ['.php'],
|
|
41
45
|
configs: ['mago.toml'],
|
|
42
46
|
copies: ['vendor/bin/mago'],
|
|
47
|
+
configExtensions: (config) => {
|
|
48
|
+
const extensions = magoConfig(config)?.source?.extensions
|
|
49
|
+
return isStrings(extensions) ? extensions.map((extension) => `.${extension}`) : undefined
|
|
50
|
+
},
|
|
51
|
+
includes: (config) => {
|
|
52
|
+
const includes = magoConfig(config)?.source?.includes
|
|
53
|
+
return isStrings(includes) ? includes : []
|
|
54
|
+
},
|
|
55
|
+
inputs: (config) => [magoConfig(config)?.linter?.baseline, magoConfig(config)?.analyzer?.baseline].filter((baseline) => typeof baseline === 'string'),
|
|
43
56
|
program: 'mago',
|
|
44
|
-
lintText: async (program, folder, file, text, timeout) => magoFindings(folder,
|
|
45
|
-
lintFolder: async (program, folder, _files, timeout) =>
|
|
57
|
+
lintText: async (program, folder, file, text, timeout) => magoFindings(folder, 'lint', await run(program, ['lint', '--stdin-input', ...MAGO_REPORT, file], folder, text, timeout, [0, 1])),
|
|
58
|
+
lintFolder: async (program, folder, _files, timeout) => (await Promise.all((['lint', 'analyze'] as const).map(async (command) => magoFindings(folder, command, await run(program, [command, ...MAGO_REPORT], folder, undefined, timeout, [0, 1]))))).flat(),
|
|
46
59
|
},
|
|
47
60
|
oxlint: {
|
|
48
61
|
extensions: SCRIPTS,
|
|
49
|
-
configs: ['.oxlintrc.json'],
|
|
62
|
+
configs: ['.oxlintrc.json', '.oxlintrc.jsonc', 'oxlint.config.ts', 'oxlint.config.mts'],
|
|
50
63
|
copies: ['node_modules/oxlint/bin/oxlint'],
|
|
51
64
|
isBuiltIn: true,
|
|
52
65
|
runsOnBun: true,
|
|
@@ -64,14 +77,22 @@ export const LINTERS: Readonly<Record<LinterName, Linter>> = {
|
|
|
64
77
|
copies: [`${BIOME}/biome`, `${BIOME}-musl/biome`],
|
|
65
78
|
isBuiltIn: true,
|
|
66
79
|
program: 'biome',
|
|
67
|
-
lintText: async (program, folder, file, text, timeout) =>
|
|
80
|
+
lintText: async (program, folder, file, text, timeout) => {
|
|
81
|
+
let isIgnored = false
|
|
82
|
+
const isIgnoredByServer = async (server: Server): Promise<boolean> => (isIgnored = await isIgnoredByBiome(server, folder, file))
|
|
83
|
+
const [diagnostics, unformatted] = await Promise.all([openedDiagnostics([...program.command, 'lsp-proxy'], program.env, folder, file, text, timeout, isIgnoredByServer), biomeFormatFindings(program, folder, file, text, timeout)])
|
|
84
|
+
if (isIgnored) return []
|
|
85
|
+
return [...diagnosticFindings(file, diagnostics, biomeRule).map((finding) => (finding.rule.startsWith('biome/assist/') ? { ...finding, level: 'error' as const } : finding)), ...unformatted]
|
|
86
|
+
},
|
|
68
87
|
lintFolder: async (program, folder, _files, timeout) => {
|
|
69
|
-
const { stdout } = await run(program, ['
|
|
70
|
-
|
|
88
|
+
const { stdout } = await run(program, ['check', '--reporter', 'github', '--max-diagnostics', 'none'], folder, undefined, timeout, [0, 1])
|
|
89
|
+
const found = stdout.split('\n').flatMap((line): readonly LinterFinding[] => {
|
|
71
90
|
const match = /^::(error|warning|notice) title=([^,]*),file=([^,]*),line=(\d+),[^:]*::(.*)$/.exec(line)
|
|
72
|
-
|
|
73
|
-
return match === null || rule === undefined ? [] : [{ file: resolve(folder, unescaped(match[3] ?? '')), line: Number(match[4]), level: levelOf(match[1] ?? ''), rule, message: oneLine(unescaped(match[5] ?? '')) }]
|
|
91
|
+
return match === null ? [] : [{ file: resolve(folder, unescaped(match[3] ?? '')), line: Number(match[4]), level: levelOf(match[1] ?? ''), rule: biomeRule(unescaped(match[2] ?? '')), message: oneLine(unescaped(match[5] ?? '')) }]
|
|
74
92
|
})
|
|
93
|
+
const unformatted = [...new Set(found.filter(({ rule }) => rule === 'biome/format').map(({ file }) => file))]
|
|
94
|
+
const formats = await Promise.all(unformatted.map((file) => biomeFormatFindings(program, folder, file, readFileSync(file, 'utf8'), timeout)))
|
|
95
|
+
return [...found.filter(({ rule }) => rule !== 'biome/format'), ...formats.flat()]
|
|
75
96
|
},
|
|
76
97
|
},
|
|
77
98
|
stylelint: {
|
|
@@ -112,22 +133,49 @@ export const LINTERS: Readonly<Record<LinterName, Linter>> = {
|
|
|
112
133
|
lintText: async (program, folder, file, text, timeout) => shellcheckFindings(folder, file, await run(program, [...SHELLCHECK_REPORT, ...shellOf(file, text), '-'], folder, text, timeout, [0, 1])),
|
|
113
134
|
lintFolder: async (program, folder, files, timeout) => shellcheckFindings(folder, undefined, await run(program, [...SHELLCHECK_REPORT, ...files.map((file) => relative(folder, file))], folder, undefined, timeout, [0, 1])),
|
|
114
135
|
},
|
|
136
|
+
pint: {
|
|
137
|
+
extensions: ['.php'],
|
|
138
|
+
configs: ['pint.json'],
|
|
139
|
+
copies: ['vendor/bin/pint'],
|
|
140
|
+
program: 'pint',
|
|
141
|
+
lintText: (program, folder, file, text, timeout) => pintFindings(program, folder, { file, text }, timeout),
|
|
142
|
+
lintFolder: (program, folder, _files, timeout) => pintFindings(program, folder, undefined, timeout),
|
|
143
|
+
},
|
|
144
|
+
tsc: {
|
|
145
|
+
extensions: SCRIPTS,
|
|
146
|
+
configs: ['tsconfig.json'],
|
|
147
|
+
copies: ['node_modules/typescript/bin/tsc'],
|
|
148
|
+
runsOnBun: true,
|
|
149
|
+
program: 'tsc',
|
|
150
|
+
lintFolder: async (program, folder, _files, timeout) => tscFindings(folder, await run(program, ['-b', '--noEmit', '--pretty', 'false'], folder, undefined, timeout, [0, 1, 2])),
|
|
151
|
+
},
|
|
115
152
|
}
|
|
116
153
|
|
|
117
|
-
export function coveringLinters(names: readonly LinterName[], file: string, text: string, root: string): readonly Covering[] {
|
|
154
|
+
export function coveringLinters(names: readonly LinterName[], programs: Partial<Record<LinterName, readonly string[]>>, file: string, text: string, root: string): readonly Covering[] {
|
|
118
155
|
return names.flatMap((name): readonly Covering[] => {
|
|
119
156
|
const linter = LINTERS[name]
|
|
120
|
-
if (!covers(linter, file, () => text)) return []
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
const config = linter.configs.map((config) => join(folder, config)).find(isConfig)
|
|
124
|
-
if (config !== undefined) return [{ name, folder, config }]
|
|
125
|
-
if (folder === root || dirname(folder) === folder) return [unconfigured]
|
|
126
|
-
}
|
|
157
|
+
if (linter.configExtensions === undefined && !covers(linter, linter.extensions, file, () => text)) return []
|
|
158
|
+
const covering = nearestCovering(name, file, root)
|
|
159
|
+
return covers(linter, extensionsOf(linter, covering.config), file, () => text) ? [{ ...covering, command: programs[name] }] : []
|
|
127
160
|
})
|
|
128
161
|
}
|
|
129
162
|
|
|
130
|
-
export function
|
|
163
|
+
export function isLinterInput(name: LinterName, file: string, root: string): boolean {
|
|
164
|
+
const linter = LINTERS[name]
|
|
165
|
+
if (linter.configs.includes(basename(file))) return true
|
|
166
|
+
const { config } = nearestCovering(name, file, root)
|
|
167
|
+
return config !== undefined && (linter.inputs?.(readFileSync(config, 'utf8')) ?? []).some((input) => resolve(dirname(config), input) === file)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function nearestCovering(name: LinterName, file: string, root: string): Covering {
|
|
171
|
+
for (let folder = dirname(file); ; folder = dirname(folder)) {
|
|
172
|
+
const config = LINTERS[name].configs.map((config) => join(folder, config)).find(isConfig)
|
|
173
|
+
if (config !== undefined) return { name, folder, config }
|
|
174
|
+
if (folder === root || dirname(folder) === folder) return { name, folder: existingFolder(dirname(file)), config: undefined }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function projectLinters(names: readonly LinterName[], programs: Partial<Record<LinterName, readonly string[]>>, files: readonly string[], root: string): readonly ProjectLinter[] {
|
|
131
179
|
return names.flatMap((name): readonly ProjectLinter[] => {
|
|
132
180
|
const linter = LINTERS[name]
|
|
133
181
|
const outermost = new Map<string, string | undefined>()
|
|
@@ -138,10 +186,13 @@ export function projectLinters(names: readonly LinterName[], files: readonly str
|
|
|
138
186
|
outermost.set(folder, config)
|
|
139
187
|
return config
|
|
140
188
|
}
|
|
141
|
-
const runs = new Map<string, { name: LinterName; folder: string; config: string | undefined; files: string[] }>()
|
|
142
|
-
|
|
189
|
+
const runs = new Map<string, { name: LinterName; folder: string; config: string | undefined; command: readonly string[] | undefined; files: string[] }>()
|
|
190
|
+
const extensions = new Map<string | undefined, readonly string[]>()
|
|
191
|
+
for (const file of files) {
|
|
143
192
|
const config = configOf(dirname(file))
|
|
144
|
-
|
|
193
|
+
if (!extensions.has(config)) extensions.set(config, extensionsOf(linter, config))
|
|
194
|
+
if (!covers(linter, extensions.get(config) ?? linter.extensions, file, () => firstLine(file))) continue
|
|
195
|
+
const run = runs.get(config ?? '') ?? { name, folder: config === undefined ? root : dirname(config), config, command: programs[name], files: [] }
|
|
145
196
|
run.files.push(file)
|
|
146
197
|
runs.set(config ?? '', run)
|
|
147
198
|
}
|
|
@@ -150,16 +201,21 @@ export function projectLinters(names: readonly LinterName[], files: readonly str
|
|
|
150
201
|
}
|
|
151
202
|
|
|
152
203
|
export async function lintText(linter: Covering, file: string, text: string, timeout: number): Promise<readonly LinterFinding[]> {
|
|
153
|
-
|
|
204
|
+
const check = LINTERS[linter.name].lintText
|
|
205
|
+
return check === undefined ? [] : check(await programOf(linter), linter.folder, file, text, timeout)
|
|
154
206
|
}
|
|
155
207
|
|
|
156
208
|
export async function lintFolder(linter: ProjectLinter, timeout: number): Promise<readonly LinterFinding[]> {
|
|
157
209
|
return LINTERS[linter.name].lintFolder(await programOf(linter), linter.folder, linter.files, timeout)
|
|
158
210
|
}
|
|
159
211
|
|
|
160
|
-
function
|
|
212
|
+
function extensionsOf(linter: Linter, config: string | undefined): readonly string[] {
|
|
213
|
+
return (config === undefined ? undefined : linter.configExtensions?.(readFileSync(config, 'utf8'))) ?? linter.extensions
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function covers(linter: Linter, extensions: readonly string[], file: string, firstLineOf: () => string): boolean {
|
|
161
217
|
const extension = extname(file)
|
|
162
|
-
return
|
|
218
|
+
return extensions.includes(extension) || (extension === '' && linter.shebang?.test(firstLineOf()) === true)
|
|
163
219
|
}
|
|
164
220
|
|
|
165
221
|
function isConfig(file: string): boolean {
|
|
@@ -179,8 +235,9 @@ function firstLine(file: string): string {
|
|
|
179
235
|
}
|
|
180
236
|
}
|
|
181
237
|
|
|
182
|
-
async function programOf({ name, folder }: Covering): Promise<Program> {
|
|
238
|
+
async function programOf({ name, folder, command }: Covering): Promise<Program> {
|
|
183
239
|
const linter = LINTERS[name]
|
|
240
|
+
if (command !== undefined) return { path: resolve(folder, command[0] ?? ''), command, env: {} }
|
|
184
241
|
const copy = copyAbove(linter, folder) ?? (linter.isBuiltIn === true ? copyAbove(linter, await builtInFolder()) : undefined)
|
|
185
242
|
if (copy !== undefined) return linter.runsOnBun === true ? { path: copy, command: [process.execPath, copy], env: { BUN_BE_BUN: '1' } } : { path: copy, command: [copy], env: {} }
|
|
186
243
|
if (linter.isBuiltIn === true) throw new Error(`this rulebook build holds no ${name}. Build it with the build script in cli/package.json, which builds oxlint, Biome, and Stylelint in.`)
|
|
@@ -253,25 +310,45 @@ function oxlintRule(code: string | undefined): string {
|
|
|
253
310
|
return match[1] === 'eslint' ? `oxlint/${match[2]}` : `oxlint/${match[1]}/${match[2]}`
|
|
254
311
|
}
|
|
255
312
|
|
|
256
|
-
function biomeRule(code: string | undefined): string
|
|
257
|
-
if (code?.startsWith('assist/') === true) return undefined
|
|
313
|
+
function biomeRule(code: string | undefined): string {
|
|
258
314
|
return `biome/${code?.replace(/^lint\//, '') ?? 'syntax'}`
|
|
259
315
|
}
|
|
260
316
|
|
|
317
|
+
async function biomeFormatFindings(program: Program, folder: string, file: string, text: string, timeout: number): Promise<readonly LinterFinding[]> {
|
|
318
|
+
const { stdout } = await run(program, ['format', '--stdin-file-path', relative(folder, file)], folder, text, timeout, [0, 1])
|
|
319
|
+
if (stdout === '' || stdout === text) return []
|
|
320
|
+
const written = text.split('\n')
|
|
321
|
+
const formatted = stdout.split('\n')
|
|
322
|
+
const changed = written.findIndex((line, index) => line !== formatted[index])
|
|
323
|
+
return [{ file, line: changed === -1 ? written.length : changed + 1, level: 'error', rule: 'biome/format', message: "The file breaks Biome's formatting, and Biome's first change is on this line. Run biome format on the file to fix it." }]
|
|
324
|
+
}
|
|
325
|
+
|
|
261
326
|
async function isIgnoredByBiome(server: Server, folder: string, file: string): Promise<boolean> {
|
|
262
327
|
await server.asked('client/registerCapability')
|
|
263
328
|
const { projectKey } = (await server.request('biome/open_project', { path: folder, openUninitialized: true })) as { projectKey: number }
|
|
264
329
|
return (await server.request('biome/is_path_ignored', { projectKey, path: file, features: ['lint'], ignoreKind: 'ancestors' })) === true
|
|
265
330
|
}
|
|
266
331
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
return
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
332
|
+
type MagoSection = { readonly [key: string]: unknown }
|
|
333
|
+
|
|
334
|
+
function magoConfig(text: string): { readonly source?: MagoSection; readonly linter?: MagoSection; readonly analyzer?: MagoSection } | undefined {
|
|
335
|
+
try {
|
|
336
|
+
return Bun.TOML.parse(text) as { source?: MagoSection; linter?: MagoSection; analyzer?: MagoSection }
|
|
337
|
+
} catch {
|
|
338
|
+
return undefined
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function magoFindings(folder: string, command: 'lint' | 'analyze', { stdout }: { readonly stdout: string }): readonly LinterFinding[] {
|
|
343
|
+
if (stdout.trim() === '') return []
|
|
344
|
+
const config = join(folder, 'mago.toml')
|
|
345
|
+
const settings = existsSync(config) ? magoConfig(readFileSync(config, 'utf8')) : undefined
|
|
346
|
+
const level = settings?.[command === 'lint' ? 'linter' : 'analyzer']?.['minimum-fail-level']
|
|
347
|
+
const failing = MAGO_LEVELS.indexOf(typeof level === 'string' ? level.toLowerCase() : 'error')
|
|
348
|
+
const { issues } = JSON.parse(stdout) as { issues: readonly { level: string; code: string; message: string; annotations: readonly { kind: string; message?: string; span: { file_id: { name: string }; start: { line: number } } }[] }[] }
|
|
349
|
+
return issues.flatMap(({ level, code, message, annotations }) => {
|
|
350
|
+
const primary = annotations.find(({ kind }) => kind === 'Primary') ?? annotations[0]
|
|
351
|
+
return primary === undefined ? [] : [{ file: resolve(folder, primary.span.file_id.name), line: primary.span.start.line + 1, level: MAGO_LEVELS.indexOf(level.toLowerCase()) >= failing ? 'error' : 'warning', rule: `mago/${code}`, message: oneLine(primary.message === undefined ? message : `${message} ${primary.message}`) }]
|
|
275
352
|
})
|
|
276
353
|
}
|
|
277
354
|
|
|
@@ -329,6 +406,55 @@ function shellcheckFindings(folder: string, file: string | undefined, { stdout }
|
|
|
329
406
|
return comments.map((comment) => ({ file: file ?? resolve(folder, comment.file), line: comment.line, level: levelOf(comment.level), rule: `shellcheck/SC${comment.code}`, message: oneLine(comment.message) }))
|
|
330
407
|
}
|
|
331
408
|
|
|
409
|
+
async function pintFindings(program: Program, folder: string, pending: { readonly file: string; readonly text: string } | undefined, timeout: number): Promise<readonly LinterFinding[]> {
|
|
410
|
+
const temporary = mkdtempSync(join(tmpdir(), 'rulebook-pint-'))
|
|
411
|
+
try {
|
|
412
|
+
const project = pending === undefined ? folder : join(temporary, 'project')
|
|
413
|
+
if (pending !== undefined) {
|
|
414
|
+
const copy = join(project, relative(folder, pending.file))
|
|
415
|
+
mkdirSync(dirname(copy), { recursive: true })
|
|
416
|
+
writeFileSync(copy, pending.text)
|
|
417
|
+
}
|
|
418
|
+
const config = join(folder, 'pint.json')
|
|
419
|
+
const report = join(temporary, 'report.json')
|
|
420
|
+
const args = ['--test', '-v', '--format', 'agent', '--output-to-file', report, '--output-format', 'json', ...(existsSync(config) ? ['--config', config] : []), ...(pending === undefined ? [] : ['--cache-file', join(temporary, 'cache')])]
|
|
421
|
+
const { stdout, stderr } = await run(program, args, project, undefined, timeout, [0, 1])
|
|
422
|
+
if (!existsSync(report)) throw new Error(`it wrote no report: ${oneLine(stderr) || oneLine(stdout)}`)
|
|
423
|
+
const fileOf = (path: string): string => pending?.file ?? resolve(folder, path)
|
|
424
|
+
const { errors = [] } = JSON.parse(stdout) as { errors?: readonly { path: string; message: string }[] }
|
|
425
|
+
const { files } = JSON.parse(readFileSync(report, 'utf8')) as { files: readonly { name: string; appliedFixers: readonly string[]; diff: string }[] }
|
|
426
|
+
return [
|
|
427
|
+
...files.flatMap(({ name, appliedFixers, diff }) => appliedFixers.map((fixer) => ({ file: fileOf(name), line: firstChangedLine(diff), level: 'error' as const, rule: `pint/${fixer}`, message: `The file breaks Pint's ${fixer}, and Pint's first change is on this line. Run pint on the file to fix it.` }))),
|
|
428
|
+
...errors.map(({ path, message }) => ({ file: fileOf(path), line: Number(/on line (\d+)/.exec(message)?.[1] ?? 1), level: 'error' as const, rule: 'pint/error', message: oneLine(message) })),
|
|
429
|
+
]
|
|
430
|
+
} finally {
|
|
431
|
+
rmSync(temporary, { recursive: true, force: true })
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function firstChangedLine(diff: string): number {
|
|
436
|
+
const rows = diff.split('\n')
|
|
437
|
+
const hunk = rows.findIndex((row) => row.startsWith('@@ '))
|
|
438
|
+
let line = Number(/^@@ -(\d+)/.exec(rows[hunk] ?? '')?.[1] ?? 1)
|
|
439
|
+
for (const row of rows.slice(hunk + 1)) {
|
|
440
|
+
if (row.startsWith('-') || row.startsWith('+')) break
|
|
441
|
+
line += 1
|
|
442
|
+
}
|
|
443
|
+
return Math.max(line, 1)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function tscFindings(folder: string, { stdout }: { readonly stdout: string }): readonly LinterFinding[] {
|
|
447
|
+
const findings: { file: string; line: number; level: Level; rule: string; message: string }[] = []
|
|
448
|
+
for (const line of stdout.split('\n').filter((line) => line.trim() !== '')) {
|
|
449
|
+
const match = /^(.+)\((\d+),\d+\): (error|warning) TS(\d+): (.*)$/.exec(line)
|
|
450
|
+
const last = findings.at(-1)
|
|
451
|
+
if (match !== null && SCRIPTS.includes(extname(match[1] ?? ''))) findings.push({ file: resolve(folder, match[1] ?? ''), line: Number(match[2]), level: levelOf(match[3] ?? ''), rule: `tsc/TS${match[4]}`, message: match[5] ?? '' })
|
|
452
|
+
else if (match === null && line.startsWith(' ') && last !== undefined) last.message = `${last.message} ${line.trim()}`
|
|
453
|
+
else throw new Error(`it reported an error outside every JavaScript and TypeScript file: ${line}`)
|
|
454
|
+
}
|
|
455
|
+
return findings
|
|
456
|
+
}
|
|
457
|
+
|
|
332
458
|
function unescaped(text: string): string {
|
|
333
459
|
return text.replace(/%(25|0D|0A|3A|2C)/gi, (escape) => decodeURIComponent(escape))
|
|
334
460
|
}
|
package/src/main.ts
CHANGED
|
@@ -3,48 +3,99 @@ import { existsSync, realpathSync, statSync } from 'node:fs'
|
|
|
3
3
|
import { dirname, resolve } from 'node:path'
|
|
4
4
|
import { parseArgs } from 'node:util'
|
|
5
5
|
import packageJson from '../package.json' with { type: 'json' }
|
|
6
|
-
import { checkFile, displayPath, isCovered, isPrompt, lintProject } from './check.ts'
|
|
6
|
+
import { checkFile, displayPath, isCovered, isPrompt, isSkipped, lintProject } from './check.ts'
|
|
7
|
+
import { checkStaged } from './commit.ts'
|
|
7
8
|
import { loadSettings, projectRoot, type Settings } from './config.ts'
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { fileRoot, realFile } from './edit.ts'
|
|
10
|
+
import { filesBySettings, importedFiles, listedFiles, loadImportedFiles, probeFiles, projectFiles } from './files.ts'
|
|
11
|
+
import { answer, checkToolCall, projectOf } from './questions.ts'
|
|
12
|
+
import { commitReport, editAnswer, textReport } from './report.ts'
|
|
11
13
|
import { loadRules, type LoadedRule } from './rules.ts'
|
|
12
14
|
import { serve } from './serve.ts'
|
|
13
15
|
|
|
14
|
-
const HELP = `rulebook ${packageJson.version}:
|
|
16
|
+
const HELP = `rulebook ${packageJson.version}: checks any file, agent reply, and tool call against your rules and your project's linters.
|
|
15
17
|
|
|
16
18
|
Usage:
|
|
17
|
-
rulebook [files...]
|
|
18
|
-
rulebook --
|
|
19
|
-
rulebook --
|
|
20
|
-
rulebook
|
|
21
|
-
rulebook
|
|
22
|
-
rulebook rules
|
|
23
|
-
rulebook
|
|
24
|
-
rulebook --version
|
|
19
|
+
rulebook check [files...] Check every file a rule covers, every Prompt, and every probe of this project, or only the files named, with every rule and linter.
|
|
20
|
+
rulebook check --staged Check what the next commit records, with every rule that runs always or on commit. Run it as the git pre-commit hook.
|
|
21
|
+
rulebook check --stdin-file-path=<path> Check stdin as the text of the file or message at <path>, such as @reply, with every rule that runs always.
|
|
22
|
+
rulebook check --reporter=json Print the results as JSON.
|
|
23
|
+
rulebook check --skip=<name> Skip a rule, every rule of a plugin or folder, a linter, or every agentic rule, such as --skip=agentic. Repeat it to skip more.
|
|
24
|
+
rulebook inspect rules Print, for each folder that holds a rulebook.config.ts, each rule that is on there, with its description and the paths it covers, and each message with the tools that send it, as JSON.
|
|
25
|
+
rulebook claude-hook Check the tool call a Claude Code PreToolUse hook sends on stdin: an Edit, Write, or MultiEdit, or a call a message's tools match. An error refuses it.
|
|
26
|
+
rulebook --version Print the version.
|
|
25
27
|
|
|
26
28
|
A file's rules and settings come from ~/.config/rulebook/rulebook.config.ts and the nearest rulebook.config.ts in the file's folder or a folder above it, with every config they extend.`
|
|
27
29
|
|
|
30
|
+
const REPORTERS = ['default', 'json']
|
|
31
|
+
|
|
28
32
|
async function main(argv: readonly string[]): Promise<number> {
|
|
29
33
|
const { values, positionals } = parseArgs({
|
|
30
34
|
args: [...argv],
|
|
31
35
|
allowPositionals: true,
|
|
32
|
-
options: {
|
|
36
|
+
options: {
|
|
37
|
+
staged: { type: 'boolean' },
|
|
38
|
+
'stdin-file-path': { type: 'string' },
|
|
39
|
+
reporter: { type: 'string', default: 'default' },
|
|
40
|
+
skip: { type: 'string', multiple: true, default: [] },
|
|
41
|
+
version: { type: 'boolean' },
|
|
42
|
+
help: { type: 'boolean', short: 'h' },
|
|
43
|
+
},
|
|
33
44
|
})
|
|
45
|
+
const [command, ...named] = positionals
|
|
34
46
|
if (values.version) return print(packageJson.version)
|
|
35
|
-
if (values.help) return print(HELP)
|
|
36
|
-
if (
|
|
37
|
-
if (
|
|
38
|
-
if (
|
|
39
|
-
if (
|
|
40
|
-
|
|
47
|
+
if (values.help || command === undefined) return print(HELP)
|
|
48
|
+
if (command === '__run_server') return serve()
|
|
49
|
+
if (command === 'claude-hook') return claudeHook(JSON.parse(await Bun.stdin.text()))
|
|
50
|
+
if (command === 'inspect') return inspect(named)
|
|
51
|
+
if (command !== 'check') throw new Error(`${command} is not a rulebook command. \`rulebook --help\` lists them.`)
|
|
52
|
+
if (!REPORTERS.includes(values.reporter)) throw new Error(`--reporter is default or json, not ${values.reporter}.`)
|
|
53
|
+
const isJson = values.reporter === 'json'
|
|
54
|
+
const stdinPath = values['stdin-file-path']
|
|
55
|
+
if ([values.staged === true, stdinPath !== undefined, named.length > 0].filter(Boolean).length > 1) throw new Error('rulebook check takes files, --staged, or --stdin-file-path, one at a time.')
|
|
56
|
+
if (values.staged === true) return staged(values.skip, isJson)
|
|
57
|
+
if (stdinPath !== undefined) return checkStdin(stdinPath, values.skip, isJson)
|
|
58
|
+
return check(named, values.skip, isJson)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function inspect([target, ...rest]: readonly string[]): Promise<number> {
|
|
62
|
+
if (target !== 'rules' || rest.length > 0) throw new Error('rulebook inspect takes rules.')
|
|
63
|
+
const input = { cwd: process.cwd() }
|
|
64
|
+
return print(JSON.stringify(await answer('rules', input, projectOf('rules', input))))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function claudeHook(input: unknown): Promise<number> {
|
|
68
|
+
const answer = await checkToolCall(input)
|
|
69
|
+
if (answer?.refuse !== undefined) {
|
|
70
|
+
await Bun.write(Bun.stderr, `${answer.refuse}\n`)
|
|
71
|
+
return 2
|
|
72
|
+
}
|
|
73
|
+
return answer?.note === undefined ? 0 : print(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: answer.note } }))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function staged(skip: readonly string[], isJson: boolean): Promise<number> {
|
|
77
|
+
const { reports, failures } = await checkStaged(projectRoot(process.cwd(), process.cwd()), skip)
|
|
78
|
+
const { text, isRefused } = commitReport(reports, failures)
|
|
79
|
+
await print(isJson ? JSON.stringify({ reports, failures }) : text)
|
|
80
|
+
return isRefused ? 1 : 0
|
|
41
81
|
}
|
|
42
82
|
|
|
43
|
-
async function
|
|
44
|
-
|
|
83
|
+
async function checkStdin(path: string, skip: readonly string[], isJson: boolean): Promise<number> {
|
|
84
|
+
const cwd = process.cwd()
|
|
85
|
+
const isMessage = path.startsWith('@')
|
|
86
|
+
const file = isMessage ? path : realFile(path, cwd)
|
|
87
|
+
const root = isMessage ? projectRoot(cwd, cwd) : fileRoot(file, cwd)
|
|
88
|
+
const settings = await loadSettings(isMessage ? cwd : dirname(file), root)
|
|
89
|
+
const { rules, failures } = await loadRules(settings)
|
|
90
|
+
const report = await checkFile(settings, rules, file, await Bun.stdin.text(), { scope: 'edit', imported: () => loadImportedFiles(root), skip })
|
|
91
|
+
const { refuse, note } = editAnswer(report)
|
|
92
|
+
const text = refuse ?? note
|
|
93
|
+
if (isJson) await print(JSON.stringify({ reports: report === undefined ? [] : [report], failures }))
|
|
94
|
+
else if (text !== undefined) await print(text)
|
|
95
|
+
return refuse === undefined ? 0 : 1
|
|
45
96
|
}
|
|
46
97
|
|
|
47
|
-
async function check(named: readonly string[],
|
|
98
|
+
async function check(named: readonly string[], skip: readonly string[], isJson: boolean): Promise<number> {
|
|
48
99
|
const listing = listedFiles(process.cwd())
|
|
49
100
|
const root = projectRoot(process.cwd(), process.cwd())
|
|
50
101
|
const settings = await loadSettings(process.cwd(), root)
|
|
@@ -56,14 +107,15 @@ async function check(named: readonly string[], isStatic: boolean, isJson: boolea
|
|
|
56
107
|
for (const failure of failures) unloaded.add(failure)
|
|
57
108
|
return rules
|
|
58
109
|
}
|
|
59
|
-
const files = named.length > 0 ? named.map((file) =>
|
|
110
|
+
const files = named.length > 0 ? named.map((file) => namedFile(file)) : await textFiles([...new Set([...(await coveredFiles(groups, rulesOf)), ...imported, ...messageFiles(settings)])])
|
|
60
111
|
const checked = await Promise.all(files.map(async (file) => {
|
|
61
112
|
const own = displayPath(settings, file).startsWith('@') ? settings : await loadSettings(dirname(file), root)
|
|
62
|
-
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope:
|
|
113
|
+
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope: 'all', imported: async () => imported, skip })
|
|
63
114
|
if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's paths cover.`)
|
|
64
115
|
return report
|
|
65
116
|
}))
|
|
66
|
-
const
|
|
117
|
+
const linted = new Map([...groups].map(([own, owned]) => [{ ...own, linters: own.linters.filter((name) => !isSkipped(skip, name)) }, owned]))
|
|
118
|
+
const reports = await lintProject(linted, checked.filter((report) => report !== undefined), named.length > 0 ? files : undefined)
|
|
67
119
|
const failures = [...unloaded]
|
|
68
120
|
await print(isJson ? JSON.stringify({ reports, failures }) : textReport(reports, failures))
|
|
69
121
|
return failures.length > 0 || reports.some((report) => report.failures.length > 0 || report.findings.some(({ level }) => level === 'error')) ? 1 : 0
|
|
@@ -86,7 +138,7 @@ async function textFiles(files: readonly string[]): Promise<readonly string[]> {
|
|
|
86
138
|
return files.filter((_, index) => texts[index])
|
|
87
139
|
}
|
|
88
140
|
|
|
89
|
-
function
|
|
141
|
+
function namedFile(file: string): string {
|
|
90
142
|
const path = resolve(file)
|
|
91
143
|
if (!existsSync(path)) throw new Error(`${file} does not exist.`)
|
|
92
144
|
return realpathSync(path)
|
package/src/questions.ts
CHANGED
|
@@ -3,12 +3,14 @@ import { checkFile, globRegExp } from './check.ts'
|
|
|
3
3
|
import { CONFIG_FILE, globalConfigFile, isRecord, loadSettings, projectRoot } from './config.ts'
|
|
4
4
|
import { checkEdit, editRoot, type ToolCall } from './edit.ts'
|
|
5
5
|
import { listedFiles } from './files.ts'
|
|
6
|
-
import { editAnswer } from './report.ts'
|
|
6
|
+
import { editAnswer, type EditAnswer } from './report.ts'
|
|
7
7
|
import { loadRules } from './rules.ts'
|
|
8
8
|
|
|
9
9
|
export type Question = 'edit' | 'text' | 'rules'
|
|
10
10
|
|
|
11
|
-
type Text = { readonly name: string; readonly text: string; readonly cwd: string }
|
|
11
|
+
type Text = { readonly name: string; readonly text: string; readonly cwd: string; readonly input?: Readonly<Record<string, unknown>> }
|
|
12
|
+
|
|
13
|
+
const EDIT_TOOLS = /^(Edit|Write|MultiEdit)$/
|
|
12
14
|
|
|
13
15
|
type Answerer = {
|
|
14
16
|
root(input: unknown): string
|
|
@@ -48,14 +50,23 @@ export function answer(question: Question, input: unknown, root: string): Promis
|
|
|
48
50
|
return QUESTIONS[question].answer(input, root)
|
|
49
51
|
}
|
|
50
52
|
|
|
51
|
-
async function checkText({ name, text, cwd }: Text, root: string): Promise<
|
|
53
|
+
async function checkText({ name, text, cwd, input }: Text, root: string): Promise<EditAnswer> {
|
|
52
54
|
const settings = await loadSettings(cwd, root)
|
|
53
|
-
if (!name.startsWith('@')) throw new Error('
|
|
55
|
+
if (!name.startsWith('@')) throw new Error('The text question checks a message by its @-name, such as @reply or @inbox/<id>.md.')
|
|
54
56
|
const { rules } = await loadRules(settings)
|
|
55
|
-
const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set() })
|
|
57
|
+
const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set(), ...(input === undefined ? {} : { input }) })
|
|
56
58
|
return editAnswer(report)
|
|
57
59
|
}
|
|
58
60
|
|
|
61
|
+
export async function checkToolCall(input: unknown): Promise<EditAnswer | undefined> {
|
|
62
|
+
const call = toolCall(input)
|
|
63
|
+
if (EDIT_TOOLS.test(call.tool_name)) return checkEdit(call, editRoot(call))
|
|
64
|
+
const root = projectRoot(call.cwd, call.cwd)
|
|
65
|
+
const messages = Object.entries((await loadSettings(call.cwd, root)).messages)
|
|
66
|
+
const name = messages.find(([, { tools }]) => tools.some((glob) => globRegExp(glob).test(call.tool_name)))?.[0]
|
|
67
|
+
return name === undefined ? undefined : checkText({ name: `@${name}`, text: textsOf(call.tool_input).join('\n\n'), cwd: call.cwd, input: call.tool_input }, root)
|
|
68
|
+
}
|
|
69
|
+
|
|
59
70
|
async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
60
71
|
const settings = await loadSettings(cwd, root)
|
|
61
72
|
await loadRules(await loadSettings(root, root))
|
|
@@ -83,16 +94,25 @@ async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
|
83
94
|
}
|
|
84
95
|
|
|
85
96
|
function toolCall(input: unknown): ToolCall {
|
|
86
|
-
if (!isRecord(input) || typeof input.tool_name !== 'string' || !isRecord(input.tool_input) || typeof input.cwd !== 'string') throw new Error('
|
|
97
|
+
if (!isRecord(input) || typeof input.tool_name !== 'string' || !isRecord(input.tool_input) || typeof input.cwd !== 'string') throw new Error('A tool call is {"tool_name", "tool_input", "cwd"}.')
|
|
87
98
|
return { tool_name: input.tool_name, tool_input: input.tool_input, cwd: input.cwd }
|
|
88
99
|
}
|
|
89
100
|
|
|
90
101
|
function textOf(input: unknown): Text {
|
|
91
|
-
if (!isRecord(input) || typeof input.name !== 'string' || typeof input.
|
|
102
|
+
if (!isRecord(input) || typeof input.name !== 'string' || typeof input.cwd !== 'string') throw new Error('The text question reads {"name", "text" or "input", "cwd"}.')
|
|
103
|
+
if (isRecord(input.input)) return { name: input.name, text: textsOf(input.input).join('\n\n'), cwd: input.cwd, input: input.input }
|
|
104
|
+
if (typeof input.text !== 'string') throw new Error('The text question reads {"name", "text" or "input", "cwd"}.')
|
|
92
105
|
return { name: input.name, text: input.text, cwd: input.cwd }
|
|
93
106
|
}
|
|
94
107
|
|
|
108
|
+
function textsOf(value: unknown): readonly string[] {
|
|
109
|
+
if (typeof value === 'string') return [value]
|
|
110
|
+
if (Array.isArray(value)) return value.flatMap(textsOf)
|
|
111
|
+
if (isRecord(value)) return Object.values(value).flatMap(textsOf)
|
|
112
|
+
return []
|
|
113
|
+
}
|
|
114
|
+
|
|
95
115
|
function cwdOf(input: unknown): string {
|
|
96
|
-
if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('
|
|
116
|
+
if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('The rules question reads {"cwd"}.')
|
|
97
117
|
return input.cwd
|
|
98
118
|
}
|
package/src/report.ts
CHANGED
|
@@ -17,7 +17,7 @@ function findingLines(findings: readonly Reported[]): string {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
function failureLines(report: FileReport): readonly string[] {
|
|
20
|
-
return report.failures.map(({ rule, reason }) => `${rule} did not run on ${report.path}: ${reason}`)
|
|
20
|
+
return report.failures.map(({ rule, reason }) => `${rule} did not run${report.path === '.' ? '' : ` on ${report.path}`}: ${reason}`)
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export function editAnswer(report: FileReport | undefined): EditAnswer {
|
|
@@ -46,7 +46,7 @@ function existingLine(report: FileReport, isMore: boolean): readonly string[] {
|
|
|
46
46
|
const errors = existing.filter(({ level }) => level === 'error').length
|
|
47
47
|
const noun = errors === existing.length ? 'error' : errors === 0 ? 'warning' : 'finding'
|
|
48
48
|
const isOne = existing.length === 1
|
|
49
|
-
return [`${existing.length}${isMore ? ' more' : ''} ${noun}${isOne ? '' : 's'} in this file ${isOne ? 'was' : 'were'} there before this edit. \`rulebook ${report.path}\` lists ${isOne ? 'it' : 'them'}.`]
|
|
49
|
+
return [`${existing.length}${isMore ? ' more' : ''} ${noun}${isOne ? '' : 's'} in this file ${isOne ? 'was' : 'were'} there before this edit. \`rulebook check ${report.path}\` lists ${isOne ? 'it' : 'them'}.`]
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
function refusal(path: string): string {
|
|
@@ -60,6 +60,17 @@ function subject(path: string): string {
|
|
|
60
60
|
return `${name.charAt(0).toUpperCase()}${name.slice(1)}`
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
export function commitReport(reports: readonly FileReport[], unloaded: readonly string[]): { readonly text: string; readonly isRefused: boolean } {
|
|
64
|
+
const isHidden = ({ isExisting, level }: Reported): boolean => isExisting && level !== 'error'
|
|
65
|
+
const written = reports.map((report) => ({ ...report, findings: report.findings.filter((finding) => !isHidden(finding)) }))
|
|
66
|
+
const isRefused = written.some(({ findings }) => findings.some(({ level }) => level === 'error'))
|
|
67
|
+
const existing = reports.flatMap(({ path, findings }) => (findings.some(isHidden) ? [path] : []))
|
|
68
|
+
const count = reports.flatMap(({ findings }) => findings.filter(isHidden)).length
|
|
69
|
+
const before = count === 0 ? [] : [`${count} ${count === 1 ? 'finding' : 'findings'} in these files ${count === 1 ? 'was' : 'were'} there before this commit. \`rulebook check ${existing.join(' ')}\` lists ${count === 1 ? 'it' : 'them'}.`]
|
|
70
|
+
const body = textReport(written, unloaded)
|
|
71
|
+
return { isRefused, text: [...(isRefused ? ['Commit refused. Fix every error, stage the fix, then commit again.'] : []), body, ...before].join('\n\n') }
|
|
72
|
+
}
|
|
73
|
+
|
|
63
74
|
export function textReport(reports: readonly FileReport[], unloaded: readonly string[]): string {
|
|
64
75
|
const flagged = reports.filter(({ findings }) => findings.length > 0)
|
|
65
76
|
const all = reports.flatMap(({ findings }) => findings)
|
package/src/rules.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, renameSync } from 'node:fs'
|
|
2
2
|
import { basename, join } from 'node:path'
|
|
3
3
|
import type { NapiConfig } from '@ast-grep/napi'
|
|
4
|
-
import type { Finding, Level,
|
|
4
|
+
import type { Finding, Level, CheckedFile, Rule, RuleSettings, Runs } from './api.ts'
|
|
5
5
|
import { importsRule, noSuppressionsRule } from './check.ts'
|
|
6
6
|
import type { Import } from './claude-md.ts'
|
|
7
7
|
import { isLevel, isRecord, isRuns, isStrings, isThreshold, isTimeout, rootRelative, type Settings } from './config.ts'
|
|
@@ -22,7 +22,7 @@ type Doc = { readonly file: string; readonly imports: readonly Import[] }
|
|
|
22
22
|
|
|
23
23
|
export type StaticRule = Common & {
|
|
24
24
|
readonly kind: 'static'
|
|
25
|
-
check(file:
|
|
25
|
+
check(file: CheckedFile, doc: Doc | undefined): readonly Finding[] | Promise<readonly Finding[]>
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export type AgenticRule = Common & {
|
|
@@ -82,7 +82,11 @@ async function rulesOf(settings: Settings): Promise<Rules> {
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
for (const id of Object.keys(settings.rules)) if (!ids.has(id)) throw new Error(`A rulebook config sets the rule "${id}", which no plugin holds. The rules are ${[...ids].join(', ')}.`)
|
|
85
|
-
|
|
85
|
+
const loaded = rules.map((rule) => overridden(rule, settings.rules[rule.id]))
|
|
86
|
+
for (const { id, paths, level } of loaded) {
|
|
87
|
+
if (paths === undefined && level !== 'off' && settings.paths.length === 0) failures.push(`The rule ${id} has no paths, and no config lists paths, so it checks no file. Give the rule paths, such as paths: ['**/*.ts'].`)
|
|
88
|
+
}
|
|
89
|
+
return { rules: loaded, failures }
|
|
86
90
|
}
|
|
87
91
|
|
|
88
92
|
function loadedRule(id: string, source: string, timeout: number): Promise<LoadedRule> {
|
|
@@ -194,7 +198,7 @@ function commonOf(id: string, source: string, keys: Readonly<Record<string, unkn
|
|
|
194
198
|
const { description, level, runs } = keys
|
|
195
199
|
if (typeof description !== 'string' || description.trim() === '' || description.trim().includes('\n')) return fail('a rule needs a description: the Rule in one line of plain words, such as "Don\'t write em dashes."')
|
|
196
200
|
if (level !== undefined && !isLevel(level)) fail('level is "error" or "warning".')
|
|
197
|
-
if (runs !== undefined && !isRuns(runs)) fail('runs is "always" or "manual".')
|
|
201
|
+
if (runs !== undefined && !isRuns(runs)) fail('runs is "always", "commit", or "manual".')
|
|
198
202
|
return {
|
|
199
203
|
id,
|
|
200
204
|
source,
|
package/src/serve.ts
CHANGED
|
@@ -91,10 +91,10 @@ export async function serve(): Promise<never> {
|
|
|
91
91
|
idleTimeout: 0,
|
|
92
92
|
async fetch(request: Request) {
|
|
93
93
|
const question = new URL(request.url).pathname.slice(1)
|
|
94
|
-
if (request.method !== 'POST' || !isQuestion(question)) return new Response('rulebook
|
|
94
|
+
if (request.method !== 'POST' || !isQuestion(question)) return new Response('The rulebook server answers POST /edit, /text, and /rules.', { status: 404 })
|
|
95
95
|
try {
|
|
96
96
|
const body: unknown = await request.json()
|
|
97
|
-
if (!isRecord(body)) throw new Error('rulebook
|
|
97
|
+
if (!isRecord(body)) throw new Error('The rulebook server reads {"input", "environment"}.')
|
|
98
98
|
const root = projectOf(question, body.input)
|
|
99
99
|
const environment = environmentOf(body.environment)
|
|
100
100
|
const key = `${root}\0${JSON.stringify(environment)}`
|
|
@@ -126,6 +126,6 @@ function isStale({ watched, startedAt }: Project): boolean {
|
|
|
126
126
|
}
|
|
127
127
|
|
|
128
128
|
function environmentOf(sent: unknown): Environment {
|
|
129
|
-
if (!isRecord(sent)) throw new Error('rulebook
|
|
129
|
+
if (!isRecord(sent)) throw new Error('The rulebook server reads {"input", "environment"}.')
|
|
130
130
|
return Object.fromEntries(ENVIRONMENT.flatMap((name) => (typeof sent[name] === 'string' ? [[name, sent[name]]] : [])))
|
|
131
131
|
}
|