@cmodjs/rulebook 0.5.0 → 0.6.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 -1
- package/src/agent.ts +1 -1
- package/src/api.ts +54 -17
- package/src/check.ts +25 -17
- package/src/config.ts +25 -21
- package/src/edit.ts +21 -14
- package/src/files.ts +1 -1
- package/src/jev.ts +1 -1
- package/src/linters.ts +2 -1
- package/src/main.ts +7 -5
- package/src/questions.ts +39 -19
- package/src/report.ts +1 -1
- package/src/rules.ts +102 -34
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cmodjs/rulebook",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
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",
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
"@ast-grep/lang-yaml": "0.0.6",
|
|
47
47
|
"@ast-grep/napi": "0.51.1",
|
|
48
48
|
"@biomejs/biome": "2.6.4",
|
|
49
|
+
"@cmodjs/core": "6.0.2",
|
|
49
50
|
"diff": "9.0.0",
|
|
50
51
|
"marked": "15.0.0",
|
|
51
52
|
"oxlint": "1.86.0",
|
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 {
|
|
4
|
+
import type { CheckedFile, Finding } from './rules.ts'
|
|
5
5
|
import { isRecord } from './config.ts'
|
|
6
6
|
import type { AgenticRule } from './rules.ts'
|
|
7
7
|
|
package/src/api.ts
CHANGED
|
@@ -1,32 +1,69 @@
|
|
|
1
|
-
export type
|
|
1
|
+
export type Severity = 'error' | 'warn'
|
|
2
2
|
|
|
3
|
-
export type Runs = 'always' | '
|
|
3
|
+
export type Runs = 'always' | 'manual'
|
|
4
4
|
|
|
5
|
-
export type
|
|
5
|
+
export type Call = {
|
|
6
|
+
readonly tool: string
|
|
7
|
+
readonly input: Readonly<Record<string, unknown>>
|
|
8
|
+
readonly cwd: string
|
|
9
|
+
readonly session?: string
|
|
10
|
+
readonly agentType?: string
|
|
11
|
+
readonly agentId?: string
|
|
12
|
+
readonly transcriptPath?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type Document = { readonly lineNumber: 1; readonly text: string }
|
|
16
|
+
|
|
17
|
+
export type Line = { readonly lineNumber: number; readonly text: string; readonly isInCodeBlock: boolean }
|
|
18
|
+
|
|
19
|
+
export type Command = {
|
|
20
|
+
readonly lineNumber: number
|
|
21
|
+
readonly program: string
|
|
22
|
+
readonly args: readonly string[]
|
|
23
|
+
readonly argv: readonly [string, ...string[]]
|
|
24
|
+
readonly folder: string
|
|
25
|
+
readonly input?: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type Shell = {
|
|
29
|
+
readonly reads: readonly string[]
|
|
30
|
+
readonly writes: readonly string[]
|
|
31
|
+
readonly fetches: readonly string[]
|
|
32
|
+
readonly isFullyParsed: boolean
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type Node = Document | Line | Command
|
|
36
|
+
|
|
37
|
+
export type Context = {
|
|
6
38
|
readonly root: string
|
|
7
39
|
readonly path: string
|
|
8
40
|
readonly text: string
|
|
9
|
-
readonly lines: readonly
|
|
10
|
-
readonly
|
|
41
|
+
readonly lines: readonly Line[]
|
|
42
|
+
readonly commands: readonly Command[]
|
|
43
|
+
readonly shell?: Shell
|
|
44
|
+
readonly call?: Call
|
|
45
|
+
report(finding: { readonly node: Node }): void
|
|
11
46
|
}
|
|
12
47
|
|
|
13
|
-
export type
|
|
14
|
-
readonly
|
|
15
|
-
readonly
|
|
48
|
+
export type Visitors = {
|
|
49
|
+
readonly Document?: (document: Document) => void | Promise<void>
|
|
50
|
+
readonly Line?: (line: Line) => void | Promise<void>
|
|
51
|
+
readonly Command?: (command: Command) => void | Promise<void>
|
|
16
52
|
}
|
|
17
53
|
|
|
18
54
|
export type Rule = {
|
|
19
55
|
readonly description: string
|
|
20
|
-
readonly
|
|
56
|
+
readonly message?: string
|
|
57
|
+
readonly files?: readonly string[]
|
|
58
|
+
readonly severity?: Severity
|
|
21
59
|
readonly runs?: Runs
|
|
22
|
-
|
|
23
|
-
check(file: CheckedFile): readonly Finding[] | Promise<readonly Finding[]>
|
|
60
|
+
create(context: Context): Visitors | Promise<Visitors>
|
|
24
61
|
}
|
|
25
62
|
|
|
26
63
|
export type RuleSettings = {
|
|
27
|
-
readonly
|
|
64
|
+
readonly severity?: Severity | 'off'
|
|
28
65
|
readonly runs?: Runs
|
|
29
|
-
readonly
|
|
66
|
+
readonly files?: readonly string[]
|
|
30
67
|
readonly timeout?: number
|
|
31
68
|
readonly agent?: string
|
|
32
69
|
readonly model?: string
|
|
@@ -39,11 +76,11 @@ export type LinterName = 'mago' | 'oxlint' | 'biome' | 'stylelint' | 'ruff' | 's
|
|
|
39
76
|
export type Config = {
|
|
40
77
|
readonly extends?: readonly (string | Config)[]
|
|
41
78
|
readonly plugins?: Readonly<Record<string, string>>
|
|
42
|
-
readonly
|
|
79
|
+
readonly files?: readonly string[]
|
|
43
80
|
readonly probes?: readonly string[]
|
|
44
81
|
readonly timeout?: number
|
|
45
|
-
readonly existingErrors?:
|
|
46
|
-
readonly rules?: Readonly<Record<string,
|
|
82
|
+
readonly existingErrors?: Severity
|
|
83
|
+
readonly rules?: Readonly<Record<string, Severity | 'off' | RuleSettings>>
|
|
47
84
|
readonly linters?: readonly LinterName[]
|
|
48
85
|
readonly programs?: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
|
49
86
|
readonly messages?: Readonly<Record<string, { readonly tools?: readonly string[]; readonly folder?: string }>>
|
|
@@ -58,6 +95,6 @@ export function defineConfig(config: Config): Config {
|
|
|
58
95
|
}
|
|
59
96
|
|
|
60
97
|
export const recommended = defineConfig({
|
|
61
|
-
|
|
98
|
+
files: ['**/{CLAUDE,Claude}.md', '**/{CLAUDE,Claude}.local.md', '**/AGENTS.md', '**/.claude/{rules,agents,commands,skills}/**/*.md'],
|
|
62
99
|
rules: { 'rulebook/imports': 'error' },
|
|
63
100
|
})
|
package/src/check.ts
CHANGED
|
@@ -2,14 +2,15 @@ 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
|
|
5
|
+
import { parseShell } from '@cmodjs/core/shell.js'
|
|
6
|
+
import type { Call, LinterName } from './api.ts'
|
|
6
7
|
import { runAgentic } from './agent.ts'
|
|
7
8
|
import { importedFile, isClaudeMd, readClaudeMd } from './claude-md.ts'
|
|
8
9
|
import { isInside, type Settings } from './config.ts'
|
|
9
10
|
import { isJev, runJev } from './jev.ts'
|
|
10
11
|
import { coveringLinters, LINTERS, lintFolder, lintText, projectLinters, type Covering, type ProjectLinter } from './linters.ts'
|
|
11
12
|
import { seconds } from './lsp.ts'
|
|
12
|
-
import type
|
|
13
|
+
import { levelOf, type CheckedFile, type Finding, type Level, type LoadedRule, type StaticRule } from './rules.ts'
|
|
13
14
|
|
|
14
15
|
type Scope = 'edit' | 'commit' | 'all'
|
|
15
16
|
|
|
@@ -34,10 +35,11 @@ type CheckOptions = {
|
|
|
34
35
|
readonly scope: Scope
|
|
35
36
|
readonly previous?: string | undefined
|
|
36
37
|
readonly imported: () => Promise<ReadonlySet<string>>
|
|
37
|
-
readonly
|
|
38
|
+
readonly call?: Call
|
|
38
39
|
readonly skip?: readonly string[]
|
|
39
40
|
}
|
|
40
41
|
|
|
42
|
+
export const COMMAND = '@command'
|
|
41
43
|
const PIN = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
|
|
42
44
|
const MAX_EDIT_LENGTH = 1_000
|
|
43
45
|
|
|
@@ -74,7 +76,7 @@ function isProbe(settings: Settings, file: string): boolean {
|
|
|
74
76
|
}
|
|
75
77
|
|
|
76
78
|
export function isPrompt(settings: Settings, file: string): boolean {
|
|
77
|
-
return isInside(settings.root, file) && matches(settings.
|
|
79
|
+
return isInside(settings.root, file) && matches(settings.files, relative(settings.root, file))
|
|
78
80
|
}
|
|
79
81
|
|
|
80
82
|
export async function checkFile(settings: Settings, rules: readonly LoadedRule[], file: string, text: string, options: CheckOptions): Promise<FileReport | undefined> {
|
|
@@ -92,7 +94,13 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
92
94
|
const mayPin = text.includes('rulebook-expect')
|
|
93
95
|
const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
|
|
94
96
|
const memory = isDoc ? claudeMd : undefined
|
|
95
|
-
const prompt: CheckedFile = {
|
|
97
|
+
const prompt: CheckedFile = {
|
|
98
|
+
root: settings.root,
|
|
99
|
+
path,
|
|
100
|
+
...(memory === undefined ? { text, lines: written } : { text: memory.lines.join('\n'), lines: memory.lines }),
|
|
101
|
+
...(path === COMMAND ? { shell: parseShell(text) } : {}),
|
|
102
|
+
...(options.call === undefined ? {} : { call: options.call }),
|
|
103
|
+
}
|
|
96
104
|
const doc = memory === undefined ? undefined : { file, imports: memory.imports }
|
|
97
105
|
const pins = mayPin ? pinsOf(written, claudeMd?.lines ?? []) : []
|
|
98
106
|
const pinned = new Set(pins.map(({ rule }) => rule))
|
|
@@ -115,18 +123,18 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
115
123
|
|
|
116
124
|
const lints = await linting
|
|
117
125
|
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
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)]
|
|
126
|
+
const found = [...runs.flatMap((run) => ('found' in run ? run.found.map(({ line, message, isWhole }) => ({ line, message: message ?? run.rule.message ?? run.rule.description, rule: run.rule.id, level: run.rule.level === 'off' ? 'error' as const : run.rule.level, ...(isWhole === true ? { isWhole } : {}) })) : [])), ...lints.flatMap((lint) => lint.flags)]
|
|
119
127
|
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
|
|
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.' }))]
|
|
128
|
+
const flagged: readonly Flag[] = 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.' }))]
|
|
121
129
|
|
|
122
130
|
return {
|
|
123
131
|
path,
|
|
124
132
|
failures,
|
|
125
133
|
findings: flagged
|
|
126
|
-
.map((finding) => {
|
|
134
|
+
.map(({ isWhole, ...finding }) => {
|
|
127
135
|
const quote = written[finding.line - 1] ?? ''
|
|
128
|
-
const isExisting = wrote !== undefined && !wrote.has(finding.line)
|
|
129
|
-
return { ...finding, quote, isExisting, level: isExisting && finding.level === 'error' ? settings.existingErrors : finding.level }
|
|
136
|
+
const isExisting = wrote !== undefined && isWhole !== true && !wrote.has(finding.line)
|
|
137
|
+
return { ...finding, quote, isExisting, level: isExisting && finding.level === 'error' ? levelOf(settings.existingErrors) : finding.level }
|
|
130
138
|
})
|
|
131
139
|
.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)),
|
|
132
140
|
}
|
|
@@ -181,14 +189,12 @@ async function linterFlags(linter: Covering, file: string, text: string, timeout
|
|
|
181
189
|
}
|
|
182
190
|
|
|
183
191
|
function covers(rule: LoadedRule, path: string, isPrompt: boolean): boolean {
|
|
184
|
-
return rule.level !== 'off' && (rule.
|
|
192
|
+
return rule.level !== 'off' && (rule.files === undefined ? isPrompt : matches(rule.files, path))
|
|
185
193
|
}
|
|
186
194
|
|
|
187
195
|
function inScope(rule: LoadedRule, { scope, skip }: CheckOptions): boolean {
|
|
188
196
|
if (isSkipped(skip, rule.id) || (rule.kind === 'agentic' && isSkipped(skip, 'agentic'))) return false
|
|
189
|
-
|
|
190
|
-
if (scope === 'commit') return rule.runs !== 'manual'
|
|
191
|
-
return rule.runs === 'always'
|
|
197
|
+
return scope !== 'edit' || rule.runs === 'always'
|
|
192
198
|
}
|
|
193
199
|
|
|
194
200
|
export function isSkipped(skip: readonly string[] | undefined, name: string): boolean {
|
|
@@ -252,9 +258,10 @@ export function importsRule(settings: Settings): StaticRule {
|
|
|
252
258
|
source: 'rulebook',
|
|
253
259
|
kind: 'static',
|
|
254
260
|
description: 'Import only files that exist.',
|
|
261
|
+
message: undefined,
|
|
255
262
|
level: 'off',
|
|
256
263
|
runs: 'always',
|
|
257
|
-
|
|
264
|
+
files: undefined,
|
|
258
265
|
check: (_, doc) => (doc === undefined ? [] : doc.imports.flatMap(({ path, line }) => {
|
|
259
266
|
const target = importedFile(doc.file, path)
|
|
260
267
|
if (target === undefined || statSync(target, { throwIfNoEntry: false })?.isFile() === true) return []
|
|
@@ -280,16 +287,17 @@ export const noSuppressionsRule: StaticRule = {
|
|
|
280
287
|
source: 'rulebook',
|
|
281
288
|
kind: 'static',
|
|
282
289
|
description: 'Fix the code instead of suppressing the rule.',
|
|
290
|
+
message: undefined,
|
|
283
291
|
level: 'off',
|
|
284
292
|
runs: 'always',
|
|
285
|
-
|
|
293
|
+
files: [`**/*.{${[...new Set(Object.values(LINTERS).flatMap(({ extensions }) => extensions.map((extension) => extension.slice(1))))].join(',')}}`, '**/!(*.*)'],
|
|
286
294
|
check: ({ lines }) => lines.flatMap((text, index) => {
|
|
287
295
|
const linter = Object.entries(SUPPRESSIONS).find(([, suppression]) => suppression.test(text))?.[0]
|
|
288
296
|
return linter === undefined ? [] : [{ line: index + 1, message: `This comment suppresses ${linter}. Fix the code ${linter} flags, and remove the comment.` }]
|
|
289
297
|
}),
|
|
290
298
|
}
|
|
291
299
|
|
|
292
|
-
type Flag = Omit<Reported, 'isExisting' | 'quote'>
|
|
300
|
+
type Flag = Omit<Reported, 'isExisting' | 'quote'> & { readonly isWhole?: true }
|
|
293
301
|
|
|
294
302
|
function probeFindings(found: readonly Flag[], pins: readonly Pin[]): readonly Flag[] {
|
|
295
303
|
const open = [...pins]
|
package/src/config.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
2
2
|
import { homedir } from 'node:os'
|
|
3
3
|
import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path'
|
|
4
|
-
import type { Config,
|
|
4
|
+
import type { Config, LinterName, RuleSettings, Runs, Severity } from './api.ts'
|
|
5
5
|
import { LINTERS } from './linters.ts'
|
|
6
6
|
import { importDefault } from './modules.ts'
|
|
7
7
|
|
|
@@ -25,19 +25,23 @@ type Layer = { readonly loaded: LoadedConfig; readonly config: Config }
|
|
|
25
25
|
export type Settings = {
|
|
26
26
|
readonly root: string
|
|
27
27
|
readonly configs: readonly LoadedConfig[]
|
|
28
|
-
readonly
|
|
28
|
+
readonly files: readonly string[]
|
|
29
29
|
readonly timeout: number
|
|
30
|
-
readonly existingErrors:
|
|
30
|
+
readonly existingErrors: Severity
|
|
31
31
|
readonly rules: Readonly<Record<string, RuleSettings>>
|
|
32
32
|
readonly linters: readonly LinterName[]
|
|
33
33
|
readonly programs: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
|
34
34
|
readonly messages: Readonly<Record<string, MessageSource>>
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
const KEYS = new Set(['extends', 'plugins', '
|
|
38
|
-
const RULE_KEYS = new Set(['
|
|
37
|
+
const KEYS = new Set(['extends', 'plugins', 'files', 'probes', 'timeout', 'existingErrors', 'rules', 'linters', 'programs', 'messages'])
|
|
38
|
+
const RULE_KEYS = new Set(['severity', 'runs', 'files', 'timeout', 'agent', 'model', 'effort', 'threshold'])
|
|
39
39
|
const MESSAGE_KEYS = new Set(['tools', 'folder'])
|
|
40
|
-
const BUILT_IN: Pick<LoadedConfig, 'file' | 'plugins' | 'messages'> = {
|
|
40
|
+
const BUILT_IN: Pick<LoadedConfig, 'file' | 'plugins' | 'messages'> = {
|
|
41
|
+
file: 'rulebook',
|
|
42
|
+
plugins: {},
|
|
43
|
+
messages: { reply: { tools: [], folder: undefined }, command: { tools: ['Bash', 'shell_command', 'exec_command'], folder: undefined } },
|
|
44
|
+
}
|
|
41
45
|
|
|
42
46
|
export function globalConfigFile(): string {
|
|
43
47
|
return join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'rulebook', CONFIG_FILE)
|
|
@@ -107,9 +111,9 @@ async function settingsOf(root: string, file: string | undefined): Promise<Setti
|
|
|
107
111
|
return {
|
|
108
112
|
root,
|
|
109
113
|
configs: configs.map(({ loaded }) => loaded),
|
|
110
|
-
|
|
114
|
+
files: [...new Set(configs.flatMap(({ loaded, config }) => rootRelative(loaded.basePath, config.files ?? [])))],
|
|
111
115
|
timeout: latest.find(({ timeout }) => timeout !== undefined)?.timeout ?? 30_000,
|
|
112
|
-
existingErrors: latest.find(({ existingErrors }) => existingErrors !== undefined)?.existingErrors ?? '
|
|
116
|
+
existingErrors: latest.find(({ existingErrors }) => existingErrors !== undefined)?.existingErrors ?? 'warn',
|
|
113
117
|
rules: overrides(configs.map(({ loaded, config }) => rootRelativeRules(loaded.basePath, config.rules ?? {}))),
|
|
114
118
|
linters: [...new Set(configs.flatMap(({ config }) => config.linters ?? []))],
|
|
115
119
|
programs: Object.assign({}, ...configs.map(({ config }) => config.programs ?? {})),
|
|
@@ -129,8 +133,8 @@ export function rootRelative(basePath: string, globs: readonly string[]): readon
|
|
|
129
133
|
|
|
130
134
|
function rootRelativeRules(basePath: string, rules: NonNullable<Config['rules']>): Readonly<Record<string, RuleSettings>> {
|
|
131
135
|
return Object.fromEntries(Object.entries(rules).map(([id, override]) => {
|
|
132
|
-
const settings = typeof override === 'string' ? {
|
|
133
|
-
return [id, settings.
|
|
136
|
+
const settings = typeof override === 'string' ? { severity: override } : override
|
|
137
|
+
return [id, settings.files === undefined ? settings : { ...settings, files: rootRelative(basePath, settings.files) }]
|
|
134
138
|
}))
|
|
135
139
|
}
|
|
136
140
|
|
|
@@ -178,10 +182,10 @@ function validConfig(file: string, value: unknown): Config {
|
|
|
178
182
|
if (value.extends !== undefined && !(Array.isArray(value.extends) && value.extends.every((entry) => typeof entry === 'string' || isRecord(entry)))) fail('extends is a list of config paths, relative to the config, and config objects, such as [recommended].')
|
|
179
183
|
if (value.plugins !== undefined && !(isRecord(value.plugins) && Object.values(value.plugins).every((folder) => typeof folder === 'string'))) fail('plugins maps each plugin name to a folder.')
|
|
180
184
|
for (const name of Object.keys(value.plugins ?? {})) if (!/^[a-z][a-z0-9-]*$/.test(name)) fail(`"${name}" is not a plugin name: use lowercase letters, digits, and "-".`)
|
|
181
|
-
for (const key of ['
|
|
185
|
+
for (const key of ['files', 'probes'] as const) if (value[key] !== undefined && !isStrings(value[key])) fail(`${key} is a list of globs.`)
|
|
182
186
|
if (value.timeout !== undefined && !isTimeout(value.timeout)) fail('timeout is a whole number of milliseconds above 0.')
|
|
183
|
-
if (value.existingErrors !== undefined && !
|
|
184
|
-
if (value.rules !== undefined && !isRecord(value.rules)) fail('rules maps each rule name, such as "global/block-em-dashes", to a
|
|
187
|
+
if (value.existingErrors !== undefined && !isSeverity(value.existingErrors)) fail('existingErrors is "error" or "warn".')
|
|
188
|
+
if (value.rules !== undefined && !isRecord(value.rules)) fail('rules maps each rule name, such as "global/block-em-dashes", to a severity or to settings.')
|
|
185
189
|
for (const [id, override] of Object.entries(isRecord(value.rules) ? value.rules : {})) validOverride(file, id, override)
|
|
186
190
|
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(', ')}.`)
|
|
187
191
|
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(', ')}.`)
|
|
@@ -210,12 +214,12 @@ function validOverride(file: string, id: string, override: unknown): void {
|
|
|
210
214
|
const fail = (problem: string): never => {
|
|
211
215
|
throw new Error(`${file}: rules["${id}"] ${problem}`)
|
|
212
216
|
}
|
|
213
|
-
if (override === 'off' ||
|
|
214
|
-
if (!isRecord(override)) return fail('is "error", "
|
|
217
|
+
if (override === 'off' || isSeverity(override)) return
|
|
218
|
+
if (!isRecord(override)) return fail('is "error", "warn", "off", or an object of rule settings.')
|
|
215
219
|
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(', ')}.`)
|
|
216
|
-
if (override.
|
|
217
|
-
if (override.runs !== undefined && !isRuns(override.runs)) fail('runs is "always"
|
|
218
|
-
if (override.
|
|
220
|
+
if (override.severity !== undefined && override.severity !== 'off' && !isSeverity(override.severity)) fail('severity is "error", "warn", or "off".')
|
|
221
|
+
if (override.runs !== undefined && !isRuns(override.runs)) fail('runs is "always" or "manual".')
|
|
222
|
+
if (override.files !== undefined && !isStrings(override.files)) fail('files is a list of globs.')
|
|
219
223
|
if (override.timeout !== undefined && !isTimeout(override.timeout)) fail('timeout is a whole number of milliseconds above 0.')
|
|
220
224
|
if (override.threshold !== undefined && !isThreshold(override.threshold)) fail('threshold is a probability above 0 and at most 1.')
|
|
221
225
|
for (const key of ['agent', 'model', 'effort'] as const) if (override[key] !== undefined && typeof override[key] !== 'string') fail(`${key} is a string.`)
|
|
@@ -238,12 +242,12 @@ export function isStrings(value: unknown): value is string[] {
|
|
|
238
242
|
return Array.isArray(value) && value.every((item) => typeof item === 'string')
|
|
239
243
|
}
|
|
240
244
|
|
|
241
|
-
export function
|
|
242
|
-
return value === 'error' || value === '
|
|
245
|
+
export function isSeverity(value: unknown): value is Severity {
|
|
246
|
+
return value === 'error' || value === 'warn'
|
|
243
247
|
}
|
|
244
248
|
|
|
245
249
|
export function isRuns(value: unknown): value is Runs {
|
|
246
|
-
return value === 'always' || value === '
|
|
250
|
+
return value === 'always' || value === 'manual'
|
|
247
251
|
}
|
|
248
252
|
|
|
249
253
|
export function isTimeout(value: unknown): value is number {
|
package/src/edit.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, realpathSync } from 'node:fs'
|
|
2
2
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
3
|
+
import type { Call } from './api.ts'
|
|
3
4
|
import { checkFile } from './check.ts'
|
|
4
5
|
import { isClaudeMd } from './claude-md.ts'
|
|
5
6
|
import { existingFolder, isRecord, loadSettings, projectRoot } from './config.ts'
|
|
@@ -9,15 +10,13 @@ import { loadRules } from './rules.ts'
|
|
|
9
10
|
|
|
10
11
|
type Replacement = { readonly old_string: string; readonly new_string: string; readonly replace_all?: boolean }
|
|
11
12
|
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
readonly cwd: string
|
|
16
|
-
}
|
|
13
|
+
export const EDIT_TOOLS: ReadonlySet<string> = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch'])
|
|
14
|
+
|
|
15
|
+
const PATCH_FILE = /^\*\*\* (?:Update|Add|Delete) File: (.+)$/m
|
|
17
16
|
|
|
18
|
-
export function editRoot(call:
|
|
19
|
-
const path = call
|
|
20
|
-
return
|
|
17
|
+
export function editRoot(call: Call): string {
|
|
18
|
+
const path = editedPath(call)
|
|
19
|
+
return path === undefined ? projectRoot(call.cwd, call.cwd) : fileRoot(realFile(path, call.cwd), call.cwd)
|
|
21
20
|
}
|
|
22
21
|
|
|
23
22
|
export function realFile(path: string, cwd: string): string {
|
|
@@ -31,20 +30,28 @@ export function fileRoot(file: string, cwd: string): string {
|
|
|
31
30
|
return projectRoot(folder, file.startsWith(`${realpathSync(cwd)}/`) ? cwd : folder)
|
|
32
31
|
}
|
|
33
32
|
|
|
34
|
-
export async function checkEdit(call:
|
|
35
|
-
const path = call
|
|
36
|
-
if (
|
|
33
|
+
export async function checkEdit(call: Call, root: string): Promise<EditAnswer> {
|
|
34
|
+
const path = editedPath(call)
|
|
35
|
+
if (path === undefined) return editAnswer(undefined)
|
|
37
36
|
const file = realFile(path, call.cwd)
|
|
38
37
|
const previous = existsSync(file) ? await Bun.file(file).text() : undefined
|
|
39
|
-
const next = editedText(call.
|
|
40
|
-
if (next === undefined) return editAnswer(undefined)
|
|
38
|
+
const next = editedText(call.tool, call.input, previous) ?? ''
|
|
41
39
|
if (isClaudeMd(file)) watchImportSource(file)
|
|
42
40
|
const settings = await loadSettings(dirname(file), root)
|
|
43
41
|
const { rules } = await loadRules(settings)
|
|
44
|
-
const
|
|
42
|
+
const isWhole = next === ''
|
|
43
|
+
const report = await checkFile(settings, rules, file, next, { scope: 'edit', previous: isWhole ? '' : previous ?? '', imported: () => loadImportedFiles(root), call })
|
|
45
44
|
return editAnswer(report)
|
|
46
45
|
}
|
|
47
46
|
|
|
47
|
+
function editedPath({ tool, input }: Call): string | undefined {
|
|
48
|
+
const path = input.file_path ?? input.notebook_path
|
|
49
|
+
if (typeof path === 'string') return path
|
|
50
|
+
if (tool !== 'apply_patch') return undefined
|
|
51
|
+
const patch = [input.command, input.input, input.patch].find((text) => typeof text === 'string' && text.includes('*** '))
|
|
52
|
+
return typeof patch === 'string' ? PATCH_FILE.exec(patch)?.[1]?.trim() : undefined
|
|
53
|
+
}
|
|
54
|
+
|
|
48
55
|
function editedText(tool: string, input: Readonly<Record<string, unknown>>, previous: string | undefined): string | undefined {
|
|
49
56
|
if (tool === 'Write') return typeof input.content === 'string' ? input.content : undefined
|
|
50
57
|
if (previous === undefined) return undefined
|
package/src/files.ts
CHANGED
|
@@ -89,7 +89,7 @@ export async function listedFiles(folder: string): Promise<readonly string[] | u
|
|
|
89
89
|
|
|
90
90
|
export function projectFiles(settings: Settings, listed: readonly string[] | undefined): readonly string[] {
|
|
91
91
|
const candidates = listed === undefined
|
|
92
|
-
? settings.
|
|
92
|
+
? settings.files.flatMap((glob) => [...new Bun.Glob(glob).scanSync({ cwd: settings.root, absolute: true, dot: true })])
|
|
93
93
|
: listed.map((path) => join(settings.root, path))
|
|
94
94
|
return [...new Set(candidates)].sort()
|
|
95
95
|
}
|
package/src/jev.ts
CHANGED
package/src/linters.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync,
|
|
|
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
|
-
import type {
|
|
5
|
+
import type { LinterName } from './api.ts'
|
|
6
|
+
import type { Level } from './rules.ts'
|
|
6
7
|
import { existingFolder, isStrings } from './config.ts'
|
|
7
8
|
import { oneLine, openedDiagnostics, seconds, type Diagnostic, type Server } from './lsp.ts'
|
|
8
9
|
|
package/src/main.ts
CHANGED
|
@@ -17,14 +17,16 @@ const HELP = `rulebook ${packageJson.version}: checks any file, agent reply, and
|
|
|
17
17
|
|
|
18
18
|
Usage:
|
|
19
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,
|
|
21
|
-
rulebook check --stdin-file-path=<path> Check stdin as the text of the file or message at <path>, such as @reply, with
|
|
20
|
+
rulebook check --staged Check what the next commit records, on the lines it writes, with every rule and linter. Run it from a 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 or @command, with the rules that run always, as an agent's write is checked.
|
|
22
22
|
rulebook check --reporter=json Print the results as JSON.
|
|
23
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
|
|
25
|
-
rulebook claude-hook Check the tool call a Claude Code PreToolUse hook sends on stdin:
|
|
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 files it covers, and each message with the tools that send it, as JSON.
|
|
25
|
+
rulebook claude-hook Check the tool call a Claude Code or codex PreToolUse hook sends on stdin: a file write, a shell command as @command, or a call a message's tools match. An error refuses it.
|
|
26
26
|
rulebook --version Print the version.
|
|
27
27
|
|
|
28
|
+
An agent's write runs only the rules that run always. Every rulebook check runs the manual rules too, whatever starts it: a person, a git hook, or CI.
|
|
29
|
+
|
|
28
30
|
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.`
|
|
29
31
|
|
|
30
32
|
const REPORTERS = ['default', 'json']
|
|
@@ -111,7 +113,7 @@ async function check(named: readonly string[], skip: readonly string[], isJson:
|
|
|
111
113
|
const checked = await Promise.all(files.map(async (file) => {
|
|
112
114
|
const own = displayPath(settings, file).startsWith('@') ? settings : await loadSettings(dirname(file), root)
|
|
113
115
|
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope: 'all', imported: async () => imported, skip })
|
|
114
|
-
if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's
|
|
116
|
+
if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's files cover.`)
|
|
115
117
|
return report
|
|
116
118
|
}))
|
|
117
119
|
const linted = new Map([...groups].map(([own, owned]) => [{ ...own, linters: own.linters.filter((name) => !isSkipped(skip, name)) }, owned]))
|
package/src/questions.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { basename, dirname, join } from 'node:path'
|
|
2
|
-
import {
|
|
2
|
+
import type { Call } from './api.ts'
|
|
3
|
+
import { checkFile, COMMAND, globRegExp } from './check.ts'
|
|
3
4
|
import { CONFIG_FILE, globalConfigFile, isRecord, loadSettings, projectRoot } from './config.ts'
|
|
4
|
-
import { checkEdit,
|
|
5
|
+
import { checkEdit, EDIT_TOOLS, editRoot } from './edit.ts'
|
|
5
6
|
import { listedFiles } from './files.ts'
|
|
6
7
|
import { editAnswer, type EditAnswer } from './report.ts'
|
|
7
8
|
import { loadRules } from './rules.ts'
|
|
8
9
|
|
|
9
10
|
export type Question = 'edit' | 'text' | 'rules'
|
|
10
11
|
|
|
11
|
-
type Text = { readonly name: string; readonly text: string; readonly cwd: string; readonly
|
|
12
|
+
type Text = { readonly name: string; readonly text: string; readonly cwd: string; readonly call?: Call }
|
|
12
13
|
|
|
13
|
-
const
|
|
14
|
+
const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'])
|
|
14
15
|
|
|
15
16
|
type Answerer = {
|
|
16
17
|
root(input: unknown): string
|
|
@@ -19,8 +20,8 @@ type Answerer = {
|
|
|
19
20
|
|
|
20
21
|
const QUESTIONS: Readonly<Record<Question, Answerer>> = {
|
|
21
22
|
edit: {
|
|
22
|
-
root: (input) => editRoot(
|
|
23
|
-
answer: (input, root) => checkEdit(
|
|
23
|
+
root: (input) => editRoot(callOf(input)),
|
|
24
|
+
answer: (input, root) => checkEdit(callOf(input), root),
|
|
24
25
|
},
|
|
25
26
|
text: {
|
|
26
27
|
root: (input) => {
|
|
@@ -50,21 +51,21 @@ export function answer(question: Question, input: unknown, root: string): Promis
|
|
|
50
51
|
return QUESTIONS[question].answer(input, root)
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
async function checkText({ name, text, cwd,
|
|
54
|
+
async function checkText({ name, text, cwd, call }: Text, root: string): Promise<EditAnswer> {
|
|
54
55
|
const settings = await loadSettings(cwd, root)
|
|
55
56
|
if (!name.startsWith('@')) throw new Error('The text question checks a message by its @-name, such as @reply or @inbox/<id>.md.')
|
|
56
57
|
const { rules } = await loadRules(settings)
|
|
57
|
-
const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set(), ...(
|
|
58
|
+
const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set(), ...(call === undefined ? {} : { call }) })
|
|
58
59
|
return editAnswer(report)
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
export async function checkToolCall(input: unknown): Promise<EditAnswer | undefined> {
|
|
62
|
-
const call =
|
|
63
|
-
if (EDIT_TOOLS.
|
|
63
|
+
const call = callOf(input)
|
|
64
|
+
if (EDIT_TOOLS.has(call.tool)) return checkEdit(call, editRoot(call))
|
|
64
65
|
const root = projectRoot(call.cwd, call.cwd)
|
|
65
66
|
const messages = Object.entries((await loadSettings(call.cwd, root)).messages)
|
|
66
|
-
const name = messages.find(([, { tools }]) => tools.some((glob) => globRegExp(glob).test(call.
|
|
67
|
-
return name === undefined ? undefined : checkText({ name: `@${name}`, text:
|
|
67
|
+
const name = messages.find(([, { tools }]) => tools.some((glob) => globRegExp(glob).test(call.tool)))?.[0]
|
|
68
|
+
return name === undefined ? undefined : checkText({ name: `@${name}`, text: messageText(`@${name}`, call.input), cwd: call.cwd, call }, root)
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
@@ -81,11 +82,11 @@ async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
|
81
82
|
sources: [...new Set([globalConfigFile(), join(root, CONFIG_FILE), ...folders.flatMap((folder) => folder.settings.configs.flatMap((config) => [config.file, ...Object.values(config.plugins)]))])],
|
|
82
83
|
folders: folders.map((folder) => ({
|
|
83
84
|
path: folder.path,
|
|
84
|
-
rules: folder.rules.filter(({ level }) => level !== 'off').map(({ id, description,
|
|
85
|
+
rules: folder.rules.filter(({ level }) => level !== 'off').map(({ id, description, files = folder.settings.files }) => ({
|
|
85
86
|
id,
|
|
86
87
|
description,
|
|
87
|
-
isEverywhere:
|
|
88
|
-
|
|
88
|
+
isEverywhere: files.some((glob) => glob === (folder.path === '' ? '**' : `${folder.path}/**`) || glob.startsWith('@')),
|
|
89
|
+
files: regExpsOf(files),
|
|
89
90
|
})),
|
|
90
91
|
})),
|
|
91
92
|
messages: Object.entries(settings.messages).map(([name, { tools }]) => ({ name: `@${name}`, tools: regExpsOf(tools) })),
|
|
@@ -93,18 +94,37 @@ async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
|
93
94
|
}
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
function
|
|
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"}.')
|
|
98
|
-
return {
|
|
97
|
+
function callOf(input: unknown): Call {
|
|
98
|
+
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"}, with "session_id", "agent_type", "agent_id", and "transcript_path" when Claude Code sends them.')
|
|
99
|
+
return { tool: input.tool_name, input: input.tool_input, cwd: input.cwd, ...whoCalls(input) }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function whoCalls(input: Readonly<Record<string, unknown>>): Omit<Call, 'tool' | 'input' | 'cwd'> {
|
|
103
|
+
const fields = { session: input.session_id, agentType: input.agent_type, agentId: input.agent_id, transcriptPath: input.transcript_path }
|
|
104
|
+
return Object.fromEntries(Object.entries(fields).filter(([, value]) => typeof value === 'string' && value !== ''))
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
function textOf(input: unknown): Text {
|
|
102
108
|
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))
|
|
109
|
+
if (isRecord(input.input)) {
|
|
110
|
+
const call = typeof input.tool_name === 'string' ? { call: { tool: input.tool_name, input: input.input, cwd: input.cwd, ...whoCalls(input) } } : {}
|
|
111
|
+
return { name: input.name, text: messageText(input.name, input.input), cwd: input.cwd, ...call }
|
|
112
|
+
}
|
|
104
113
|
if (typeof input.text !== 'string') throw new Error('The text question reads {"name", "text" or "input", "cwd"}.')
|
|
105
114
|
return { name: input.name, text: input.text, cwd: input.cwd }
|
|
106
115
|
}
|
|
107
116
|
|
|
117
|
+
function messageText(name: string, input: Readonly<Record<string, unknown>>): string {
|
|
118
|
+
return name === COMMAND ? commandText(input.command ?? input.cmd) : textsOf(input).join('\n\n')
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function commandText(command: unknown): string {
|
|
122
|
+
if (typeof command === 'string') return command
|
|
123
|
+
if (!Array.isArray(command) || !command.every((word) => typeof word === 'string')) return ''
|
|
124
|
+
const [shell = '', flag = '', script] = command
|
|
125
|
+
return command.length === 3 && SHELLS.has(basename(shell)) && /^-[a-z]*c$/.test(flag) && script !== undefined ? script : command.join(' ')
|
|
126
|
+
}
|
|
127
|
+
|
|
108
128
|
function textsOf(value: unknown): readonly string[] {
|
|
109
129
|
if (typeof value === 'string') return [value]
|
|
110
130
|
if (Array.isArray(value)) return value.flatMap(textsOf)
|
package/src/report.ts
CHANGED
|
@@ -12,7 +12,7 @@ function findingLines(findings: readonly Reported[]): string {
|
|
|
12
12
|
const levelWidth = Math.max(...findings.map(({ level }) => level.length))
|
|
13
13
|
const ruleWidth = Math.max(...findings.map(({ rule }) => rule.length))
|
|
14
14
|
return findings
|
|
15
|
-
.map(({ line, level, rule, message, quote }) => ` ${String(line).padStart(lineWidth)} ${level.padEnd(levelWidth)} ${rule.padEnd(ruleWidth)} ${message}
|
|
15
|
+
.map(({ line, level, rule, message, quote }) => ` ${String(line).padStart(lineWidth)} ${level.padEnd(levelWidth)} ${rule.padEnd(ruleWidth)} ${message}${quote.trim() === '' ? '' : `\n ${' '.repeat(lineWidth)} > ${quote.trim()}`}`.trimEnd())
|
|
16
16
|
.join('\n')
|
|
17
17
|
}
|
|
18
18
|
|
package/src/rules.ts
CHANGED
|
@@ -1,21 +1,36 @@
|
|
|
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 {
|
|
4
|
+
import type { ParsedShell } from '@cmodjs/core/shell.js'
|
|
5
|
+
import type { Call, Command, Context, Document, Line, Rule, RuleSettings, Runs, Severity, Visitors } from './api.ts'
|
|
5
6
|
import { importsRule, noSuppressionsRule } from './check.ts'
|
|
6
7
|
import type { Import } from './claude-md.ts'
|
|
7
|
-
import {
|
|
8
|
+
import { isRecord, isRuns, isSeverity, isStrings, isThreshold, isTimeout, rootRelative, type Settings } from './config.ts'
|
|
8
9
|
import { isJev } from './jev.ts'
|
|
9
10
|
import { cacheFolder } from './linters.ts'
|
|
10
11
|
import { importDefault } from './modules.ts'
|
|
11
12
|
|
|
13
|
+
export type Level = 'error' | 'warning'
|
|
14
|
+
|
|
15
|
+
export type Finding = { readonly line: number; readonly message?: string; readonly isWhole?: true }
|
|
16
|
+
|
|
17
|
+
export type CheckedFile = {
|
|
18
|
+
readonly root: string
|
|
19
|
+
readonly path: string
|
|
20
|
+
readonly text: string
|
|
21
|
+
readonly lines: readonly string[]
|
|
22
|
+
readonly shell?: ParsedShell
|
|
23
|
+
readonly call?: Call
|
|
24
|
+
}
|
|
25
|
+
|
|
12
26
|
type Common = {
|
|
13
27
|
readonly id: string
|
|
14
28
|
readonly source: string
|
|
15
29
|
readonly description: string
|
|
30
|
+
readonly message: string | undefined
|
|
16
31
|
readonly level: Level | 'off'
|
|
17
32
|
readonly runs: Runs
|
|
18
|
-
readonly
|
|
33
|
+
readonly files: readonly string[] | undefined
|
|
19
34
|
}
|
|
20
35
|
|
|
21
36
|
type Doc = { readonly file: string; readonly imports: readonly Import[] }
|
|
@@ -42,12 +57,14 @@ export type LoadedRule = StaticRule | AgenticRule
|
|
|
42
57
|
export type Rules = { readonly rules: readonly LoadedRule[]; readonly failures: readonly string[] }
|
|
43
58
|
|
|
44
59
|
const RULE_FILES = new Bun.Glob('**/*.{ts,md,yml}')
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const
|
|
60
|
+
const COMMON_KEYS = ['description', 'message', 'files', 'severity', 'runs']
|
|
61
|
+
const SCRIPT_KEYS = new Set([...COMMON_KEYS, 'create'])
|
|
62
|
+
const FRONTMATTER_KEYS = new Set([...COMMON_KEYS, 'timeout', 'threshold', 'agent', 'model', 'effort', 'allowed-tools', 'disallowed-tools'])
|
|
48
63
|
const CLAUDE_KEYS = ['agent', 'effort', 'allowed-tools', 'disallowed-tools'] as const
|
|
49
|
-
const PATTERN_KEYS = new Set([
|
|
64
|
+
const PATTERN_KEYS = new Set([...COMMON_KEYS, 'language', 'rule'])
|
|
65
|
+
const VISITORS = new Set(['Document', 'Line', 'Command'])
|
|
50
66
|
const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown']
|
|
67
|
+
const CODE_FENCE = /^\s*(`{3,}|~{3,})(.*)$/
|
|
51
68
|
|
|
52
69
|
let astGrep: Promise<typeof import('@ast-grep/napi')> | undefined
|
|
53
70
|
|
|
@@ -74,7 +91,7 @@ async function rulesOf(settings: Settings): Promise<Rules> {
|
|
|
74
91
|
ids.add(id)
|
|
75
92
|
try {
|
|
76
93
|
const rule = await loadedRule(id, source, settings.timeout)
|
|
77
|
-
rules.push({ ...rule,
|
|
94
|
+
rules.push({ ...rule, files: rule.files && rootRelative(config.basePath, rule.files) })
|
|
78
95
|
} catch (error) {
|
|
79
96
|
failures.push(`${error instanceof Error ? error.message : String(error)} The rule ${id} checks nothing until it loads.`)
|
|
80
97
|
}
|
|
@@ -83,8 +100,8 @@ async function rulesOf(settings: Settings): Promise<Rules> {
|
|
|
83
100
|
}
|
|
84
101
|
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
102
|
const loaded = rules.map((rule) => overridden(rule, settings.rules[rule.id]))
|
|
86
|
-
for (const { id,
|
|
87
|
-
if (
|
|
103
|
+
for (const { id, files, level } of loaded) {
|
|
104
|
+
if (files === undefined && level !== 'off' && settings.files.length === 0) failures.push(`The rule ${id} has no files, and no config lists files, so it checks no file. Give the rule files, such as files: ['**/*.ts'].`)
|
|
88
105
|
}
|
|
89
106
|
return { rules: loaded, failures }
|
|
90
107
|
}
|
|
@@ -97,10 +114,58 @@ function loadedRule(id: string, source: string, timeout: number): Promise<Loaded
|
|
|
97
114
|
|
|
98
115
|
async function scriptRule(id: string, source: string): Promise<StaticRule> {
|
|
99
116
|
const rule = await importDefault(source)
|
|
100
|
-
if (!isRecord(rule) || typeof rule.
|
|
117
|
+
if (!isRecord(rule) || typeof rule.create !== 'function') throw new Error(`${source}: the default export is not a rule. Export defineRule({ description, create }).`)
|
|
101
118
|
for (const key of Object.keys(rule)) if (!SCRIPT_KEYS.has(key)) throw new Error(`${source}: rulebook does not read the key "${key}". It reads ${[...SCRIPT_KEYS].join(', ')}.`)
|
|
102
|
-
const
|
|
103
|
-
return { ...commonOf(id, source, rule), kind: 'static', check: (file) =>
|
|
119
|
+
const create = rule.create as Rule['create']
|
|
120
|
+
return { ...commonOf(id, source, rule), kind: 'static', check: (file) => visited(source, create, file) }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function visited(source: string, create: Rule['create'], file: CheckedFile): Promise<readonly Finding[]> {
|
|
124
|
+
const found: Finding[] = []
|
|
125
|
+
const lines = linesOf(file)
|
|
126
|
+
const commands = commandsOf(file)
|
|
127
|
+
const document: Document = { lineNumber: 1, text: file.text }
|
|
128
|
+
const context: Context = {
|
|
129
|
+
root: file.root,
|
|
130
|
+
path: file.path,
|
|
131
|
+
text: file.text,
|
|
132
|
+
lines,
|
|
133
|
+
commands,
|
|
134
|
+
...(file.shell === undefined ? {} : { shell: { reads: file.shell.reads, writes: file.shell.writes, fetches: file.shell.fetches, isFullyParsed: file.shell.isFullyParsed } }),
|
|
135
|
+
...(file.call === undefined ? {} : { call: file.call }),
|
|
136
|
+
report: ({ node }) => {
|
|
137
|
+
found.push(node === document ? { line: 1, isWhole: true } : { line: node.lineNumber })
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
const visitors: Visitors = await create(context)
|
|
141
|
+
if (!isRecord(visitors)) throw new Error(`${source}: create returns an object of visitors, such as { Line(line) { … } }.`)
|
|
142
|
+
for (const key of Object.keys(visitors)) if (!VISITORS.has(key)) throw new Error(`${source}: create returns the visitor "${key}". rulebook visits ${[...VISITORS].join(', ')}.`)
|
|
143
|
+
await visitors.Document?.(document)
|
|
144
|
+
if (visitors.Line !== undefined) for (const line of lines) await visitors.Line(line)
|
|
145
|
+
if (visitors.Command !== undefined) for (const command of commands) await visitors.Command(command)
|
|
146
|
+
return found
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function linesOf({ path, lines }: CheckedFile): readonly Line[] {
|
|
150
|
+
const isMarkdown = (path.startsWith('@') && path !== '@command') || /\.(md|mdx|markdown)$/i.test(path)
|
|
151
|
+
let fence: { readonly marker: string; readonly length: number } | undefined
|
|
152
|
+
return lines.map((text, index) => {
|
|
153
|
+
const match = isMarkdown ? CODE_FENCE.exec(text) : null
|
|
154
|
+
const isInCodeBlock = fence !== undefined || match !== null
|
|
155
|
+
if (match !== null) {
|
|
156
|
+
const marker = match[1] ?? ''
|
|
157
|
+
if (fence === undefined) fence = { marker: marker[0] ?? '`', length: marker.length }
|
|
158
|
+
else if (marker[0] === fence.marker && marker.length >= fence.length && (match[2] ?? '').trim() === '') fence = undefined
|
|
159
|
+
}
|
|
160
|
+
return { lineNumber: index + 1, text, isInCodeBlock }
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function commandsOf({ shell, lines }: CheckedFile): readonly Command[] {
|
|
165
|
+
return (shell?.commands ?? []).map(({ argv, folder, input }) => {
|
|
166
|
+
const index = lines.findIndex((line) => line.includes(argv[0]))
|
|
167
|
+
return { lineNumber: index === -1 ? 1 : index + 1, program: basename(argv[0]), args: argv.slice(1), argv, folder, ...(input === undefined ? {} : { input }) }
|
|
168
|
+
})
|
|
104
169
|
}
|
|
105
170
|
|
|
106
171
|
async function agenticRule(id: string, source: string, timeout: number): Promise<AgenticRule> {
|
|
@@ -115,23 +180,20 @@ async function agenticRule(id: string, source: string, timeout: number): Promise
|
|
|
115
180
|
for (const key of Object.keys(frontmatter)) if (!FRONTMATTER_KEYS.has(key)) fail(`rulebook does not read the key "${key}". It reads ${[...FRONTMATTER_KEYS].join(', ')}.`)
|
|
116
181
|
for (const key of ['agent', 'model', 'effort'] as const) if (frontmatter[key] !== undefined && typeof frontmatter[key] !== 'string') fail(`${key} is a string.`)
|
|
117
182
|
for (const key of ['allowed-tools', 'disallowed-tools'] as const) if (frontmatter[key] !== undefined && typeof frontmatter[key] !== 'string' && !isStrings(frontmatter[key])) fail(`${key} is a string or a list.`)
|
|
118
|
-
|
|
119
|
-
if (!
|
|
120
|
-
for (const key of Object.keys(metadata)) if (!METADATA_KEYS.has(key)) fail(`metadata.${key} is not a rulebook key. rulebook reads metadata.level, metadata.runs, metadata.timeout, and metadata.threshold.`)
|
|
121
|
-
if (metadata.timeout !== undefined && !isTimeout(metadata.timeout)) fail('metadata.timeout is a whole number of milliseconds above 0.')
|
|
122
|
-
if (metadata.threshold !== undefined && !isThreshold(metadata.threshold)) fail('metadata.threshold is a probability above 0 and at most 1.')
|
|
183
|
+
if (frontmatter.timeout !== undefined && !isTimeout(frontmatter.timeout)) fail('timeout is a whole number of milliseconds above 0.')
|
|
184
|
+
if (frontmatter.threshold !== undefined && !isThreshold(frontmatter.threshold)) fail('threshold is a probability above 0 and at most 1.')
|
|
123
185
|
if (body === '') fail('the rule has no body. The body is the check.')
|
|
124
186
|
if (isJev(frontmatter.model)) for (const key of CLAUDE_KEYS) if (frontmatter[key] !== undefined) fail(`model jev runs the rule on Jev, which runs no agent, so rulebook does not read ${key}.`)
|
|
125
|
-
if (
|
|
187
|
+
if (frontmatter.threshold !== undefined && !isJev(frontmatter.model)) fail('threshold is the probability Jev must give a line to pass, so it needs model: jev.')
|
|
126
188
|
return {
|
|
127
|
-
...commonOf(id, source,
|
|
189
|
+
...commonOf(id, source, frontmatter),
|
|
128
190
|
kind: 'agentic',
|
|
129
|
-
timeout: (
|
|
191
|
+
timeout: (frontmatter.timeout as number | undefined) ?? timeout,
|
|
130
192
|
body,
|
|
131
193
|
agent: frontmatter.agent as string | undefined,
|
|
132
194
|
model: frontmatter.model as string | undefined,
|
|
133
195
|
effort: frontmatter.effort as string | undefined,
|
|
134
|
-
threshold:
|
|
196
|
+
threshold: frontmatter.threshold as number | undefined,
|
|
135
197
|
allowedTools: frontmatter['allowed-tools'] as string | readonly string[] | undefined,
|
|
136
198
|
disallowedTools: frontmatter['disallowed-tools'] as string | readonly string[] | undefined,
|
|
137
199
|
}
|
|
@@ -195,25 +257,31 @@ function commonOf(id: string, source: string, keys: Readonly<Record<string, unkn
|
|
|
195
257
|
const fail = (problem: string): never => {
|
|
196
258
|
throw new Error(`${source}: ${problem}`)
|
|
197
259
|
}
|
|
198
|
-
const { description,
|
|
260
|
+
const { description, message, severity, runs } = keys
|
|
199
261
|
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."')
|
|
200
|
-
if (
|
|
201
|
-
if (
|
|
262
|
+
if (message !== undefined && (typeof message !== 'string' || message.trim() === '')) fail('message is the text of each finding, a string. Leave it out to show the description.')
|
|
263
|
+
if (severity !== undefined && !isSeverity(severity)) fail('severity is "error" or "warn".')
|
|
264
|
+
if (runs !== undefined && !isRuns(runs)) fail('runs is "always" or "manual".')
|
|
202
265
|
return {
|
|
203
266
|
id,
|
|
204
267
|
source,
|
|
205
268
|
description: description.trim(),
|
|
206
|
-
|
|
269
|
+
message: typeof message === 'string' ? message.trim() : undefined,
|
|
270
|
+
level: levelOf((severity as Severity | undefined) ?? 'error'),
|
|
207
271
|
runs: (runs as Runs | undefined) ?? 'always',
|
|
208
|
-
|
|
272
|
+
files: filesOf(source, keys.files),
|
|
209
273
|
}
|
|
210
274
|
}
|
|
211
275
|
|
|
212
|
-
function
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
276
|
+
export function levelOf(severity: Severity): Level {
|
|
277
|
+
return severity === 'warn' ? 'warning' : 'error'
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function filesOf(source: string, files: unknown): readonly string[] | undefined {
|
|
281
|
+
if (files === undefined) return undefined
|
|
282
|
+
if (typeof files === 'string') return files.split(',').map((file) => file.trim()).filter((file) => file !== '')
|
|
283
|
+
if (isStrings(files)) return files
|
|
284
|
+
throw new Error(`${source}: files is a list of globs or a comma-separated string.`)
|
|
217
285
|
}
|
|
218
286
|
|
|
219
287
|
function yamlOf(source: string, text: string): unknown {
|
|
@@ -226,8 +294,8 @@ function yamlOf(source: string, text: string): unknown {
|
|
|
226
294
|
|
|
227
295
|
function overridden(rule: LoadedRule, override: RuleSettings | undefined): LoadedRule {
|
|
228
296
|
if (override === undefined) return rule
|
|
229
|
-
const {
|
|
230
|
-
const common = { ...rule, ...(
|
|
297
|
+
const { severity, runs, files } = override
|
|
298
|
+
const common = { ...rule, ...(severity === undefined ? {} : { level: severity === 'off' ? 'off' as const : levelOf(severity) }), ...(runs === undefined ? {} : { runs }), ...(files === undefined ? {} : { files }) }
|
|
231
299
|
if (common.kind === 'static') {
|
|
232
300
|
for (const key of ['agent', 'model', 'effort', 'timeout', 'threshold'] as const) if (override[key] !== undefined) throw new Error(`A rulebook config sets ${key} on ${rule.id}, a static rule, which runs no agent.`)
|
|
233
301
|
return common
|