@cmodjs/rulebook 0.7.0 → 0.9.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.7.0",
3
+ "version": "0.9.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",
@@ -42,6 +42,7 @@
42
42
  "@ast-grep/lang-markdown": "0.0.6",
43
43
  "@ast-grep/lang-php": "0.0.7",
44
44
  "@ast-grep/lang-python": "0.0.6",
45
+ "@ast-grep/lang-rust": "0.0.7",
45
46
  "@ast-grep/lang-toml": "0.0.9",
46
47
  "@ast-grep/lang-yaml": "0.0.6",
47
48
  "@ast-grep/napi": "0.51.1",
package/src/api.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { SgNode } from '@ast-grep/napi'
2
+
1
3
  export type Severity = 'error' | 'warn'
2
4
 
3
5
  export type Runs = 'always' | 'manual'
@@ -12,9 +14,9 @@ export type Call = {
12
14
  readonly transcriptPath?: string
13
15
  }
14
16
 
15
- export type Document = { readonly lineNumber: 1; readonly text: string }
17
+ export type { SgNode }
16
18
 
17
- export type Line = { readonly lineNumber: number; readonly text: string; readonly isInCodeBlock: boolean }
19
+ export type Document = { readonly text: string }
18
20
 
19
21
  export type Command = {
20
22
  readonly lineNumber: number
@@ -27,29 +29,37 @@ export type Command = {
27
29
  }
28
30
 
29
31
  export type Shell = {
32
+ readonly commands: readonly Command[]
30
33
  readonly reads: readonly string[]
31
34
  readonly writes: readonly string[]
32
35
  readonly fetches: readonly string[]
33
36
  readonly isFullyParsed: boolean
34
37
  }
35
38
 
36
- export type Node = Document | Line | Command
39
+ export type Node = SgNode | Command | Shell | Document
40
+
41
+ export type SourceCode = {
42
+ readonly text: string
43
+ readonly lines: readonly string[]
44
+ readonly ast: SgNode | Shell | Document
45
+ }
46
+
47
+ export type Position = { readonly line: number; readonly column: number }
48
+
49
+ export type Problem = { readonly node: Node } | { readonly loc: { readonly start: Position; readonly end?: Position } }
37
50
 
38
51
  export type Context = {
39
52
  readonly root: string
40
- readonly path: string
41
- readonly text: string
42
- readonly lines: readonly Line[]
43
- readonly commands: readonly Command[]
44
- readonly shell?: Shell
53
+ readonly filename: string
54
+ readonly sourceCode: SourceCode
55
+ readonly previous?: SourceCode
45
56
  readonly call?: Call
46
- report(finding: { readonly node: Node }): void
57
+ report(problem: Problem): void
47
58
  }
48
59
 
49
60
  export type Visitors = {
50
- readonly Document?: (document: Document) => void | Promise<void>
51
- readonly Line?: (line: Line) => void | Promise<void>
52
61
  readonly Command?: (command: Command) => void | Promise<void>
62
+ readonly [kind: string]: ((node: SgNode) => void | Promise<void>) | ((command: Command) => void | Promise<void>) | undefined
53
63
  }
54
64
 
55
65
  export type Rule = {
package/src/check.ts CHANGED
@@ -94,10 +94,12 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
94
94
  const mayPin = text.includes('rulebook-expect')
95
95
  const claudeMd = isDoc || probe || (mayPin && written.some((line) => PIN.test(line))) ? readClaudeMd(text) : undefined
96
96
  const memory = isDoc ? claudeMd : undefined
97
+ const before = options.previous === undefined || !isDoc ? options.previous : readClaudeMd(options.previous).lines.join('\n')
97
98
  const prompt: CheckedFile = {
98
99
  root: settings.root,
99
100
  path,
100
101
  ...(memory === undefined ? { text, lines: written } : { text: memory.lines.join('\n'), lines: memory.lines }),
102
+ ...(before === undefined ? {} : { previous: { text: before, lines: before.split('\n') } }),
101
103
  ...(path === COMMAND ? { shell: parseShell(text) } : {}),
102
104
  ...(options.call === undefined ? {} : { call: options.call }),
103
105
  }
@@ -125,7 +127,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
125
127
  const failures = [...runs.flatMap((run) => ('failure' in run ? [{ rule: run.rule.id, reason: run.failure }] : [])), ...lints.flatMap((lint) => lint.failures)]
126
128
  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: run.rule.level === 'off' ? 'error' as const : run.rule.level, ...(isWhole === true ? { isWhole } : {}) })) : [])), ...lints.flatMap((lint) => lint.flags)]
