Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(setup): retain skill recovery backup cleanup ownership

morlutoeba64e9386a8
diff --git a/src/application/SetupRecoveryBackup.ts b/src/application/SetupRecoveryBackup.ts
index 6e2de2fd1..f457582d9 100644
--- a/src/application/SetupRecoveryBackup.ts
+++ b/src/application/SetupRecoveryBackup.ts
@@ -113,15 +113,19 @@ export const preserveCurrentRecoveryBackup = async (
);
if (!selection.ok) return selection;
const { backupPath } = selection.value;
- try {
- await copy(source, backupPath);
- } catch (cause: unknown) {
- if (!(cause instanceof Error && "code" in cause && cause.code === "EEXIST"))
- return err({
- kind: "copy",
- path: backupPath,
- detail: `The recovery backup could not be written: ${errorDetail(cause)}`,
- });
+ if (!selection.value.present) {
+ try {
+ await copy(source, backupPath);
+ } catch (cause: unknown) {
+ if (
+ !(cause instanceof Error && "code" in cause && cause.code === "EEXIST")
+ )
+ return err({
+ kind: "copy",
+ path: backupPath,
+ detail: `The recovery backup could not be written: ${errorDetail(cause)}`,
+ });
+ }
}
const verified = await selectCurrentRecoveryBackup(
firstBackupPath,
diff --git a/src/application/SetupSkill.ts b/src/application/SetupSkill.ts
index 9a5e200e4..87adb71ab 100644
--- a/src/application/SetupSkill.ts
+++ b/src/application/SetupSkill.ts
@@ -17,7 +17,7 @@ import {
withRegularFile,
} from "./RegularFileRead.js";
import { clientSkillDirectories } from "./SupportedClients.js";
-import { selectCurrentRecoveryBackup } from "./SetupRecoveryBackup.js";
+import { preserveCurrentRecoveryBackup } from "./SetupRecoveryBackup.js";
export const MANAGED_SKILL_FILES = [
"SKILL.md",
@@ -153,15 +153,8 @@ const systemSkillInstallFileOperations: SkillInstallFileOperations = {
mkdir: async (path) => {
await mkdir(path, { recursive: true });
},
- backup: async (source, destination) => {
- try {
- await copyFile(source, destination, fsConstants.COPYFILE_EXCL);
- } catch (cause: unknown) {
- if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
- return;
- throw cause;
- }
- },
+ backup: (source, destination) =>
+ copyFile(source, destination, fsConstants.COPYFILE_EXCL),
write: (path, content, mode) =>
writeFileAtomic(path, content, { encoding: "utf8", mode }),
remove: (path) => rm(path, { force: true }),
@@ -513,32 +506,6 @@ const restoreSkillFiles = async (
return failures;
};
-const preserveCurrentSkillBackup = async (
- destination: string,
- original: Buffer,
- operations: SkillInstallFileOperations,
-): Promise<string> => {
- const firstBackupPath = `${destination}.rea.backup`;
- const selection = await selectCurrentRecoveryBackup(
- firstBackupPath,
- original,
- );
- if (!selection.ok) throw new Error(selection.error.detail);
- if (selection.value.present) return selection.value.backupPath;
-
- await operations.backup(destination, selection.value.backupPath);
- const verified = await selectCurrentRecoveryBackup(firstBackupPath, original);
- if (
- !verified.ok ||
- verified.value.backupPath !== selection.value.backupPath ||
- !verified.value.present
- )
- throw new Error(
- `The current file was not preserved at ${selection.value.backupPath}`,
- );
- return verified.value.backupPath;
-};
-
/** Transactionally install the canonical skill bundle and optional references. */
export const installCanonicalSkill = async (
home: string,
@@ -571,14 +538,17 @@ export const installCanonicalSkill = async (
failingPath = destination;
await operations.mkdir(dirname(destination));
if (original !== undefined) {
- recoveryPaths.set(
+ const preserved = await preserveCurrentRecoveryBackup(
+ `${destination}.rea.backup`,
destination,
- await preserveCurrentSkillBackup(
- destination,
- original.bytes,
- operations,
- ),
+ original.bytes,
+ {
+ copy: operations.backup,
+ ...(resources === undefined ? {} : { resources }),
+ },
);
+ if (!preserved.ok) throw new Error(preserved.error.detail);
+ recoveryPaths.set(destination, preserved.value);
}
}
stage = "write";
diff --git a/tests/boundary/filesystem/setupSkill.test.ts b/tests/boundary/filesystem/setupSkill.test.ts
index fae651cc7..9cedb03e5 100644
--- a/tests/boundary/filesystem/setupSkill.test.ts
+++ b/tests/boundary/filesystem/setupSkill.test.ts
@@ -46,6 +46,31 @@ const expectPermissionMode = async (
};
describe("skill recovery backup selection", () => {
+ it("reuses a verified existing backup without copying it again", async () => {
+ const home = await createTestTempDirectory("rea-skill-matching-backup-");
+ const [destination] = skillDestinations(home, []);
+ if (destination === undefined) throw new Error("Missing shared skill root");
+ const manifest = join(destination.path, "SKILL.md");
+ const current = "currently installed instructions\n";
+ await mkdir(dirname(manifest), { recursive: true });
+ await writeFile(manifest, current);
+ await writeFile(`${manifest}.rea.backup`, current);
+ const result = await installCanonicalSkill(home, [], {}, process.platform, {
+ mkdir: async (path) =>
+ mkdir(path, { recursive: true }).then(() => undefined),
+ backup: async () => {
+ throw new Error("A matching backup must not be copied again");
+ },
+ write: (path, content, mode) =>
+ writeFileAtomic(path, content, { encoding: "utf8", mode }),
+ remove: async (path) => rm(path, { force: true }),
+ });
+
+ expect(result).toEqual({ ok: true, value: "installed" });
+ expect(await readFile(`${manifest}.rea.backup`, "utf8")).toBe(current);
+ expect(await canonicalSkillNeedsInstall(home, [])).toBe(false);
+ });
+
it("advertises a current recovery snapshot when the first backup is historical", async () => {
const home = await createTestTempDirectory("rea-skill-historical-backup-");
const [destination] = skillDestinations(home, []);
diff --git a/tests/boundary/filesystem/setupSkillCleanupOwnership.test.ts b/tests/boundary/filesystem/setupSkillCleanupOwnership.test.ts
index 4ca9ea407..0a2799ba4 100644
--- a/tests/boundary/filesystem/setupSkillCleanupOwnership.test.ts
+++ b/tests/boundary/filesystem/setupSkillCleanupOwnership.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import {
mkdir,
open as fsOpen,
@@ -68,6 +69,58 @@ const failFirstCloses = (path: string) => {
};
describe("skill regular-file cleanup ownership", () => {
+ it.each(["first", "recovery", "verification"] as const)(
+ "retains a failed %s backup read until setup host disposal",
+ async (stage) => {
+ const home = await createTestTempDirectory(
+ "rea-setup-skill-backup-close-",
+ );
+ const [destination] = skillDestinations(home, [], {}, "linux");
+ if (destination === undefined)
+ throw new Error("Shared skill root missing");
+ const manifest = join(destination.path, "SKILL.md");
+ const original = "stale managed skill\n";
+ const firstBackup = `${manifest}.rea.backup`;
+ const backup =
+ stage === "recovery"
+ ? `${firstBackup}.${createHash("sha256").update(original).digest("hex")}.recovery`
+ : firstBackup;
+ await mkdir(dirname(manifest), { recursive: true });
+ await writeFile(manifest, original);
+ if (stage === "recovery")
+ await writeFile(firstBackup, "historical skill\n");
+ if (stage !== "verification") await writeFile(backup, original);
+ const close = failFirstCloses(backup);
+ const host = systemSetupHost(
+ { platform: "linux", homeDirectory: home } as DoctorHost,
+ { HOME: home },
+ );
+
+ try {
+ const result = await host.installSkill([]);
+ expect(result).toMatchObject({ ok: false, error: { stage: "backup" } });
+ expect(close.attempts.length).toBeGreaterThan(0);
+ expect(new Set(close.attempts).size).toBe(1);
+ const opensBeforeAdmission = openMock.mock.calls.length;
+ expect((await host.installSkill([])).ok).toBe(false);
+ expect(openMock).toHaveBeenCalledTimes(opensBeforeAdmission);
+ expect(new Set(close.attempts).size).toBe(1);
+ expect(await actualFs.readFile(manifest, "utf8")).toBe(original);
+ expect(await host.close?.()).toContain(backup);
+ const attemptsBeforeClose = close.attempts.length;
+ close.release();
+ expect(await host.close?.()).toBeUndefined();
+ expect(close.attempts.length).toBeGreaterThan(attemptsBeforeClose);
+ expect(close.attempts[0]?.fd).toBe(-1);
+ } finally {
+ close.release();
+ await host.close?.();
+ // Reclaim the real test descriptor even when the retention regression fails.
+ for (const handle of new Set(close.attempts)) await handle.close();
+ }
+ },
+ );
+
it("retains a failed setup skill read until setup host disposal", async () => {
const home = await createTestTempDirectory("rea-setup-skill-close-");
const [destination] = skillDestinations(home, [], {}, "linux");