返回 CodeWhale
review-adapter.ts
根目录 / crates / engine / extension-host / src / builtin / shared / review-adapter.ts
1 /** Presentation of immutable Core review facts. No provider, I/O, pass or publication authority. */
2 import { isJson } from '../../json.ts'
3
4 type Row = Record<string, unknown>
5 interface Result { ok: true; result: { content: string; success: true; metadata: null } }
6 export const REVIEW_LIMIT = 16 * 1024 * 1024
7 const OPERATIONS = ['review_source_prompt', 'review_pass_prompt', 'review_interactive_pr', 'review_report']
8 export function isReviewOperation(value: unknown): value is string { return typeof value === 'string' && OPERATIONS.includes(value) }
9 export function reviewEnvelopeBytes(value: unknown): number { return 8 + Buffer.byteLength(`{"jsonrpc":"2.0","id":18446744073709551615,"result":${JSON.stringify(value)}}`) }
10 function row(value: unknown): Row { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('invalid Core review snapshot'); return value as Row }
11 function text(value: unknown): string { if (typeof value !== 'string') throw new Error('invalid Core review text'); return value }
12 function bool(value: unknown): boolean { if (typeof value !== 'boolean') throw new Error('invalid Core review flag'); return value }
13 function integer(value: unknown): number { if (!Number.isSafeInteger(value) || (value as number) < 0) throw new Error('invalid Core review count'); return value as number }
14 function list(value: unknown): unknown[] { if (!Array.isArray(value)) throw new Error('invalid Core review list'); return value }
15 function optional(value: unknown): string | undefined { return value === null || value === undefined ? undefined : text(value) }
16 function trim(value: string): string { return value.replace(/^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, '') }
17 function lines(value: string): string[] {
18 if (!value.length) return []
19 const out = value.split('\n')
20 if (value.endsWith('\n')) out.pop()
21 return out.map((line, i) => (i < out.length - 1 || value.endsWith('\n')) && line.endsWith('\r') ? line.slice(0, -1) : line)
22 }
23 function skipped(value: unknown): string { return list(value).map(value => { const skip = row(value); return `${text(skip.file)} (${integer(skip.chars)} chars; ${text(skip.reason)})` }).join(', ') }
24 function ordered(value: unknown): unknown {
25 if (Array.isArray(value)) return value.map(ordered)
26 if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => [key, ordered(value)]))
27 return value
28 }
29 function intent(value: unknown): string {
30 const commits = value === undefined ? '' : text(value)
31 return commits.trim() ? `The author's commit messages for this range follow. They state what the change is meant to do; check them against the diff rather than trusting them.\n\n${commits}\n\nEnd of commit messages.\n\n` : ''
32 }
33 function source(input: Row): string {
34 const kind = text(input.kind)
35 if (kind === 'file') {
36 const content = lines(text(input.content)).map((line, i) => `${String(i + 1).padStart(4)} | ${line}`).join('\n')
37 return `Review the following file and provide feedback.\nPath: ${text(input.display)}\n\n${content}\n\nEnd of file.`
38 }
39 if (kind === 'diff') return `Review the following ${text(input.label)} and provide feedback.\n\n${text(input.diff)}\n\nEnd of diff.`
40 if (kind === 'cli_diff') return `${intent(input.commits)}Review the following diff and provide feedback:\n\n${text(input.diff)}\n\nEnd of diff.`
41 if (kind === 'pr') return `Review the complete pull request diff (${text(input.label)}) at head ${text(input.head_sha)} and base ${text(input.base_sha)}. Binary changes are represented by metadata; their contents are not semantically inspected. Exact binary object IDs remain in the review evidence.\n\n${text(input.diff)}\n\nEnd of diff.`
42 throw new Error('unadmitted review source')
43 }
44 function pass(input: Row): string {
45 const manifest = row(input.manifest), part = row(input.pass), view = row(input.view)
46 const scope = list(manifest.skipped_files).length === 0
47 ? 'Review only defects introduced in this pass.'
48 : `Review only defects introduced in this pass. This is a partial review (pass ${integer(part.number)} of ${list(manifest.passes).length}): the gate did not read ${skipped(manifest.skipped_files)}. Do not claim full coverage.`
49 const task = `${scope} Use supplementary source to check surrounding guards and declarations. If the prompt omits relevant caller bodies and read-only tools are offered, inspect those callers with the tools. Anchor findings to the commentable diff and scope coverage claims to the pass manifest. Binary changes are represented by metadata. No build or tests have been run.`
50 if (!isJson(input.context)) throw new Error('invalid Core review context')
51 const prompt = {task, untrusted_repository_data: true, pull_request: {number: integer(input.number), title: text(view.title), description: text(view.body)}, manifest, pass: part, diff: text(input.diff), repository_context: input.context,
52 context_limit: 'Context is bounded supplementary excerpts from the exact head. Null means no source context could fit. Missing files or omitted lines are not evidence of a defect.'}
53 return JSON.stringify(bool(input.sort_keys) ? ordered(prompt) : prompt)
54 }
55 function interactive(input: Row): string {
56 const view = row(input.view), number = integer(input.number)
57 const base = text(view.base), head = text(view.head)
58 const branches = base && head ? `${base} ← ${head}` : base || head || '(unknown)'
59 return `Review PR #${number} — ${trim(text(view.title)) || `(PR #${number})`}\n\nURL: ${text(view.url) || '(unavailable)'}\nBranches: ${branches}\nRevision: ${text(view.head_sha)} (base ${text(view.base_sha)}); ${integer(view.changed_files)} file patches.\nBinary changes are represented by metadata; their contents are not semantically inspected. Exact binary object IDs remain in the review evidence.\n\n## Description\n\n${trim(text(view.body)) || '(no description)'}\n\n## Diff\n\n\`\`\`diff\n${text(input.diff)}\n\`\`\`\n`
60 }
61 function fence(value: string): string { let longest = 0, run = 0; for (const char of value) { run = char === '`' ? run + 1 : 0; longest = Math.max(longest, run) } return '`'.repeat(Math.max(3, longest + 1)) }
62 function location(value: Row): string {
63 const path = optional(value.path)
64 return path === undefined ? '' : value.line === null || value.line === undefined ? `\`${trim(path)}\`` : `\`${trim(path)}:${integer(value.line)}\``
65 }
66 function report(input: Row): string {
67 if (input.review === null) return text(input.output)
68 const review = row(input.review), posted = bool(input.posted)
69 let out = '## Codewhale review\n\n'
70 const summary = text(review.summary), assessment = text(review.overall_assessment)
71 if (summary.length) out += trim(summary) + '\n\n'
72 const issues = list(review.issues), suggestions = list(review.suggestions)
73 if (issues.length) {
74 out += '### Findings\n\n'
75 for (const item of issues) {
76 const issue = row(item), at = location(issue)
77 out += `- **[${text(issue.severity).toUpperCase()}] ${text(issue.title)}**${at ? ` (${at})` : ''}\n`
78 const description = text(issue.description)
79 if (description.length) out += ` ${description}\n`
80 }
81 out += '\n'
82 }
83 if (suggestions.length) {
84 out += '### Suggestions\n\n'
85 for (const item of suggestions) {
86 const suggestion = row(item), at = location(suggestion)
87 out += `- ${at ? `${at} — ` : ''}${text(suggestion.suggestion)}\n`
88 const replacement = optional(suggestion.replacement)
89 if (replacement !== undefined && trim(replacement).length) {
90 const codeFence = fence(replacement)
91 out += `\n ${codeFence}${posted ? 'diff' : 'suggestion'}\n`
92 for (const line of replacement.split('\n')) out += ` ${line}\n`
93 out += ` ${codeFence}\n`
94 }
95 }
96 out += '\n'
97 }
98 if (assessment.length) out += '### Assessment\n\n' + trim(assessment) + '\n\n'
99 const tally = {blocker: 0, concern: 0, nit: 0, introduced: 0, preexisting: 0}
100 for (const item of issues) {
101 const issue = row(item), severity = text(issue.severity)
102 if (severity === 'blocker') tally.blocker += 1
103 else if (severity === 'concern') tally.concern += 1
104 else if (severity === 'nit') tally.nit += 1
105 if (optional(issue.authorship) === 'preexisting') tally.preexisting += 1
106 else tally.introduced += 1
107 }
108 out += `<!-- codewhale-review: {"blocker":${tally.blocker},"concern":${tally.concern},"nit":${tally.nit},"introduced":${tally.introduced},"preexisting":${tally.preexisting}} -->\n`
109 return out
110 }
111 export function transformReviewSnapshot(operation: string, value: unknown): Result {
112 if (!isReviewOperation(operation)) throw new Error('unadmitted review operation')
113 const input = row(value)
114 const content = operation === 'review_source_prompt' ? source(input) : operation === 'review_pass_prompt' ? pass(input) : operation === 'review_interactive_pr' ? interactive(input) : report(input)
115 const result: Result = {ok: true, result: {content, success: true, metadata: null}}
116 // Same upper-bound JSON-RPC envelope as Core; limits include escaping and headers.
117 if (reviewEnvelopeBytes(result) > REVIEW_LIMIT) throw new Error('serialized review result exceeds 16 MiB')
118 return result
119 }
120
120 lines TYPESCRIPT