Repository navigation
Expand file tree
/
Copy pathfirst-pass-lib.mjs
More file actions
439 lines (397 loc) · 14.5 KB
/
Copy pathfirst-pass-lib.mjs
File metadata and controls
439 lines (397 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import {
closeSync,
constants,
fstatSync,
lstatSync,
openSync,
readSync,
realpathSync,
} from 'node:fs';
import { isAbsolute, join, resolve, sep } from 'node:path';
const GENERATORS = Object.freeze({
deepseek: Object.freeze({
id: 'deepseek',
label: 'DeepSeek',
url: 'https://www.deepseek.com/',
modelPattern: /deepseek/i,
transports: new Set(['anthropic-messages']),
}),
claude: Object.freeze({
id: 'claude',
label: 'Claude',
url: 'https://www.anthropic.com/claude',
modelPattern: /(?:^|[-_/])claude(?:$|[-_/])/i,
transports: new Set(['anthropic-messages']),
}),
codex: Object.freeze({
id: 'codex',
label: 'OpenAI Codex',
url: 'https://developers.openai.com/codex/',
modelPattern: /(?:^|[-_/])codex(?:$|[-_/])/i,
transports: new Set(['openai-responses-codex']),
}),
});
function inferGenerator(modelName) {
const matches = Object.values(GENERATORS).filter((item) => item.modelPattern.test(modelName));
if (matches.length !== 1) {
throw new Error(`Cannot infer generator from model ${modelName}`);
}
return matches[0].id;
}
export function resolveGeneratorAttribution(rawId, rawModelName, transport) {
const modelName = String(rawModelName || '').trim();
if (!modelName) throw new Error('A model id is required for generator attribution');
const id = String(rawId || inferGenerator(modelName)).trim().toLowerCase();
const generator = GENERATORS[id];
if (!generator) throw new Error(`Unsupported generator: ${id}`);
if (!generator.modelPattern.test(modelName)) {
throw new Error(`Model ${modelName} does not match configured generator ${id}`);
}
if (!generator.transports.has(transport)) {
const required = [...generator.transports].join(' or ');
throw new Error(`Generator ${id} requires transport ${required}; received ${transport}`);
}
return Object.freeze({
id: generator.id,
label: generator.label,
url: generator.url,
transport,
modelName,
automaticFooter:
`🤖 Generated by [${generator.label}](${generator.url}) ` +
'as an automated first pass — not a maintainer decision.',
});
}
function visibleLine(rawLine) {
let line = rawLine.trim();
let previous;
do {
previous = line;
line = line
.replace(/^>\s?/, '')
.replace(/^(?:[-+*]|\d+[.)])\s+/, '')
.replace(/^`{3,}[a-z0-9_-]*\s*/i, '')
.trim();
} while (line !== previous);
return line
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
.replace(/[*_~`]/g, '')
.replace(/^🤖\s*/u, '')
.trim()
.toLowerCase();
}
function isSpoofLine(line) {
const visible = visibleLine(line);
return /^(?:automated first-pass|generated (?:with|by)|this is model-generated\b.*not (?:a )?maintainer decision)/iu.test(visible);
}
function isOrphanable(line) {
return /^\s*(?:---+|`{3,}[a-z0-9_-]*)?\s*$/i.test(line);
}
function sanitizeUntrustedBody(rawReply) {
const lines = String(rawReply || '').replace(/\r\n?/g, '\n').split('\n');
const removed = lines.map(isSpoofLine);
for (let index = 0; index < removed.length; index += 1) {
if (!removed[index]) continue;
for (const direction of [-1, 1]) {
let adjacent = index + direction;
while (adjacent >= 0 && adjacent < lines.length && isOrphanable(lines[adjacent])) {
removed[adjacent] = true;
adjacent += direction;
}
}
}
return lines
.filter((_, index) => !removed[index])
.join('\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
export function formatAutomatedComment(reply, { kind, generator }) {
if (!['reply', 'review'].includes(kind)) {
throw new Error(`Unsupported first-pass kind: ${kind}`);
}
if (!generator?.automaticFooter) {
throw new Error('A trusted generator attribution is required');
}
const body = sanitizeUntrustedBody(reply);
if (!body) throw new Error('Cannot format an empty first-pass body');
const suffix = ['---', generator.automaticFooter].join('\n');
const comment = [
`🤖 Automated first-pass ${kind}`,
'',
body,
'',
suffix,
].join('\n');
const markers = comment.match(/generated\s+(?:with|by)/giu) ?? [];
if (markers.length !== 1 || !comment.endsWith(suffix)) {
throw new Error('Trusted first-pass attribution invariant failed');
}
return comment;
}
const ALLOWED_ROOT_FILES = new Set([
'AGENTS.md', 'ARCHITECTURE.md', 'CLAUDE.md', 'CONTRIBUTING.md',
'CHANGELOG.md', 'package.json', 'tsconfig.json',
]);
const ALLOWED_SOURCE_EXTENSION = /\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|ya?ml|txt)$/i;
const DENIED_COMPONENT = /^(?:\..+|(?:auth|oauth|token|credentials?|secrets?)(?:\..*)?|.*\.(?:pem|key|p12|pfx))$/i;
function normalizedRepoPath(raw) {
const value = String(raw || '').trim();
if (!value || value.includes('\0')) return null;
const normalized = value.replace(/\\/g, '/');
if (/^[a-z]:\//i.test(normalized) || isAbsolute(normalized) || normalized.startsWith('/')) {
return null;
}
const components = normalized.split('/');
if (components.some((component) => !component || component === '.' || component === '..')) {
return null;
}
return normalized;
}
export function isAllowedRepoPath(raw) {
const normalized = normalizedRepoPath(raw);
if (!normalized) return false;
const components = normalized.split('/');
if (components.some((component) => DENIED_COMPONENT.test(component))) return false;
if (ALLOWED_ROOT_FILES.has(normalized)) return true;
return components[0] === 'src' && components.length > 1 && ALLOWED_SOURCE_EXTENSION.test(normalized);
}
function containedWithin(root, candidate) {
return candidate === root || candidate.startsWith(`${root}${sep}`);
}
function boundedOption(value, hardMaximum) {
if (!Number.isInteger(value) || value <= 0) return hardMaximum;
return Math.min(value, hardMaximum);
}
function decodeCompleteUtf8(buffer) {
const decoder = new TextDecoder('utf-8', { fatal: true });
for (let end = buffer.length; end >= Math.max(0, buffer.length - 4); end -= 1) {
try {
return { text: decoder.decode(buffer.subarray(0, end)), bytes: end };
} catch {
// A byte budget may cut the final UTF-8 code point; backtrack at most 4 bytes.
}
}
return null;
}
export function createRepoReadSession(options = {}) {
const repoRoot = realpathSync(resolve(String(options.repoRoot || process.cwd())));
const maxFiles = boundedOption(options.maxFiles, 6);
const fileBudget = boundedOption(options.fileBudget, 16_000);
const totalBudget = boundedOption(options.totalBudget, 60_000);
const seenPaths = new Set();
let filesRead = 0;
let totalBytes = 0;
function read(wanted) {
const files = [];
for (const raw of Array.isArray(wanted) ? wanted : []) {
const relativePath = normalizedRepoPath(raw);
if (!relativePath || seenPaths.has(relativePath) || !isAllowedRepoPath(relativePath)) continue;
seenPaths.add(relativePath);
if (filesRead >= maxFiles || totalBytes >= totalBudget) break;
let descriptor;
try {
const lexicalPath = resolve(repoRoot, relativePath);
if (!containedWithin(repoRoot, lexicalPath)) continue;
let prefix = repoRoot;
let leafStat;
for (const component of relativePath.split('/')) {
prefix = join(prefix, component);
const currentStat = lstatSync(prefix);
if (currentStat.isSymbolicLink()) {
leafStat = null;
break;
}
leafStat = currentStat;
}
if (!leafStat?.isFile()) continue;
const realFile = realpathSync(lexicalPath);
if (!containedWithin(repoRoot, realFile)) continue;
descriptor = openSync(lexicalPath, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
const openedStat = fstatSync(descriptor);
if (
!openedStat.isFile() ||
openedStat.dev !== leafStat.dev ||
openedStat.ino !== leafStat.ino
) continue;
const remaining = totalBudget - totalBytes;
const requestedBytes = Math.min(fileBudget, remaining);
if (requestedBytes <= 0) break;
const buffer = Buffer.alloc(requestedBytes);
const bytesRead = readSync(descriptor, buffer, 0, requestedBytes, 0);
const decoded = decodeCompleteUtf8(buffer.subarray(0, bytesRead));
if (!decoded) continue;
filesRead += 1;
totalBytes += decoded.bytes;
files.push({
path: relativePath,
text: decoded.text,
bytes: decoded.bytes,
});
} catch {
// Missing, unreadable, replaced, or unsafe files are skipped without path disclosure.
} finally {
if (descriptor !== undefined) {
try {
closeSync(descriptor);
} catch {
// Nothing useful can be done if closing an already-failed descriptor fails.
}
}
}
}
return {
text: files.map((file) => `# ${file.path}\n${file.text}`).join('\n\n'),
files,
totalBytes,
};
}
return Object.freeze({
read,
snapshot: () => Object.freeze({ filesRead, totalBytes }),
});
}
export function validateFirstPassEnvironment(env) {
const required = ['GH_TOKEN', 'REPO', 'EVENT_KIND', 'ITEM_NUMBER', 'ANTHROPIC_API_KEY'];
const missing = required.filter((name) => !String(env?.[name] || '').trim());
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
const repo = String(env.REPO).trim();
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) {
throw new Error('REPO must use owner/name format');
}
const eventKind = String(env.EVENT_KIND).trim();
if (!['issue', 'pr'].includes(eventKind)) {
throw new Error('EVENT_KIND must be issue or pr');
}
const itemNumber = Number(env.ITEM_NUMBER);
if (!Number.isInteger(itemNumber) || itemNumber <= 0) {
throw new Error('ITEM_NUMBER must be a positive integer');
}
if (eventKind === 'pr' && !String(env.DIFF_FILE || '').trim()) {
throw new Error('DIFF_FILE is required for pull requests');
}
const [owner, name] = repo.split('/');
return Object.freeze({
owner,
repo: name,
itemNumber,
isPr: eventKind === 'pr',
diffFile: eventKind === 'pr' ? String(env.DIFF_FILE).trim() : undefined,
});
}
function tag(text, name) {
const match = String(text || '').match(new RegExp(`<${name}>([\\s\\S]*?)<\\/${name}>`, 'i'));
return match ? match[1].trim() : null;
}
export function parseFirstPassResponse(raw) {
const text = String(raw || '');
const taggedReply = tag(text, 'reply');
const fallback = text.replace(/<control>[\s\S]*?<\/control>/i, '').trim();
const reply = (taggedReply !== null ? taggedReply : fallback).trim();
let control = { answerable: true, want_files: [] };
const taggedControl = tag(text, 'control');
if (taggedControl) {
try {
const value = JSON.parse(taggedControl);
control = {
answerable: value.answerable !== false,
want_files: Array.isArray(value.want_files) ? value.want_files : [],
};
} catch {
// Malformed control never grants additional file reads.
}
}
return { reply, ...control };
}
export function needsProFirstPass(parsed) {
return parsed?.answerable === false || String(parsed?.reply || '').trim() === '';
}
export function formatFirstPassFallback({ kind, isChinese = false }) {
if (!['reply', 'review'].includes(kind)) {
throw new Error(`Unsupported first-pass kind: ${kind}`);
}
const subject = kind === 'reply' ? 'issue' : 'pull request';
const lines = [
`🤖 Automated first-pass ${kind}`,
'',
`The configured analysis model did not return a usable analysis for this ${subject}. ` +
'The item has still been received and remains available for maintainer review.',
'',
kind === 'reply'
? 'To help with triage, please ensure the extension, VS Code, and operating-system versions plus anonymous diagnostic logs are included.'
: 'To help with review, please ensure the change summary, tests, and any user-facing documentation or localization updates are included.',
];
if (isChinese) {
lines.push(
'',
`自动分析服务没有为这个${kind === 'reply' ? '问题' : '拉取请求'}返回可用结果。` +
'该条目已经成功收到,维护者仍可继续审阅。',
'',
kind === 'reply'
? '为便于排查,请确认已提供扩展、VS Code、操作系统版本以及匿名诊断日志。'
: '为便于审阅,请确认已提供改动摘要、测试结果,以及必要的文档和本地化更新。',
);
}
lines.push(
'',
'---',
'🤖 Posted automatically by CCU Bot — not a maintainer decision.',
);
return lines.join('\n');
}
export function hasTrustedFirstPass(comments, kind) {
if (!['reply', 'review'].includes(kind)) return false;
const marker = `🤖 Automated first-pass ${kind}`;
return Array.isArray(comments) && comments.some((comment) =>
comment?.user?.login === 'github-actions[bot]' &&
String(comment?.body || '').trimStart().startsWith(marker)
);
}
export async function resolveFirstPassCandidates({ cheap, pro, onFailure = () => {} }) {
let cheapCandidate;
try {
cheapCandidate = await cheap();
if (!String(cheapCandidate?.reply || '').trim()) {
onFailure({ tier: 'cheap', reason: 'empty-reply' });
} else if (cheapCandidate.answerable === false) {
onFailure({ tier: 'cheap', reason: 'needs-source' });
}
} catch (error) {
onFailure({ tier: 'cheap', reason: safeFailureReason(error) });
cheapCandidate = null;
}
let proCandidate;
if (!cheapCandidate || needsProFirstPass(cheapCandidate)) {
try {
proCandidate = await pro(cheapCandidate);
if (!String(proCandidate?.reply || '').trim()) {
onFailure({ tier: 'pro', reason: 'empty-reply' });
}
} catch (error) {
onFailure({ tier: 'pro', reason: safeFailureReason(error) });
proCandidate = null;
}
}
try {
return chooseFinalReply(cheapCandidate, proCandidate);
} catch {
return null;
}
}
function safeFailureReason(error) {
const status = error?.status;
return Number.isInteger(status) && status >= 400 && status <= 599
? `http-${status}`
: 'request-error';
}
export function chooseFinalReply(cheap, pro) {
if (pro && typeof pro.reply === 'string' && pro.reply.trim() !== '') {
return { reply: pro.reply.trim(), generator: pro.generator };
}
if (cheap?.answerable !== false && typeof cheap?.reply === 'string' && cheap.reply.trim() !== '') {
return { reply: cheap.reply.trim(), generator: cheap.generator };
}
throw new Error('No non-empty model reply');
}