@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,98 @@
1
+ import { basename, dirname, join } from 'node:path'
2
+ import { checkFile, globRegExp } from './check.ts'
3
+ import { CONFIG_FILE, globalConfigFile, isRecord, loadSettings, projectRoot } from './config.ts'
4
+ import { checkEdit, editRoot, type ToolCall } from './edit.ts'
5
+ import { listedFiles } from './files.ts'
6
+ import { editAnswer } from './report.ts'
7
+ import { loadRules } from './rules.ts'
8
+
9
+ export type Question = 'edit' | 'text' | 'rules'
10
+
11
+ type Text = { readonly name: string; readonly text: string; readonly cwd: string }
12
+
13
+ type Answerer = {
14
+ root(input: unknown): string
15
+ answer(input: unknown, root: string): Promise<unknown>
16
+ }
17
+
18
+ const QUESTIONS: Readonly<Record<Question, Answerer>> = {
19
+ edit: {
20
+ root: (input) => editRoot(toolCall(input)),
21
+ answer: (input, root) => checkEdit(toolCall(input), root),
22
+ },
23
+ text: {
24
+ root: (input) => {
25
+ const { cwd } = textOf(input)
26
+ return projectRoot(cwd, cwd)
27
+ },
28
+ answer: (input, root) => checkText(textOf(input), root),
29
+ },
30
+ rules: {
31
+ root: (input) => {
32
+ const cwd = cwdOf(input)
33
+ return projectRoot(cwd, cwd)
34
+ },
35
+ answer: (input, root) => listRules(cwdOf(input), root),
36
+ },
37
+ }
38
+
39
+ export function isQuestion(name: string): name is Question {
40
+ return Object.hasOwn(QUESTIONS, name)
41
+ }
42
+
43
+ export function projectOf(question: Question, input: unknown): string {
44
+ return QUESTIONS[question].root(input)
45
+ }
46
+
47
+ export function answer(question: Question, input: unknown, root: string): Promise<unknown> {
48
+ return QUESTIONS[question].answer(input, root)
49
+ }
50
+
51
+ async function checkText({ name, text, cwd }: Text, root: string): Promise<unknown> {
52
+ const settings = await loadSettings(cwd, root)
53
+ if (!name.startsWith('@')) throw new Error('rulebook text checks a message by its @-name, such as @reply or @inbox/<id>.md.')
54
+ const { rules } = await loadRules(settings)
55
+ const report = await checkFile(settings, rules, name, text, { scope: 'edit', imported: async () => new Set() })
56
+ return editAnswer(report)
57
+ }
58
+
59
+ async function listRules(cwd: string, root: string): Promise<unknown> {
60
+ const settings = await loadSettings(cwd, root)
61
+ await loadRules(await loadSettings(root, root))
62
+ const configured = ((await listedFiles(cwd)) ?? []).filter((path) => basename(path) === CONFIG_FILE && path !== CONFIG_FILE).map(dirname)
63
+ const folders = await Promise.all(['', ...configured].map(async (path) => {
64
+ const own = await loadSettings(join(root, path), root)
65
+ return { path, settings: own, ...(await loadRules(own)) }
66
+ }))
67
+ const regExpsOf = (globs: readonly string[]) => globs.map(globRegExp).map(({ source, flags }) => ({ source, flags }))
68
+ return {
69
+ root,
70
+ sources: [...new Set([globalConfigFile(), join(root, CONFIG_FILE), ...folders.flatMap((folder) => folder.settings.configs.flatMap((config) => [config.file, ...Object.values(config.plugins)]))])],
71
+ folders: folders.map((folder) => ({
72
+ path: folder.path,
73
+ rules: folder.rules.filter(({ level }) => level !== 'off').map(({ id, description, paths = folder.settings.paths }) => ({
74
+ id,
75
+ description,
76
+ isEverywhere: paths.some((glob) => glob === (folder.path === '' ? '**' : `${folder.path}/**`) || glob.startsWith('@')),
77
+ paths: regExpsOf(paths),
78
+ })),
79
+ })),
80
+ messages: Object.entries(settings.messages).map(([name, { tools }]) => ({ name: `@${name}`, tools: regExpsOf(tools) })),
81
+ failures: [...new Set(folders.flatMap((folder) => folder.failures))],
82
+ }
83
+ }
84
+
85
+ function toolCall(input: unknown): ToolCall {
86
+ if (!isRecord(input) || typeof input.tool_name !== 'string' || !isRecord(input.tool_input) || typeof input.cwd !== 'string') throw new Error('rulebook edit reads {"tool_name", "tool_input", "cwd"}.')
87
+ return { tool_name: input.tool_name, tool_input: input.tool_input, cwd: input.cwd }
88
+ }
89
+
90
+ function textOf(input: unknown): Text {
91
+ if (!isRecord(input) || typeof input.name !== 'string' || typeof input.text !== 'string' || typeof input.cwd !== 'string') throw new Error('rulebook text reads {"name", "text", "cwd"}.')
92
+ return { name: input.name, text: input.text, cwd: input.cwd }
93
+ }
94
+
95
+ function cwdOf(input: unknown): string {
96
+ if (!isRecord(input) || typeof input.cwd !== 'string') throw new Error('rulebook rules reads {"cwd"}.')
97
+ return input.cwd
98
+ }
package/src/report.ts ADDED
@@ -0,0 +1,71 @@
1
+ import type { FileReport, Reported } from './check.ts'
2
+
3
+ export type EditAnswer = {
4
+ readonly refuse?: string
5
+ readonly note?: string
6
+ readonly failures: readonly string[]
7
+ readonly findings: readonly Reported[]
8
+ }
9
+
10
+ function findingLines(findings: readonly Reported[]): string {
11
+ const lineWidth = Math.max(...findings.map(({ line }) => String(line).length))
12
+ const levelWidth = Math.max(...findings.map(({ level }) => level.length))
13
+ const ruleWidth = Math.max(...findings.map(({ rule }) => rule.length))
14
+ return findings
15
+ .map(({ line, level, rule, message, quote }) => ` ${String(line).padStart(lineWidth)} ${level.padEnd(levelWidth)} ${rule.padEnd(ruleWidth)} ${message}\n ${' '.repeat(lineWidth)} > ${quote.trim()}`.trimEnd())
16
+ .join('\n')
17
+ }
18
+
19
+ function failureLines(report: FileReport): readonly string[] {
20
+ return report.failures.map(({ rule, reason }) => `${rule} did not run on ${report.path}: ${reason}`)
21
+ }
22
+
23
+ export function editAnswer(report: FileReport | undefined): EditAnswer {
24
+ if (report === undefined) return { failures: [], findings: [] }
25
+ const { findings } = report
26
+ const written = findings.filter(({ isExisting }) => !isExisting)
27
+ const errors = written.filter(({ level }) => level === 'error')
28
+ const warnings = written.filter(({ level }) => level === 'warning')
29
+ const failures = failureLines(report)
30
+ const isRefused = findings.some(({ level }) => level === 'error')
31
+ const blocks = [
32
+ ...(errors.length === 0 ? [] : [findingLines(errors)]),
33
+ ...(warnings.length === 0 ? [] : [isRefused ? `Warnings:\n${findingLines(warnings)}` : findingLines(warnings)]),
34
+ ...existingLine(report, written.length > 0),
35
+ ...(failures.length === 0 ? [] : [failures.join('\n')]),
36
+ ]
37
+ if (isRefused) return { refuse: [refusal(report.path), ...blocks].join('\n\n'), failures, findings }
38
+ if (findings.length > 0) return { note: [`${subject(report.path)} allowed with warnings:`, ...blocks].join('\n\n'), failures, findings }
39
+ if (failures.length > 0) return { note: [`${subject(report.path)} allowed, but not every rule checked it:`, ...blocks].join('\n\n'), failures, findings }
40
+ return { failures, findings }
41
+ }
42
+
43
+ function existingLine(report: FileReport, isMore: boolean): readonly string[] {
44
+ const existing = report.findings.filter(({ isExisting }) => isExisting)
45
+ if (existing.length === 0) return []
46
+ const errors = existing.filter(({ level }) => level === 'error').length
47
+ const noun = errors === existing.length ? 'error' : errors === 0 ? 'warning' : 'finding'
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'}.`]
50
+ }
51
+
52
+ function refusal(path: string): string {
53
+ const again = path === '@reply' ? 'write the whole reply again' : path.startsWith('@') ? 'send it again' : 'edit again'
54
+ return `${subject(path)} refused. Fix every error, then ${again}.`
55
+ }
56
+
57
+ function subject(path: string): string {
58
+ if (!path.startsWith('@')) return `Edit to ${path}`
59
+ const [name = ''] = path.slice(1).split('/')
60
+ return `${name.charAt(0).toUpperCase()}${name.slice(1)}`
61
+ }
62
+
63
+ export function textReport(reports: readonly FileReport[], unloaded: readonly string[]): string {
64
+ const flagged = reports.filter(({ findings }) => findings.length > 0)
65
+ const all = reports.flatMap(({ findings }) => findings)
66
+ const errors = all.filter(({ level }) => level === 'error').length
67
+ const failures = [...unloaded, ...reports.flatMap(failureLines)]
68
+ const blocks = flagged.map((report) => `${report.path}\n${findingLines(report.findings)}`)
69
+ const counts = `${errors} ${errors === 1 ? 'error' : 'errors'}, ${all.length - errors} ${all.length - errors === 1 ? 'warning' : 'warnings'} in ${reports.length} ${reports.length === 1 ? 'file' : 'files'}`
70
+ return [...blocks, ...(failures.length === 0 ? [] : [failures.join('\n')]), counts].join('\n\n')
71
+ }
package/src/rules.ts ADDED
@@ -0,0 +1,225 @@
1
+ import { existsSync, mkdirSync, renameSync } from 'node:fs'
2
+ import { basename, join } from 'node:path'
3
+ import type { NapiConfig } from '@ast-grep/napi'
4
+ import type { Finding, Level, PromptFile, Rule, RuleSettings, Runs } from './api.ts'
5
+ import { importsRule, noSuppressionsRule } from './check.ts'
6
+ import type { Import } from './claude-md.ts'
7
+ import { isLevel, isRecord, isRuns, isStrings, isTimeout, rootRelative, type Settings } from './config.ts'
8
+ import { cacheFolder } from './linters.ts'
9
+ import { importDefault } from './modules.ts'
10
+
11
+ type Common = {
12
+ readonly id: string
13
+ readonly source: string
14
+ readonly description: string
15
+ readonly level: Level | 'off'
16
+ readonly runs: Runs
17
+ readonly paths: readonly string[] | undefined
18
+ }
19
+
20
+ type Doc = { readonly file: string; readonly imports: readonly Import[] }
21
+
22
+ export type StaticRule = Common & {
23
+ readonly kind: 'static'
24
+ check(file: PromptFile, doc: Doc | undefined): readonly Finding[] | Promise<readonly Finding[]>
25
+ }
26
+
27
+ export type AgenticRule = Common & {
28
+ readonly kind: 'agentic'
29
+ readonly timeout: number
30
+ readonly body: string
31
+ readonly agent: string | undefined
32
+ readonly model: string | undefined
33
+ readonly effort: string | undefined
34
+ readonly allowedTools: string | readonly string[] | undefined
35
+ readonly disallowedTools: string | readonly string[] | undefined
36
+ }
37
+
38
+ export type LoadedRule = StaticRule | AgenticRule
39
+
40
+ export type Rules = { readonly rules: readonly LoadedRule[]; readonly failures: readonly string[] }
41
+
42
+ const RULE_FILES = new Bun.Glob('**/*.{ts,md,yml}')
43
+ const SCRIPT_KEYS = new Set(['description', 'level', 'runs', 'paths', 'check'])
44
+ const FRONTMATTER_KEYS = new Set(['description', 'agent', 'model', 'effort', 'paths', 'allowed-tools', 'disallowed-tools', 'metadata'])
45
+ const METADATA_KEYS = new Set(['level', 'runs', 'timeout'])
46
+ const PATTERN_KEYS = new Set(['description', 'language', 'paths', 'level', 'runs', 'rule'])
47
+ const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown']
48
+
49
+ let astGrep: Promise<typeof import('@ast-grep/napi')> | undefined
50
+
51
+ const loadedRules = new WeakMap<Settings, Promise<Rules>>()
52
+
53
+ export function loadRules(settings: Settings): Promise<Rules> {
54
+ const known = loadedRules.get(settings)
55
+ if (known !== undefined) return known
56
+ const rules = rulesOf(settings)
57
+ loadedRules.set(settings, rules)
58
+ return rules
59
+ }
60
+
61
+ async function rulesOf(settings: Settings): Promise<Rules> {
62
+ const rules: LoadedRule[] = [importsRule(settings), noSuppressionsRule]
63
+ const failures: string[] = []
64
+ const ids = new Set(rules.map(({ id }) => id))
65
+ for (const config of settings.configs) {
66
+ for (const [plugin, folder] of Object.entries(config.plugins)) {
67
+ for (const path of [...RULE_FILES.scanSync({ cwd: folder })].filter((path) => !path.endsWith('.d.ts') && !path.endsWith('.test.ts')).sort()) {
68
+ const id = `${plugin}/${path.slice(0, path.lastIndexOf('.'))}`
69
+ const source = join(folder, path)
70
+ if (ids.has(id)) throw new Error(`${source}: another file is already the rule ${id}. Give each rule its own name.`)
71
+ ids.add(id)
72
+ try {
73
+ const rule = await loadedRule(id, source, settings.timeout)
74
+ rules.push({ ...rule, paths: rule.paths && rootRelative(config.basePath, rule.paths) })
75
+ } catch (error) {
76
+ failures.push(`${error instanceof Error ? error.message : String(error)} The rule ${id} checks nothing until it loads.`)
77
+ }
78
+ }
79
+ }
80
+ }
81
+ for (const id of Object.keys(settings.rules)) if (!ids.has(id)) throw new Error(`A rulebook config sets the rule "${id}", which no plugin holds. The rules are ${[...ids].join(', ')}.`)
82
+ return { rules: rules.map((rule) => overridden(rule, settings.rules[rule.id])), failures }
83
+ }
84
+
85
+ function loadedRule(id: string, source: string, timeout: number): Promise<LoadedRule> {
86
+ if (source.endsWith('.ts')) return scriptRule(id, source)
87
+ if (source.endsWith('.md')) return agenticRule(id, source, timeout)
88
+ return patternRule(id, source)
89
+ }
90
+
91
+ async function scriptRule(id: string, source: string): Promise<StaticRule> {
92
+ const rule = await importDefault(source)
93
+ if (!isRecord(rule) || typeof rule.check !== 'function') throw new Error(`${source}: the default export is not a rule. Export defineRule({ description, check }).`)
94
+ for (const key of Object.keys(rule)) if (!SCRIPT_KEYS.has(key)) throw new Error(`${source}: rulebook does not read the key "${key}". It reads ${[...SCRIPT_KEYS].join(', ')}.`)
95
+ const check = rule.check as Rule['check']
96
+ return { ...commonOf(id, source, rule), kind: 'static', check: (file) => check(file) }
97
+ }
98
+
99
+ async function agenticRule(id: string, source: string, timeout: number): Promise<AgenticRule> {
100
+ const fail = (problem: string): never => {
101
+ throw new Error(`${source}: ${problem}`)
102
+ }
103
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(await Bun.file(source).text())
104
+ if (match === null) return fail('the rule has no frontmatter between --- lines.')
105
+ const frontmatter = yamlOf(source, match[1] ?? '')
106
+ const body = (match[2] ?? '').trim()
107
+ if (!isRecord(frontmatter)) return fail('the frontmatter is not a map of keys.')
108
+ for (const key of Object.keys(frontmatter)) if (!FRONTMATTER_KEYS.has(key)) fail(`rulebook does not read the key "${key}". It reads ${[...FRONTMATTER_KEYS].join(', ')}.`)
109
+ for (const key of ['agent', 'model', 'effort'] as const) if (frontmatter[key] !== undefined && typeof frontmatter[key] !== 'string') fail(`${key} is a string.`)
110
+ for (const key of ['allowed-tools', 'disallowed-tools'] as const) if (frontmatter[key] !== undefined && typeof frontmatter[key] !== 'string' && !isStrings(frontmatter[key])) fail(`${key} is a string or a list.`)
111
+ const metadata = frontmatter.metadata ?? {}
112
+ if (!isRecord(metadata)) return fail('metadata is a map.')
113
+ for (const key of Object.keys(metadata)) if (!METADATA_KEYS.has(key)) fail(`metadata.${key} is not a rulebook key. rulebook reads metadata.level, metadata.runs, and metadata.timeout.`)
114
+ if (metadata.timeout !== undefined && !isTimeout(metadata.timeout)) fail('metadata.timeout is a whole number of milliseconds above 0.')
115
+ if (body === '') fail('the rule has no body. The body is the check.')
116
+ return {
117
+ ...commonOf(id, source, { ...metadata, description: frontmatter.description, paths: frontmatter.paths }),
118
+ kind: 'agentic',
119
+ timeout: (metadata.timeout as number | undefined) ?? timeout,
120
+ body,
121
+ agent: frontmatter.agent as string | undefined,
122
+ model: frontmatter.model as string | undefined,
123
+ effort: frontmatter.effort as string | undefined,
124
+ allowedTools: frontmatter['allowed-tools'] as string | readonly string[] | undefined,
125
+ disallowedTools: frontmatter['disallowed-tools'] as string | readonly string[] | undefined,
126
+ }
127
+ }
128
+
129
+ async function patternRule(id: string, source: string): Promise<StaticRule> {
130
+ const fail = (problem: string): never => {
131
+ throw new Error(`${source}: ${problem}`)
132
+ }
133
+ const rule = yamlOf(source, await Bun.file(source).text())
134
+ if (!isRecord(rule)) return fail('the rule is not a map of keys.')
135
+ for (const key of Object.keys(rule)) if (!PATTERN_KEYS.has(key)) fail(`rulebook does not read the key "${key}". It reads ${[...PATTERN_KEYS].join(', ')}.`)
136
+ const { language } = rule
137
+ if (typeof language !== 'string' || !LANGUAGES.includes(language)) return fail(`language is one of ${LANGUAGES.join(', ')}.`)
138
+ if (!isRecord(rule.rule)) fail('rule is an ast-grep rule, such as { pattern: "console.log($$$ARGS)" }.')
139
+ const common = commonOf(id, source, rule)
140
+ const matcher = { rule: rule.rule } as NapiConfig
141
+ const { parse } = await (astGrep ??= loadAstGrep())
142
+ try {
143
+ parse(language, '').root().findAll(matcher)
144
+ } catch (error) {
145
+ fail(`ast-grep refuses the rule: ${error instanceof Error ? error.message : String(error)}`)
146
+ }
147
+ return { ...common, kind: 'static', check: ({ text }) => parse(language, text).root().findAll(matcher).map((node) => ({ line: node.range().start.line + 1 })) }
148
+ }
149
+
150
+ async function loadAstGrep(): Promise<typeof import('@ast-grep/napi')> {
151
+ const [napi, php, python, bash, lua, json, yaml, toml, markdown] = await Promise.all([
152
+ import('@ast-grep/napi'),
153
+ import('@ast-grep/lang-php'),
154
+ import('@ast-grep/lang-python'),
155
+ import('@ast-grep/lang-bash'),
156
+ import('@ast-grep/lang-lua'),
157
+ import('@ast-grep/lang-json'),
158
+ import('@ast-grep/lang-yaml'),
159
+ import('@ast-grep/lang-toml'),
160
+ import('@ast-grep/lang-markdown'),
161
+ ])
162
+ const packages = { php, python, bash, lua, json, yaml, toml, markdown }
163
+ napi.registerDynamicLanguage(Object.fromEntries(await Promise.all(Object.entries(packages).map(async ([language, { default: registration }]) => {
164
+ const { extensions, languageSymbol = `tree_sitter_${language}`, expandoChar = '$' } = registration
165
+ return [language, { libraryPath: Bun.isStandaloneExecutable ? await embeddedParser(language) : registration.libraryPath, extensions, languageSymbol, expandoChar }] as const
166
+ }))))
167
+ return napi
168
+ }
169
+
170
+ async function embeddedParser(language: string): Promise<string> {
171
+ const embedded = (Bun.embeddedFiles as readonly Bun.BunFile[]).find((file) => file.name?.includes(`/lang-${language}/`))
172
+ if (embedded?.name === undefined) throw new Error(`This rulebook build holds no ${language} parser. Build it with the build script in cli/package.json, which embeds each parser.`)
173
+ const folder = cacheFolder()
174
+ const file = join(folder, `${language}-${basename(embedded.name)}`)
175
+ if (existsSync(file)) return file
176
+ mkdirSync(folder, { recursive: true })
177
+ const partial = `${file}.${crypto.randomUUID()}`
178
+ await Bun.write(partial, embedded)
179
+ renameSync(partial, file)
180
+ return file
181
+ }
182
+
183
+ function commonOf(id: string, source: string, keys: Readonly<Record<string, unknown>>): Common {
184
+ const fail = (problem: string): never => {
185
+ throw new Error(`${source}: ${problem}`)
186
+ }
187
+ const { description, level, runs } = keys
188
+ if (typeof description !== 'string' || description.trim() === '' || description.trim().includes('\n')) return fail('a rule needs a description: the Rule in one line of plain words, such as "Don\'t write em dashes."')
189
+ if (level !== undefined && !isLevel(level)) fail('level is "error" or "warning".')
190
+ if (runs !== undefined && !isRuns(runs)) fail('runs is "always" or "manual".')
191
+ return {
192
+ id,
193
+ source,
194
+ description: description.trim(),
195
+ level: (level as Level | undefined) ?? 'error',
196
+ runs: (runs as Runs | undefined) ?? 'always',
197
+ paths: pathsOf(source, keys.paths),
198
+ }
199
+ }
200
+
201
+ function pathsOf(source: string, paths: unknown): readonly string[] | undefined {
202
+ if (paths === undefined) return undefined
203
+ if (typeof paths === 'string') return paths.split(',').map((path) => path.trim()).filter((path) => path !== '')
204
+ if (isStrings(paths)) return paths
205
+ throw new Error(`${source}: paths is a list of globs or a comma-separated string.`)
206
+ }
207
+
208
+ function yamlOf(source: string, text: string): unknown {
209
+ try {
210
+ return Bun.YAML.parse(text)
211
+ } catch (error) {
212
+ throw new Error(`${source}: ${error instanceof Error ? error.message : String(error)}`)
213
+ }
214
+ }
215
+
216
+ function overridden(rule: LoadedRule, override: RuleSettings | undefined): LoadedRule {
217
+ if (override === undefined) return rule
218
+ const { level, runs, paths } = override
219
+ const common = { ...rule, ...(level === undefined ? {} : { level }), ...(runs === undefined ? {} : { runs }), ...(paths === undefined ? {} : { paths }) }
220
+ if (common.kind === 'static') {
221
+ for (const key of ['agent', 'model', 'effort', 'timeout'] as const) if (override[key] !== undefined) throw new Error(`A rulebook config sets ${key} on ${rule.id}, a static rule, which runs no agent.`)
222
+ return common
223
+ }
224
+ return { ...common, ...(override.timeout === undefined ? {} : { timeout: override.timeout }), ...(override.agent === undefined ? {} : { agent: override.agent }), ...(override.model === undefined ? {} : { model: override.model }), ...(override.effort === undefined ? {} : { effort: override.effort }) }
225
+ }
package/src/serve.ts ADDED
@@ -0,0 +1,117 @@
1
+ import { rmSync, statSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { isRecord } from './config.ts'
5
+ import { isQuestion, projectOf, type Question } from './questions.ts'
6
+ import type { Answered, Asked } from './worker.ts'
7
+
8
+ const ENVIRONMENT = ['CLAUDE_CONFIG_DIR', 'HOME', 'PATH', 'XDG_CACHE_HOME', 'XDG_CONFIG_HOME']
9
+ const IDLE_MS = 15 * 60_000
10
+ const WORKER = new URL(Bun.isStandaloneExecutable ? './src/worker.ts' : './worker.ts', import.meta.url)
11
+
12
+ type Environment = Readonly<Record<string, string>>
13
+
14
+ type Project = {
15
+ readonly worker: Worker
16
+ readonly startedAt: number
17
+ readonly watched: Map<string, boolean>
18
+ readonly asking: Map<number, PromiseWithResolvers<unknown>>
19
+ isRetired: boolean
20
+ idle: Timer | undefined
21
+ }
22
+
23
+ export async function serve(): Promise<never> {
24
+ const socket = join(tmpdir(), `rulebook-${process.pid}.sock`)
25
+ const projects = new Map<string, Project>()
26
+ let lastId = 0
27
+
28
+ const stop = (project: Project): void => {
29
+ project.isRetired = true
30
+ clearTimeout(project.idle)
31
+ if (project.asking.size === 0) project.worker.terminate()
32
+ }
33
+
34
+ const fail = (key: string, project: Project, reason: string): void => {
35
+ for (const asked of project.asking.values()) asked.reject(new Error(reason))
36
+ project.asking.clear()
37
+ if (projects.get(key) === project) projects.delete(key)
38
+ stop(project)
39
+ }
40
+
41
+ const started = (key: string, root: string, environment: Environment): Project => {
42
+ const env = { ...Object.fromEntries(Object.entries(process.env).flatMap(([name, value]) => (value === undefined || ENVIRONMENT.includes(name) ? [] : [[name, value]]))), ...environment }
43
+ const project: Project = { worker: new Worker(WORKER, { env }), startedAt: Date.now(), watched: new Map(), asking: new Map(), isRetired: false, idle: undefined }
44
+ project.worker.onmessage = ({ data }: MessageEvent<Answered>) => {
45
+ for (const path of data.watched) if (!project.watched.has(path)) project.watched.set(path, statSync(path, { throwIfNoEntry: false }) !== undefined)
46
+ const asked = project.asking.get(data.id)
47
+ project.asking.delete(data.id)
48
+ if ('error' in data) asked?.reject(new Error(data.error))
49
+ else asked?.resolve(data.answer)
50
+ if (project.asking.size > 0) return
51
+ if (project.isRetired) project.worker.terminate()
52
+ else project.idle = setTimeout(() => (projects.get(key) === project ? (projects.delete(key), stop(project)) : undefined), IDLE_MS)
53
+ }
54
+ project.worker.onerror = (event) => fail(key, project, `the worker for ${root} failed: ${event.message}`)
55
+ project.worker.addEventListener('close', () => fail(key, project, `the worker for ${root} stopped`))
56
+ return project
57
+ }
58
+
59
+ const projectFor = (root: string, environment: Environment): Project => {
60
+ const key = `${root}\0${JSON.stringify(environment)}`
61
+ const known = projects.get(key)
62
+ if (known !== undefined && !isStale(known)) return known
63
+ if (known !== undefined) stop(known)
64
+ const project = started(key, root, environment)
65
+ projects.set(key, project)
66
+ return project
67
+ }
68
+
69
+ const ask = (project: Project, question: Question, input: unknown, root: string): Promise<unknown> => {
70
+ lastId += 1
71
+ const asked = Promise.withResolvers<unknown>()
72
+ project.asking.set(lastId, asked)
73
+ clearTimeout(project.idle)
74
+ project.worker.postMessage({ id: lastId, question, input, root } satisfies Asked)
75
+ return asked.promise
76
+ }
77
+
78
+ const server = Bun.serve({
79
+ unix: socket,
80
+ idleTimeout: 0,
81
+ async fetch(request: Request) {
82
+ const question = new URL(request.url).pathname.slice(1)
83
+ if (request.method !== 'POST' || !isQuestion(question)) return new Response('rulebook serve answers POST /edit, /text, and /rules.', { status: 404 })
84
+ try {
85
+ const body: unknown = await request.json()
86
+ if (!isRecord(body)) throw new Error('rulebook serve reads {"input", "environment"}.')
87
+ const root = projectOf(question, body.input)
88
+ return Response.json(await ask(projectFor(root, environmentOf(body.environment)), question, body.input, root))
89
+ } catch (error) {
90
+ return new Response(error instanceof Error ? error.message : String(error), { status: 500 })
91
+ }
92
+ },
93
+ } as unknown as Bun.Serve.Options<undefined>)
94
+
95
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
96
+ process.on(signal, () => {
97
+ void server.stop(true)
98
+ rmSync(socket, { force: true })
99
+ process.exit(0)
100
+ })
101
+ }
102
+ await Bun.write(Bun.stdout, `unix:${socket}\n`)
103
+ return new Promise<never>(() => undefined)
104
+ }
105
+
106
+ function isStale({ watched, startedAt }: Project): boolean {
107
+ for (const [path, existed] of watched) {
108
+ const stats = statSync(path, { throwIfNoEntry: false })
109
+ if ((stats !== undefined) !== existed || (stats !== undefined && stats.ctimeMs >= startedAt)) return true
110
+ }
111
+ return false
112
+ }
113
+
114
+ function environmentOf(sent: unknown): Environment {
115
+ if (!isRecord(sent)) throw new Error('rulebook serve reads {"input", "environment"}.')
116
+ return Object.fromEntries(ENVIRONMENT.flatMap((name) => (typeof sent[name] === 'string' ? [[name, sent[name]]] : [])))
117
+ }
package/src/worker.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { statSync } from 'node:fs'
2
+ import { isAbsolute, join } from 'node:path'
3
+ import { claudeConfigFolder, userMemoryPaths } from './claude-md.ts'
4
+ import { settingsSources } from './config.ts'
5
+ import { importSources } from './files.ts'
6
+ import { answer, type Question } from './questions.ts'
7
+
8
+ declare const self: Worker
9
+
10
+ export type Asked = { readonly id: number; readonly question: Question; readonly input: unknown; readonly root: string }
11
+
12
+ export type Answered = { readonly id: number; readonly watched: readonly string[] } & ({ readonly answer: unknown } | { readonly error: string })
13
+
14
+ self.onmessage = async ({ data: { id, question, input, root } }: MessageEvent<Asked>) => {
15
+ try {
16
+ const answered = await answer(question, input, root)
17
+ postMessage({ id, answer: answered, watched: watchedPaths() } satisfies Answered)
18
+ } catch (error) {
19
+ postMessage({ id, error: error instanceof Error ? error.message : String(error), watched: watchedPaths() } satisfies Answered)
20
+ }
21
+ }
22
+
23
+ function watchedPaths(): readonly string[] {
24
+ const modules = Object.keys(require.cache).filter((path) => isAbsolute(path))
25
+ const sources = [...settingsSources(), ...importSources()].flatMap((path) => [path, ...entriesUnder(path)])
26
+ const memory = [join(claudeConfigFolder(), 'CLAUDE.md'), join(claudeConfigFolder(), 'rules'), ...userMemoryPaths()]
27
+ return [...new Set([...modules, ...sources, ...memory])]
28
+ }
29
+
30
+ function entriesUnder(path: string): readonly string[] {
31
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory() !== true) return []
32
+ return [...new Bun.Glob('**').scanSync({ cwd: path, absolute: true, onlyFiles: false })]
33
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.