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