Checks each edit against the repository's traits (.agents/traits) with the traits CLI and TypeSafe Jev, and tells Claude what to fix

hooks/register.ts 368 lines1import type { EngineInterface, FsEntry, PluginOptions, Register, ToolCallInput } from 'claude-code'
2
3import {
4 dirOf,
5 editArgs,
6 failureText,
7 formatReport,
8 judged,
9 KEYCHAIN_SERVICE,
10 plural,
11 relativeTo,
12 reviewFrom,
13 settingsFrom,
14 SKIP,
15 TARGETS,
16 targetArgs,
17 targetFrom,
18 traitFile,
19 TRAITS_DIR,
20} from './check'
21import type { ChangeKind, Judgment, Review, Target } from './check'
22
23const CHECK_TOOL = 'mcp__jev-traits__check_traits'
24
25const EDIT_TIMEOUT_MS = 6_000
26const CHECK_TIMEOUT_MS = 8_000
27const LS_TIMEOUT_MS = 5_000
28const MAX_EDIT_CHARS = 48_000
29
30const KEY_HELP = [
31 'jev-traits found no TypeSafe API key. Store it once, by hand, in the macOS Keychain (jev-lint reads the same item):',
32 '',
33 ` security add-generic-password -U -a "$USER" -s ${KEYCHAIN_SERVICE} -w`,
34 '',
35 'The command prompts for the key, so it stays out of your shell history and this chat. Then run /traits again.',
36 'Lookup order: the typesafe_api_key option (kept in secure storage, once the plugin is installed from a marketplace),',
37 `then the Keychain item ${KEYCHAIN_SERVICE}, then TYPESAFE_API_KEY as a fallback for machines without the item, such as CI.`,
38 'Do not keep the key in a .env file.',
39].join('\n')
40
41type Entry = { readonly at: number; readonly line: string }
42const history: Entry[] = []
43type ApiKey = { readonly key: string; readonly source: string }
44let cachedKey: ApiKey | undefined
45let lastKeyMissAt = -Infinity
46
47async function findRoot($: EngineInterface, from: string): Promise<string | undefined> {
48 for (let dir = from; ; dir = dirOf(dir)) {
49 if (await $.fs.exists(`${dir}/${TRAITS_DIR}`)) return dir
50 if (dir === '/') return undefined
51 }
52}
53
54async function listDir($: EngineInterface, path: string): Promise<FsEntry[]> {
55 return $.fs.list(path).catch((): FsEntry[] => [])
56}
57
58// The CLI exits 2 without a key even when no trait exists, so an empty store
59// must not reach it.
60async function hasTraits($: EngineInterface, root: string): Promise<boolean> {
61 const base = `${root}/${TRAITS_DIR}`
62 const isTrait = (entry: FsEntry) => entry.kind === 'file' && entry.name.endsWith('.md')
63 const entries = await listDir($, base)
64 if (entries.some(isTrait)) return true
65 for (const group of entries)
66 if ((group.kind === 'dir' || group.isLink) && !group.name.startsWith('.'))
67 if ((await listDir($, `${base}/${group.name}`)).some(isTrait)) return true
68 return false
69}
70
71async function apiKey($: EngineInterface, options: PluginOptions): Promise<ApiKey | undefined> {
72 const option = typeof options.typesafe_api_key === 'string' ? options.typesafe_api_key.trim() : ''
73 if (option) return { key: option, source: 'the typesafe_api_key plugin option' }
74 if (cachedKey) return cachedKey
75 if (Date.now() - lastKeyMissAt < 30_000) return undefined
76 const keychain = await $.process
77 .run(['security', 'find-generic-password', '-s', KEYCHAIN_SERVICE, '-w'], { timeoutMs: 3000 })
78 .catch(() => undefined)
79 const fromKeychain = keychain?.exitCode === 0 ? keychain.stdout.trim() : ''
80 if (fromKeychain) return (cachedKey = { key: fromKeychain, source: `the Keychain item ${KEYCHAIN_SERVICE}` })
81 // The Keychain wins so a key that direnv, mise or bun loads from a plaintext
82 // .env cannot override it; the env var only serves machines without the item.
83 const fromEnv = (await $.env.get('TYPESAFE_API_KEY'))?.trim()
84 if (fromEnv) return (cachedKey = { key: fromEnv, source: 'TYPESAFE_API_KEY (fallback, no Keychain item)' })
85 lastKeyMissAt = Date.now()
86 return undefined
87}
88
89function forgetKey() {
90 cachedKey = undefined
91 lastKeyMissAt = -Infinity
92}
93
94// Home Manager sets TRAITS_BIN to the store path, since a GUI-launched Claude
95// Code may not have the Nix profile on PATH.
96async function traitsBin($: EngineInterface): Promise<string> {
97 return (await $.env.get('TRAITS_BIN'))?.trim() || 'traits'
98}
99
100type Run = { readonly ok: true; readonly review: Review } | { readonly ok: false; readonly message: string }
101
102async function runTraits(
103 $: EngineInterface,
104 root: string,
105 args: readonly string[],
106 init: { key?: string; stdin?: string; timeoutMs: number },
107): Promise<Run> {
108 const startedAt = Date.now()
109 const ran = await $.process
110 .run([await traitsBin($), ...args], {
111 cwd: root,
112 timeoutMs: init.timeoutMs,
113 ...(init.key === undefined ? {} : { env: { TYPESAFE_API_KEY: init.key } }),
114 ...(init.stdin === undefined ? {} : { stdin: init.stdin }),
115 })
116 .catch((error: unknown) => errorText(error))
117 if (typeof ran === 'string')
118 return /time/i.test(ran)
119 ? { ok: false, message: `traits did not finish within ${init.timeoutMs / 1000} s` }
120 : { ok: false, message: `could not run traits: ${ran}` }
121 if (ran.exitCode !== 0 && ran.exitCode !== 1) {
122 if (/\b401\b|unauthori[sz]ed/i.test(ran.stderr)) forgetKey()
123 return { ok: false, message: failureText(ran.stderr) }
124 }
125 try {
126 return { ok: true, review: reviewFrom(root, ran.stdout, Date.now() - startedAt) }
127 } catch {
128 return { ok: false, message: 'traits printed no JSON report' }
129 }
130}
131
132const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error))
133const shortPath = (path: string) => (path.length > 44 ? `…${path.slice(-43)}` : path)
134
135type EditedChange = { readonly path: string; readonly kind: ChangeKind; readonly code: string }
136
137function editedChange(e: ToolCallInput): EditedChange | undefined {
138 if (e.tool === 'Edit') return { path: e.file_path, kind: 'edit', code: e.new_string }
139 if (e.tool === 'Write') return { path: e.file_path, kind: 'write', code: e.content }
140 if (e.tool === 'NotebookEdit' && e.edit_mode !== 'delete')
141 return { path: e.notebook_path, kind: 'edit', code: e.new_source }
142 return undefined
143}
144
145function flaggedByTrait(result: Review): Judgment[] {
146 const worst = new Map<string, Judgment>()
147 for (const judgment of result.judgments) {
148 if (judgment.verdict !== 'fix' && judgment.verdict !== 'check') continue
149 const seen = worst.get(judgment.trait.id)
150 if (!seen || seen.probabilities.violation < judgment.probabilities.violation) worst.set(judgment.trait.id, judgment)
151 }
152 return [...worst.values()].sort((a, b) => b.probabilities.violation - a.probabilities.violation)
153}
154
155function editStatus(rel: string, result: Review): string {
156 const flagged = flaggedByTrait(result)
157 const fixes = flagged.filter(j => j.verdict === 'fix').length
158 const checks = flagged.length - fixes
159 const head = fixes > 0 ? `jev ⚠ ${fixes} to fix` : checks > 0 ? `jev ? ${checks} to double-check` : 'jev ✓'
160 const skipped = result.skipped.length > 0 ? ` · ${result.skipped.length} skipped as too large` : ''
161 return `${head} · ${shortPath(rel)} · ${plural(judged(result), 'judgment')}${skipped} · ${result.ms} ms`
162}
163
164function feedbackFor(rel: string, kind: ChangeKind, result: Review): string | undefined {
165 const flagged = flaggedByTrait(result)
166 if (flagged.length === 0) return undefined
167 const line = (j: Judgment) =>
168 ` - ${j.trait.id} (p=${j.probabilities.violation.toFixed(2)}): ${j.trait.title} [${traitFile(j.trait.id)}]`
169 const fixes = flagged.filter(j => j.verdict === 'fix')
170 const checks = flagged.filter(j => j.verdict === 'check')
171 const scope = kind === 'write' ? 'the whole file this write produced' : 'the code this edit added'
172 return [
173 `jev-traits checked ${scope} at ${rel} against the repository's traits.`,
174 ...(fixes.length > 0 ? ['Likely violations, fix these:', ...fixes.map(line)] : []),
175 ...(checks.length > 0 ? ['Possible violations, double-check and keep the code if it is fine:', ...checks.map(line)] : []),
176 'These are fast model judgments and can be wrong: read the trait file before changing code.',
177 ].join('\n')
178}
179
180function report($: EngineInterface, line: string) {
181 history.push({ at: Date.now(), line })
182 history.splice(0, Math.max(0, history.length - 50))
183 $.ui.status(line)
184}
185
186async function checkEdit($: EngineInterface, options: PluginOptions, e: ToolCallInput): Promise<string | undefined> {
187 const edited = editedChange(e)
188 if (!edited || !edited.code.trim()) return undefined
189 const root = await findRoot($, dirOf(edited.path))
190 if (!root) return undefined
191 const rel = relativeTo(root, edited.path)
192 if (SKIP.test(rel)) return undefined
193 if (!(await hasTraits($, root))) return undefined
194 if (edited.code.length > MAX_EDIT_CHARS) {
195 report($, `jev: ${shortPath(rel)} is too large to check per edit; use /traits check`)
196 return undefined
197 }
198 const key = await apiKey($, options)
199 if (!key) {
200 report($, 'jev: no TypeSafe API key; run /traits')
201 return undefined
202 }
203 const ran = await runTraits($, root, editArgs(rel, edited.kind, settingsFrom(options)), {
204 key: key.key,
205 stdin: edited.code,
206 timeoutMs: EDIT_TIMEOUT_MS,
207 })
208 if (!ran.ok) {
209 report($, `jev: ${ran.message}; ${shortPath(rel)} not checked`)
210 return undefined
211 }
212 if (judged(ran.review) === 0) {
213 const skipped = ran.review.skipped.length
214 report(
215 $,
216 skipped > 0
217 ? `jev · ${shortPath(rel)}: ${skipped} skipped as too large; use /traits check`
218 : `jev · ${shortPath(rel)}: no trait applies`,
219 )
220 return undefined
221 }
222 report($, editStatus(rel, ran.review))
223 return feedbackFor(rel, edited.kind, ran.review)
224}
225
226async function checkTarget(
227 $: EngineInterface,
228 options: PluginOptions,
229 target: Target,
230 files: readonly string[],
231 traitId?: string,
232 path?: string,
233): Promise<string> {
234 const sessionRoot = await $.session.root()
235 const start = path
236 ? path.startsWith('/') ? path : `${sessionRoot}/${path}`
237 : (files.find(file => file.startsWith('/')) ?? sessionRoot)
238 const root = await findRoot($, start)
239 if (!root) return `No ${TRAITS_DIR} folder at or above ${start}. Add a trait as ${TRAITS_DIR}/<name>.md first.`
240 if (!(await hasTraits($, root))) return `No traits in ${root}/${TRAITS_DIR}.`
241 const key = await apiKey($, options)
242 if (!key) return KEY_HELP
243 const settings = settingsFrom(options)
244 const ran = await runTraits($, root, targetArgs(root, target, files, settings, traitId), {
245 key: key.key,
246 timeoutMs: CHECK_TIMEOUT_MS,
247 })
248 if (!ran.ok) return `jev-traits ${target}: not checked, ${ran.message}.`
249 if (judged(ran.review) === 0 && ran.review.skipped.length === 0)
250 return `jev-traits ${target}: nothing to check (${ran.review.files > 0 ? 'no trait applies to the changes' : 'no changes'}).`
251 return formatReport(target, settings, ran.review)
252}
253
254async function storedTraits($: EngineInterface, root: string): Promise<string[]> {
255 const ran = await $.process
256 .run([await traitsBin($), 'ls', '--json'], { cwd: root, timeoutMs: LS_TIMEOUT_MS })
257 .catch((error: unknown) => errorText(error))
258 if (typeof ran === 'string') return [` traits ls failed: ${ran}`]
259 if (ran.exitCode !== 0) return [` traits ls failed: ${failureText(ran.stderr)}`]
260 try {
261 const traits = JSON.parse(ran.stdout) as { name: string; path: string }[]
262 return traits.map(trait => ` ${trait.name}: ${relativeTo(root, trait.path)}`)
263 } catch {
264 return [' traits ls printed no JSON list']
265 }
266}
267
268async function summary($: EngineInterface, options: PluginOptions): Promise<string> {
269 const settings = settingsFrom(options)
270 forgetKey()
271 const key = await apiKey($, options)
272 const sessionRoot = await $.session.root()
273 const root = await findRoot($, sessionRoot)
274 const traits = root && (await hasTraits($, root)) ? await storedTraits($, root) : []
275 return [
276 `jev-traits · ${settings.model} · fix ≥ ${settings.fix} · double-check ≥ ${settings.check} · pass ≥ ${settings.pass}` +
277 ` · edits ${options.check_edits === false ? 'not checked' : 'checked'}`,
278 key ? `Key: from ${key.source}.` : KEY_HELP,
279 root
280 ? `Traits: ${traits.length} in ${root}/${TRAITS_DIR}`
281 : `Traits: no ${TRAITS_DIR} folder at or above ${sessionRoot}. Add one as ${TRAITS_DIR}/<name>.md.`,
282 ...traits,
283 ...(history.length > 0
284 ? ['Recent checks:', ...history.slice(-10).map(entry => ` ${new Date(entry.at).toTimeString().slice(0, 8)} ${entry.line}`)]
285 : []),
286 'Run /traits check [changed|staged|unstaged|untracked|<files…>] to check work in progress.',
287 ].join('\n')
288}
289
290export const register: Register = (on, options: PluginOptions) => {
291 on('session.start', async ($, e, next) => {
292 await $.command.register({
293 name: 'traits',
294 description: 'Show jev-traits status, or check changes against the repository traits',
295 argumentHint: '[check [changed|staged|unstaged|untracked|<files…>]]',
296 })
297 await $.tool.register({
298 name: 'check_traits',
299 description:
300 "Checks code against this repository's traits (.agents/traits/*.md and .agents/traits/<group>/*.md) with the traits CLI and TypeSafe Jev. " +
301 'Use it before committing (target staged), after adding or revising a trait, or to audit files. ' +
302 'Findings are fast model judgments: read the trait and the code before changing anything, ' +
303 'and report unsure results as unsure, never as passes.',
304 inputSchema: {
305 type: 'object',
306 properties: {
307 target: {
308 type: 'string',
309 enum: [...TARGETS],
310 description: 'changed = staged + unstaged + untracked; files = the whole files listed in `files`',
311 },
312 files: {
313 type: 'array',
314 items: { type: 'string' },
315 description: 'Paths or globs relative to the folder holding .agents/, or absolute; for target files',
316 },
317 trait: {
318 type: 'string',
319 description: 'Check one trait only, by name, or group/name for a grouped trait (for example project/no_default_exports)',
320 },
321 path: {
322 type: 'string',
323 description:
324 'A folder or file inside the repository to check, absolute or relative to the session folder. ' +
325 'Needed when the session was opened above the repository; defaults to the session folder.',
326 },
327 },
328 required: ['target'],
329 },
330 isDeferred: false,
331 })
332 return next(e)
333 })
334
335 on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit'] }, async ($, e, next) => {
336 const ran = await next(e)
337 if (options.check_edits === false || ran.deny !== undefined || ran.isError) return ran
338 if ((ran.result as { staged?: boolean } | undefined)?.staged) return ran
339 const feedback = await checkEdit($, options, e).catch((error: unknown) => {
340 report($, `jev: ${errorText(error)}; edit not checked`)
341 return undefined
342 })
343 return feedback ? { ...ran, context: [...(ran.context ?? []), feedback] } : ran
344 }).catch(($, e, next) => next(e))
345
346 on('tool.call', { tool: CHECK_TOOL }, async ($, e) => {
347 const input = e as unknown as { target?: unknown; files?: unknown; trait?: unknown; path?: unknown }
348 const target = TARGETS.find(one => one === input.target) ?? 'changed'
349 const files = Array.isArray(input.files) ? input.files.filter((f): f is string => typeof f === 'string') : []
350 const trait = typeof input.trait === 'string' && input.trait ? input.trait : undefined
351 const path = typeof input.path === 'string' && input.path ? input.path : undefined
352 const text = await checkTarget($, options, target, files, trait, path).catch(
353 (error: unknown) => `jev-traits could not check: ${errorText(error)}`,
354 )
355 return { result: text }
356 }).catch(() => ({ result: 'jev-traits could not check: the check did not finish in time.' }))
357
358 on('command.run', { command: 'traits' }, async ($, e) => {
359 const [sub, ...rest] = e.args.trim().split(/\s+/).filter(Boolean)
360 if (sub !== 'check') return { text: await summary($, options) }
361 const { target, files } = targetFrom(rest)
362 const text = await checkTarget($, options, target, files).catch(
363 (error: unknown) => `jev-traits could not check: ${errorText(error)}`,
364 )
365 return { text }
366 })
367}
368hooks/check.ts 205 lines1export const TRAITS_DIR = '.agents/traits'
2export const KEYCHAIN_SERVICE = 'typesafe-api-key'
3export const DEFAULT_MODEL = 'jev-latest'
4
5export const TARGETS = ['changed', 'staged', 'unstaged', 'untracked', 'files'] as const
6export type Target = (typeof TARGETS)[number]
7
8export const SKIP = new RegExp(
9 `(^|/)(\\.git|node_modules|${TRAITS_DIR.replace('.', '\\.')})/|` +
10 '(^|/)(package-lock\\.json|bun\\.lockb?|pnpm-lock\\.yaml|yarn\\.lock|Cargo\\.lock|uv\\.lock|poetry\\.lock)$',
11)
12
13export type ChangeKind = 'edit' | 'write'
14export type Verdict = 'fix' | 'check' | 'unsure' | 'pass'
15export type Probabilities = {
16 readonly compliant: number
17 readonly violation: number
18 readonly 'not-applicable': number
19 readonly inconclusive: number
20}
21export type Judgment = {
22 readonly trait: { readonly id: string; readonly title: string }
23 readonly path: string
24 readonly line?: number
25 readonly probabilities: Probabilities
26 readonly verdict: Verdict
27}
28export type Skip = {
29 readonly path: string
30 readonly trait: string
31 readonly line: number
32 readonly bytes: number
33 readonly maxBytes: number
34}
35export type Review = {
36 readonly judgments: Judgment[]
37 readonly skipped: Skip[]
38 readonly verdicts: Readonly<Record<Verdict, number>>
39 readonly files: number
40 readonly requests: number
41 readonly ms: number
42}
43export type Settings = {
44 readonly model: string
45 readonly fix: number
46 readonly check: number
47 readonly pass: number
48}
49
50export const dirOf = (path: string) => path.slice(0, Math.max(path.lastIndexOf('/'), 0)) || '/'
51
52export const relativeTo = (root: string, path: string) =>
53 path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path
54
55export const traitFile = (id: string) => `${TRAITS_DIR}/${id}.md`
56
57export function settingsFrom(options: Readonly<Record<string, unknown>>): Settings {
58 const fraction = (value: unknown, fallback: number) =>
59 typeof value === 'number' && value >= 0 && value <= 1 ? value : fallback
60 return {
61 model: typeof options.model === 'string' && options.model.trim() ? options.model.trim() : DEFAULT_MODEL,
62 fix: fraction(options.fix_threshold, 0.8),
63 check: fraction(options.check_threshold, 0.5),
64 pass: fraction(options.pass_threshold, 0.9),
65 }
66}
67
68// A traits.ts that exports a fixed decision-model Layer rejects --model, so the
69// default model is left to the CLI.
70export function settingsArgs(settings: Settings): string[] {
71 return [
72 ...(settings.model === DEFAULT_MODEL ? [] : ['--model', settings.model]),
73 '--fix-threshold', String(settings.fix),
74 '--check-threshold', String(settings.check),
75 '--pass-threshold', String(settings.pass),
76 '--fail-on', 'never',
77 '--json',
78 '--quiet',
79 ]
80}
81
82export function editArgs(rel: string, kind: ChangeKind, settings: Settings): string[] {
83 return ['check', '--stdin', '--stdin-filepath', rel, '--kind', kind, ...settingsArgs(settings)]
84}
85
86export function targetArgs(
87 root: string,
88 target: Target,
89 files: readonly string[],
90 settings: Settings,
91 traitId?: string,
92): string[] {
93 const selection =
94 target === 'files'
95 ? files.flatMap(file => ['--include', file.startsWith('/') ? file : `${root}/${file}`])
96 : ['--target', target]
97 return ['check', '--path', root, ...selection, ...(traitId ? ['--trait', traitId] : []), ...settingsArgs(settings)]
98}
99
100export function targetFrom(args: readonly string[]): { target: Target; files: string[] } {
101 const named = TARGETS.find(one => one === args[0] && one !== 'files')
102 if (named) return { target: named, files: [] }
103 return args.length > 0 ? { target: 'files', files: [...args] } : { target: 'changed', files: [] }
104}
105
106type CliFinding = {
107 trait: { name: string; purpose?: string }
108 source: { location?: { _tag: string; path?: string; startLine?: number } }
109 assessment: { probabilities: Probabilities; verdict: Verdict }
110}
111type CliSkip = { path: string; trait: string; startLine: number; bytes: number; maxBytes: number }
112type CliReport = {
113 findings: CliFinding[]
114 skipped: CliSkip[]
115 summary: { files: number; requests: number; verdicts: Record<Verdict, number> }
116}
117
118export function reviewFrom(root: string, stdout: string, ms: number): Review {
119 const report = JSON.parse(stdout) as CliReport
120 return {
121 judgments: report.findings.map(finding => {
122 const location = finding.source.location
123 const file = location?._tag === 'File' ? location : undefined
124 return {
125 trait: { id: finding.trait.name, title: finding.trait.purpose ?? finding.trait.name },
126 path: file?.path ? relativeTo(root, file.path) : '(generated)',
127 ...(file?.startLine === undefined ? {} : { line: file.startLine }),
128 probabilities: finding.assessment.probabilities,
129 verdict: finding.assessment.verdict,
130 }
131 }),
132 skipped: report.skipped.map(skip => ({
133 path: relativeTo(root, skip.path),
134 trait: skip.trait,
135 line: skip.startLine,
136 bytes: skip.bytes,
137 maxBytes: skip.maxBytes,
138 })),
139 verdicts: report.summary.verdicts,
140 files: report.summary.files,
141 requests: report.summary.requests,
142 ms,
143 }
144}
145
146export const judged = (review: Review) =>
147 review.verdicts.fix + review.verdicts.check + review.verdicts.unsure + review.verdicts.pass
148
149export function failureText(stderr: string): string {
150 const line = stderr.split('\n').map(text => text.trim()).find(Boolean) ?? 'traits failed'
151 return line.length > 200 ? `${line.slice(0, 199)}…` : line
152}
153
154export const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`
155
156const VERDICT_ORDER = { fix: 0, check: 1, unsure: 2, pass: 3 } as const
157const MAX_SKIP_LINES = 20
158
159export function formatReport(target: Target, settings: Settings, result: Review): string {
160 const flagged = result.judgments
161 .filter(j => j.verdict === 'fix' || j.verdict === 'check')
162 .sort(
163 (a, b) =>
164 a.path.localeCompare(b.path) || (a.line ?? 0) - (b.line ?? 0) || VERDICT_ORDER[a.verdict] - VERDICT_ORDER[b.verdict],
165 )
166 const unsure = result.judgments.filter(j => j.verdict === 'unsure')
167 const status =
168 flagged.length > 0 ? 'violations' : unsure.length > 0 || result.skipped.length > 0 ? 'inconclusive' : 'pass'
169 const lines = [
170 `jev-traits ${target}: ${status} · ${plural(judged(result), 'judgment')} over ${plural(result.files, 'file')}` +
171 ` · ${plural(result.requests, 'request')} · ${result.ms} ms · ${settings.model}` +
172 (result.skipped.length > 0 ? ` · ${result.skipped.length} skipped as too large` : ''),
173 ]
174 let heading = ''
175 for (const j of flagged) {
176 const at = j.line === undefined ? j.path : `${j.path}:${j.line}`
177 if (at !== heading) {
178 heading = at
179 lines.push(heading)
180 }
181 lines.push(` ${j.verdict.padEnd(6)} ${j.trait.id} p(violation) ${j.probabilities.violation.toFixed(2)}: ${j.trait.title}`)
182 }
183 if (unsure.length > 0) {
184 lines.push('Unsure, Jev lacked context:')
185 const byPath = new Map<string, Judgment[]>()
186 for (const j of unsure) byPath.set(j.path, [...(byPath.get(j.path) ?? []), j])
187 for (const [path, judgments] of [...byPath].sort(([a], [b]) => a.localeCompare(b)))
188 lines.push(` ${path}: ${judgments.length} (${[...new Set(judgments.map(j => j.trait.id))].sort().join(', ')})`)
189 }
190 if (result.skipped.length > 0) {
191 lines.push('Skipped as too large, not checked:')
192 for (const skip of result.skipped.slice(0, MAX_SKIP_LINES))
193 lines.push(` ${skip.path}:${skip.line} ${skip.trait} (${skip.bytes}/${skip.maxBytes} bytes)`)
194 if (result.skipped.length > MAX_SKIP_LINES) lines.push(` … and ${result.skipped.length - MAX_SKIP_LINES} more`)
195 }
196 if (flagged.length > 0 || unsure.length > 0) {
197 const traitFiles = new Set([...flagged, ...unsure].map(j => traitFile(j.trait.id)))
198 lines.push(`Trait files: ${[...traitFiles].join(', ')}`)
199 lines.push(
200 'These are fast model judgments. Read the trait and the code before changing anything, and report unsure results as unsure, not as passes.',
201 )
202 }
203 return lines.join('\n')
204}
205