@cmodjs/rulebook 0.4.0 → 0.5.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 +1 -1
- package/src/check.ts +12 -7
- package/src/commit.ts +4 -4
- package/src/edit.ts +16 -15
- package/src/main.ts +65 -34
- package/src/questions.ts +5 -5
- package/src/report.ts +2 -2
- package/src/serve.ts +3 -3
package/package.json
CHANGED
package/src/check.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { coveringLinters, LINTERS, lintFolder, lintText, projectLinters, type Co
|
|
|
11
11
|
import { seconds } from './lsp.ts'
|
|
12
12
|
import type { LoadedRule, StaticRule } from './rules.ts'
|
|
13
13
|
|
|
14
|
-
type Scope = 'edit' | 'commit' | 'all'
|
|
14
|
+
type Scope = 'edit' | 'commit' | 'all'
|
|
15
15
|
|
|
16
16
|
export type Reported = {
|
|
17
17
|
readonly rule: string
|
|
@@ -35,6 +35,7 @@ type CheckOptions = {
|
|
|
35
35
|
readonly previous?: string | undefined
|
|
36
36
|
readonly imported: () => Promise<ReadonlySet<string>>
|
|
37
37
|
readonly input?: Readonly<Record<string, unknown>>
|
|
38
|
+
readonly skip?: readonly string[]
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
const PIN = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
|
|
@@ -83,8 +84,8 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
83
84
|
const configured = probe || (!isMessage && isPrompt(settings, file))
|
|
84
85
|
const isMemory = !isMessage && isClaudeMd(file)
|
|
85
86
|
const imported = !isMessage && !(configured && isMemory) && existsSync(file) && (await options.imported()).has(realpathSync(file))
|
|
86
|
-
const covered = rules.filter((rule) => inScope(rule, options
|
|
87
|
-
const linted = !isMessage && !probe ? coveringLinters(settings.linters, settings.programs, file, text, settings.root) : []
|
|
87
|
+
const covered = rules.filter((rule) => inScope(rule, options) && covers(rule, path, configured || imported))
|
|
88
|
+
const linted = !isMessage && !probe ? coveringLinters(settings.linters.filter((name) => !isSkipped(options.skip, name)), settings.programs, file, text, settings.root) : []
|
|
88
89
|
if (!configured && !imported && covered.length === 0 && linted.length === 0) return undefined
|
|
89
90
|
const written = text.split('\n')
|
|
90
91
|
const isDoc = imported || isMemory
|
|
@@ -95,7 +96,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
95
96
|
const doc = memory === undefined ? undefined : { file, imports: memory.imports }
|
|
96
97
|
const pins = mayPin ? pinsOf(written, claudeMd?.lines ?? []) : []
|
|
97
98
|
const pinned = new Set(pins.map(({ rule }) => rule))
|
|
98
|
-
const chosen = probe ? rules.filter((rule) => inScope(rule, options
|
|
99
|
+
const chosen = probe ? rules.filter((rule) => inScope(rule, options) && pinned.has(rule.id)) : covered
|
|
99
100
|
const wrote = options.previous === undefined ? undefined : linesWritten(options.previous, written)
|
|
100
101
|
const changed = wrote === undefined ? undefined : [...wrote].filter((line) => written[line - 1]?.trim() !== '')
|
|
101
102
|
|
|
@@ -115,7 +116,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
|
|
|
115
116
|
const lints = await linting
|
|
116
117
|
const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
|
|
117
118
|
const found = [...runs.flatMap((run) => ('found' in run ? run.found.map(({ line, message }) => ({ line, message: message ?? run.rule.description, rule: run.rule.id, level: run.rule.level === 'off' ? 'error' as const : run.rule.level })) : [])), ...lints.flatMap((lint) => lint.flags)]
|
|
118
|
-
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options
|
|
119
|
+
const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
|
|
119
120
|
const flagged = probe ? probeFindings(found, pins.filter(({ rule }) => !unscoped.has(rule))) : [...found, ...pins.map((pin) => ({ rule: 'rulebook/pins', line: pin.line, level: 'error' as const, message: 'A rulebook-expect pin works only in a probe file. Remove it.' }))]
|
|
120
121
|
|
|
121
122
|
return {
|
|
@@ -183,13 +184,17 @@ function covers(rule: LoadedRule, path: string, isPrompt: boolean): boolean {
|
|
|
183
184
|
return rule.level !== 'off' && (rule.paths === undefined ? isPrompt : matches(rule.paths, path))
|
|
184
185
|
}
|
|
185
186
|
|
|
186
|
-
function inScope(rule: LoadedRule, scope:
|
|
187
|
+
function inScope(rule: LoadedRule, { scope, skip }: CheckOptions): boolean {
|
|
188
|
+
if (isSkipped(skip, rule.id) || (rule.kind === 'agentic' && isSkipped(skip, 'agentic'))) return false
|
|
187
189
|
if (scope === 'all') return true
|
|
188
|
-
if (scope === 'static') return rule.kind === 'static'
|
|
189
190
|
if (scope === 'commit') return rule.runs !== 'manual'
|
|
190
191
|
return rule.runs === 'always'
|
|
191
192
|
}
|
|
192
193
|
|
|
194
|
+
export function isSkipped(skip: readonly string[] | undefined, name: string): boolean {
|
|
195
|
+
return skip?.some((skipped) => name === skipped || name.startsWith(`${skipped}/`)) ?? false
|
|
196
|
+
}
|
|
197
|
+
|
|
193
198
|
type Pin = { readonly rule: string; readonly line: number; readonly target: number }
|
|
194
199
|
|
|
195
200
|
function pinsOf(written: readonly string[], shown: readonly string[]): readonly Pin[] {
|
package/src/commit.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync,
|
|
|
2
2
|
import { constants, tmpdir } from 'node:os'
|
|
3
3
|
import { basename, dirname, join, relative } from 'node:path'
|
|
4
4
|
import type { LinterName } from './api.ts'
|
|
5
|
-
import { checkFile, lintProject, type FileReport, type Reported } from './check.ts'
|
|
5
|
+
import { checkFile, isSkipped, lintProject, type FileReport, type Reported } from './check.ts'
|
|
6
6
|
import { isInside, loadSettings } from './config.ts'
|
|
7
7
|
import { filesBySettings, loadImportedFiles } from './files.ts'
|
|
8
8
|
import { isLinterInput, LINTERS, projectLinters } from './linters.ts'
|
|
@@ -13,7 +13,7 @@ export type CommitReport = { readonly reports: readonly FileReport[]; readonly f
|
|
|
13
13
|
const DEPENDENCIES = new Set(Object.values(LINTERS).flatMap(({ copies }) => copies.map((copy) => copy.split('/')[0] ?? copy)))
|
|
14
14
|
const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
|
|
15
15
|
|
|
16
|
-
export async function
|
|
16
|
+
export async function checkStaged(root: string, skip: readonly string[]): Promise<CommitReport> {
|
|
17
17
|
const unloaded = new Set<string>()
|
|
18
18
|
const staged = await gitPaths(root, ['diff', '--cached', '--name-only', '-z', '--diff-filter=ACMR'])
|
|
19
19
|
const deleted = await gitPaths(root, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--diff-filter=D'])
|
|
@@ -25,10 +25,10 @@ export async function checkCommit(root: string): Promise<CommitReport> {
|
|
|
25
25
|
const settings = await loadSettings(dirname(file), root)
|
|
26
26
|
const { rules, failures } = await loadRules(settings)
|
|
27
27
|
for (const failure of failures) unloaded.add(failure)
|
|
28
|
-
return checkFile(settings, rules, file, text, { scope: 'commit', previous: await committed(root, renamed.get(path) ?? path), imported: () => loadImportedFiles(root) })
|
|
28
|
+
return checkFile(settings, rules, file, text, { scope: 'commit', previous: await committed(root, renamed.get(path) ?? path), imported: () => loadImportedFiles(root), skip })
|
|
29
29
|
}))
|
|
30
30
|
const reports = checked.filter((report) => report !== undefined)
|
|
31
|
-
const linters = new Set((await Promise.all([...staged, ...deleted].map((path) => lintersCovering(root, path)))).flat())
|
|
31
|
+
const linters = new Set((await Promise.all([...staged, ...deleted].map((path) => lintersCovering(root, path)))).flat().filter((name) => !isSkipped(skip, name)))
|
|
32
32
|
return { reports: linters.size === 0 ? reports : withAddedErrors(reports, await addedErrors(root, linters, renamed)), failures: [...unloaded] }
|
|
33
33
|
}
|
|
34
34
|
|
package/src/edit.ts
CHANGED
|
@@ -16,15 +16,25 @@ export type ToolCall = {
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
export function editRoot(call: ToolCall): string {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
const path = call.tool_input.file_path
|
|
20
|
+
return typeof path === 'string' ? fileRoot(realFile(path, call.cwd), call.cwd) : projectRoot(call.cwd, call.cwd)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function realFile(path: string, cwd: string): string {
|
|
24
|
+
const file = isAbsolute(path) ? path : resolve(cwd, path)
|
|
25
|
+
const nearest = existingFolder(file)
|
|
26
|
+
return join(realpathSync(nearest), relative(nearest, file))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function fileRoot(file: string, cwd: string): string {
|
|
30
|
+
const folder = existingFolder(dirname(file))
|
|
31
|
+
return projectRoot(folder, file.startsWith(`${realpathSync(cwd)}/`) ? cwd : folder)
|
|
22
32
|
}
|
|
23
33
|
|
|
24
34
|
export async function checkEdit(call: ToolCall, root: string): Promise<EditAnswer> {
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
-
const
|
|
35
|
+
const path = call.tool_input.file_path
|
|
36
|
+
if (typeof path !== 'string') return editAnswer(undefined)
|
|
37
|
+
const file = realFile(path, call.cwd)
|
|
28
38
|
const previous = existsSync(file) ? await Bun.file(file).text() : undefined
|
|
29
39
|
const next = editedText(call.tool_name, call.tool_input, previous)
|
|
30
40
|
if (next === undefined) return editAnswer(undefined)
|
|
@@ -35,15 +45,6 @@ export async function checkEdit(call: ToolCall, root: string): Promise<EditAnswe
|
|
|
35
45
|
return editAnswer(report)
|
|
36
46
|
}
|
|
37
47
|
|
|
38
|
-
function editedFile(call: ToolCall): { readonly file: string; readonly folder: string } | undefined {
|
|
39
|
-
const path = call.tool_input.file_path
|
|
40
|
-
if (typeof path !== 'string') return undefined
|
|
41
|
-
const file = isAbsolute(path) ? path : resolve(call.cwd, path)
|
|
42
|
-
const nearest = existingFolder(file)
|
|
43
|
-
const real = join(realpathSync(nearest), relative(nearest, file))
|
|
44
|
-
return { file: real, folder: existingFolder(dirname(real)) }
|
|
45
|
-
}
|
|
46
|
-
|
|
47
48
|
function editedText(tool: string, input: Readonly<Record<string, unknown>>, previous: string | undefined): string | undefined {
|
|
48
49
|
if (tool === 'Write') return typeof input.content === 'string' ? input.content : undefined
|
|
49
50
|
if (previous === undefined) return undefined
|
package/src/main.ts
CHANGED
|
@@ -3,49 +3,68 @@ import { existsSync, realpathSync, statSync } from 'node:fs'
|
|
|
3
3
|
import { dirname, resolve } from 'node:path'
|
|
4
4
|
import { parseArgs } from 'node:util'
|
|
5
5
|
import packageJson from '../package.json' with { type: 'json' }
|
|
6
|
-
import { checkFile, displayPath, isCovered, isPrompt, lintProject } from './check.ts'
|
|
6
|
+
import { checkFile, displayPath, isCovered, isPrompt, isSkipped, lintProject } from './check.ts'
|
|
7
|
+
import { checkStaged } from './commit.ts'
|
|
7
8
|
import { loadSettings, projectRoot, type Settings } from './config.ts'
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { commitReport, textReport } from './report.ts'
|
|
9
|
+
import { fileRoot, realFile } from './edit.ts'
|
|
10
|
+
import { filesBySettings, importedFiles, listedFiles, loadImportedFiles, probeFiles, projectFiles } from './files.ts'
|
|
11
|
+
import { answer, checkToolCall, projectOf } from './questions.ts'
|
|
12
|
+
import { commitReport, editAnswer, textReport } from './report.ts'
|
|
12
13
|
import { loadRules, type LoadedRule } from './rules.ts'
|
|
13
14
|
import { serve } from './serve.ts'
|
|
14
15
|
|
|
15
16
|
const HELP = `rulebook ${packageJson.version}: checks any file, agent reply, and tool call against your rules and your project's linters.
|
|
16
17
|
|
|
17
18
|
Usage:
|
|
18
|
-
rulebook [files...]
|
|
19
|
-
rulebook --
|
|
20
|
-
rulebook --
|
|
21
|
-
rulebook
|
|
22
|
-
rulebook
|
|
23
|
-
rulebook
|
|
24
|
-
rulebook
|
|
25
|
-
rulebook
|
|
26
|
-
rulebook serve Answer edit, text, and rules as POST /edit, /text, and /rules on a Unix socket, keeping each project's configs and rules loaded, and print unix:<socket path> first.
|
|
27
|
-
rulebook --version Print the version.
|
|
19
|
+
rulebook check [files...] Check every file a rule covers, every Prompt, and every probe of this project, or only the files named, with every rule and linter.
|
|
20
|
+
rulebook check --staged Check what the next commit records, with every rule that runs always or on commit. Run it as the git pre-commit hook.
|
|
21
|
+
rulebook check --stdin-file-path=<path> Check stdin as the text of the file or message at <path>, such as @reply, with every rule that runs always.
|
|
22
|
+
rulebook check --reporter=json Print the results as JSON.
|
|
23
|
+
rulebook check --skip=<name> Skip a rule, every rule of a plugin or folder, a linter, or every agentic rule, such as --skip=agentic. Repeat it to skip more.
|
|
24
|
+
rulebook inspect rules Print, for each folder that holds a rulebook.config.ts, each rule that is on there, with its description and the paths it covers, and each message with the tools that send it, as JSON.
|
|
25
|
+
rulebook claude-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.
|
|
26
|
+
rulebook --version Print the version.
|
|
28
27
|
|
|
29
28
|
A file's rules and settings come from ~/.config/rulebook/rulebook.config.ts and the nearest rulebook.config.ts in the file's folder or a folder above it, with every config they extend.`
|
|
30
29
|
|
|
30
|
+
const REPORTERS = ['default', 'json']
|
|
31
|
+
|
|
31
32
|
async function main(argv: readonly string[]): Promise<number> {
|
|
32
33
|
const { values, positionals } = parseArgs({
|
|
33
34
|
args: [...argv],
|
|
34
35
|
allowPositionals: true,
|
|
35
|
-
options: {
|
|
36
|
+
options: {
|
|
37
|
+
staged: { type: 'boolean' },
|
|
38
|
+
'stdin-file-path': { type: 'string' },
|
|
39
|
+
reporter: { type: 'string', default: 'default' },
|
|
40
|
+
skip: { type: 'string', multiple: true, default: [] },
|
|
41
|
+
version: { type: 'boolean' },
|
|
42
|
+
help: { type: 'boolean', short: 'h' },
|
|
43
|
+
},
|
|
36
44
|
})
|
|
45
|
+
const [command, ...named] = positionals
|
|
37
46
|
if (values.version) return print(packageJson.version)
|
|
38
|
-
if (values.help) return print(HELP)
|
|
39
|
-
if (
|
|
40
|
-
if (
|
|
41
|
-
if (
|
|
42
|
-
if (
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
if (values.help || command === undefined) return print(HELP)
|
|
48
|
+
if (command === '__run_server') return serve()
|
|
49
|
+
if (command === 'claude-hook') return claudeHook(JSON.parse(await Bun.stdin.text()))
|
|
50
|
+
if (command === 'inspect') return inspect(named)
|
|
51
|
+
if (command !== 'check') throw new Error(`${command} is not a rulebook command. \`rulebook --help\` lists them.`)
|
|
52
|
+
if (!REPORTERS.includes(values.reporter)) throw new Error(`--reporter is default or json, not ${values.reporter}.`)
|
|
53
|
+
const isJson = values.reporter === 'json'
|
|
54
|
+
const stdinPath = values['stdin-file-path']
|
|
55
|
+
if ([values.staged === true, stdinPath !== undefined, named.length > 0].filter(Boolean).length > 1) throw new Error('rulebook check takes files, --staged, or --stdin-file-path, one at a time.')
|
|
56
|
+
if (values.staged === true) return staged(values.skip, isJson)
|
|
57
|
+
if (stdinPath !== undefined) return checkStdin(stdinPath, values.skip, isJson)
|
|
58
|
+
return check(named, values.skip, isJson)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function inspect([target, ...rest]: readonly string[]): Promise<number> {
|
|
62
|
+
if (target !== 'rules' || rest.length > 0) throw new Error('rulebook inspect takes rules.')
|
|
63
|
+
const input = { cwd: process.cwd() }
|
|
64
|
+
return print(JSON.stringify(await answer('rules', input, projectOf('rules', input))))
|
|
46
65
|
}
|
|
47
66
|
|
|
48
|
-
async function
|
|
67
|
+
async function claudeHook(input: unknown): Promise<number> {
|
|
49
68
|
const answer = await checkToolCall(input)
|
|
50
69
|
if (answer?.refuse !== undefined) {
|
|
51
70
|
await Bun.write(Bun.stderr, `${answer.refuse}\n`)
|
|
@@ -54,18 +73,29 @@ async function hook(input: unknown): Promise<number> {
|
|
|
54
73
|
return answer?.note === undefined ? 0 : print(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: answer.note } }))
|
|
55
74
|
}
|
|
56
75
|
|
|
57
|
-
async function
|
|
58
|
-
const { reports, failures } = await
|
|
76
|
+
async function staged(skip: readonly string[], isJson: boolean): Promise<number> {
|
|
77
|
+
const { reports, failures } = await checkStaged(projectRoot(process.cwd(), process.cwd()), skip)
|
|
59
78
|
const { text, isRefused } = commitReport(reports, failures)
|
|
60
79
|
await print(isJson ? JSON.stringify({ reports, failures }) : text)
|
|
61
80
|
return isRefused ? 1 : 0
|
|
62
81
|
}
|
|
63
82
|
|
|
64
|
-
async function
|
|
65
|
-
|
|
83
|
+
async function checkStdin(path: string, skip: readonly string[], isJson: boolean): Promise<number> {
|
|
84
|
+
const cwd = process.cwd()
|
|
85
|
+
const isMessage = path.startsWith('@')
|
|
86
|
+
const file = isMessage ? path : realFile(path, cwd)
|
|
87
|
+
const root = isMessage ? projectRoot(cwd, cwd) : fileRoot(file, cwd)
|
|
88
|
+
const settings = await loadSettings(isMessage ? cwd : dirname(file), root)
|
|
89
|
+
const { rules, failures } = await loadRules(settings)
|
|
90
|
+
const report = await checkFile(settings, rules, file, await Bun.stdin.text(), { scope: 'edit', imported: () => loadImportedFiles(root), skip })
|
|
91
|
+
const { refuse, note } = editAnswer(report)
|
|
92
|
+
const text = refuse ?? note
|
|
93
|
+
if (isJson) await print(JSON.stringify({ reports: report === undefined ? [] : [report], failures }))
|
|
94
|
+
else if (text !== undefined) await print(text)
|
|
95
|
+
return refuse === undefined ? 0 : 1
|
|
66
96
|
}
|
|
67
97
|
|
|
68
|
-
async function check(named: readonly string[],
|
|
98
|
+
async function check(named: readonly string[], skip: readonly string[], isJson: boolean): Promise<number> {
|
|
69
99
|
const listing = listedFiles(process.cwd())
|
|
70
100
|
const root = projectRoot(process.cwd(), process.cwd())
|
|
71
101
|
const settings = await loadSettings(process.cwd(), root)
|
|
@@ -77,14 +107,15 @@ async function check(named: readonly string[], isStatic: boolean, isJson: boolea
|
|
|
77
107
|
for (const failure of failures) unloaded.add(failure)
|
|
78
108
|
return rules
|
|
79
109
|
}
|
|
80
|
-
const files = named.length > 0 ? named.map((file) =>
|
|
110
|
+
const files = named.length > 0 ? named.map((file) => namedFile(file)) : await textFiles([...new Set([...(await coveredFiles(groups, rulesOf)), ...imported, ...messageFiles(settings)])])
|
|
81
111
|
const checked = await Promise.all(files.map(async (file) => {
|
|
82
112
|
const own = displayPath(settings, file).startsWith('@') ? settings : await loadSettings(dirname(file), root)
|
|
83
|
-
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope:
|
|
113
|
+
const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope: 'all', imported: async () => imported, skip })
|
|
84
114
|
if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's paths cover.`)
|
|
85
115
|
return report
|
|
86
116
|
}))
|
|
87
|
-
const
|
|
117
|
+
const linted = new Map([...groups].map(([own, owned]) => [{ ...own, linters: own.linters.filter((name) => !isSkipped(skip, name)) }, owned]))
|
|
118
|
+
const reports = await lintProject(linted, checked.filter((report) => report !== undefined), named.length > 0 ? files : undefined)
|
|
88
119
|
const failures = [...unloaded]
|
|
89
120
|
await print(isJson ? JSON.stringify({ reports, failures }) : textReport(reports, failures))
|
|
90
121
|
return failures.length > 0 || reports.some((report) => report.failures.length > 0 || report.findings.some(({ level }) => level === 'error')) ? 1 : 0
|
|
@@ -107,7 +138,7 @@ async function textFiles(files: readonly string[]): Promise<readonly string[]> {
|
|
|
107
138
|
return files.filter((_, index) => texts[index])
|
|
108
139
|
}
|
|
109
140
|
|
|
110
|
-
function
|
|
141
|
+
function namedFile(file: string): string {
|
|
111
142
|
const path = resolve(file)
|
|
112
143
|
if (!existsSync(path)) throw new Error(`${file} does not exist.`)
|
|
113
144
|
return realpathSync(path)
|
package/src/questions.ts
CHANGED
|
@@ -52,7 +52,7 @@ export function answer(question: Question, input: unknown, root: string): Promis
|
|
|
52
52
|
|
|
53
53
|
async function checkText({ name, text, cwd, input }: Text, root: string): Promise<EditAnswer> {
|
|
54
54
|
const settings = await loadSettings(cwd, root)
|
|
55
|
-
if (!name.startsWith('@')) throw new Error('
|
|
55
|
+
if (!name.startsWith('@')) throw new Error('The text question checks a message by its @-name, such as @reply or @inbox/<id>.md.')
|
|
56
56
|
const { rules } = await loadRules(settings)
|
|
57
57
|
const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set(), ...(input === undefined ? {} : { input }) })
|
|
58
58
|
return editAnswer(report)
|
|
@@ -94,14 +94,14 @@ async function listRules(cwd: string, root: string): Promise<unknown> {
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
function toolCall(input: unknown): ToolCall {
|
|
97
|
-
if (!isRecord(input) || typeof input.tool_name !== 'string' || !isRecord(input.tool_input) || typeof input.cwd !== 'string') throw new Error('
|
|
97
|
+
if (!isRecord(input) || typeof input.tool_name !== 'string' || !isRecord(input.tool_input) || typeof input.cwd !== 'string') throw new Error('A tool call is {"tool_name", "tool_input", "cwd"}.')
|
|
98
98
|
return { tool_name: input.tool_name, tool_input: input.tool_input, cwd: input.cwd }
|
|
99
99
|
}
|
|
100
100
|
|
|
101
101
|
function textOf(input: unknown): Text {
|
|
102
|
-
if (!isRecord(input) || typeof input.name !== 'string' || typeof input.cwd !== 'string') throw new Error('
|
|
102
|
+
if (!isRecord(input) || typeof input.name !== 'string' || typeof input.cwd !== 'string') throw new Error('The text question reads {"name", "text" or "input", "cwd"}.')
|
|
103
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('
|
|
104
|
+
if (typeof input.text !== 'string') throw new Error('The text question reads {"name", "text" or "input", "cwd"}.')
|
|
105
105
|
return { name: input.name, text: input.text, cwd: input.cwd }
|
|
106
106
|
}
|
|
107
107
|
|
|
@@ -113,6 +113,6 @@ function textsOf(value: unknown): readonly string[] {
|
|
|
113
113
|
}
|
|
114
114
|
|
|
115
115
|
function cwdOf(input: unknown): string {
|
|
116
|
-
if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('
|
|
116
|
+
if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('The rules question reads {"cwd"}.')
|
|
117
117
|
return input.cwd
|
|
118
118
|
}
|
package/src/report.ts
CHANGED
|
@@ -46,7 +46,7 @@ function existingLine(report: FileReport, isMore: boolean): readonly string[] {
|
|
|
46
46
|
const errors = existing.filter(({ level }) => level === 'error').length
|
|
47
47
|
const noun = errors === existing.length ? 'error' : errors === 0 ? 'warning' : 'finding'
|
|
48
48
|
const isOne = existing.length === 1
|
|
49
|
-
return [`${existing.length}${isMore ? ' more' : ''} ${noun}${isOne ? '' : 's'} in this file ${isOne ? 'was' : 'were'} there before this edit. \`rulebook ${report.path}\` lists ${isOne ? 'it' : 'them'}.`]
|
|
49
|
+
return [`${existing.length}${isMore ? ' more' : ''} ${noun}${isOne ? '' : 's'} in this file ${isOne ? 'was' : 'were'} there before this edit. \`rulebook check ${report.path}\` lists ${isOne ? 'it' : 'them'}.`]
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
function refusal(path: string): string {
|
|
@@ -66,7 +66,7 @@ export function commitReport(reports: readonly FileReport[], unloaded: readonly
|
|
|
66
66
|
const isRefused = written.some(({ findings }) => findings.some(({ level }) => level === 'error'))
|
|
67
67
|
const existing = reports.flatMap(({ path, findings }) => (findings.some(isHidden) ? [path] : []))
|
|
68
68
|
const count = reports.flatMap(({ findings }) => findings.filter(isHidden)).length
|
|
69
|
-
const before = count === 0 ? [] : [`${count} ${count === 1 ? 'finding' : 'findings'} in these files ${count === 1 ? 'was' : 'were'} there before this commit. \`rulebook ${existing.join(' ')}\` lists ${count === 1 ? 'it' : 'them'}.`]
|
|
69
|
+
const before = count === 0 ? [] : [`${count} ${count === 1 ? 'finding' : 'findings'} in these files ${count === 1 ? 'was' : 'were'} there before this commit. \`rulebook check ${existing.join(' ')}\` lists ${count === 1 ? 'it' : 'them'}.`]
|
|
70
70
|
const body = textReport(written, unloaded)
|
|
71
71
|
return { isRefused, text: [...(isRefused ? ['Commit refused. Fix every error, stage the fix, then commit again.'] : []), body, ...before].join('\n\n') }
|
|
72
72
|
}
|
package/src/serve.ts
CHANGED
|
@@ -91,10 +91,10 @@ export async function serve(): Promise<never> {
|
|
|
91
91
|
idleTimeout: 0,
|
|
92
92
|
async fetch(request: Request) {
|
|
93
93
|
const question = new URL(request.url).pathname.slice(1)
|
|
94
|
-
if (request.method !== 'POST' || !isQuestion(question)) return new Response('rulebook
|
|
94
|
+
if (request.method !== 'POST' || !isQuestion(question)) return new Response('The rulebook server answers POST /edit, /text, and /rules.', { status: 404 })
|
|
95
95
|
try {
|
|
96
96
|
const body: unknown = await request.json()
|
|
97
|
-
if (!isRecord(body)) throw new Error('rulebook
|
|
97
|
+
if (!isRecord(body)) throw new Error('The rulebook server reads {"input", "environment"}.')
|
|
98
98
|
const root = projectOf(question, body.input)
|
|
99
99
|
const environment = environmentOf(body.environment)
|
|
100
100
|
const key = `${root}\0${JSON.stringify(environment)}`
|
|
@@ -126,6 +126,6 @@ function isStale({ watched, startedAt }: Project): boolean {
|
|
|
126
126
|
}
|
|
127
127
|
|
|
128
128
|
function environmentOf(sent: unknown): Environment {
|
|
129
|
-
if (!isRecord(sent)) throw new Error('rulebook
|
|
129
|
+
if (!isRecord(sent)) throw new Error('The rulebook server reads {"input", "environment"}.')
|
|
130
130
|
return Object.fromEntries(ENVIRONMENT.flatMap((name) => (typeof sent[name] === 'string' ? [[name, sent[name]]] : [])))
|
|
131
131
|
}
|