127
129
  const unscoped = new Set(rules.filter((rule) => !inScope(rule, options)).map(({ id }) => id))
128
- const flagged: readonly Flag[] = probe ? probeFindings(found, pins.filter(({ rule }) => !unscoped.has(rule))) : [...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.' }))]
130
+ const flagged: readonly Flag[] = probe ? probeFindings(found, pins.filter(({ rule }) => !unscoped.has(rule)), written.findLastIndex((line) => line.trim() !== '') + 1) :[...found, ...pins.map((pin) => ({ rule: 'rulebook/pins', line: pin.line, level: 'error' as const, message: 'A rulebook-expect pin works only in a probe file. Remove it.' }))]
129
131
 
130
132
  return {
131
133
  path,
@@ -299,17 +301,18 @@ export const noSuppressionsRule: StaticRule = {
299
301
 
300
302
  type Flag = Omit<Reported, 'isExisting' | 'quote'> & { readonly isWhole?: true }
301
303
 
302
- function probeFindings(found: readonly Flag[], pins: readonly Pin[]): readonly Flag[] {
304
+ function probeFindings(found: readonly Flag[], pins: readonly Pin[], lastLine: number): readonly Flag[] {
303
305
  const open = [...pins]
306
+ const isWholePin = (pin: Pin): boolean => pin.target > lastLine
304
307
  const unexpected = found.filter((finding) => {
305
- const index = open.findIndex((pin) => pin.rule === finding.rule && pin.target === finding.line)
308
+ const index = open.findIndex((pin) => pin.rule === finding.rule && (finding.isWhole === true ? isWholePin(pin) : !isWholePin(pin) && pin.target === finding.line))
306
309
  if (index === -1) return true
307
310
  open.splice(index, 1)
308
311
  return false
309
312
  })
310
313
  return [
311
314
  ...unexpected.map((finding) => ({ ...finding, level: 'error' as const, message: `${finding.message} (no pin expects this flag)` })),
312
- ...open.map((pin) => ({ rule: pin.rule, line: pin.line, level: 'error' as const, message: `The pin expects ${pin.rule} to flag line ${pin.target}, and it does not.` })),
315
+ ...open.map((pin) => ({ rule: pin.rule, line: pin.line, level: 'error' as const, message: `The pin expects ${pin.rule} to flag ${isWholePin(pin) ? 'the whole file' : `line ${pin.target}`}, and it does not.` })),
313
316
  ]
314
317
  }
315
318
 
package/src/commit.ts CHANGED
@@ -117,10 +117,10 @@ function withAddedErrors(reports: readonly FileReport[], added: readonly FileRep
117
117
  return [...merged.values()]
118
118
  }
119
119
 
120
- async function committed(root: string, path: string): Promise<string> {
120
+ async function committed(root: string, path: string): Promise<string | undefined> {
121
121
  const show = Bun.spawn(['git', 'show', `HEAD:${path}`], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'ignore' })
122
122
  const [text, code] = await Promise.all([new Response(show.stdout).text(), show.exited])
123
- return code === 0 ? text : ''
123
+ return code === 0 ? text : undefined
124
124
  }
125
125
 
126
126
  async function hasHead(root: string): Promise<boolean> {
package/src/edit.ts CHANGED
@@ -40,7 +40,7 @@ export async function checkEdit(call: Call, root: string): Promise<EditAnswer> {
40
40
  const settings = await loadSettings(dirname(file), root)
41
41
  const { rules } = await loadRules(settings)
42
42
  const isWhole = next === ''
43
- const report = await checkFile(settings, rules, file, next, { scope: 'edit', previous: isWhole ? '' : previous ?? '', imported: () => loadImportedFiles(root), call })
43
+ const report = await checkFile(settings, rules, file, next, { scope: 'edit', previous: isWhole ? '' : previous,imported: () => loadImportedFiles(root), call })
44
44
  return editAnswer(report)
45
45
  }
46
46
 
package/src/rules.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { existsSync, mkdirSync, renameSync } from 'node:fs'
2
- import { basename, join } from 'node:path'
3
- import type { NapiConfig } from '@ast-grep/napi'
2
+ import { basename, extname, join, resolve } from 'node:path'
3
+ import type { NapiConfig, SgNode } from '@ast-grep/napi'
4
4
  import type { ParsedShell } from '@cmodjs/core/shell.js'
5
- import type { Call, Command, Context, Document, Line, Rule, RuleSettings, Runs, Severity, Visitors } from './api.ts'
6
- import { importsRule, noSuppressionsRule } from './check.ts'
5
+ import type { Call, Command, Context, Node, Rule, RuleSettings, Runs, Severity, Shell, SourceCode, Visitors } from './api.ts'
6
+ import { COMMAND, importsRule, noSuppressionsRule } from './check.ts'
7
7
  import type { Import } from './claude-md.ts'
8
8
  import { isRecord, isRuns, isSeverity, isStrings, isThreshold, isTimeout, rootRelative, type Settings } from './config.ts'
9
9
  import { isJev } from './jev.ts'
@@ -14,12 +14,12 @@ export type Level = 'error' | 'warning'
14
14
 
15
15
  export type Finding = { readonly line: number; readonly message?: string; readonly isWhole?: true }
16
16
 
17
- export type CheckedFile = {
17
+ type Text = { readonly text: string; readonly lines: readonly string[]; readonly shell?: ParsedShell }
18
+
19
+ export type CheckedFile = Text & {
18
20
  readonly root: string
19
21
  readonly path: string
20
- readonly text: string
21
- readonly lines: readonly string[]
22
- readonly shell?: ParsedShell
22
+ readonly previous?: Text
23
23
  readonly call?: Call
24
24
  }
25
25
 
@@ -62,9 +62,12 @@ const SCRIPT_KEYS = new Set([...COMMON_KEYS, 'create'])
62
62
  const FRONTMATTER_KEYS = new Set([...COMMON_KEYS, 'timeout', 'threshold', 'agent', 'model', 'effort', 'allowed-tools', 'disallowed-tools'])
63
63
  const CLAUDE_KEYS = ['agent', 'effort', 'allowed-tools', 'disallowed-tools'] as const
64
64
  const PATTERN_KEYS = new Set([...COMMON_KEYS, 'language', 'rule'])
65
- const VISITORS = new Set(['Document', 'Line', 'Command'])
66
- const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown']
67
- const CODE_FENCE = /^\s*(`{3,}|~{3,})(.*)$/
65
+ const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown', 'rust']
66
+ const EXTENSIONS: Readonly<Record<string, string>> = {
67
+ ts: 'typescript', mts: 'typescript', cts: 'typescript', tsx: 'tsx', js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'javascript',
68
+ html: 'html', htm: 'html', css: 'css', php: 'php', phpt: 'php', py: 'python', pyi: 'python', sh: 'bash', bash: 'bash', zsh: 'bash', ksh: 'bash', bats: 'bash',
69
+ lua: 'lua', json: 'json', yaml: 'yaml', yml: 'yaml', toml: 'toml', md: 'markdown', mdx: 'markdown', markdown: 'markdown', rs: 'rust',
70
+ }
68
71
 
69
72
  let astGrep: Promise<typeof import('@ast-grep/napi')> | undefined
70
73
 
@@ -122,52 +125,107 @@ async function scriptRule(id: string, source: string): Promise<StaticRule> {
122
125
 
123
126
  async function visited(source: string, create: Rule['create'], file: CheckedFile): Promise<readonly Finding[]> {
124
127
  const found: Finding[] = []
125
- const lines = linesOf(file)
126
- const commands = commandsOf(file)
127
- const document: Document = { lineNumber: 1, text: file.text }
128
+ const language = languageOf(file.path)
129
+ const sourceCode = await sourceCodeOf(file, language)
128
130
  const context: Context = {
129
131
  root: file.root,
130
- path: file.path,
131
- text: file.text,
132
- lines,
133
- commands,
134
- ...(file.shell === undefined ? {} : { shell: { reads: file.shell.reads, writes: file.shell.writes, fetches: file.shell.fetches, isFullyParsed: file.shell.isFullyParsed } }),
132
+ filename: file.path.startsWith('@') ? file.path : resolve(file.root, file.path),
133
+ sourceCode,
134
+ ...(file.previous === undefined ? {} : { previous: await sourceCodeOf(file.previous, language) }),
135
135
  ...(file.call === undefined ? {} : { call: file.call }),
136
- report: ({ node }) => {
137
- found.push(node === document ? { line: 1, isWhole: true } : { line: node.lineNumber })
136
+ report: (problem) => {
137
+ found.push('loc' in problem ? { line: problem.loc.start.line } : findingOf(problem.node))
138
138
  },
139
139
  }
140
140
  const visitors: Visitors = await create(context)
141
- if (!isRecord(visitors)) throw new Error(`${source}: create returns an object of visitors, such as { Line(line) { … } }.`)
142
- for (const key of Object.keys(visitors)) if (!VISITORS.has(key)) throw new Error(`${source}: create returns the visitor "${key}". rulebook visits ${[...VISITORS].join(', ')}.`)
143
- await visitors.Document?.(document)
144
- if (visitors.Line !== undefined) for (const line of lines) await visitors.Line(line)
145
- if (visitors.Command !== undefined) for (const command of commands) await visitors.Command(command)
141
+ if (!isRecord(visitors)) throw new Error(`${source}: create returns an object of visitors, such as { call_expression(call) { … } }.`)
142
+ const kinds = Object.keys(visitors).filter((key) => key !== 'Command')
143
+ const unknown = await unknownKinds(kinds)
144
+ if (unknown.length > 0) throw new Error(`${source}: create returns the visitor "${unknown[0]}", which names no node. A visitor names Command or a node kind of ${LANGUAGES.join(', ')}.`)
145
+ const { ast } = sourceCode
146
+ if (isShell(ast)) {
147
+ if (visitors.Command !== undefined) for (const command of ast.commands) await visitors.Command(command)
148
+ } else if (language !== undefined) {
149
+ const own = await ownKinds(language, kinds)
150
+ if (own.length > 0) for (const node of (ast as SgNode).findAll({ rule: { any: own.map((kind) => ({ kind })) } })) await (visitors[node.kind()] as (node: SgNode) => void | Promise<void>)(node)
151
+ }
146
152
  return found
147
153
  }
148
154
 
149
- function linesOf({ path, lines }: CheckedFile): readonly Line[] {
150
- const isMarkdown = (path.startsWith('@') && path !== '@command') || /\.(md|mdx|markdown)$/i.test(path)
151
- let fence: { readonly marker: string; readonly length: number } | undefined
152
- return lines.map((text, index) => {
153
- const match = isMarkdown ? CODE_FENCE.exec(text) : null
154
- const isInCodeBlock = fence !== undefined || match !== null
155
- if (match !== null) {
156
- const marker = match[1] ?? ''
157
- if (fence === undefined) fence = { marker: marker[0] ?? '`', length: marker.length }
158
- else if (marker[0] === fence.marker && marker.length >= fence.length && (match[2] ?? '').trim() === '') fence = undefined
159
- }
160
- return { lineNumber: index + 1, text, isInCodeBlock }
161
- })
155
+ function findingOf(node: Node): Finding {
156
+ if ('lineNumber' in node) return { line: node.lineNumber }
157
+ if (!('kind' in node) || node.parent() === null) return { line: 1, isWhole: true }
158
+ return { line: node.range().start.line + 1 }
159
+ }
160
+
161
+ function isShell(node: Node): node is Shell {
162
+ return 'commands' in node
163
+ }
164
+
165
+ const sourceCodes = new WeakMap<Text, Promise<SourceCode>>()
166
+
167
+ function sourceCodeOf(file: Text, language: string | undefined): Promise<SourceCode> {
168
+ const known = sourceCodes.get(file)
169
+ if (known !== undefined) return known
170
+ const sourceCode = parsed(file, language)
171
+ sourceCodes.set(file, sourceCode)
172
+ return sourceCode
173
+ }
174
+
175
+ async function parsed({ text, lines, shell }: Text, language: string | undefined): Promise<SourceCode> {
176
+ if (shell !== undefined) return { text, lines, ast: { commands: commandsOf(shell, lines), reads: shell.reads, writes: shell.writes, fetches: shell.fetches, isFullyParsed: shell.isFullyParsed } }
177
+ if (language === undefined) return { text, lines, ast: { text } }
178
+ const { parse } = await (astGrep ??= loadAstGrep())
179
+ let root: SgNode | undefined
180
+ return {
181
+ text,
182
+ lines,
183
+ get ast() {
184
+ root ??= parse(language, text).root()
185
+ return root
186
+ },
187
+ }
162
188
  }
163
189
 
164
- function commandsOf({ shell, lines }: CheckedFile): readonly Command[] {
165
- return (shell?.commands ?? []).map(({ argv, folder, input, runner }) => {
190
+ function languageOf(path: string): string | undefined {
191
+ if (path === COMMAND) return undefined
192
+ if (path.startsWith('@')) return 'markdown'
193
+ return EXTENSIONS[extname(path).slice(1).toLowerCase()]
194
+ }
195
+
196
+ function commandsOf(shell: ParsedShell, lines: readonly string[]): readonly Command[] {
197
+ return shell.commands.map(({ argv, folder, input, runner }) => {
166
198
  const index = lines.findIndex((line) => line.includes(argv[0]))
167
199
  return { lineNumber: index === -1 ? 1 : index + 1, program: basename(argv[0]), args: argv.slice(1), argv, folder, ...(input === undefined ? {} : { input }), ...(runner === undefined ? {} : { runner }) }
168
200
  })
169
201
  }
170
202
 
203
+ const kindsOfLanguages = new Map<string, boolean>()
204
+
205
+ async function ownKinds(language: string, kinds: readonly string[]): Promise<readonly string[]> {
206
+ const { parse } = await (astGrep ??= loadAstGrep())
207
+ return kinds.filter((kind) => {
208
+ const key = `${language}\0${kind}`
209
+ let isOwn = kindsOfLanguages.get(key)
210
+ if (isOwn === undefined) {
211
+ try {
212
+ parse(language, '').root().findAll({ rule: { kind } })
213
+ isOwn = true
214
+ } catch {
215
+ isOwn = false
216
+ }
217
+ kindsOfLanguages.set(key, isOwn)
218
+ }
219
+ return isOwn
220
+ })
221
+ }
222
+
223
+ async function unknownKinds(kinds: readonly string[]): Promise<readonly string[]> {
224
+ if (kinds.length === 0) return []
225
+ const known = new Set((await Promise.all(LANGUAGES.map((language) => ownKinds(language, kinds)))).flat())
226
+ return kinds.filter((kind) => !known.has(kind))
227
+ }
228
+
171
229
  async function agenticRule(id: string, source: string, timeout: number): Promise<AgenticRule> {
172
230
  const fail = (problem: string): never => {
173
231
  throw new Error(`${source}: ${problem}`)
@@ -221,7 +279,7 @@ async function patternRule(id: string, source: string): Promise<StaticRule> {
221
279
  }
222
280
 
223
281
  async function loadAstGrep(): Promise<typeof import('@ast-grep/napi')> {
224
- const [napi, php, python, bash, lua, json, yaml, toml, markdown] = await Promise.all([
282
+ const [napi, php, python, bash, lua, json, yaml, toml, markdown, rust] = await Promise.all([
225
283
  import('@ast-grep/napi'),
226
284
  import('@ast-grep/lang-php'),
227
285
  import('@ast-grep/lang-python'),
@@ -231,8 +289,9 @@ async function loadAstGrep(): Promise<typeof import('@ast-grep/napi')> {
231
289
  import('@ast-grep/lang-yaml'),
232
290
  import('@ast-grep/lang-toml'),
233
291
  import('@ast-grep/lang-markdown'),
292
+ import('@ast-grep/lang-rust'),
234
293
  ])
235
- const packages = { php, python, bash, lua, json, yaml, toml, markdown }
294
+ const packages = { php, python, bash, lua, json, yaml, toml, markdown, rust }
236
295
  napi.registerDynamicLanguage(Object.fromEntries(await Promise.all(Object.entries(packages).map(async ([language, { default: registration }]) => {
237
296
  const { extensions, languageSymbol = `tree_sitter_${language}`, expandoChar = '$' } = registration
238
297
  return [language, { libraryPath: Bun.isStandaloneExecutable ? await embeddedParser(language) : registration.libraryPath, extensions, languageSymbol, expandoChar }] as const