39 lines
1.9 KiB
JavaScript
39 lines
1.9 KiB
JavaScript
"use strict";
|
|
|
|
const { createHash } = require("node:crypto");
|
|
const fileHashPattern = /^[a-f0-9]{64}$/;
|
|
|
|
function hashAgentFile(text) {
|
|
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
}
|
|
|
|
function applyAgentFileEdit(current, oldText, newText, maxBytes, { targetedOnly = false } = {}) {
|
|
if (typeof current !== "string" || typeof oldText !== "string" || typeof newText !== "string" || (!oldText && !newText)) {
|
|
return { error: "review_edit_invalid" };
|
|
}
|
|
if (!oldText && current !== "") return { error: "review_edit_not_found" };
|
|
const offset = current.indexOf(oldText);
|
|
if (offset === -1) return { error: "review_edit_not_found" };
|
|
if (offset !== current.lastIndexOf(oldText)) return { error: "review_edit_ambiguous" };
|
|
if (oldText && oldText !== newText && (targetedOnly || /[\r\n]/.test(current.trim())) && oldText.trim() === current.trim()) {
|
|
return { error: "review_edit_whole_file" };
|
|
}
|
|
const content = current.slice(0, offset) + newText + current.slice(offset + oldText.length);
|
|
if (!content && current) return { error: "review_edit_whole_file" };
|
|
if (Buffer.byteLength(content, "utf8") > maxBytes) return { error: "review_edit_too_large" };
|
|
return { content, offset };
|
|
}
|
|
|
|
function revertAgentFileEdit(current, edit, snapshot, maxBytes) {
|
|
if (!snapshot || !fileHashPattern.test(snapshot.afterSha256) || !Number.isSafeInteger(snapshot.offset) || snapshot.offset < 0) {
|
|
return { error: "review_revert_unavailable" };
|
|
}
|
|
const { offset } = snapshot;
|
|
if (hashAgentFile(current) !== snapshot.afterSha256 || offset > current.length || !current.startsWith(edit.newText, offset)) {
|
|
return { error: "review_revert_changed" };
|
|
}
|
|
const content = current.slice(0, offset) + edit.oldText + current.slice(offset + edit.newText.length);
|
|
return Buffer.byteLength(content, "utf8") <= maxBytes ? { content } : { error: "review_edit_too_large" };
|
|
}
|
|
|
|
module.exports = { hashAgentFile, applyAgentFileEdit, revertAgentFileEdit }; |