"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("../../../src/utils");
const diff_1 = require("diff");
const tools_1 = require("../../../src/agents/tools");
const agents_1 = require("../../../src/agents");
const services_1 = require("../../../src/services");
const list_1 = require("../../../src/agents/tools/list");
const allTools = __importStar(require("../../../src/agents/tools"));
const inputPath = "tests/integration/patching/input.txt";
const outputPath = "tests/integration/patching/output.txt";
const patchPath = "tests/integration/patching/patch.txt";
const brokenPatch = `Index: tests/integration/patching/input.txt
===================================================================
--- tests/integration/patching/input.txt
+++ tests/integration/patching/input.txt
@@ -116,9 +116,9 @@
         // Add the tool responses to the thread
         messages.push(
           ...(toolMessages as Array<ChatCompletionToolMessageParam>)
         );
-        const finalMessage = toolMessages.find((m) => m.name === "finalAnswer");
+        const finalMessage = toolMessages.find((m) => m.name === "FinalAnswer");
         if (finalMessage) {
           return finalMessage.content;
         }
       }\n`;
describe("Patcher", () => {
    let Agents, Tools;
    beforeAll(async () => {
        const { Patcher } = (0, agents_1.agents)();
        ({ Agents, Tools } = (0, services_1.services)());
        Agents.registerAgent(Patcher);
        Tools.addTools(list_1.includedTools);
        const toolFunctions = Object.entries(allTools)
            .filter(([_, value]) => typeof value === "function")
            .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
        Tools.addFunctions(toolFunctions);
    });
    test("should be able to apply actual patch", async () => {
        const oldString = (await (0, utils_1.readFile)(inputPath)).toString();
        const newString = (await (0, utils_1.readFile)(outputPath)).toString();
        const workingPatch = (await (0, utils_1.readFile)(patchPath)).toString();
        const applied = await (0, diff_1.applyPatch)(oldString, patchPath);
        expect(applied).toBe(oldString);
        const workingApply = (0, diff_1.applyPatch)(oldString, workingPatch);
        expect(workingApply).toBe(newString);
        console.log({
            brokenPatch: Buffer.from(brokenPatch),
            workingPatch: Buffer.from(workingPatch),
        });
        const buffer1 = Buffer.from(brokenPatch);
        const buffer2 = Buffer.from(workingPatch);
        console.log("bufferLength", buffer1.length, buffer2.length);
        const length = Math.max(buffer1.length, buffer2.length);
        for (let i = 0; i < length; i++) {
            if (buffer1[i] !== buffer2[i]) {
                console.log("not equal", i, buffer1[i], buffer2[i]);
            }
        }
        expect(brokenPatch).toBe(workingPatch);
    });
    test("should generate the diff", async () => {
        const oldString = (await (0, utils_1.readFile)(inputPath)).toString();
        const newString = (await (0, utils_1.readFile)(outputPath)).toString();
        const patch = (0, diff_1.createPatch)(inputPath, oldString, newString);
        await (0, utils_1.writeFile)(patchPath, patch);
        console.log(patch);
        const scanned = await (0, tools_1.scanFile)(inputPath, 120, 120);
        console.log(JSON.parse(scanned));
        expect(patch).toBe(brokenPatch);
    });
    test("should be able to patch a codebase", async () => {
        const originalText = (await (0, utils_1.readFile)(inputPath)).toString();
        console.log(await Agents.callAgent("Patcher", `Update the file in ${inputPath} change the string "finalAnswer" to "FinalAnswer", as we are changing the tool name to be FinalAnswer instead of finalAnswer. This should be around line 120. Do not modify anything else. Treat this file as a typescript file. Only try one patch. If it fails stop`));
        const updatedText = (await (0, utils_1.readFile)(inputPath)).toString();
        await (0, utils_1.writeFile)(inputPath, originalText);
        expect(updatedText).toBe(originalText.replace(`"finalAnswer"`, `"FinalAnswer"`));
    });
    it("should be able to patch when given the answer", async () => {
        const originalText = (await (0, utils_1.readFile)(inputPath)).toString();
        await Agents.callAgent("Patcher", `Update the file in ${inputPath} change the string "finalAnswer" to "FinalAnswer" on line 120. Do not modify anything else. Heres the answer: ${brokenPatch}.`);
        const updatedText = (await (0, utils_1.readFile)(inputPath)).toString();
        await (0, utils_1.writeFile)(inputPath, originalText);
        expect(updatedText).toBe(originalText.replace(`"finalAnswer"`, `"FinalAnswer"`));
    });
    test("should be able to update the unseen file", async () => {
        const unseenPath = "tests/integration/patching/unseen.txt";
        const originalText = (await (0, utils_1.readFile)(unseenPath)).toString();
        await Agents.callAgent("Patcher", `Update the file in ${unseenPath} change the file additions and deletions count from 200 to 300. Do not modify anything else. Treat this file as a typescript file.`);
        const updatedText = (await (0, utils_1.readFile)(unseenPath)).toString();
        await (0, utils_1.writeFile)(unseenPath, originalText);
        expect(updatedText).toBe(originalText.replaceAll("200", "300"));
    });
});
//# sourceMappingURL=patching.test.js.map