@cmodjs/rulebook 0.10.1 → 0.11.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmodjs/rulebook",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Checks every file, reply, tool call, and commit against your rules and linters before it lands.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/api.ts CHANGED
@@ -89,7 +89,7 @@ export type Config = {
89
89
  readonly extends?: readonly (string | Config)[]
90
90
  readonly plugins?: Readonly<Record<string, string>>
91
91
  readonly files?: readonly string[]
92
- readonly probes?: readonly string[]
92
+ readonly tests?: readonly string[]
93
93
  readonly timeout?: number
94
94
  readonly existingErrors?: 'error' | 'warn'
95
95
  readonly rules?: Readonly<Record<string, Severity | 'off' | RuleSettings>>
package/src/check.ts CHANGED
@@ -40,7 +40,7 @@ type CheckOptions = {
40
40
  }
41
41
 
42
42
  export const COMMAND = '@command'
43
- const PIN = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
43
+ const EXPECT = /^\s*<!--\s*rulebook-expect\s+(\S+)\s*-->\s*$/
44
44
  const MAX_EDIT_LENGTH = 1_000
45
45
 
46
46
  function matches(globs: readonly string[], path: string): boolean {
@@ -71,8 +71,8 @@ export function isCovered(settings: Settings, rules: readonly LoadedRule[], file
71
71
  return rules.some((rule) => covers(rule, path, false))
72
72
  }
73
73
 
74
- function isProbe(settings: Settings, file: string): boolean {
75
- return settings.configs.some((config) => isInside(config.dir, file) && matches(config.probes, relative(config.dir, file)))
74
+ function isRuleTest(settings: Settings, file: string): boolean {
75
+ return settings.configs.some((config) => isInside(config.dir, file) && matches(config.tests, relative(config.dir, file)))
76
76
  }
77
77
 
78
78
  export function isPrompt(settings: Settings, file: string): boolean {
@@ -82,17 +82,17 @@ export function isPrompt(settings: Settings, file: string): boolean {
82
82
  export async function checkFile(settings: Settings, rules: readonly LoadedRule[], file: string, text: string, options: CheckOptions): Promise<FileReport | undefined> {
83
83
  const path = displayPath(settings, file)
84
84
  const isMessage = path.startsWith('@')
85
- const probe = !isMessage && isProbe(settings, file)
86
- const configured = probe || (!isMessage && isPrompt(settings, file))
85
+ const ruleTest = !isMessage && isRuleTest(settings, file)
86
+ const configured = ruleTest || (!isMessage && isPrompt(settings, file))
87
87
  const isMemory = !isMessage && isClaudeMd(file)
88
88
  const imported = !isMessage && !(configured && isMemory) && existsSync(file) && (await options.imported()).has(realpathSync(file))
89
89
  const covered = rules.filter((rule) => inScope(rule, options) && covers(rule, path, configured || imported))
90
- const linted = !isMessage && !probe ? coveringLinters(settings.linters.filter((name) => !isSkipped(options.skip, name)), settings.programs, file, text, settings.root) : []
90
+ const linted = !isMessage && !ruleTest ? coveringLinters(settings.linters.filter((name) => !isSkipped(options.skip, name)), settings.programs, file, text, settings.root) : []
91
91
  if (!configured && !imported && covered.length === 0 && linted.length === 0) return undefined
92
92
  const written = text.split('\n')
93
93
  const isDoc = imported || isMemory
94
- const mayPin = text.includes('rulebook-expect')
95
- const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
94
+ const mayExpect = text.includes('rulebook-expect')
95
+ const claudeMd = isDoc || ruleTest || (mayExpect && written.some((line) => EXPECT.test(line))) ? readClaudeMd(text) : undefined
96
96
  const memory = isDoc ? claudeMd : undefined
97
97
  const before = options.previous === undefined || !isDoc ? options.previous : readClaudeMd(options.previous).lines.join('\n')
98
98
  const prompt: CheckedFile = {
@@ -104,9 +104,9 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
104
104
  ...(options.call === undefined ? {} : { call: options.call }),
105
105
  }
106
106
  const doc = memory === undefined ? undefined : { file, imports: memory.imports }
107
- const pins = mayPin ? pinsOf(written, claudeMd?.lines ?? []) : []
108
- const pinned = new Set(pins.map(({ rule }) => rule))
109
- const chosen = probe ? rules.filter((rule) => inScope(rule, options) && pinned.has(rule.id)) : covered
107
+ const expectations = mayExpect ? expectationsOf(written, claudeMd?.lines ?? []) : []
108
+ const expected = new Set(expectations.map(({ rule }) => rule))
109
+ const chosen = ruleTest ? rules.filter((rule) => inScope(rule, options) && expected.has(rule.id)) : covered
110
110
  const wrote = options.previous === undefined ? undefined : linesWritten(options.previous, written)
111
111
  const changed = wrote === undefined ? undefined : [...wrote].filter((line) => written[line - 1]?.trim() !== '')
112
112
 
@@ -128,7 +128,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
128
128
  const levelOfRule = ({ level }: LoadedRule): Level => (level === 'off' || (level === 'ask' && options.call === undefined) ? 'error' : level)
129
129
  const found = [...runs.flatMap((run) => ('found' in run ? run.found.map(({ line, message, isWhole }) => ({ line, message: message ?? run.rule.message ?? run.rule.description, rule: run.rule.id, level: levelOfRule(run.rule), ...(isWhole === true ? { isWhole } : {}) })) : [])), ...lints.flatMap((lint) => lint.flags)]
130
130
  const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
131
- const flagged: readonly Flag[] = probe ? probeFindings(found, pins.filter(({ rule }) => !unscoped.has(rule)), written.findLastIndex((line) => line.trim() !== '') + 1) :[...found, ...pins.map((pin) => ({ rule: 'rulebook/pins', line: pin.line, level: 'error' as const, message: 'A rulebook-expect pin works only in a probe file. Remove it.' }))]
131
+ const flagged: readonly Flag[] = ruleTest ? ruleTestFindings(found, expectations.filter(({ rule }) => !unscoped.has(rule)), written.findLastIndex((line) => line.trim() !== '') + 1) : [...found, ...expectations.map((expectation) => ({ rule: 'rulebook/expect-comments', line: expectation.line, level: 'error' as const, message: 'A rulebook-expect comment works only in a rule test. Remove it.' }))]
132
132
 
133
133
  return {
134
134
  path,
@@ -204,17 +204,17 @@ export function isSkipped(skip: readonly string[] | undefined, name: string): bo
204
204
  return skip?.some((skipped) => name === skipped || name.startsWith(`${skipped}/`)) ?? false
205
205
  }
206
206
 
207
- type Pin = { readonly rule: string; readonly line: number; readonly target: number }
207
+ type Expectation = { readonly rule: string; readonly line: number; readonly target: number }
208
208
 
209
- function pinsOf(written: readonly string[], shown: readonly string[]): readonly Pin[] {
210
- const pins: Pin[] = []
209
+ function expectationsOf(written: readonly string[], shown: readonly string[]): readonly Expectation[] {
210
+ const expectations: Expectation[] = []
211
211
  const waiting: { rule: string; line: number }[] = []
212
212
  written.forEach((text, index) => {
213
- const rule = PIN.test(shown[index] ?? '') ? undefined : PIN.exec(text)?.[1]
213
+ const rule = EXPECT.test(shown[index] ?? '') ? undefined : EXPECT.exec(text)?.[1]
214
214
  if (rule !== undefined) waiting.push({ rule, line: index + 1 })
215
- else for (const pin of waiting.splice(0)) pins.push({ ...pin, target: index + 1 })
215
+ else for (const expectation of waiting.splice(0)) expectations.push({ ...expectation, target: index + 1 })
216
216
  })
217
- return [...pins, ...waiting.map((pin) => ({ ...pin, target: written.length + 1 }))]
217
+ return [...expectations, ...waiting.map((expectation) => ({ ...expectation, target: written.length + 1 }))]
218
218
  }
219
219
 
220
220
  function linesWritten(previous: string, written: readonly string[]): ReadonlySet<number> {
@@ -304,18 +304,18 @@ export const noSuppressionsRule: StaticRule = {
304
304
 
305
305
  type Flag = Omit<Reported, 'isExisting' | 'quote'> & { readonly isWhole?: true }
306
306
 
307
- function probeFindings(found: readonly Flag[], pins: readonly Pin[], lastLine: number): readonly Flag[] {
308
- const open = [...pins]
309
- const isWholePin = (pin: Pin): boolean => pin.target > lastLine
307
+ function ruleTestFindings(found: readonly Flag[], expectations: readonly Expectation[], lastLine: number): readonly Flag[] {
308
+ const open = [...expectations]
309
+ const isWhole = (expectation: Expectation): boolean => expectation.target > lastLine
310
310
  const unexpected = found.filter((finding) => {
311
- const index = open.findIndex((pin) => pin.rule === finding.rule && (finding.isWhole === true ? isWholePin(pin) : !isWholePin(pin) && pin.target === finding.line))
311
+ const index = open.findIndex((expectation) => expectation.rule === finding.rule && (finding.isWhole === true ? isWhole(expectation) : !isWhole(expectation) && expectation.target === finding.line))
312
312
  if (index === -1) return true
313
313
  open.splice(index, 1)
314
314
  return false
315
315
  })
316
316
  return [
317
- ...unexpected.map((finding) => ({ ...finding, level: 'error' as const, message: `${finding.message} (no pin expects this flag)` })),
318
- ...open.map((pin) => ({ rule: pin.rule, line: pin.line, level: 'error' as const, message: `The pin expects ${pin.rule} to flag ${isWholePin(pin) ? 'the whole file' : `line ${pin.target}`}, and it does not.` })),
317
+ ...unexpected.map((finding) => ({ ...finding, level: 'error' as const, message: `${finding.message} (no rulebook-expect comment expects this flag)` })),
318
+ ...open.map((expectation) => ({ rule: expectation.rule, line: expectation.line, level: 'error' as const, message: `This rulebook-expect comment expects ${expectation.rule} to flag ${isWhole(expectation) ? 'the whole file' : `line ${expectation.target}`}, and it does not.` })),
319
319
  ]
320
320
  }
321
321
 
package/src/config.ts CHANGED
@@ -12,7 +12,7 @@ type LoadedConfig = {
12
12
  readonly dir: string
13
13
  readonly basePath: string
14
14
  readonly plugins: Readonly<Record<string, string>>
15
- readonly probes: readonly string[]
15
+ readonly tests: readonly string[]
16
16
  readonly messages: Readonly<Record<string, MessageSource>>
17
17
  }
18
18
 
@@ -34,7 +34,7 @@ export type Settings = {
34
34
  readonly messages: Readonly<Record<string, MessageSource>>
35
35
  }
36
36
 
37
- const KEYS = new Set(['extends', 'plugins', 'files', 'probes', 'timeout', 'existingErrors', 'rules', 'linters', 'programs', 'messages'])
37
+ const KEYS = new Set(['extends', 'plugins', 'files', 'tests', 'timeout', 'existingErrors', 'rules', 'linters', 'programs', 'messages'])
38
38
  const RULE_KEYS = new Set(['severity', 'runs', 'files', 'timeout', 'agent', 'model', 'effort', 'threshold'])
39
39
  const MESSAGE_KEYS = new Set(['tools', 'folder'])
40
40
  const BUILT_IN: Pick<LoadedConfig, 'file' | 'plugins' | 'messages'> = {
@@ -164,7 +164,7 @@ function loadedConfig(config: Config, { file, dir, basePath }: Place): LoadedCon
164
164
  const path = folder === undefined ? undefined : resolve(dir, folder)
165
165
  return [name, { tools, folder: path !== undefined && existsSync(path) ? realpathSync(path) : path }]
166
166
  }))
167
- return { file, dir, basePath, plugins, probes: config.probes ?? [], messages }
167
+ return { file, dir, basePath, plugins, tests: config.tests ?? [], messages }
168
168
  }
169
169
 
170
170
  function realFolder(file: string, folder: string): string {
@@ -182,7 +182,7 @@ function validConfig(file: string, value: unknown): Config {
182
182
  if (value.extends !== undefined && !(Array.isArray(value.extends) && value.extends.every((entry) => typeof entry === 'string' || isRecord(entry)))) fail('extends is a list of config paths, relative to the config, and config objects, such as [recommended].')
183
183
  if (value.plugins !== undefined && !(isRecord(value.plugins) && Object.values(value.plugins).every((folder) => typeof folder === 'string'))) fail('plugins maps each plugin name to a folder.')
184
184
  for (const name of Object.keys(value.plugins ?? {})) if (!/^[a-z][a-z0-9-]*$/.test(name)) fail(`"${name}" is not a plugin name: use lowercase letters, digits, and "-".`)
185
- for (const key of ['files', 'probes'] as const) if (value[key] !== undefined && !isStrings(value[key])) fail(`${key} is a list of globs.`)
185
+ for (const key of ['files', 'tests'] as const) if (value[key] !== undefined && !isStrings(value[key])) fail(`${key} is a list of globs.`)
186
186
  if (value.timeout !== undefined && !isTimeout(value.timeout)) fail('timeout is a whole number of milliseconds above 0.')
187
187
  if (value.existingErrors !== undefined && value.existingErrors !== 'error' && value.existingErrors !== 'warn') fail('existingErrors is "error" or "warn".')
188
188
  if (value.rules !== undefined && !isRecord(value.rules)) fail('rules maps each rule name, such as "global/block-em-dashes", to a severity or to settings.')
package/src/files.ts CHANGED
@@ -76,9 +76,9 @@ function isRulesLink(entry: string): boolean {
76
76
  return statSync(entry, { throwIfNoEntry: false })?.isDirectory() === true && isRulesFolder(entry)
77
77
  }
78
78
 
79
- export function probeFiles(settings: Settings): readonly string[] {
80
- const probes = settings.configs.flatMap((config) => config.probes.flatMap((glob) => [...new Bun.Glob(glob).scanSync({ cwd: config.dir, absolute: true, dot: true })]))
81
- return [...new Set(probes.map((file) => realpathSync(file)))].filter((file) => isInside(settings.root, file)).sort()
79
+ export function ruleTestFiles(settings: Settings): readonly string[] {
80
+ const ruleTests = settings.configs.flatMap((config) => config.tests.flatMap((glob) => [...new Bun.Glob(glob).scanSync({ cwd: config.dir, absolute: true, dot: true })]))
81
+ return [...new Set(ruleTests.map((file) => realpathSync(file)))].filter((file) => isInside(settings.root, file)).sort()
82
82
  }
83
83
 
84
84
  export async function listedFiles(folder: string): Promise<readonly string[] | undefined> {
package/src/main.ts CHANGED
@@ -7,7 +7,7 @@ import { checkFile, displayPath, isCovered, isPrompt, isSkipped, lintProject } f
7
7
  import { checkStaged } from './commit.ts'
8
8
  import { loadSettings, projectRoot, type Settings } from './config.ts'
9
9
  import { fileRoot, realFile } from './edit.ts'
10
- import { filesBySettings, importedFiles, listedFiles, loadImportedFiles, probeFiles, projectFiles } from './files.ts'
10
+ import { filesBySettings, importedFiles, listedFiles, loadImportedFiles, projectFiles, ruleTestFiles } from './files.ts'
11
11
  import { answer, checkToolCall, projectOf } from './questions.ts'
12
12
  import { commitReport, editAnswer, textReport } from './report.ts'
13
13
  import { loadRules, type LoadedRule } from './rules.ts'
@@ -16,7 +16,7 @@ import { serve } from './serve.ts'
16
16
  const HELP = `rulebook ${packageJson.version}: checks any file, agent reply, and tool call against your rules and your project's linters.
17
17
 
18
18
  Usage:
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.
19
+ rulebook check [files...] Check every file a rule covers, every Prompt, and every rule test of this project, or only the files named, with every rule and linter.
20
20
  rulebook check --staged Check what the next commit records, on the lines it writes, with every rule and linter. Run it from a git pre-commit hook.
21
21
  rulebook check --stdin-file-path=<path> Check stdin as the text of the file or message at <path>, such as @reply or @command, with the rules that run always, as an agent's write is checked.
22
22
  rulebook check --reporter=json Print the results as JSON.
@@ -114,7 +114,7 @@ async function check(named: readonly string[], skip: readonly string[], isJson:
114
114
  const checked = await Promise.all(files.map(async (file) => {
115
115
  const own = displayPath(settings, file).startsWith('@') ? settings : await loadSettings(dirname(file), root)
116
116
  const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope: 'all', imported: async () => imported, skip })
117
- if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's files cover.`)
117
+ if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a rule test, or a file a rule's files cover.`)
118
118
  return report
119
119
  }))
120
120
  const linted = new Map([...groups].map(([own, owned]) => [{ ...own, linters: own.linters.filter((name) => !isSkipped(skip, name)) }, owned]))
@@ -127,7 +127,7 @@ async function check(named: readonly string[], skip: readonly string[], isJson:
127
127
  async function coveredFiles(groups: ReadonlyMap<Settings, readonly string[]>, rulesOf: (settings: Settings) => Promise<readonly LoadedRule[]>): Promise<readonly string[]> {
128
128
  const covered = await Promise.all([...groups].map(async ([settings, files]) => {
129
129
  const rules = await rulesOf(settings)
130
- return [...files.filter((file) => isPrompt(settings, file) || isCovered(settings, rules, file)), ...probeFiles(settings)]
130
+ return [...files.filter((file) => isPrompt(settings, file) || isCovered(settings, rules, file)), ...ruleTestFiles(settings)]
131
131
  }))
132
132
  return covered.flat()
133
133
  }