@cmodjs/rulebook 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/api.ts +4 -2
- package/src/check.ts +12 -6
- package/src/commit.ts +2 -2
- package/src/config.ts +5 -5
- package/src/edit.ts +4 -4
- package/src/main.ts +2 -1
- package/src/questions.ts +22 -11
- package/src/report.ts +4 -2
- package/src/rules.ts +27 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cmodjs/rulebook",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.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",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"@ast-grep/lang-yaml": "0.0.6",
|
|
48
48
|
"@ast-grep/napi": "0.51.1",
|
|
49
49
|
"@biomejs/biome": "2.6.4",
|
|
50
|
-
"@cmodjs/core": "
|
|
50
|
+
"@cmodjs/core": "8.0.0",
|
|
51
51
|
"diff": "9.0.0",
|
|
52
52
|
"marked": "15.0.0",
|
|
53
53
|
"oxlint": "1.86.0",
|
package/src/api.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SgNode } from '@ast-grep/napi'
|
|
2
2
|
|
|
3
|
-
export type Severity = 'error' | 'warn'
|
|
3
|
+
export type Severity = 'error' | 'warn' | 'ask'
|
|
4
4
|
|
|
5
5
|
export type Runs = 'always' | 'manual'
|
|
6
6
|
|
|
@@ -52,6 +52,7 @@ export type Context = {
|
|
|
52
52
|
readonly root: string
|
|
53
53
|
readonly filename: string
|
|
54
54
|
readonly sourceCode: SourceCode
|
|
55
|
+
readonly previous?: SourceCode
|
|
55
56
|
readonly call?: Call
|
|
56
57
|
report(problem: Problem): void
|
|
57
58
|
}
|
|
@@ -67,6 +68,7 @@ export type Rule = {
|
|
|
67
68
|
readonly files?: readonly string[]
|
|
68
69
|
readonly severity?: Severity
|
|
69
70
|
readonly runs?: Runs
|
|
71
|
+
readonly metadata?: Readonly<Record<string, unknown>>
|
|
70
72
|
create(context: Context): Visitors | Promise<Visitors>
|
|
71
73
|
}
|
|
72
74
|
|
|
@@ -89,7 +91,7 @@ export type Config = {
|
|
|
89
91
|
readonly files?: readonly string[]
|
|
90
92
|
readonly probes?: readonly string[]
|
|
91
93
|
readonly timeout?: number
|
|
92
|
-
readonly existingErrors?:
|
|
94
|
+
readonly existingErrors?: 'error' | 'warn'
|
|
93
95
|
readonly rules?: Readonly<Record<string, Severity | 'off' | RuleSettings>>
|
|
94
96
|
readonly linters?: readonly LinterName[]
|
|
95
97
|
readonly programs?: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
package/src/check.ts
CHANGED
|
@@ -94,10 +94,12 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
94
94
|
const mayPin = text.includes('rulebook-expect')
|
|
95
95
|
const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
|
|
96
96
|
const memory = isDoc ? claudeMd : undefined
|
|
97
|
+
const before = options.previous === undefined || !isDoc ? options.previous : readClaudeMd(options.previous).lines.join('\n')
|
|
97
98
|
const prompt: CheckedFile = {
|
|
98
99
|
root: settings.root,
|
|
99
100
|
path,
|
|
100
101
|
...(memory === undefined ? { text, lines: written } : { text: memory.lines.join('\n'), lines: memory.lines }),
|
|
102
|
+
...(before === undefined ? {} : { previous: { text: before, lines: before.split('\n') } }),
|
|
101
103
|
...(path === COMMAND ? { shell: parseShell(text) } : {}),
|
|
102
104
|
...(options.call === undefined ? {} : { call: options.call }),
|
|
103
105
|
}
|
|
@@ -123,9 +125,10 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
123
125
|
|
|
124
126
|
const lints = await linting
|
|
125
127
|
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
126
|
-
const
|
|
128
|
+
const levelOfRule = ({ level }: LoadedRule): Level => (level === 'off' || (level === 'ask' && options.call === undefined) ? 'error' : level)
|
|
129
|
+
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: levelOfRule(run.rule), ...(isWhole === true ? { isWhole } : {}) })) : [])), ...lints.flatMap((lint) => lint.flags)]
|
|
127
130
|
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))) :
|
|
131
|
+
const flagged: readonly Flag[] = probe ? probeFindings(found, pins.filter(({ rule }) => !unscoped.has(rule)), written.findLastIndex((line) => line.trim() !== '') + 1) :[...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.' }))]
|
|
129
132
|
|
|
130
133
|
return {
|
|
131
134
|
path,
|
|
@@ -134,7 +137,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
134
137
|
.map(({ isWhole, ...finding }) => {
|
|
135
138
|
const quote = written[finding.line - 1] ?? ''
|
|
136
139
|
const isExisting = wrote !== undefined && isWhole !== true && !wrote.has(finding.line)
|
|
137
|
-
return { ...finding, quote, isExisting, level: isExisting && finding.level
|
|
140
|
+
return { ...finding, quote, isExisting, level: isExisting && finding.level !== 'warning' ? levelOf(settings.existingErrors) : finding.level }
|
|
138
141
|
})
|
|
139
142
|
.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)),
|
|
140
143
|
}
|
|
@@ -262,6 +265,7 @@ export function importsRule(settings: Settings): StaticRule {
|
|
|
262
265
|
level: 'off',
|
|
263
266
|
runs: 'always',
|
|
264
267
|
files: undefined,
|
|
268
|
+
metadata: {},
|
|
265
269
|
check: (_, doc) => (doc === undefined ? [] : doc.imports.flatMap(({ path, line }) => {
|
|
266
270
|
const target = importedFile(doc.file, path)
|
|
267
271
|
if (target === undefined || statSync(target, { throwIfNoEntry: false })?.isFile() === true) return []
|
|
@@ -291,6 +295,7 @@ export const noSuppressionsRule: StaticRule = {
|
|
|
291
295
|
level: 'off',
|
|
292
296
|
runs: 'always',
|
|
293
297
|
files: [`**/*.{${[...new Set(Object.values(LINTERS).flatMap(({ extensions }) => extensions.map((extension) => extension.slice(1))))].join(',')}}`, '**/!(*.*)'],
|
|
298
|
+
metadata: {},
|
|
294
299
|
check: ({ lines }) => lines.flatMap((text, index) => {
|
|
295
300
|
const linter = Object.entries(SUPPRESSIONS).find(([, suppression]) => suppression.test(text))?.[0]
|
|
296
301
|
return linter === undefined ? [] : [{ line: index + 1, message: `This comment suppresses ${linter}. Fix the code ${linter} flags, and remove the comment.` }]
|
|
@@ -299,17 +304,18 @@ export const noSuppressionsRule: StaticRule = {
|
|
|
299
304
|
|
|
300
305
|
type Flag = Omit<Reported, 'isExisting' | 'quote'> & { readonly isWhole?: true }
|
|
301
306
|
|
|
302
|
-
function probeFindings(found: readonly Flag[], pins: readonly Pin[]): readonly Flag[] {
|
|
307
|
+
function probeFindings(found: readonly Flag[], pins: readonly Pin[], lastLine: number): readonly Flag[] {
|
|
303
308
|
const open = [...pins]
|
|
309
|
+
const isWholePin = (pin: Pin): boolean => pin.target > lastLine
|
|
304
310
|
const unexpected = found.filter((finding) => {
|
|
305
|
-
const index = open.findIndex((pin) => pin.rule === finding.rule && pin.target === finding.line)
|
|
311
|
+
const index = open.findIndex((pin) => pin.rule === finding.rule && (finding.isWhole === true ? isWholePin(pin) : !isWholePin(pin) && pin.target === finding.line))
|
|
306
312
|
if (index === -1) return true
|
|
307
313
|
open.splice(index, 1)
|
|
308
314
|
return false
|
|
309
315
|
})
|
|
310
316
|
return [
|
|
311
317
|
...unexpected.map((finding) => ({ ...finding, level: 'error' as const, message: `${finding.message} (no pin expects this flag)` })),
|
|
312
|
-
...open.map((pin) => ({ rule: pin.rule, line: pin.line, level: 'error' as const, message: `The pin expects ${pin.rule} to flag line ${pin.target}, and it does not.` })),
|
|
318
|
+
...open.map((pin) => ({ rule: pin.rule, line: pin.line, level: 'error' as const, message: `The pin expects ${pin.rule} to flag ${isWholePin(pin) ? 'the whole file' : `line ${pin.target}`}, and it does not.` })),
|
|
313
319
|
]
|
|
314
320
|
}
|
|
315
321
|
|
package/src/commit.ts
CHANGED
|
@@ -117,10 +117,10 @@ function withAddedErrors(reports: readonly FileReport[], added: readonly FileRep
|
|
|
117
117
|
return [...merged.values()]
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
async function committed(root: string, path: string): Promise<string> {
|
|
120
|
+
async function committed(root: string, path: string): Promise<string | undefined> {
|
|
121
121
|
const show = Bun.spawn(['git', 'show', `HEAD:${path}`], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'ignore' })
|
|
122
122
|
const [text, code] = await Promise.all([new Response(show.stdout).text(), show.exited])
|
|
123
|
-
return code === 0 ? text :
|
|
123
|
+
return code === 0 ? text : undefined
|
|
124
124
|
}
|
|
125
125
|
|
|
126
126
|
async function hasHead(root: string): Promise<boolean> {
|
package/src/config.ts
CHANGED
|
@@ -27,7 +27,7 @@ export type Settings = {
|
|
|
27
27
|
readonly configs: readonly LoadedConfig[]
|
|
28
28
|
readonly files: readonly string[]
|
|
29
29
|
readonly timeout: number
|
|
30
|
-
readonly existingErrors:
|
|
30
|
+
readonly existingErrors: 'error' | 'warn'
|
|
31
31
|
readonly rules: Readonly<Record<string, RuleSettings>>
|
|
32
32
|
readonly linters: readonly LinterName[]
|
|
33
33
|
readonly programs: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
|
@@ -184,7 +184,7 @@ function validConfig(file: string, value: unknown): Config {
|
|
|
184
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 "-".`)
|
|
185
185
|
for (const key of ['files', 'probes'] as const) if (value[key] !== undefined && !isStrings(value[key])) fail(`${key} is a list of globs.`)
|
|
186
186
|
if (value.timeout !== undefined && !isTimeout(value.timeout)) fail('timeout is a whole number of milliseconds above 0.')
|
|
187
|
-
if (value.existingErrors !== undefined &&
|
|
187
|
+
if (value.existingErrors !== undefined && value.existingErrors !== 'error' && value.existingErrors !== 'warn') fail('existingErrors is "error" or "warn".')
|
|
188
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.')
|
|
189
189
|
for (const [id, override] of Object.entries(isRecord(value.rules) ? value.rules : {})) validOverride(file, id, override)
|
|
190
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(', ')}.`)
|
|
@@ -215,9 +215,9 @@ function validOverride(file: string, id: string, override: unknown): void {
|
|
|
215
215
|
throw new Error(`${file}: rules["${id}"] ${problem}`)
|
|
216
216
|
}
|
|
217
217
|
if (override === 'off' || isSeverity(override)) return
|
|
218
|
-
if (!isRecord(override)) return fail('is "error", "warn", "off", or an object of rule settings.')
|
|
218
|
+
if (!isRecord(override)) return fail('is "error", "warn", "ask", "off", or an object of rule settings.')
|
|
219
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(', ')}.`)
|
|
220
|
-
if (override.severity !== undefined && override.severity !== 'off' && !isSeverity(override.severity)) fail('severity is "error", "warn", or "off".')
|
|
220
|
+
if (override.severity !== undefined && override.severity !== 'off' && !isSeverity(override.severity)) fail('severity is "error", "warn", "ask", or "off".')
|
|
221
221
|
if (override.runs !== undefined && !isRuns(override.runs)) fail('runs is "always" or "manual".')
|
|
222
222
|
if (override.files !== undefined && !isStrings(override.files)) fail('files is a list of globs.')
|
|
223
223
|
if (override.timeout !== undefined && !isTimeout(override.timeout)) fail('timeout is a whole number of milliseconds above 0.')
|
|
@@ -243,7 +243,7 @@ export function isStrings(value: unknown): value is string[] {
|
|
|
243
243
|
}
|
|
244
244
|
|
|
245
245
|
export function isSeverity(value: unknown): value is Severity {
|
|
246
|
-
return value === 'error' || value === 'warn'
|
|
246
|
+
return value === 'error' || value === 'warn' || value === 'ask'
|
|
247
247
|
}
|
|
248
248
|
|
|
249
249
|
export function isRuns(value: unknown): value is Runs {
|
package/src/edit.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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
|
+
import type { Call, Severity } from './api.ts'
|
|
4
4
|
import { checkFile } from './check.ts'
|
|
5
5
|
import { isClaudeMd } from './claude-md.ts'
|
|
6
6
|
import { existingFolder, isRecord, loadSettings, projectRoot } from './config.ts'
|
|
7
7
|
import { loadImportedFiles, watchImportSource } from './files.ts'
|
|
8
8
|
import { editAnswer, type EditAnswer } from './report.ts'
|
|
9
|
-
import { loadRules } from './rules.ts'
|
|
9
|
+
import { loadRules, withSeverities } from './rules.ts'
|
|
10
10
|
|
|
11
11
|
type Replacement = { readonly old_string: string; readonly new_string: string; readonly replace_all?: boolean }
|
|
12
12
|
|
|
@@ -30,7 +30,7 @@ export function fileRoot(file: string, cwd: string): string {
|
|
|
30
30
|
return projectRoot(folder, file.startsWith(`${realpathSync(cwd)}/`) ? cwd : folder)
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
export async function checkEdit(call: Call, root: string): Promise<EditAnswer> {
|
|
33
|
+
export async function checkEdit(call: Call, root: string, severities: Readonly<Record<string, Severity | 'off'>>): Promise<EditAnswer> {
|
|
34
34
|
const path = editedPath(call)
|
|
35
35
|
if (path === undefined) return editAnswer(undefined)
|
|
36
36
|
const file = realFile(path, call.cwd)
|
|
@@ -40,7 +40,7 @@ export async function checkEdit(call: Call, root: string): Promise<EditAnswer> {
|
|
|
40
40
|
const settings = await loadSettings(dirname(file), root)
|
|
41
41
|
const { rules } = await loadRules(settings)
|
|
42
42
|
const isWhole = next === ''
|
|
43
|
-
const report = await checkFile(settings, rules, file, next, { scope: 'edit', previous: isWhole ? '' : previous
|
|
43
|
+
const report = await checkFile(settings, withSeverities(rules, severities), file, next, { scope: 'edit', previous: isWhole ? '' : previous, imported: () => loadImportedFiles(root), call })
|
|
44
44
|
return editAnswer(report)
|
|
45
45
|
}
|
|
46
46
|
|
package/src/main.ts
CHANGED
|
@@ -22,7 +22,7 @@ Usage:
|
|
|
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
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.
|
|
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, and an ask asks the person first.
|
|
26
26
|
rulebook --version Print the version.
|
|
27
27
|
|
|
28
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.
|
|
@@ -72,6 +72,7 @@ async function claudeHook(input: unknown): Promise<number> {
|
|
|
72
72
|
await Bun.write(Bun.stderr, `${answer.refuse}\n`)
|
|
73
73
|
return 2
|
|
74
74
|
}
|
|
75
|
+
if (answer?.ask !== undefined) return print(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: answer.ask } }))
|
|
75
76
|
return answer?.note === undefined ? 0 : print(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: answer.note } }))
|
|
76
77
|
}
|
|
77
78
|
|
package/src/questions.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { basename, dirname, join } from 'node:path'
|
|
2
|
-
import type { Call } from './api.ts'
|
|
2
|
+
import type { Call, Severity } from './api.ts'
|
|
3
3
|
import { checkFile, COMMAND, globRegExp } from './check.ts'
|
|
4
|
-
import { CONFIG_FILE, globalConfigFile, isRecord, loadSettings, projectRoot } from './config.ts'
|
|
4
|
+
import { CONFIG_FILE, globalConfigFile, isRecord, isSeverity, loadSettings, projectRoot } from './config.ts'
|
|
5
5
|
import { checkEdit, EDIT_TOOLS, editRoot } from './edit.ts'
|
|
6
6
|
import { listedFiles } from './files.ts'
|
|
7
7
|
import { editAnswer, type EditAnswer } from './report.ts'
|
|
8
|
-
import { loadRules } from './rules.ts'
|
|
8
|
+
import { loadRules, severityOf, withSeverities } from './rules.ts'
|
|
9
9
|
|
|
10
10
|
export type Question = 'edit' | 'text' | 'rules'
|
|
11
11
|
|
|
12
|
+
type Severities = Readonly<Record<string, Severity | 'off'>>
|
|
13
|
+
|
|
12
14
|
type Text = { readonly name: string; readonly text: string; readonly cwd: string; readonly call?: Call }
|
|
13
15
|
|
|
14
16
|
const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'])
|
|
@@ -21,14 +23,14 @@ type Answerer = {
|
|
|
21
23
|
const QUESTIONS: Readonly<Record<Question, Answerer>> = {
|
|
22
24
|
edit: {
|
|
23
25
|
root: (input) => editRoot(callOf(input)),
|
|
24
|
-
answer: (input, root) => checkEdit(callOf(input), root),
|
|
26
|
+
answer: (input, root) => checkEdit(callOf(input), root, severitiesOf(input)),
|
|
25
27
|
},
|
|
26
28
|
text: {
|
|
27
29
|
root: (input) => {
|
|
28
30
|
const { cwd } = textOf(input)
|
|
29
31
|
return projectRoot(cwd, cwd)
|
|
30
32
|
},
|
|
31
|
-
answer: (input, root) => checkText(textOf(input), root),
|
|
33
|
+
answer: (input, root) => checkText(textOf(input), root, severitiesOf(input)),
|
|
32
34
|
},
|
|
33
35
|
rules: {
|
|
34
36
|
root: (input) => {
|
|
@@ -51,21 +53,28 @@ export function answer(question: Question, input: unknown, root: string): Promis
|
|
|
51
53
|
return QUESTIONS[question].answer(input, root)
|
|
52
54
|
}
|
|
53
55
|
|
|
54
|
-
async function checkText({ name, text, cwd, call }: Text, root: string): Promise<EditAnswer> {
|
|
56
|
+
async function checkText({ name, text, cwd, call }: Text, root: string, severities: Severities): Promise<EditAnswer> {
|
|
55
57
|
const settings = await loadSettings(cwd, root)
|
|
56
58
|
if (!name.startsWith('@')) throw new Error('The text question checks a message by its @-name, such as @reply or @inbox/<id>.md.')
|
|
57
59
|
const { rules } = await loadRules(settings)
|
|
58
|
-
const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set(), ...(call === undefined ? {} : { call }) })
|
|
60
|
+
const report = await checkFile(settings, withSeverities(rules, severities), name, text, { scope: 'edit', imported: async () => new Set(), ...(call === undefined ? {} : { call }) })
|
|
59
61
|
return editAnswer(report)
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
export async function checkToolCall(input: unknown): Promise<EditAnswer | undefined> {
|
|
63
65
|
const call = callOf(input)
|
|
64
|
-
if (EDIT_TOOLS.has(call.tool)) return checkEdit(call, editRoot(call))
|
|
66
|
+
if (EDIT_TOOLS.has(call.tool)) return checkEdit(call, editRoot(call), {})
|
|
65
67
|
const root = projectRoot(call.cwd, call.cwd)
|
|
66
68
|
const messages = Object.entries((await loadSettings(call.cwd, root)).messages)
|
|
67
69
|
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)
|
|
70
|
+
return name === undefined ? undefined : checkText({ name: `@${name}`, text: messageText(`@${name}`, call.input), cwd: call.cwd, call }, root, {})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function severitiesOf(input: unknown): Severities {
|
|
74
|
+
const rules = isRecord(input) ? input.rules : undefined
|
|
75
|
+
if (rules === undefined) return {}
|
|
76
|
+
if (!isRecord(rules) || !Object.values(rules).every((severity) => severity === 'off' || isSeverity(severity))) throw new Error('"rules" maps each rule name to "error", "warn", "ask", or "off", as a config\'s rules do.')
|
|
77
|
+
return rules as Severities
|
|
69
78
|
}
|
|
70
79
|
|
|
71
80
|
async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
@@ -82,12 +91,14 @@ async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
|
82
91
|
sources: [...new Set([globalConfigFile(), join(root, CONFIG_FILE), ...folders.flatMap((folder) => folder.settings.configs.flatMap((config) => [config.file, ...Object.values(config.plugins)]))])],
|
|
83
92
|
folders: folders.map((folder) => ({
|
|
84
93
|
path: folder.path,
|
|
85
|
-
rules: folder.rules.
|
|
94
|
+
rules: folder.rules.flatMap(({ id, description, level, metadata, files = folder.settings.files }) => (level === 'off' ? [] : [{
|
|
86
95
|
id,
|
|
87
96
|
description,
|
|
97
|
+
severity: severityOf(level),
|
|
98
|
+
metadata,
|
|
88
99
|
isEverywhere: files.some((glob) => glob === (folder.path === '' ? '**' : `${folder.path}/**`) || glob.startsWith('@')),
|
|
89
100
|
files: regExpsOf(files),
|
|
90
|
-
})),
|
|
101
|
+
}])),
|
|
91
102
|
})),
|
|
92
103
|
messages: Object.entries(settings.messages).map(([name, { tools }]) => ({ name: `@${name}`, tools: regExpsOf(tools) })),
|
|
93
104
|
failures: [...new Set(folders.flatMap((folder) => folder.failures))],
|
package/src/report.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { FileReport, Reported } from './check.ts'
|
|
|
2
2
|
|
|
3
3
|
export type EditAnswer = {
|
|
4
4
|
readonly refuse?: string
|
|
5
|
+
readonly ask?: string
|
|
5
6
|
readonly note?: string
|
|
6
7
|
readonly failures: readonly string[]
|
|
7
8
|
readonly findings: readonly Reported[]
|
|
@@ -24,17 +25,18 @@ export function editAnswer(report: FileReport | undefined): EditAnswer {
|
|
|
24
25
|
if (report === undefined) return { failures: [], findings: [] }
|
|
25
26
|
const { findings } = report
|
|
26
27
|
const written = findings.filter(({ isExisting }) => !isExisting)
|
|
27
|
-
const errors = written.filter(({ level }) => level
|
|
28
|
+
const errors = written.filter(({ level }) => level !== 'warning')
|
|
28
29
|
const warnings = written.filter(({ level }) => level === 'warning')
|
|
29
30
|
const failures = failureLines(report)
|
|
30
31
|
const isRefused = findings.some(({ level }) => level === 'error')
|
|
31
32
|
const blocks = [
|
|
32
33
|
...(errors.length === 0 ? [] : [findingLines(errors)]),
|
|
33
|
-
...(warnings.length === 0 ? [] : [
|
|
34
|
+
...(warnings.length === 0 ? [] : [errors.length > 0 ? `Warnings:\n${findingLines(warnings)}` : findingLines(warnings)]),
|
|
34
35
|
...existingLine(report, written.length > 0),
|
|
35
36
|
...(failures.length === 0 ? [] : [failures.join('\n')]),
|
|
36
37
|
]
|
|
37
38
|
if (isRefused) return { refuse: [refusal(report.path), ...blocks].join('\n\n'), failures, findings }
|
|
39
|
+
if (findings.some(({ level }) => level === 'ask')) return { ask: [`${subject(report.path)} needs your approval:`, ...blocks].join('\n\n'), failures, findings }
|
|
38
40
|
if (findings.length > 0) return { note: [`${subject(report.path)} allowed with warnings:`, ...blocks].join('\n\n'), failures, findings }
|
|
39
41
|
if (failures.length > 0) return { note: [`${subject(report.path)} allowed, but not every rule checked it:`, ...blocks].join('\n\n'), failures, findings }
|
|
40
42
|
return { failures, findings }
|
package/src/rules.ts
CHANGED
|
@@ -10,16 +10,16 @@ import { isJev } from './jev.ts'
|
|
|
10
10
|
import { cacheFolder } from './linters.ts'
|
|
11
11
|
import { importDefault } from './modules.ts'
|
|
12
12
|
|
|
13
|
-
export type Level = 'error' | 'warning'
|
|
13
|
+
export type Level = 'error' | 'warning' | 'ask'
|
|
14
14
|
|
|
15
15
|
export type Finding = { readonly line: number; readonly message?: string; readonly isWhole?: true }
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
type Text = { readonly text: string; readonly lines: readonly string[]; readonly shell?: ParsedShell }
|
|
18
|
+
|
|
19
|
+
export type CheckedFile = Text & {
|
|
18
20
|
readonly root: string
|
|
19
21
|
readonly path: string
|
|
20
|
-
readonly
|
|
21
|
-
readonly lines: readonly string[]
|
|
22
|
-
readonly shell?: ParsedShell
|
|
22
|
+
readonly previous?: Text
|
|
23
23
|
readonly call?: Call
|
|
24
24
|
}
|
|
25
25
|
|
|
@@ -31,6 +31,7 @@ type Common = {
|
|
|
31
31
|
readonly level: Level | 'off'
|
|
32
32
|
readonly runs: Runs
|
|
33
33
|
readonly files: readonly string[] | undefined
|
|
34
|
+
readonly metadata: Readonly<Record<string, unknown>>
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
type Doc = { readonly file: string; readonly imports: readonly Import[] }
|
|
@@ -57,7 +58,7 @@ export type LoadedRule = StaticRule | AgenticRule
|
|
|
57
58
|
export type Rules = { readonly rules: readonly LoadedRule[]; readonly failures: readonly string[] }
|
|
58
59
|
|
|
59
60
|
const RULE_FILES = new Bun.Glob('**/*.{ts,md,yml}')
|
|
60
|
-
const COMMON_KEYS = ['description', 'message', 'files', 'severity', 'runs']
|
|
61
|
+
const COMMON_KEYS = ['description', 'message', 'files', 'severity', 'runs', 'metadata']
|
|
61
62
|
const SCRIPT_KEYS = new Set([...COMMON_KEYS, 'create'])
|
|
62
63
|
const FRONTMATTER_KEYS = new Set([...COMMON_KEYS, 'timeout', 'threshold', 'agent', 'model', 'effort', 'allowed-tools', 'disallowed-tools'])
|
|
63
64
|
const CLAUDE_KEYS = ['agent', 'effort', 'allowed-tools', 'disallowed-tools'] as const
|
|
@@ -131,6 +132,7 @@ async function visited(source: string, create: Rule['create'], file: CheckedFile
|
|
|
131
132
|
root: file.root,
|
|
132
133
|
filename: file.path.startsWith('@') ? file.path : resolve(file.root, file.path),
|
|
133
134
|
sourceCode,
|
|
135
|
+
...(file.previous === undefined ? {} : { previous: await sourceCodeOf(file.previous, language) }),
|
|
134
136
|
...(file.call === undefined ? {} : { call: file.call }),
|
|
135
137
|
report: (problem) => {
|
|
136
138
|
found.push('loc' in problem ? { line: problem.loc.start.line } : findingOf(problem.node))
|
|
@@ -161,9 +163,9 @@ function isShell(node: Node): node is Shell {
|
|
|
161
163
|
return 'commands' in node
|
|
162
164
|
}
|
|
163
165
|
|
|
164
|
-
const sourceCodes = new WeakMap<
|
|
166
|
+
const sourceCodes = new WeakMap<Text, Promise<SourceCode>>()
|
|
165
167
|
|
|
166
|
-
function sourceCodeOf(file:
|
|
168
|
+
function sourceCodeOf(file: Text, language: string | undefined): Promise<SourceCode> {
|
|
167
169
|
const known = sourceCodes.get(file)
|
|
168
170
|
if (known !== undefined) return known
|
|
169
171
|
const sourceCode = parsed(file, language)
|
|
@@ -171,7 +173,7 @@ function sourceCodeOf(file: CheckedFile, language: string | undefined): Promise<
|
|
|
171
173
|
return sourceCode
|
|
172
174
|
}
|
|
173
175
|
|
|
174
|
-
async function parsed({ text, lines, shell }:
|
|
176
|
+
async function parsed({ text, lines, shell }: Text, language: string | undefined): Promise<SourceCode> {
|
|
175
177
|
if (shell !== undefined) return { text, lines, ast: { commands: commandsOf(shell, lines), reads: shell.reads, writes: shell.writes, fetches: shell.fetches, isFullyParsed: shell.isFullyParsed } }
|
|
176
178
|
if (language === undefined) return { text, lines, ast: { text } }
|
|
177
179
|
const { parse } = await (astGrep ??= loadAstGrep())
|
|
@@ -315,11 +317,12 @@ function commonOf(id: string, source: string, keys: Readonly<Record<string, unkn
|
|
|
315
317
|
const fail = (problem: string): never => {
|
|
316
318
|
throw new Error(`${source}: ${problem}`)
|
|
317
319
|
}
|
|
318
|
-
const { description, message, severity, runs } = keys
|
|
320
|
+
const { description, message, severity, runs, metadata = {} } = keys
|
|
319
321
|
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."')
|
|
320
322
|
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.')
|
|
321
|
-
if (severity !== undefined && !isSeverity(severity)) fail('severity is "error" or "
|
|
323
|
+
if (severity !== undefined && !isSeverity(severity)) fail('severity is "error", "warn", or "ask".')
|
|
322
324
|
if (runs !== undefined && !isRuns(runs)) fail('runs is "always" or "manual".')
|
|
325
|
+
if (!isRecord(metadata)) return fail('metadata is a map of keys, such as { mode: "propose" }, that rulebook passes on and never reads.')
|
|
323
326
|
return {
|
|
324
327
|
id,
|
|
325
328
|
source,
|
|
@@ -328,11 +331,23 @@ function commonOf(id: string, source: string, keys: Readonly<Record<string, unkn
|
|
|
328
331
|
level: levelOf((severity as Severity | undefined) ?? 'error'),
|
|
329
332
|
runs: (runs as Runs | undefined) ?? 'always',
|
|
330
333
|
files: filesOf(source, keys.files),
|
|
334
|
+
metadata,
|
|
331
335
|
}
|
|
332
336
|
}
|
|
333
337
|
|
|
334
338
|
export function levelOf(severity: Severity): Level {
|
|
335
|
-
return severity === 'warn' ? 'warning' :
|
|
339
|
+
return severity === 'warn' ? 'warning' : severity
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function severityOf(level: Level): Severity {
|
|
343
|
+
return level === 'warning' ? 'warn' : level
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function withSeverities(rules: readonly LoadedRule[], severities: Readonly<Record<string, Severity | 'off'>>): readonly LoadedRule[] {
|
|
347
|
+
return rules.map((rule) => {
|
|
348
|
+
const severity = severities[rule.id]
|
|
349
|
+
return severity === undefined ? rule : overridden(rule, { severity })
|
|
350
|
+
})
|
|
336
351
|
}
|
|
337
352
|
|
|
338
353
|
function filesOf(source: string, files: unknown): readonly string[] | undefined {
|