@cmodjs/rulebook 0.4.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 +37 -24
- package/src/commit.ts +4 -4
- package/src/config.ts +25 -21
- package/src/edit.ts +30 -22
- package/src/files.ts +1 -1
- package/src/jev.ts +1 -1
- package/src/linters.ts +2 -1
- package/src/main.ts +68 -35
- package/src/questions.ts +43 -23
- package/src/report.ts +3 -3
- package/src/rules.ts +102 -34
- package/src/serve.ts +3 -3
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,16 +2,17 @@ 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
|
-
type Scope = 'edit' | 'commit' | 'all'
|
|
15
|
+
type Scope = 'edit' | 'commit' | 'all'
|
|
15
16
|
|
|
16
17
|
export type Reported = {
|
|
17
18
|
readonly rule: string
|
|
@@ -34,9 +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
|
|
39
|
+
readonly skip?: readonly string[]
|
|
38
40
|
}
|
|
39
41
|
|
|
42
|
+
export const COMMAND = '@command'
|
|
40
43
|
const PIN = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
|
|
41
44
|
const MAX_EDIT_LENGTH = 1_000
|
|
42
45
|
|
|
@@ -73,7 +76,7 @@ function isProbe(settings: Settings, file: string): boolean {
|
|
|
73
76
|
}
|
|
74
77
|
|
|
75
78
|
export function isPrompt(settings: Settings, file: string): boolean {
|
|
76
|
-
return isInside(settings.root, file) && matches(settings.
|
|
79
|
+
return isInside(settings.root, file) && matches(settings.files, relative(settings.root, file))
|
|
77
80
|
}
|
|
78
81
|
|
|
79
82
|
export async function checkFile(settings: Settings, rules: readonly LoadedRule[], file: string, text: string, options: CheckOptions): Promise<FileReport | undefined> {
|
|
@@ -83,19 +86,25 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
83
86
|
const configured = probe || (!isMessage && isPrompt(settings, file))
|
|
84
87
|
const isMemory = !isMessage && isClaudeMd(file)
|
|
85
88
|
const imported = !isMessage && !(configured && isMemory) && existsSync(file) && (await options.imported()).has(realpathSync(file))
|
|
86
|
-
const covered = rules.filter((rule) => inScope(rule, options
|
|
87
|
-
const linted = !isMessage && !probe ? coveringLinters(settings.linters, settings.programs, file, text, settings.root) : []
|
|
89
|
+
const covered = rules.filter((rule) => inScope(rule, options) && covers(rule, path, configured || imported))
|
|
90
|
+
const linted = !isMessage && !probe ? coveringLinters(settings.linters.filter((name) => !isSkipped(options.skip, name)), settings.programs, file, text, settings.root) : []
|
|
88
91
|
if (!configured && !imported && covered.length === 0 && linted.length === 0) return undefined
|
|
89
92
|
const written = text.split('\n')
|
|
90
93
|
const isDoc = imported || isMemory
|
|
91
94
|
const mayPin = text.includes('rulebook-expect')
|
|
92
95
|
const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
|
|
93
96
|
const memory = isDoc ? claudeMd : undefined
|
|
94
|
-
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
|
+
}
|
|
95
104
|
const doc = memory === undefined ? undefined : { file, imports: memory.imports }
|
|
96
105
|
const pins = mayPin ? pinsOf(written, claudeMd?.lines ?? []) : []
|
|
97
106
|
const pinned = new Set(pins.map(({ rule }) => rule))
|
|
98
|
-
const chosen = probe ? rules.filter((rule) => inScope(rule, options
|
|
107
|
+
const chosen = probe ? rules.filter((rule) => inScope(rule, options) && pinned.has(rule.id)) : covered
|
|
99
108
|
const wrote = options.previous === undefined ? undefined : linesWritten(options.previous, written)
|
|
100
109
|
const changed = wrote === undefined ? undefined : [...wrote].filter((line) => written[line - 1]?.trim() !== '')
|
|
101
110
|
|
|
@@ -114,18 +123,18 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
114
123
|
|
|
115
124
|
const lints = await linting
|
|
116
125
|
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
117
|
-
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)]
|
|
118
|
-
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options
|
|
119
|
-
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.' }))]
|
|
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)]
|
|
127
|
+
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
|
|
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.' }))]
|
|
120
129
|
|
|
121
130
|
return {
|
|
122
131
|
path,
|
|
123
132
|
failures,
|
|
124
133
|
findings: flagged
|
|
125
|
-
.map((finding) => {
|
|
134
|
+
.map(({ isWhole, ...finding }) => {
|
|
126
135
|
const quote = written[finding.line - 1] ?? ''
|
|
127
|
-
const isExisting = wrote !== undefined && !wrote.has(finding.line)
|
|
128
|
-
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 }
|
|
129
138
|
})
|
|
130
139
|
.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)),
|
|
131
140
|
}
|
|
@@ -180,14 +189,16 @@ async function linterFlags(linter: Covering, file: string, text: string, timeout
|
|
|
180
189
|
}
|
|
181
190
|
|
|
182
191
|
function covers(rule: LoadedRule, path: string, isPrompt: boolean): boolean {
|
|
183
|
-
return rule.level !== 'off' && (rule.
|
|
192
|
+
return rule.level !== 'off' && (rule.files === undefined ? isPrompt : matches(rule.files, path))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function inScope(rule: LoadedRule, { scope, skip }: CheckOptions): boolean {
|
|
196
|
+
if (isSkipped(skip, rule.id) || (rule.kind === 'agentic' && isSkipped(skip, 'agentic'))) return false
|
|
197
|
+
return scope !== 'edit' || rule.runs === 'always'
|
|
184
198
|
}
|
|
185
199
|
|
|
186
|
-
function
|
|
187
|
-
|
|
188
|
-
if (scope === 'static') return rule.kind === 'static'
|
|
189
|
-
if (scope === 'commit') return rule.runs !== 'manual'
|
|
190
|
-
return rule.runs === 'always'
|
|
200
|
+
export function isSkipped(skip: readonly string[] | undefined, name: string): boolean {
|
|
201
|
+
return skip?.some((skipped) => name === skipped || name.startsWith(`${skipped}/`)) ?? false
|
|
191
202
|
}
|
|
192
203
|
|
|
193
204
|
type Pin = { readonly rule: string; readonly line: number; readonly target: number }
|
|
@@ -247,9 +258,10 @@ export function importsRule(settings: Settings): StaticRule {
|
|
|
247
258
|
source: 'rulebook',
|
|
248
259
|
kind: 'static',
|
|
249
260
|
description: 'Import only files that exist.',
|
|
261
|
+
message: undefined,
|
|
250
262
|
level: 'off',
|
|
251
263
|
runs: 'always',
|
|
252
|
-
|
|
264
|
+
files: undefined,
|
|
253
265
|
check: (_, doc) => (doc === undefined ? [] : doc.imports.flatMap(({ path, line }) => {
|
|
254
266
|
const target = importedFile(doc.file, path)
|
|
255
267
|
if (target === undefined || statSync(target, { throwIfNoEntry: false })?.isFile() === true) return []
|
|
@@ -275,16 +287,17 @@ export const noSuppressionsRule: StaticRule = {
|
|
|
275
287
|
source: 'rulebook',
|
|
276
288
|
kind: 'static',
|
|
277
289
|
description: 'Fix the code instead of suppressing the rule.',
|
|
290
|
+
message: undefined,
|
|
278
291
|
level: 'off',
|
|
279
292
|
runs: 'always',
|
|
280
|
-
|
|
293
|
+
files: [`**/*.{${[...new Set(Object.values(LINTERS).flatMap(({ extensions }) => extensions.map((extension) => extension.slice(1))))].join(',')}}`, '**/!(*.*)'],
|
|
281
294
|
check: ({ lines }) => lines.flatMap((text, index) => {
|
|
282
295
|
const linter = Object.entries(SUPPRESSIONS).find(([, suppression]) => suppression.test(text))?.[0]
|
|
283
296
|
return linter === undefined ? [] : [{ line: index + 1, message: `This comment suppresses ${linter}. Fix the code ${linter} flags, and remove the comment.` }]
|
|
284
297
|
}),
|
|
285
298
|
}
|
|
286
299
|
|
|
287
|
-
type Flag = Omit<Reported, 'isExisting' | 'quote'>
|
|
300
|
+
type Flag = Omit<Reported, 'isExisting' | 'quote'> & { readonly isWhole?: true }
|
|
288
301
|
|
|
289
302
|
function probeFindings(found: readonly Flag[], pins: readonly Pin[]): readonly Flag[] {
|
|
290
303
|
const open = [...pins]
|
package/src/commit.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync,
|
|
|
2
2
|
import { constants, tmpdir } from 'node:os'
|
|
3
3
|
import { basename, dirname, join, relative } from 'node:path'
|
|
4
4
|
import type { LinterName } from './api.ts'
|
|
5
|
-
import { checkFile, lintProject, type FileReport, type Reported } from './check.ts'
|
|
5
|
+
import { checkFile, isSkipped, lintProject, type FileReport, type Reported } from './check.ts'
|
|
6
6
|
import { isInside, loadSettings } from './config.ts'
|
|
7
7
|
import { filesBySettings, loadImportedFiles } from './files.ts'
|
|
8
8
|
import { isLinterInput, LINTERS, projectLinters } from './linters.ts'
|
|
@@ -13,7 +13,7 @@ export type CommitReport = { readonly reports: readonly FileReport[]; readonly f
|
|
|
13
13
|
const DEPENDENCIES = new Set(Object.values(LINTERS).flatMap(({ copies }) => copies.map((copy) => copy.split('/')[0] ?? copy)))
|
|
14
14
|
const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
|
|
15
15
|
|
|
16
|
-
export async function
|
|
16
|
+
export async function checkStaged(root: string, skip: readonly string[]): Promise<CommitReport> {
|
|
17
17
|
const unloaded = new Set<string>()
|
|
18
18
|
const staged = await gitPaths(root, ['diff', '--cached', '--name-only', '-z', '--diff-filter=ACMR'])
|
|
19
19
|
const deleted = await gitPaths(root, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--diff-filter=D'])
|
|
@@ -25,10 +25,10 @@ export async function checkCommit(root: string): Promise<CommitReport> {
|
|
|
25
25
|
const settings = await loadSettings(dirname(file), root)
|
|
26
26
|
const { rules, failures } = await loadRules(settings)
|
|
27
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) })
|
|
28
|
+
return checkFile(settings, rules, file, text, { scope: 'commit', previous: await committed(root, renamed.get(path) ?? path), imported: () => loadImportedFiles(root), skip })
|
|
29
29
|
}))
|
|
30
30
|
const reports = checked.filter((report) => report !== undefined)
|
|
31
|
-
const linters = new Set((await Promise.all([...staged, ...deleted].map((path) => lintersCovering(root, path)))).flat())
|
|
31
|
+
const linters = new Set((await Promise.all([...staged, ...deleted].map((path) => lintersCovering(root, path)))).flat().filter((name) => !isSkipped(skip, name)))
|
|
32
32
|
return { reports: linters.size === 0 ? reports : withAddedErrors(reports, await addedErrors(root, linters, renamed)), failures: [...unloaded] }
|
|
33
33
|
}
|
|
34
34
|
|
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,39 +10,46 @@ 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
|
-
|
|
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
|
|
16
|
+
|
|
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)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function realFile(path: string, cwd: string): string {
|
|
23
|
+
const file = isAbsolute(path) ? path : resolve(cwd, path)
|
|
24
|
+
const nearest = existingFolder(file)
|
|
25
|
+
return join(realpathSync(nearest), relative(nearest, file))
|
|
16
26
|
}
|
|
17
27
|
|
|
18
|
-
export function
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
return projectRoot(edited.folder, edited.file.startsWith(`${realpathSync(call.cwd)}/`) ? call.cwd : edited.folder)
|
|
28
|
+
export function fileRoot(file: string, cwd: string): string {
|
|
29
|
+
const folder = existingFolder(dirname(file))
|
|
30
|
+
return projectRoot(folder, file.startsWith(`${realpathSync(cwd)}/`) ? cwd : folder)
|
|
22
31
|
}
|
|
23
32
|
|
|
24
|
-
export async function checkEdit(call:
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
-
const
|
|
33
|
+
export async function checkEdit(call: Call, root: string): Promise<EditAnswer> {
|
|
34
|
+
const path = editedPath(call)
|
|
35
|
+
if (path === undefined) return editAnswer(undefined)
|
|
36
|
+
const file = realFile(path, call.cwd)
|
|
28
37
|
const previous = existsSync(file) ? await Bun.file(file).text() : undefined
|
|
29
|
-
const next = editedText(call.
|
|
30
|
-
if (next === undefined) return editAnswer(undefined)
|
|
38
|
+
const next = editedText(call.tool, call.input, previous) ?? ''
|
|
31
39
|
if (isClaudeMd(file)) watchImportSource(file)
|
|
32
40
|
const settings = await loadSettings(dirname(file), root)
|
|
33
41
|
const { rules } = await loadRules(settings)
|
|
34
|
-
const
|
|
42
|
+
const isWhole = next === ''
|
|
43
|
+
const report = await checkFile(settings, rules, file, next, { scope: 'edit', previous: isWhole ? '' : previous ?? '', imported: () => loadImportedFiles(root), call })
|
|
35
44
|
return editAnswer(report)
|
|
36
45
|
}
|
|
37
46
|
|
|
38
|
-
function
|
|
39
|
-
const path =
|
|
40
|
-
if (typeof path
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
return { file: real, folder: existingFolder(dirname(real)) }
|
|
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
|
|
45
53
|
}
|
|
46
54
|
|
|
47
55
|
function editedText(tool: string, input: Readonly<Record<string, unknown>>, previous: string | undefined): string | 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
|
@@ -3,49 +3,70 @@ 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 {
|
|
11
|
-
import { commitReport, textReport } from './report.ts'
|
|
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'
|
|
12
13
|
import { loadRules, type LoadedRule } from './rules.ts'
|
|
13
14
|
import { serve } from './serve.ts'
|
|
14
15
|
|
|
15
16
|
const HELP = `rulebook ${packageJson.version}: checks any file, agent reply, and tool call against your rules and your project's linters.
|
|
16
17
|
|
|
17
18
|
Usage:
|
|
18
|
-
rulebook [files...]
|
|
19
|
-
rulebook --
|
|
20
|
-
rulebook --
|
|
21
|
-
rulebook
|
|
22
|
-
rulebook
|
|
23
|
-
rulebook
|
|
24
|
-
rulebook
|
|
25
|
-
rulebook
|
|
26
|
-
|
|
27
|
-
|
|
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, 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
|
+
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 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
|
+
rulebook --version Print the version.
|
|
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.
|
|
28
29
|
|
|
29
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.`
|
|
30
31
|
|
|
32
|
+
const REPORTERS = ['default', 'json']
|
|
33
|
+
|
|
31
34
|
async function main(argv: readonly string[]): Promise<number> {
|
|
32
35
|
const { values, positionals } = parseArgs({
|
|
33
36
|
args: [...argv],
|
|
34
37
|
allowPositionals: true,
|
|
35
|
-
options: {
|
|
38
|
+
options: {
|
|
39
|
+
staged: { type: 'boolean' },
|
|
40
|
+
'stdin-file-path': { type: 'string' },
|
|
41
|
+
reporter: { type: 'string', default: 'default' },
|
|
42
|
+
skip: { type: 'string', multiple: true, default: [] },
|
|
43
|
+
version: { type: 'boolean' },
|
|
44
|
+
help: { type: 'boolean', short: 'h' },
|
|
45
|
+
},
|
|
36
46
|
})
|
|
47
|
+
const [command, ...named] = positionals
|
|
37
48
|
if (values.version) return print(packageJson.version)
|
|
38
|
-
if (values.help) return print(HELP)
|
|
39
|
-
if (
|
|
40
|
-
if (
|
|
41
|
-
if (
|
|
42
|
-
if (
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
|
|
49
|
+
if (values.help || command === undefined) return print(HELP)
|
|
50
|
+
if (command === '__run_server') return serve()
|
|
51
|
+
if (command === 'claude-hook') return claudeHook(JSON.parse(await Bun.stdin.text()))
|
|
52
|
+
if (command === 'inspect') return inspect(named)
|
|
53
|
+
if (command !== 'check') throw new Error(`${command} is not a rulebook command. \`rulebook --help\` lists them.`)
|
|
54
|
+
if (!REPORTERS.includes(values.reporter)) throw new Error(`--reporter is default or json, not ${values.reporter}.`)
|
|
55
|
+
const isJson = values.reporter === 'json'
|
|
56
|
+
const stdinPath = values['stdin-file-path']
|
|
57
|
+
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.')
|
|
58
|
+
if (values.staged === true) return staged(values.skip, isJson)
|
|
59
|
+
if (stdinPath !== undefined) return checkStdin(stdinPath, values.skip, isJson)
|
|
60
|
+
return check(named, values.skip, isJson)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function inspect([target, ...rest]: readonly string[]): Promise<number> {
|
|
64
|
+
if (target !== 'rules' || rest.length > 0) throw new Error('rulebook inspect takes rules.')
|
|
65
|
+
const input = { cwd: process.cwd() }
|
|
66
|
+
return print(JSON.stringify(await answer('rules', input, projectOf('rules', input))))
|
|
46
67
|
}
|
|
47
68
|
|
|
48
|
-
async function
|
|
69
|
+
async function claudeHook(input: unknown): Promise<number> {
|
|
49
70
|
const answer = await checkToolCall(input)
|
|
50
71
|
if (answer?.refuse !== undefined) {
|
|
51
72
|
await Bun.write(Bun.stderr, `${answer.refuse}\n`)
|
|
@@ -54,18 +75,29 @@ async function hook(input: unknown): Promise<number> {
|
|
|
54
75
|
return answer?.note === undefined ? 0 : print(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: answer.note } }))
|
|
55
76
|
}
|
|
56
77
|
|
|
57
|
-
async function
|
|
58
|
-
const { reports, failures } = await
|
|
78
|
+
async function staged(skip: readonly string[], isJson: boolean): Promise<number> {
|
|
79
|
+
const { reports, failures } = await checkStaged(projectRoot(process.cwd(), process.cwd()), skip)
|
|
59
80
|
const { text, isRefused } = commitReport(reports, failures)
|
|
60
81
|
await print(isJson ? JSON.stringify({ reports, failures }) : text)
|
|
61
82
|
return isRefused ? 1 : 0
|
|
62
83
|
}
|
|
63
84
|
|
|
64
|
-
async function
|
|
65
|
-
|
|
85
|
+
async function checkStdin(path: string, skip: readonly string[], isJson: boolean): Promise<number> {
|
|
86
|
+
const cwd = process.cwd()
|
|
87
|
+
const isMessage = path.startsWith('@')
|
|
88
|
+
const file = isMessage ? path : realFile(path, cwd)
|
|
89
|
+
const root = isMessage ? projectRoot(cwd, cwd) : fileRoot(file, cwd)
|
|
90
|
+
const settings = await loadSettings(isMessage ? cwd : dirname(file), root)
|
|
91
|
+
const { rules, failures } = await loadRules(settings)
|
|
92
|
+
const report = await checkFile(settings, rules, file, await Bun.stdin.text(), { scope: 'edit', imported: () => loadImportedFiles(root), skip })
|
|
93
|
+
const { refuse, note } = editAnswer(report)
|
|
94
|
+
const text = refuse ?? note
|
|
95
|
+
if (isJson) await print(JSON.stringify({ reports: report === undefined ? [] : [report], failures }))
|
|
96
|
+
else if (text !== undefined) await print(text)
|
|
97
|
+
return refuse === undefined ? 0 : 1
|
|
66
98
|
}
|
|
67
99
|
|
|
68
|
-
async function check(named: readonly string[],
|
|
100
|
+
async function check(named: readonly string[], skip: readonly string[], isJson: boolean): Promise<number> {
|
|
69
101
|
const listing = listedFiles(process.cwd())
|
|
70
102
|
const root = projectRoot(process.cwd(), process.cwd())
|
|
71
103
|
const settings = await loadSettings(process.cwd(), root)
|
|
@@ -77,14 +109,15 @@ async function check(named: readonly string[], isStatic: boolean, isJson: boolea
|
|
|
77
109
|
for (const failure of failures) unloaded.add(failure)
|
|
78
110
|
return rules
|
|
79
111
|
}
|
|
80
|
-
const files = named.length > 0 ? named.map((file) =>
|
|
112
|
+
const files = named.length > 0 ? named.map((file) => namedFile(file)) : await textFiles([...new Set([...(await coveredFiles(groups, rulesOf)), ...imported, ...messageFiles(settings)])])
|
|
81
113
|
const checked = await Promise.all(files.map(async (file) => {
|
|
82
114
|
const own = displayPath(settings, file).startsWith('@') ? settings : await loadSettings(dirname(file), root)
|
|
83
|
-
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope:
|
|
84
|
-
if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's
|
|
115
|
+
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope: 'all', imported: async () => imported, skip })
|
|
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.`)
|
|
85
117
|
return report
|
|
86
118
|
}))
|
|
87
|
-
const
|
|
119
|
+
const linted = new Map([...groups].map(([own, owned]) => [{ ...own, linters: own.linters.filter((name) => !isSkipped(skip, name)) }, owned]))
|
|
120
|
+
const reports = await lintProject(linted, checked.filter((report) => report !== undefined), named.length > 0 ? files : undefined)
|
|
88
121
|
const failures = [...unloaded]
|
|
89
122
|
await print(isJson ? JSON.stringify({ reports, failures }) : textReport(reports, failures))
|
|
90
123
|
return failures.length > 0 || reports.some((report) => report.failures.length > 0 || report.findings.some(({ level }) => level === 'error')) ? 1 : 0
|
|
@@ -107,7 +140,7 @@ async function textFiles(files: readonly string[]): Promise<readonly string[]> {
|
|
|
107
140
|
return files.filter((_, index) => texts[index])
|
|
108
141
|
}
|
|
109
142
|
|
|
110
|
-
function
|
|
143
|
+
function namedFile(file: string): string {
|
|
111
144
|
const path = resolve(file)
|
|
112
145
|
if (!existsSync(path)) throw new Error(`${file} does not exist.`)
|
|
113
146
|
return realpathSync(path)
|
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
|
-
if (!name.startsWith('@')) throw new Error('
|
|
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('
|
|
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
|
-
if (!isRecord(input) || typeof input.name !== 'string' || typeof input.cwd !== 'string') throw new Error('
|
|
103
|
-
if (isRecord(input.input))
|
|
104
|
-
|
|
108
|
+
if (!isRecord(input) || typeof input.name !== 'string' || typeof input.cwd !== 'string') throw new Error('The text question reads {"name", "text" or "input", "cwd"}.')
|
|
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
|
+
}
|
|
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)
|
|
@@ -113,6 +133,6 @@ function textsOf(value: unknown): readonly string[] {
|
|
|
113
133
|
}
|
|
114
134
|
|
|
115
135
|
function cwdOf(input: unknown): string {
|
|
116
|
-
if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('
|
|
136
|
+
if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('The rules question reads {"cwd"}.')
|
|
117
137
|
return input.cwd
|
|
118
138
|
}
|
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
|
|
|
@@ -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 {
|
|
@@ -66,7 +66,7 @@ export function commitReport(reports: readonly FileReport[], unloaded: readonly
|
|
|
66
66
|
const isRefused = written.some(({ findings }) => findings.some(({ level }) => level === 'error'))
|
|
67
67
|
const existing = reports.flatMap(({ path, findings }) => (findings.some(isHidden) ? [path] : []))
|
|
68
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 ${existing.join(' ')}\` lists ${count === 1 ? 'it' : 'them'}.`]
|
|
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
70
|
const body = textReport(written, unloaded)
|
|
71
71
|
return { isRefused, text: [...(isRefused ? ['Commit refused. Fix every error, stage the fix, then commit again.'] : []), body, ...before].join('\n\n') }
|
|
72
72
|
}
|
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
|
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
|
}
|