@cmodjs/rulebook 0.2.5 → 0.3.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.2.5",
3
+ "version": "0.3.0",
4
4
  "description": "Checks every file, reply, and tool call a Claude Code agent writes against your rules and linters before it lands.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/api.ts CHANGED
@@ -29,6 +29,7 @@ export type RuleSettings = {
29
29
  readonly agent?: string
30
30
  readonly model?: string
31
31
  readonly effort?: string
32
+ readonly threshold?: number
32
33
  }
33
34
 
34
35
  export type LinterName = 'mago' | 'oxlint' | 'biome' | 'stylelint' | 'ruff' | 'selene' | 'shellcheck'
package/src/check.ts CHANGED
@@ -6,6 +6,7 @@ import type { Finding, Level, LinterName, PromptFile } from './api.ts'
6
6
  import { runAgentic } from './agent.ts'
7
7
  import { importedFile, isClaudeMd, readClaudeMd } from './claude-md.ts'
8
8
  import { isInside, type Settings } from './config.ts'
9
+ import { isJev, runJev } from './jev.ts'
9
10
  import { coveringLinters, LINTERS, lintFolder, lintText, projectLinters, type Covering, type ProjectLinter } from './linters.ts'
10
11
  import { seconds } from './lsp.ts'
11
12
  import type { LoadedRule, StaticRule } from './rules.ts'
