@cmodjs/rulebook 0.0.0-stage → 0.2.2

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.
@@ -0,0 +1,160 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { basename, dirname, extname, join, resolve } from 'node:path'
4
+ import { Lexer } from 'marked'
5
+
6
+ export type Import = { readonly path: string; readonly line: number }
7
+
8
+ type ClaudeMd = {
9
+ readonly lines: readonly string[]
10
+ readonly imports: readonly Import[]
11
+ }
12
+
13
+ type Token = {
14
+ readonly type: string
15
+ readonly raw: string
16
+ readonly text?: string | undefined
17
+ readonly tokens?: readonly Token[] | undefined
18
+ readonly items?: readonly Token[] | undefined
19
+ }
20
+
21
+ const NAMES = new Set(['claude.md', 'claude.local.md', 'agents.md'])
22
+
23
+ const TEXT_EXTENSIONS = new Set([
24
+ '.md', '.txt', '.text', '.json', '.yaml', '.yml', '.toml', '.xml', '.csv', '.html', '.htm', '.css', '.scss', '.sass', '.less',
25
+ '.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.mts', '.cts', '.py', '.pyi', '.pyw', '.rb', '.erb', '.rake', '.go', '.rs',
26
+ '.java', '.kt', '.kts', '.scala', '.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hxx', '.cs', '.swift', '.sh', '.bash', '.zsh',
27
+ '.fish', '.ps1', '.bat', '.cmd', '.env', '.ini', '.cfg', '.conf', '.config', '.properties', '.sql', '.graphql', '.gql',
28
+ '.proto', '.vue', '.svelte', '.astro', '.ejs', '.hbs', '.pug', '.jade', '.php', '.pl', '.pm', '.lua', '.r', '.dart', '.ex',
29
+ '.exs', '.erl', '.hrl', '.clj', '.cljs', '.cljc', '.edn', '.hs', '.lhs', '.elm', '.ml', '.mli', '.f', '.f90', '.f95', '.for',
30
+ '.cmake', '.make', '.makefile', '.gradle', '.sbt', '.rst', '.adoc', '.asciidoc', '.org', '.tex', '.latex', '.lock', '.log',
31
+ '.diff', '.patch',
32
+ ])
33
+
34
+ const FRONTMATTER = /^---\s*\n([\s\S]*?)---\s*\n?/
35
+ const COMMENT = /<!--[\s\S]*?-->/g
36
+ const IMPORT = /(?:^|\s)@((?:[^\s\\]|\\ )+)/g
37
+ const RULES_FOLDER = /(?:^|\/)\.claude\/rules\//
38
+
39
+ export function isClaudeMd(file: string): boolean {
40
+ if (NAMES.has(basename(file).toLowerCase())) return true
41
+ return file.endsWith('.md') && isRulesFolder(dirname(file))
42
+ }
43
+
44
+ export function isRulesFolder(folder: string): boolean {
45
+ if (RULES_FOLDER.test(`${folder}/`)) return true
46
+ if (!existsSync(folder)) return false
47
+ const real = `${realpathSync(folder)}/`
48
+ return userMemoryPaths().some((path) => real.startsWith(`${path}/`))
49
+ }
50
+
51
+ export function claudeConfigFolder(): string {
52
+ return process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude')
53
+ }
54
+
55
+ export function claudeJsonFile(): string {
56
+ const file = join(process.env.CLAUDE_CONFIG_DIR || homedir(), '.claude.json')
57
+ const legacy = join(claudeConfigFolder(), '.config.json')
58
+ const stats = statSync(legacy, { throwIfNoEntry: false })
59
+ const isLegacy = stats?.isFile() === true && (stats.size > 0 || ((stats.mode & 0o222) !== 0 && !existsSync(file)))
60
+ return isLegacy ? legacy : file
61
+ }
62
+
63
+ let userPaths: readonly string[] | undefined
64
+
65
+ export function userMemoryPaths(): readonly string[] {
66
+ if (userPaths !== undefined) return userPaths
67
+ const rules = join(claudeConfigFolder(), 'rules')
68
+ const entries = existsSync(rules) ? [...new Bun.Glob('**').scanSync({ cwd: rules, absolute: true, dot: true, onlyFiles: false, followSymlinks: true })] : []
69
+ const folders = [rules, ...entries].filter((path) => statSync(path, { throwIfNoEntry: false })?.isDirectory() === true)
70
+ userPaths = [...new Set([join(claudeConfigFolder(), 'CLAUDE.md'), ...folders].filter((path) => existsSync(path)).map((path) => realpathSync(path)))]
71
+ return userPaths
72
+ }
73
+
74
+ export function importedFile(doc: string, path: string): string | undefined {
75
+ const extension = extname(path).toLowerCase()
76
+ if (extension !== '' && !TEXT_EXTENSIONS.has(extension)) return undefined
77
+ if (path.startsWith('~/')) return join(homedir(), path.slice(2))
78
+ return resolve(dirname(existsSync(doc) ? realpathSync(doc) : doc), path)
79
+ }
80
+
81
+ export function readClaudeMd(text: string): ClaudeMd {
82
+ const source = text.replace(/\r\n|\r/g, '\n')
83
+ const body = withoutFrontmatter(source)
84
+ const start = source.length - body.length
85
+ const strips = body.includes('<!--')
86
+ const hidden: [number, number][] = [[0, start]]
87
+ const found = new Map<string, number>()
88
+ const tokens: readonly Token[] = strips || body.includes('@') ? [...new Lexer().lex(body)] : []
89
+ let cursor = 0
90
+ for (const token of tokens) {
91
+ const at = body.indexOf(token.raw, cursor)
92
+ if (at === -1) throw new Error(`marked read a ${token.type} the text does not hold: ${JSON.stringify(token.raw.slice(0, 60))}`)
93
+ if (strips) hidden.push([start + cursor, start + at], ...commentsOf(token).map(([from, to]): [number, number] => [start + at + from, start + at + to]))
94
+ walk([token], (scanned) => {
95
+ for (const match of scanned.matchAll(IMPORT)) {
96
+ const path = importPath(match[1] ?? '')
97
+ if (path === undefined || found.has(path)) continue
98
+ const offset = token.raw.indexOf(`@${match[1]}`)
99
+ found.set(path, lineOf(source, start + at + Math.max(offset, 0)))
100
+ }
101
+ })
102
+ cursor = at + token.raw.length
103
+ }
104
+ if (strips) hidden.push([start + cursor, source.length])
105
+
106
+ let masked = ''
107
+ let kept = 0
108
+ for (const [from, to] of hidden) {
109
+ masked += source.slice(kept, from) + source.slice(from, to).replace(/[^\n]/g, '')
110
+ kept = to
111
+ }
112
+ return {
113
+ lines: (masked + source.slice(kept)).split('\n'),
114
+ imports: [...found].map(([path, line]) => ({ path, line })),
115
+ }
116
+ }
117
+
118
+ function withoutFrontmatter(text: string): string {
119
+ const plain = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
120
+ if (plain.indexOf('---', 3) < 0) return text
121
+ const match = FRONTMATTER.exec(plain)
122
+ return match === null ? text : plain.slice(match[0].length)
123
+ }
124
+
125
+ function isComment(token: Token): boolean {
126
+ const start = token.raw.trimStart()
127
+ return token.type === 'html' && start.startsWith('<!--') && start.includes('-->')
128
+ }
129
+
130
+ function commentsOf(token: Token): readonly (readonly [number, number])[] {
131
+ if (!isComment(token)) return []
132
+ if (token.raw.replace(COMMENT, '').trim().length === 0) return [[0, token.raw.length]]
133
+ return [...token.raw.matchAll(COMMENT)].map((comment) => [comment.index, comment.index + comment[0].length])
134
+ }
135
+
136
+ function walk(tokens: readonly Token[], scan: (text: string) => void): void {
137
+ for (const token of tokens) {
138
+ if (token.type === 'code' || token.type === 'codespan') continue
139
+ if (token.type === 'html') {
140
+ const rest = token.raw.replace(COMMENT, '')
141
+ if (isComment(token) && rest.trim().length > 0) scan(rest)
142
+ continue
143
+ }
144
+ if (token.type === 'text') scan(token.text || '')
145
+ if (token.tokens) walk(token.tokens, scan)
146
+ if (token.items) walk(token.items, scan)
147
+ }
148
+ }
149
+
150
+ function importPath(written: string): string | undefined {
151
+ const hash = written.indexOf('#')
152
+ const path = (hash === -1 ? written : written.substring(0, hash)).replaceAll('\\ ', ' ')
153
+ if (path === '') return undefined
154
+ const isPath = path.startsWith('./') || path.startsWith('~/') || (path.startsWith('/') && path !== '/') || (!path.startsWith('@') && !/^[#%^&*()]+/.test(path) && /^[a-zA-Z0-9._-]/.test(path))
155
+ return isPath ? path : undefined
156
+ }
157
+
158
+ function lineOf(text: string, offset: number): number {
159
+ return text.slice(0, offset).split('\n').length
160
+ }
package/src/config.ts ADDED
@@ -0,0 +1,243 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path'
4
+ import type { Config, Level, LinterName, RuleSettings, Runs } from './api.ts'
5
+ import { LINTERS } from './linters.ts'
6
+ import { importDefault } from './modules.ts'
7
+
8
+ export const CONFIG_FILE = 'rulebook.config.ts'
9
+
10
+ type LoadedConfig = {
11
+ readonly file: string
12
+ readonly dir: string
13
+ readonly basePath: string
14
+ readonly plugins: Readonly<Record<string, string>>
15
+ readonly probes: readonly string[]
16
+ readonly messages: Readonly<Record<string, MessageSource>>
17
+ }
18
+
19
+ type MessageSource = { readonly tools: readonly string[]; readonly folder: string | undefined }
20
+
21
+ type Place = Pick<LoadedConfig, 'file' | 'dir' | 'basePath'>
22
+
23
+ type Layer = { readonly loaded: LoadedConfig; readonly config: Config }
24
+
25
+ export type Settings = {
26
+ readonly root: string
27
+ readonly configs: readonly LoadedConfig[]
28
+ readonly paths: readonly string[]
29
+ readonly timeout: number
30
+ readonly existingErrors: Level
31
+ readonly rules: Readonly<Record<string, RuleSettings>>
32
+ readonly linters: readonly LinterName[]
33
+ readonly messages: Readonly<Record<string, MessageSource>>
34
+ }
35
+
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'])
38
+ const MESSAGE_KEYS = new Set(['tools', 'folder'])
39
+ const BUILT_IN: Pick<LoadedConfig, 'file' | 'plugins' | 'messages'> = { file: 'rulebook', plugins: {}, messages: { reply: { tools: [], folder: undefined } } }
40
+
41
+ export function globalConfigFile(): string {
42
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'rulebook', CONFIG_FILE)
43
+ }
44
+
45
+ export function projectRoot(folder: string, outsideGit: string): string {
46
+ const real = realpathSync(folder)
47
+ if (real.split(sep).includes('.git')) return realpathSync(outsideGit)
48
+ for (let dir = real; ; dir = dirname(dir)) {
49
+ if (isWorkTree(join(dir, '.git'))) return dir
50
+ if (dirname(dir) === dir) return realpathSync(outsideGit)
51
+ }
52
+ }
53
+
54
+ function isWorkTree(git: string): boolean {
55
+ const stats = statSync(git, { throwIfNoEntry: false })
56
+ if (stats?.isDirectory() === true) return existsSync(join(git, 'HEAD'))
57
+ return stats?.isFile() === true && readFileSync(git, 'utf8').startsWith('gitdir: ')
58
+ }
59
+
60
+ const nearest = new Map<string, string | undefined>()
61
+ const loadedSettings = new Map<string, Promise<Settings>>()
62
+ const readPaths = new Set<string>()
63
+
64
+ export function settingsSources(): readonly string[] {
65
+ return [globalConfigFile(), ...[...nearest.keys()].map((folder) => join(folder, CONFIG_FILE)), ...readPaths]
66
+ }
67
+
68
+ export function loadSettings(folder: string, root: string): Promise<Settings> {
69
+ const file = nearestConfig(folder)
70
+ const key = `${root}\0${file ?? ''}`
71
+ const known = loadedSettings.get(key)
72
+ if (known !== undefined) return known
73
+ const settings = settingsOf(root, file)
74
+ loadedSettings.set(key, settings)
75
+ return settings
76
+ }
77
+
78
+ function nearestConfig(folder: string): string | undefined {
79
+ if (nearest.has(folder)) return nearest.get(folder)
80
+ const file = join(folder, CONFIG_FILE)
81
+ const above = dirname(folder)
82
+ const found = existsSync(file) ? realpathSync(file) : above === folder ? undefined : nearestConfig(above)
83
+ nearest.set(folder, found)
84
+ return found
85
+ }
86
+
87
+ async function settingsOf(root: string, file: string | undefined): Promise<Settings> {
88
+ const global = globalConfigFile()
89
+ const found = [...(existsSync(global) ? await fileLayers(realpathSync(global), root, true, []) : []), ...(file === undefined ? [] : await fileLayers(file, root, false, []))]
90
+ const seen = new Set<Config>()
91
+ const configs = found.filter(({ config }) => !seen.has(config) && seen.add(config))
92
+
93
+ const sources = [BUILT_IN, ...configs.map(({ loaded }) => loaded)]
94
+ for (const [key, noun] of [['plugins', 'plugin'], ['messages', 'message']] as const) {
95
+ const owners = new Map<string, string>()
96
+ for (const source of sources) {
97
+ for (const name of Object.keys(source[key])) {
98
+ if (owners.has(name)) throw new Error(`${source.file}: the ${noun} "${name}" is already named by ${owners.get(name)}. Give each ${noun} its own name.`)
99
+ owners.set(name, source.file)
100
+ }
101
+ }
102
+ }
103
+
104
+ const latest = configs.map(({ config }) => config).toReversed()
105
+
106
+ return {
107
+ root,
108
+ configs: configs.map(({ loaded }) => loaded),
109
+ paths: [...new Set(configs.flatMap(({ loaded, config }) => rootRelative(loaded.basePath, config.paths ?? [])))],
110
+ timeout: latest.find(({ timeout }) => timeout !== undefined)?.timeout ?? 30_000,
111
+ existingErrors: latest.find(({ existingErrors }) => existingErrors !== undefined)?.existingErrors ?? 'warning',
112
+ rules: overrides(configs.map(({ loaded, config }) => rootRelativeRules(loaded.basePath, config.rules ?? {}))),
113
+ linters: [...new Set(configs.flatMap(({ config }) => config.linters ?? []))],
114
+ messages: Object.assign({}, ...sources.map(({ messages }) => messages)),
115
+ }
116
+ }
117
+
118
+ function overrides(layers: readonly Readonly<Record<string, RuleSettings>>[]): Record<string, RuleSettings> {
119
+ const merged: Record<string, RuleSettings> = {}
120
+ for (const layer of layers) for (const [id, settings] of Object.entries(layer)) merged[id] = { ...merged[id], ...settings }
121
+ return merged
122
+ }
123
+
124
+ export function rootRelative(basePath: string, globs: readonly string[]): readonly string[] {
125
+ return basePath === '' ? globs : globs.map((glob) => (glob.startsWith('@') ? glob : posix.join(basePath, glob)))
126
+ }
127
+
128
+ function rootRelativeRules(basePath: string, rules: NonNullable<Config['rules']>): Readonly<Record<string, RuleSettings>> {
129
+ return Object.fromEntries(Object.entries(rules).map(([id, override]) => {
130
+ const settings = typeof override === 'string' ? { level: override } : override
131
+ return [id, settings.paths === undefined ? settings : { ...settings, paths: rootRelative(basePath, settings.paths) }]
132
+ }))
133
+ }
134
+
135
+ async function fileLayers(file: string, root: string, isGlobal: boolean, chain: readonly string[]): Promise<readonly Layer[]> {
136
+ if (chain.includes(file)) throw new Error(`${chain.at(-1)}: extends ${file}, which extends it back through ${[...chain.slice(chain.indexOf(file)), file].join(' -> ')}. Remove one of these extends.`)
137
+ const dir = dirname(file)
138
+ const basePath = isGlobal || !isInside(root, dir) ? '' : relative(root, dir)
139
+ return configLayers(validConfig(file, await importDefault(file)), { file, dir, basePath }, root, [...chain, file])
140
+ }
141
+
142
+ async function configLayers(config: Config, place: Place, root: string, chain: readonly string[]): Promise<readonly Layer[]> {
143
+ const layers: Layer[] = []
144
+ for (const entry of config.extends ?? []) layers.push(...(typeof entry === 'string' ? await fileLayers(extendedFile(place, entry), root, false, chain) : await configLayers(validConfig(place.file, entry), place, root, chain)))
145
+ return [...layers, { loaded: loadedConfig(config, place), config }]
146
+ }
147
+
148
+ function extendedFile({ file, dir }: Place, path: string): string {
149
+ const target = path === '~' || path.startsWith('~/') ? join(homedir(), path.slice(1)) : resolve(dir, path)
150
+ readPaths.add(target)
151
+ if (statSync(target, { throwIfNoEntry: false })?.isFile() !== true) throw new Error(`${file}: extends "${path}", but ${target} is not a file.`)
152
+ return realpathSync(target)
153
+ }
154
+
155
+ function loadedConfig(config: Config, { file, dir, basePath }: Place): LoadedConfig {
156
+ const plugins = Object.fromEntries(Object.entries(config.plugins ?? {}).map(([name, folder]) => [name, realFolder(file, resolve(dir, folder))]))
157
+ const messages = Object.fromEntries(Object.entries(config.messages ?? {}).map(([name, { tools = [], folder }]) => {
158
+ const path = folder === undefined ? undefined : resolve(dir, folder)
159
+ return [name, { tools, folder: path !== undefined && existsSync(path) ? realpathSync(path) : path }]
160
+ }))
161
+ return { file, dir, basePath, plugins, probes: config.probes ?? [], messages }
162
+ }
163
+
164
+ function realFolder(file: string, folder: string): string {
165
+ readPaths.add(folder)
166
+ if (!existsSync(folder)) throw new Error(`${file}: the plugin folder ${folder} does not exist.`)
167
+ return realpathSync(folder)
168
+ }
169
+
170
+ function validConfig(file: string, value: unknown): Config {
171
+ const fail = (problem: string): never => {
172
+ throw new Error(`${file}: ${problem}`)
173
+ }
174
+ if (!isRecord(value)) return fail('the default export is not a config object. Export defineConfig({ … }).')
175
+ for (const key of Object.keys(value)) if (!KEYS.has(key)) fail(`"${key}" is not a rulebook config key. The keys are ${[...KEYS].join(', ')}.`)
176
+ 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].')
177
+ 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.')
178
+ 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 "-".`)
179
+ for (const key of ['paths', 'probes'] as const) if (value[key] !== undefined && !isStrings(value[key])) fail(`${key} is a list of globs.`)
180
+ if (value.timeout !== undefined && !isTimeout(value.timeout)) fail('timeout is a whole number of milliseconds above 0.')
181
+ if (value.existingErrors !== undefined && !isLevel(value.existingErrors)) fail('existingErrors is "error" or "warning".')
182
+ if (value.rules !== undefined && !isRecord(value.rules)) fail('rules maps each rule name, such as "global/block-em-dashes", to a level or to settings.')
183
+ for (const [id, override] of Object.entries(isRecord(value.rules) ? value.rules : {})) validOverride(file, id, override)
184
+ 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
+ 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(', ')}.`)
186
+ 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
+ for (const [name, message] of Object.entries(isRecord(value.messages) ? value.messages : {})) validMessage(file, name, message)
188
+ return value as Config
189
+ }
190
+
191
+ function validMessage(file: string, name: string, message: unknown): void {
192
+ const fail = (problem: string): never => {
193
+ throw new Error(`${file}: messages["${name}"] ${problem}`)
194
+ }
195
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) fail('is not a message name: use lowercase letters, digits, and "-".')
196
+ if (!isRecord(message)) return fail('is an object of tools and a folder.')
197
+ for (const key of Object.keys(message)) if (!MESSAGE_KEYS.has(key)) fail(`sets "${key}". A message sets ${[...MESSAGE_KEYS].join(' and ')}.`)
198
+ if (message.tools !== undefined && !isStrings(message.tools)) fail('tools is a list of tool name globs, such as "mcp__inbox__*".')
199
+ if (message.folder !== undefined && typeof message.folder !== 'string') fail('folder is the path of a folder.')
200
+ }
201
+
202
+ function validOverride(file: string, id: string, override: unknown): void {
203
+ const fail = (problem: string): never => {
204
+ throw new Error(`${file}: rules["${id}"] ${problem}`)
205
+ }
206
+ if (override === 'off' || isLevel(override)) return
207
+ if (!isRecord(override)) return fail('is "error", "warning", "off", or an object of rule settings.')
208
+ 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
+ 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".')
211
+ if (override.paths !== undefined && !isStrings(override.paths)) fail('paths is a list of globs.')
212
+ if (override.timeout !== undefined && !isTimeout(override.timeout)) fail('timeout is a whole number of milliseconds above 0.')
213
+ for (const key of ['agent', 'model', 'effort'] as const) if (override[key] !== undefined && typeof override[key] !== 'string') fail(`${key} is a string.`)
214
+ }
215
+
216
+ export function isInside(folder: string, file: string): boolean {
217
+ const path = relative(folder, file)
218
+ return !path.startsWith('..') && !isAbsolute(path)
219
+ }
220
+
221
+ export function existingFolder(folder: string): string {
222
+ return existsSync(folder) ? folder : existingFolder(dirname(folder))
223
+ }
224
+
225
+ export function isRecord(value: unknown): value is Record<string, unknown> {
226
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
227
+ }
228
+
229
+ export function isStrings(value: unknown): value is string[] {
230
+ return Array.isArray(value) && value.every((item) => typeof item === 'string')
231
+ }
232
+
233
+ export function isLevel(value: unknown): value is Level {
234
+ return value === 'error' || value === 'warning'
235
+ }
236
+
237
+ export function isRuns(value: unknown): value is Runs {
238
+ return value === 'always' || value === 'manual'
239
+ }
240
+
241
+ export function isTimeout(value: unknown): value is number {
242
+ return Number.isInteger(value) && (value as number) > 0
243
+ }
package/src/edit.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { existsSync, realpathSync } from 'node:fs'
2
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
3
+ import { checkFile } from './check.ts'
4
+ import { isClaudeMd } from './claude-md.ts'
5
+ import { existingFolder, isRecord, loadSettings, projectRoot } from './config.ts'
6
+ import { loadImportedFiles, watchImportSource } from './files.ts'
7
+ import { editAnswer, type EditAnswer } from './report.ts'
8
+ import { loadRules } from './rules.ts'
9
+
10
+ type Replacement = { readonly old_string: string; readonly new_string: string; readonly replace_all?: boolean }
11
+
12
+ export type ToolCall = {
13
+ readonly tool_name: string
14
+ readonly tool_input: Readonly<Record<string, unknown>>
15
+ readonly cwd: string
16
+ }
17
+
18
+ export function editRoot(call: ToolCall): string {
19
+ const edited = editedFile(call)
20
+ if (edited === undefined) return projectRoot(call.cwd, call.cwd)
21
+ return projectRoot(edited.folder, edited.file.startsWith(`${realpathSync(call.cwd)}/`) ? call.cwd : edited.folder)
22
+ }
23
+
24
+ export async function checkEdit(call: ToolCall, root: string): Promise<EditAnswer> {
25
+ const edited = editedFile(call)
26
+ if (edited === undefined) return editAnswer(undefined)
27
+ const { file } = edited
28
+ const previous = existsSync(file) ? await Bun.file(file).text() : undefined
29
+ const next = editedText(call.tool_name, call.tool_input, previous)
30
+ if (next === undefined) return editAnswer(undefined)
31
+ if (isClaudeMd(file)) watchImportSource(file)
32
+ const settings = await loadSettings(dirname(file), root)
33
+ const { rules } = await loadRules(settings)
34
+ const report = await checkFile(settings, rules, file, next, { scope: 'edit', previous: previous ?? '', imported: () => loadImportedFiles(root) })
35
+ return editAnswer(report)
36
+ }
37
+
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
+ function editedText(tool: string, input: Readonly<Record<string, unknown>>, previous: string | undefined): string | undefined {
48
+ if (tool === 'Write') return typeof input.content === 'string' ? input.content : undefined
49
+ if (previous === undefined) return undefined
50
+ if (tool === 'Edit') return replaced(previous, [input])
51
+ if (tool === 'MultiEdit') return Array.isArray(input.edits) ? replaced(previous, input.edits) : undefined
52
+ return undefined
53
+ }
54
+
55
+ function replaced(text: string, edits: readonly unknown[]): string | undefined {
56
+ let result = text
57
+ for (const edit of edits) {
58
+ if (!isReplacement(edit) || !result.includes(edit.old_string)) return undefined
59
+ result = edit.replace_all === true ? result.replaceAll(edit.old_string, edit.new_string) : result.replace(edit.old_string, () => edit.new_string)
60
+ }
61
+ return result
62
+ }
63
+
64
+ function isReplacement(value: unknown): value is Replacement {
65
+ return isRecord(value) && typeof value.old_string === 'string' && typeof value.new_string === 'string'
66
+ }
package/src/files.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { isPrompt } from './check.ts'
4
+ import { claudeJsonFile, importedFile, isClaudeMd, isRulesFolder, readClaudeMd, userMemoryPaths } from './claude-md.ts'
5
+ import { isInside, isRecord, loadSettings, type Settings } from './config.ts'
6
+
7
+ const IMPORT_HOPS = 4
8
+
9
+ const loadedImports = new Map<string, Promise<ReadonlySet<string>>>()
10
+ const importPaths = new Set<string>()
11
+
12
+ export function importSources(): readonly string[] {
13
+ return [...importPaths]
14
+ }
15
+
16
+ export function watchImportSource(file: string): void {
17
+ importPaths.add(file)
18
+ }
19
+
20
+ export function loadImportedFiles(root: string): Promise<ReadonlySet<string>> {
21
+ const known = loadedImports.get(root)
22
+ if (known !== undefined) return known
23
+ const imported = loadSettings(root, root).then(async (settings) => {
24
+ const candidates = projectFiles(settings, await listedFiles(root)).filter((file) => isClaudeMd(file) || isRulesLink(file))
25
+ return importedFiles(root, await filesBySettings(root, candidates))
26
+ })
27
+ loadedImports.set(root, imported)
28
+ return imported
29
+ }
30
+
31
+ export async function filesBySettings(root: string, files: readonly string[]): Promise<ReadonlyMap<Settings, readonly string[]>> {
32
+ const groups = new Map<Settings, string[]>()
33
+ for (const file of files) {
34
+ const settings = await loadSettings(dirname(file), root)
35
+ const group = groups.get(settings) ?? []
36
+ group.push(file)
37
+ groups.set(settings, group)
38
+ }
39
+ return groups
40
+ }
41
+
42
+ export function importedFiles(root: string, groups: ReadonlyMap<Settings, readonly string[]>): ReadonlySet<string> {
43
+ const userPaths = userMemoryPaths()
44
+ const isUserMemory = (file: string): boolean => userPaths.some((path) => isInside(path, file))
45
+ let isApproved: boolean | undefined
46
+ const reaches = (isUser: boolean, target: string, real: string): boolean => isUser || (isInside(root, target) && isInside(root, real)) || (isApproved ??= externalImportsApproved(root))
47
+ const claudeMds = [...groups].flatMap(([settings, files]) => files.filter((file) => isPrompt(settings, file) && isClaudeMd(file) && existsSync(file)))
48
+ const links = [...groups].flatMap(([settings, files]) => files.filter(isRulesLink).map((link) => ({ settings, link })))
49
+ for (const { link } of links) importPaths.add(link)
50
+ const linked = new Set(links
51
+ .flatMap(({ settings, link }) => [...new Bun.Glob('**/*.md').scanSync({ cwd: link, absolute: true, dot: true, followSymlinks: true })].filter((file) => isPrompt(settings, file)))
52
+ .map((file) => ({ file, real: realpathSync(file) }))
53
+ .filter(({ file, real }) => reaches(isUserMemory(real), file, real))
54
+ .map(({ real }) => real))
55
+ const roots = new Set([...claudeMds, ...linked])
56
+ const queue = [...roots].map((file) => ({ file, hops: 0, isUser: isUserMemory(file) }))
57
+ const seen = new Set(queue.map(({ file }) => realpathSync(file)))
58
+ for (const { file, hops, isUser } of queue) {
59
+ importPaths.add(file)
60
+ if (hops === IMPORT_HOPS) continue
61
+ for (const { path } of readClaudeMd(readFileSync(file, 'utf8')).imports) {
62
+ const target = importedFile(file, path)
63
+ if (target === undefined) continue
64
+ importPaths.add(target)
65
+ if (statSync(target, { throwIfNoEntry: false })?.isFile() !== true) continue
66
+ const real = realpathSync(target)
67
+ if (seen.has(real) || !reaches(isUser, target, real)) continue
68
+ seen.add(real)
69
+ queue.push({ file: real, hops: hops + 1, isUser })
70
+ }
71
+ }
72
+ return new Set([...linked, ...queue.filter(({ hops }) => hops > 0).map(({ file }) => file)])
73
+ }
74
+
75
+ function isRulesLink(entry: string): boolean {
76
+ return statSync(entry, { throwIfNoEntry: false })?.isDirectory() === true && isRulesFolder(entry)
77
+ }
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()
82
+ }
83
+
84
+ export async function listedFiles(folder: string): Promise<readonly string[] | undefined> {
85
+ const git = Bun.spawn(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z', '--full-name', '--', ':/'], { cwd: folder, stdout: 'pipe', stderr: 'ignore' })
86
+ const [listed, exitCode] = await Promise.all([new Response(git.stdout).text(), git.exited])
87
+ return exitCode === 0 ? listed.split('\0').filter((path) => path !== '') : undefined
88
+ }
89
+
90
+ export function projectFiles(settings: Settings, listed: readonly string[] | undefined): readonly string[] {
91
+ const candidates = listed === undefined
92
+ ? settings.paths.flatMap((glob) => [...new Bun.Glob(glob).scanSync({ cwd: settings.root, absolute: true, dot: true })])
93
+ : listed.map((path) => join(settings.root, path))
94
+ return [...new Set(candidates)].sort()
95
+ }
96
+
97
+ function externalImportsApproved(root: string): boolean {
98
+ const file = claudeJsonFile()
99
+ if (!existsSync(file)) return false
100
+ const config: unknown = JSON.parse(readFileSync(file, 'utf8'))
101
+ const project = isRecord(config) && isRecord(config.projects) ? config.projects[root] : undefined
102
+ return isRecord(project) && project.hasClaudeMdExternalIncludesApproved === true
103
+ }