@cmodjs/rulebook 0.9.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 +3 -2
- package/src/check.ts +5 -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 +19 -5
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
|
|
|
@@ -68,6 +68,7 @@ export type Rule = {
|
|
|
68
68
|
readonly files?: readonly string[]
|
|
69
69
|
readonly severity?: Severity
|
|
70
70
|
readonly runs?: Runs
|
|
71
|
+
readonly metadata?: Readonly<Record<string, unknown>>
|
|
71
72
|
create(context: Context): Visitors | Promise<Visitors>
|
|
72
73
|
}
|
|
73
74
|
|
|
@@ -90,7 +91,7 @@ export type Config = {
|
|
|
90
91
|
readonly files?: readonly string[]
|
|
91
92
|
readonly probes?: readonly string[]
|
|
92
93
|
readonly timeout?: number
|
|
93
|
-
readonly existingErrors?:
|
|
94
|
+
readonly existingErrors?: 'error' | 'warn'
|
|
94
95
|
readonly rules?: Readonly<Record<string, Severity | 'off' | RuleSettings>>
|
|
95
96
|
readonly linters?: readonly LinterName[]
|
|
96
97
|
readonly programs?: Readonly<Partial<Record<LinterName, readonly string[]>>>
|
package/src/check.ts
CHANGED
|
@@ -125,7 +125,8 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
125
125
|
|
|
126
126
|
const lints = await linting
|
|
127
127
|
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
128
|
-
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)]
|
|
129
130
|
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
|
|
130
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.' }))]
|
|
131
132
|
|
|
@@ -136,7 +137,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
136
137
|
.map(({ isWhole, ...finding }) => {
|
|
137
138
|
const quote = written[finding.line - 1] ?? ''
|
|
138
139
|
const isExisting = wrote !== undefined && isWhole !== true && !wrote.has(finding.line)
|
|
139
|
-
return { ...finding, quote, isExisting, level: isExisting && finding.level
|
|
140
|
+
return { ...finding, quote, isExisting, level: isExisting && finding.level !== 'warning' ? levelOf(settings.existingErrors) : finding.level }
|
|
140
141
|
})
|
|
141
142
|
.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule)),
|
|
142
143
|
}
|
|
@@ -264,6 +265,7 @@ export function importsRule(settings: Settings): StaticRule {
|
|
|
264
265
|
level: 'off',
|
|
265
266
|
runs: 'always',
|
|
266
267
|
files: undefined,
|
|
268
|
+
metadata: {},
|
|
267
269
|
check: (_, doc) => (doc === undefined ? [] : doc.imports.flatMap(({ path, line }) => {
|
|
268
270
|
const target = importedFile(doc.file, path)
|
|
269
271
|
if (target === undefined || statSync(target, { throwIfNoEntry: false })?.isFile() === true) return []
|
|
@@ -293,6 +295,7 @@ export const noSuppressionsRule: StaticRule = {
|
|
|
293
295
|
level: 'off',
|
|
294
296
|
runs: 'always',
|
|
295
297
|
files: [`**/*.{${[...new Set(Object.values(LINTERS).flatMap(({ extensions }) => extensions.map((extension) => extension.slice(1))))].join(',')}}`, '**/!(*.*)'],
|
|
298
|
+
metadata: {},
|
|
296
299
|
check: ({ lines }) => lines.flatMap((text, index) => {
|
|
297
300
|
const linter = Object.entries(SUPPRESSIONS).find(([, suppression]) => suppression.test(text))?.[0]
|
|
298
301
|
return linter === undefined ? [] : [{ line: index + 1, message: `This comment suppresses ${linter}. Fix the code ${linter} flags, and remove the comment.` }]
|
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,imported: () => loadImportedFiles(root), call })
|
|
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,7 +10,7 @@ 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
|
|
|
@@ -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
|
|
@@ -316,11 +317,12 @@ function commonOf(id: string, source: string, keys: Readonly<Record<string, unkn
|
|
|
316
317
|
const fail = (problem: string): never => {
|
|
317
318
|
throw new Error(`${source}: ${problem}`)
|
|
318
319
|
}
|
|
319
|
-
const { description, message, severity, runs } = keys
|
|
320
|
+
const { description, message, severity, runs, metadata = {} } = keys
|
|
320
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."')
|
|
321
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.')
|
|
322
|
-
if (severity !== undefined && !isSeverity(severity)) fail('severity is "error" or "
|
|
323
|
+
if (severity !== undefined && !isSeverity(severity)) fail('severity is "error", "warn", or "ask".')
|
|
323
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.')
|
|
324
326
|
return {
|
|
325
327
|
id,
|
|
326
328
|
source,
|
|
@@ -329,11 +331,23 @@ function commonOf(id: string, source: string, keys: Readonly<Record<string, unkn
|
|
|
329
331
|
level: levelOf((severity as Severity | undefined) ?? 'error'),
|
|
330
332
|
runs: (runs as Runs | undefined) ?? 'always',
|
|
331
333
|
files: filesOf(source, keys.files),
|
|
334
|
+
metadata,
|
|
332
335
|
}
|
|
333
336
|
}
|
|
334
337
|
|
|
335
338
|
export function levelOf(severity: Severity): Level {
|
|
336
|
-
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
|
+
})
|
|
337
351
|
}
|
|
338
352
|
|
|
339
353
|
function filesOf(source: string, files: unknown): readonly string[] | undefined {
|