@@ -103,7 +104,7 @@ export async function checkFile(settings: Settings, rules: readonly LoadedRule[]
103
104
  const timer = longest === 0 ? undefined : setTimeout(() => deadline.abort(new Error(`it ran past ${seconds(longest)}`)), longest)
104
105
  const runs = await Promise.all(chosen.map(async (rule) => {
105
106
  try {
106
- const found = rule.kind === 'static' ? await rule.check(prompt, doc) : await runAgentic(rule, prompt, settings.root, changed, deadline.signal)
107
+ const found = rule.kind === 'static' ? await rule.check(prompt, doc) : isJev(rule.model) ? await runJev(rule, prompt, deadline.signal) : await runAgentic(rule, prompt, settings.root, changed, deadline.signal)
107
108
  return { rule, found: validFindings(rule.id, prompt, found) }
108
109
  } catch (error) {
109
110
  return { rule, failure: error instanceof Error ? error.message : String(error) }
package/src/config.ts CHANGED
@@ -34,7 +34,7 @@ export type Settings = {
34
34
  }
35
35
 
36
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'])
37
+ const RULE_KEYS = new Set(['level', 'runs', 'paths', 'timeout', 'agent', 'model', 'effort', 'threshold'])
38
38
  const MESSAGE_KEYS = new Set(['tools', 'folder'])
39
39
  const BUILT_IN: Pick<LoadedConfig, 'file' | 'plugins' | 'messages'> = { file: 'rulebook', plugins: {}, messages: { reply: { tools: [], folder: undefined } } }
40
40
 
@@ -210,6 +210,7 @@ function validOverride(file: string, id: string, override: unknown): void {
210
210
  if (override.runs !== undefined && !isRuns(override.runs)) fail('runs is "always" or "manual".')
211
211
  if (override.paths !== undefined && !isStrings(override.paths)) fail('paths is a list of globs.')
212
212
  if (override.timeout !== undefined && !isTimeout(override.timeout)) fail('timeout is a whole number of milliseconds above 0.')
213
+ if (override.threshold !== undefined && !isThreshold(override.threshold)) fail('threshold is a probability above 0 and at most 1.')
213
214
  for (const key of ['agent', 'model', 'effort'] as const) if (override[key] !== undefined && typeof override[key] !== 'string') fail(`${key} is a string.`)
214
215
  }
215
216
 
@@ -241,3 +242,7 @@ export function isRuns(value: unknown): value is Runs {
241
242
  export function isTimeout(value: unknown): value is number {
242
243
  return Number.isInteger(value) && (value as number) > 0
243
244
  }
245
+
246
+ export function isThreshold(value: unknown): value is number {
247
+ return typeof value === 'number' && value > 0 && value <= 1
248
+ }
package/src/jev.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { join } from 'node:path'
2
+ import type { Finding, PromptFile } from './api.ts'
3
+ import { isRecord } from './config.ts'
4
+ import type { AgenticRule } from './rules.ts'
5
+
6
+ const API = 'https://api.typesafe.ai'
7
+ const MODEL = 'jev-latest'
8
+ const THRESHOLD = 0.7
9
+ const WINDOW = 120_000
10
+
11
+ let storedKey: Promise<string> | undefined
12
+
13
+ export function isJev(model: unknown): boolean {
14
+ return model === 'jev'
15
+ }
16
+
17
+ export async function runJev(rule: AgenticRule, file: PromptFile, deadline: AbortSignal): Promise<readonly Finding[]> {
18
+ const key = await jevKey()
19
+ if (key === '') throw new Error(`${rule.id} runs on Jev, and rulebook has no Jev key. Store your TypeSafe API key with \`cmod secret store rulebook jev\`, which reads it on stdin.`)
20
+ const width = String(file.lines.length).length
21
+ const windows: { lines: string[]; asked: number[]; size: number }[] = []
22
+ file.lines.forEach((text, index) => {
23
+ const numbered = `${String(index + 1).padStart(width)} | ${text}`
24
+ const asks = text.trim() !== ''
25
+ const size = numbered.length + (asks ? 200 : 0)
26
+ const last = windows.at(-1)
27
+ const window = last !== undefined && last.size + size <= WINDOW ? last : { lines: [], asked: [], size: 0 }
28
+ if (window !== last) windows.push(window)
29
+ window.lines.push(numbered)
30
+ if (asks) window.asked.push(index + 1)
31
+ window.size += size
32
+ })
33
+ const found = await Promise.all(windows.filter(({ asked }) => asked.length > 0).map((window) => flagged(rule, file.path, window, key, deadline)))
34
+ return found.flat()
35
+ }
36
+
37
+ async function jevKey(): Promise<string> {
38
+ storedKey ??= readKey()
39
+ const key = await storedKey.catch((error: unknown) => {
40
+ storedKey = undefined
41
+ throw error
42
+ })
43
+ if (key === '') storedKey = undefined
44
+ return key
45
+ }
46
+
47
+ async function readKey(): Promise<string> {
48
+ const cmod = join(process.env.XDG_DATA_HOME || join(process.env.HOME ?? '', '.local', 'share'), 'cmod', 'programs', 'cmod')
49
+ if (!(await Bun.file(cmod).exists())) return ''
50
+ const read = Bun.spawn([cmod, 'secret', 'get', 'rulebook', 'jev'], { env: process.env, stdout: 'pipe', stderr: 'pipe' })
51
+ const [key, error, code] = await Promise.all([new Response(read.stdout).text(), new Response(read.stderr).text(), read.exited])
52
+ if (code !== 0) throw new Error(`cmod secret get rulebook jev failed: ${error.trim()}`)
53
+ return key
54
+ }
55
+
56
+ async function flagged(rule: AgenticRule, path: string, { lines, asked }: { readonly lines: readonly string[]; readonly asked: readonly number[] }, key: string, deadline: AbortSignal): Promise<readonly Finding[]> {
57
+ const response = await fetch(`${(process.env.JEV_BASE_URL || API).replace(/\/+$/, '')}/v1/systemone`, {
58
+ method: 'POST',
59
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
60
+ body: JSON.stringify({
61
+ model: MODEL,
62
+ state: { rule: `${rule.description}\n\n${rule.body}`, file: path, lines: lines.join('\n') },
63
+ questions: Object.fromEntries(asked.map((line) => [`line_${line}`, {
64
+ type: 'noul',
65
+ instructions: `Line ${line} of the file follows the rule.`,
66
+ criteria: { true: `Line ${line} follows the rule, or the rule does not apply to it.`, false: `Line ${line} breaks the rule.` },
67
+ }])),
68
+ }),
69
+ signal: deadline,
70
+ })
71
+ const text = await response.text()
72
+ if (!response.ok) throw new Error(`Jev answered ${response.status}: ${text.slice(0, 300)}`)
73
+ const answer: unknown = JSON.parse(text)
74
+ const answers = isRecord(answer) && isRecord(answer.answers) ? answer.answers : {}
75
+ return asked.flatMap((line) => {
76
+ const noul = answers[`line_${line}`]
77
+ if (!isRecord(noul) || typeof noul.noul !== 'number') throw new Error(`Jev answered no noul for line ${line}`)
78
+ return noul.noul >= (rule.threshold ?? THRESHOLD) ? [] : [{ line }]
79
+ })
80
+ }
package/src/rules.ts CHANGED
@@ -4,7 +4,8 @@ import type { NapiConfig } from '@ast-grep/napi'
4
4
  import type { Finding, Level, PromptFile, Rule, RuleSettings, Runs } from './api.ts'
5
5
  import { importsRule, noSuppressionsRule } from './check.ts'
6
6
  import type { Import } from './claude-md.ts'
7
- import { isLevel, isRecord, isRuns, isStrings, isTimeout, rootRelative, type Settings } from './config.ts'
7
+ import { isLevel, isRecord, isRuns, isStrings, isThreshold, isTimeout, rootRelative, type Settings } from './config.ts'
8
+ import { isJev } from './jev.ts'
8
9
  import { cacheFolder } from './linters.ts'
9
10
  import { importDefault } from './modules.ts'
10
11
 
@@ -31,6 +32,7 @@ export type AgenticRule = Common & {
31
32
  readonly agent: string | undefined
32
33
  readonly model: string | undefined
33
34
  readonly effort: string | undefined
35
+ readonly threshold: number | undefined
34
36
  readonly allowedTools: string | readonly string[] | undefined
35
37
  readonly disallowedTools: string | readonly string[] | undefined
36
38
  }
@@ -42,7 +44,8 @@ export type Rules = { readonly rules: readonly LoadedRule[]; readonly failures:
42
44
  const RULE_FILES = new Bun.Glob('**/*.{ts,md,yml}')
43
45
  const SCRIPT_KEYS = new Set(['description', 'level', 'runs', 'paths', 'check'])
44
46
  const FRONTMATTER_KEYS = new Set(['description', 'agent', 'model', 'effort', 'paths', 'allowed-tools', 'disallowed-tools', 'metadata'])
45
- const METADATA_KEYS = new Set(['level', 'runs', 'timeout'])
47
+ const METADATA_KEYS = new Set(['level', 'runs', 'timeout', 'threshold'])
48
+ const CLAUDE_KEYS = ['agent', 'effort', 'allowed-tools', 'disallowed-tools'] as const
46
49
  const PATTERN_KEYS = new Set(['description', 'language', 'paths', 'level', 'runs', 'rule'])
47
50
  const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown']
48
51
 
@@ -110,9 +113,12 @@ async function agenticRule(id: string, source: string, timeout: number): Promise
110
113
  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
114
  const metadata = frontmatter.metadata ?? {}
112
115
  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.`)
116
+ 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, metadata.timeout, and metadata.threshold.`)
114
117
  if (metadata.timeout !== undefined && !isTimeout(metadata.timeout)) fail('metadata.timeout is a whole number of milliseconds above 0.')
118
+ if (metadata.threshold !== undefined && !isThreshold(metadata.threshold)) fail('metadata.threshold is a probability above 0 and at most 1.')
115
119
  if (body === '') fail('the rule has no body. The body is the check.')
120
+ if (isJev(frontmatter.model)) for (const key of CLAUDE_KEYS) if (frontmatter[key] !== undefined) fail(`model jev runs the rule on Jev, which runs no agent, so rulebook does not read ${key}.`)
121
+ if (metadata.threshold !== undefined && !isJev(frontmatter.model)) fail('metadata.threshold is the probability Jev must give a line to pass, so it needs model: jev.')
116
122
  return {
117
123
  ...commonOf(id, source, { ...metadata, description: frontmatter.description, paths: frontmatter.paths }),
118
124
  kind: 'agentic',
@@ -121,6 +127,7 @@ async function agenticRule(id: string, source: string, timeout: number): Promise
121
127
  agent: frontmatter.agent as string | undefined,
122
128
  model: frontmatter.model as string | undefined,
123
129
  effort: frontmatter.effort as string | undefined,
130
+ threshold: metadata.threshold as number | undefined,
124
131
  allowedTools: frontmatter['allowed-tools'] as string | readonly string[] | undefined,
125
132
  disallowedTools: frontmatter['disallowed-tools'] as string | readonly string[] | undefined,
126
133
  }
@@ -218,8 +225,11 @@ function overridden(rule: LoadedRule, override: RuleSettings | undefined): Loade
218
225
  const { level, runs, paths } = override
219
226
  const common = { ...rule, ...(level === undefined ? {} : { level }), ...(runs === undefined ? {} : { runs }), ...(paths === undefined ? {} : { paths }) }
220
227
  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.`)
228
+ for (const key of ['agent', 'model', 'effort', 'timeout', 'threshold'] 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
229
  return common
223
230
  }
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 }) }
231
+ const agentic = { ...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 }), ...(override.threshold === undefined ? {} : { threshold: override.threshold }) }
232
+ if (isJev(agentic.model)) for (const key of ['agent', 'effort'] as const) if (override[key] !== undefined) throw new Error(`A rulebook config sets ${key} on ${rule.id}, which runs on Jev, and Jev runs no agent.`)
233
+ if (!isJev(agentic.model) && override.threshold !== undefined) throw new Error(`A rulebook config sets threshold on ${rule.id}, which runs on Claude Code. threshold is the probability Jev must give a line to pass, so it needs model: 'jev'.`)
234
+ return agentic
225
235
  }
package/src/serve.ts CHANGED
@@ -5,7 +5,7 @@ import { isRecord, isStrings } from './config.ts'
5
5
  import { isQuestion, projectOf, type Question } from './questions.ts'
6
6
  import type { Answered, Asked } from './worker.ts'
7
7
 
8
- const ENVIRONMENT = ['CLAUDE_CONFIG_DIR', 'HOME', 'PATH', 'XDG_CACHE_HOME', 'XDG_CONFIG_HOME']
8
+ const ENVIRONMENT = ['CLAUDE_CONFIG_DIR', 'HOME', 'JEV_BASE_URL', 'PATH', 'XDG_CACHE_HOME', 'XDG_CONFIG_HOME']
9
9
  const IDLE_MS = 15 * 60_000
10
10
  const WORKER = new URL(Bun.isStandaloneExecutable ? './src/worker.ts' : './worker.ts', import.meta.url)
11
11