feat: add project index and exact patch review
This commit is contained in:
+47
-8
@@ -10,6 +10,11 @@ const secretName = /(^|\/)(\.env($|\.)|id_rsa($|\.)|id_ed25519($|\.)|credentials
|
||||
const normalize = value => process.platform === 'win32' ? value.toLowerCase() : value;
|
||||
const inside = (root, target) => normalize(target) === normalize(root) || normalize(target).startsWith(normalize(root + path.sep));
|
||||
|
||||
export function excludedFromInventory(relative) {
|
||||
const portable = relative.replaceAll('\\', '/');
|
||||
return secretName.test(portable) || portable.split('/').some(part => ignored.has(part.toLowerCase()) || part.startsWith('.awb-'));
|
||||
}
|
||||
|
||||
export function safePath(project, relative = '', allowMissing = false) {
|
||||
if (typeof relative !== 'string' || relative.includes('\0') || relative.includes(':') || path.isAbsolute(relative) || path.win32.isAbsolute(relative)) throw new Error('路径必须相对于项目文件夹。');
|
||||
const portable = relative.replaceAll('\\', '/');
|
||||
@@ -43,7 +48,7 @@ export function listFiles(project, relative = '', depth = 4, limit = 700) {
|
||||
const entries = fs.readdirSync(current.absolute, { withFileTypes: true })
|
||||
.sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
||||
for (const entry of entries) {
|
||||
if (ignored.has(entry.name) || entry.name.startsWith('.awb-') || secretName.test(entry.name)) continue;
|
||||
if (excludedFromInventory(entry.name)) continue;
|
||||
const absolute = path.join(current.absolute, entry.name);
|
||||
const relativePath = path.relative(project.root, absolute).replaceAll('\\', '/');
|
||||
if (entry.isSymbolicLink()) continue;
|
||||
@@ -65,7 +70,7 @@ export function readText(project, relative) {
|
||||
const bytes = fs.readFileSync(target);
|
||||
if (bytes.includes(0)) throw new Error('这是二进制文件,无法作为文本打开。');
|
||||
const text = new TextDecoder('utf8', { fatal: true }).decode(bytes);
|
||||
return { path: relative, content: text, sha256: hash(bytes), bytes: bytes.length };
|
||||
return { path: relative, content: text, sha256: hash(bytes), bytes: bytes.length, bom: bytes.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) };
|
||||
}
|
||||
|
||||
export function readLines(project, args) {
|
||||
@@ -74,7 +79,7 @@ export function readLines(project, args) {
|
||||
const start = Math.max(1, Number(args.start_line) || 1);
|
||||
const end = Math.min(lines.length, start + 299, Math.max(start, Number(args.end_line) || start + 199));
|
||||
return { path: file.path, start_line: start, end_line: end, total_lines: lines.length,
|
||||
content: lines.slice(start - 1, end).join('\n'), sha256: file.sha256, truncated: start > 1 || end < lines.length };
|
||||
content: lines.slice(start - 1, end).join('\n'), sha256: file.sha256, bom: file.bom, truncated: start > 1 || end < lines.length };
|
||||
}
|
||||
|
||||
export function searchFiles(project, args) {
|
||||
@@ -103,7 +108,7 @@ export function searchFiles(project, args) {
|
||||
scope: '有数量/体积上限的文本搜索;无结果不表示所有文件都已搜索。' };
|
||||
}
|
||||
|
||||
export function proposeFile(store, session, args) {
|
||||
export function proposeFile(store, session, args, { patch = null } = {}) {
|
||||
if (typeof args.path !== 'string' || typeof args.content !== 'string') throw new Error('文件提案需要文本路径和完整文本内容。');
|
||||
const project = store.project(session.projectId);
|
||||
const target = safePath(project, args.path, true);
|
||||
@@ -112,13 +117,15 @@ export function proposeFile(store, session, args) {
|
||||
if (Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== (original?.sha256 ?? null)) throw Object.assign(new Error('文件已经在读取后发生变化,请重新读取并生成提案。'), { status: 409 });
|
||||
const content = String(args.content ?? '');
|
||||
if (Buffer.byteLength(content, 'utf8') > 512000) throw new Error('单次提案不能超过 512 KB。');
|
||||
if (content.includes('\0')) throw new Error('只能提出文本改动。');
|
||||
if (original?.content === content) return { status: 'unchanged', path: args.path };
|
||||
const parts = diffLines(original?.content ?? '', content);
|
||||
if (content.includes('\0') || !content.isWellFormed()) throw new Error('只能提出有效Unicode文本改动。');
|
||||
const baseContent = original ? (original.bom ? '\uFEFF' : '') + original.content : '';
|
||||
if (original && baseContent === content) return { status: 'unchanged', path: args.path };
|
||||
const parts = diffLines(baseContent, content);
|
||||
const change = {
|
||||
taskId: session.taskId ?? null, runId: session.runId ?? null,
|
||||
id: randomUUID(), path: args.path, reason: String(args.reason ?? '建议修改').slice(0, 600), status: 'pending',
|
||||
baseExists: !!original, baseSha256: original?.sha256 ?? null, baseContent: original?.content ?? '',
|
||||
baseExists: !!original, baseSha256: original?.sha256 ?? null, baseContent,
|
||||
...(patch ? { editKind: 'exact-patch', patch } : {}),
|
||||
content, sha256: hash(Buffer.from(content, 'utf8')), diff: parts, createdAt: now(),
|
||||
additions: parts.filter(part => part.added).reduce((sum, part) => sum + (part.count ?? 0), 0),
|
||||
deletions: parts.filter(part => part.removed).reduce((sum, part) => sum + (part.count ?? 0), 0),
|
||||
@@ -130,6 +137,38 @@ export function proposeFile(store, session, args) {
|
||||
additions: change.additions, deletions: change.deletions, message: '提案已保存,项目文件尚未改变。等待用户查看差异并应用。' };
|
||||
}
|
||||
|
||||
export function proposePatch(store, session, args) {
|
||||
if (typeof args.path !== 'string' || typeof args.base_sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(args.base_sha256)
|
||||
|| typeof args.reason !== 'string' || !Array.isArray(args.edits) || !args.edits.length || args.edits.length > 32) throw new Error('精确补丁需要路径、读取时的SHA256、说明和1到32个替换。');
|
||||
const original = readText(store.project(session.projectId), args.path);
|
||||
if (original.sha256 !== args.base_sha256.toLowerCase()) throw Object.assign(new Error('文件在读取后已变化,请重新读取并核对补丁锚点。'), { status: 409 });
|
||||
const lineEnding = /\r(?!\n)/.test(original.content) ? 'mixed' : original.content.includes('\r\n') ? /(^|[^\r])\n/.test(original.content) ? 'mixed' : 'crlf' : 'lf';
|
||||
const format = value => lineEnding === 'crlf' ? value.replace(/\r\n|\n/g, '\r\n') : lineEnding === 'lf' ? value.replaceAll('\r\n', '\n') : value;
|
||||
const edits = [];
|
||||
for (const edit of args.edits) {
|
||||
if (!edit || typeof edit !== 'object' || Array.isArray(edit) || typeof edit.old_text !== 'string' || !edit.old_text.length
|
||||
|| typeof edit.new_text !== 'string' || edit.old_text.includes('\0') || edit.new_text.includes('\0')
|
||||
|| !edit.old_text.isWellFormed() || !edit.new_text.isWellFormed()) throw new Error('补丁替换需要非空old_text和有效Unicode文本new_text。');
|
||||
const before = format(edit.old_text), after = format(edit.new_text), start = original.content.indexOf(before);
|
||||
if (start < 0) throw Object.assign(new Error('补丁锚点未找到;请用当前文件的实际文本重新生成。'), { status: 409 });
|
||||
if (original.content.indexOf(before, start + 1) >= 0) throw Object.assign(new Error('补丁锚点出现多次,需提供更多上下文以确定唯一位置。'), { status: 409 });
|
||||
const end = start + before.length;
|
||||
edits.push({ start, end, after, startLine: original.content.slice(0, start).split('\n').length, endLine: original.content.slice(0, end).split('\n').length,
|
||||
anchorSha256: hash(Buffer.from(before)), replacementSha256: hash(Buffer.from(after)) });
|
||||
}
|
||||
edits.sort((a, b) => a.start - b.start);
|
||||
if (edits.some((edit, index) => index > 0 && edit.start < edits[index - 1].end)) throw Object.assign(new Error('补丁替换范围重叠,请合并为一个唯一锚点后重新生成。'), { status: 409 });
|
||||
let content = original.content;
|
||||
for (let index = edits.length - 1; index >= 0; index--) content = content.slice(0, edits[index].start) + edits[index].after + content.slice(edits[index].end);
|
||||
if (content === original.content) return { status: 'unchanged', path: args.path, base_sha256: original.sha256 };
|
||||
if (original.bom) content = '\uFEFF' + content;
|
||||
const patch = { edits: edits.length, lineEnding, preservedBom: original.bom,
|
||||
ranges: edits.map(({ startLine, endLine, anchorSha256, replacementSha256 }) => ({ startLine, endLine, anchorSha256, replacementSha256 })) };
|
||||
const result = proposeFile(store, session, { path: args.path, base_sha256: original.sha256, content, reason: args.reason }, { patch });
|
||||
return { ...result, edit_kind: 'exact-patch', base_sha256: original.sha256, patch,
|
||||
message: '精确补丁已成为待审查提案;未写入项目。唯一锚点、原文件哈希与不重叠范围均已核对。' };
|
||||
}
|
||||
|
||||
export function applyChange(store, session, id) {
|
||||
const change = session.changes.find(item => item.id === id);
|
||||
if (!change || change.status !== 'pending') throw new Error('这项改动不处于待审查状态。');
|
||||
|
||||
Reference in New Issue
Block a user