fix(setup): preserve skill files and report rollback failures
Track attempted writes, preserve original content and modes from one regular-file observation, and continue rollback after individual failures. Return tagged failure details and retained backup paths through setup. Validation: setup filesystem and recovery tests, combined compile/typecheck/lint/format/metadata/architecture checks. Filesystem fault injection covers backup, ambiguous publication, and rollback failures.
This commit is contained in:
+183
-46
@@ -2,10 +2,15 @@ import { copyFile, lstat, mkdir, readFile, rm } from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
RegularFileChangedError,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { withRegularFile } from "./RegularFileRead.js";
|
||||
import { clientSkillDirectories } from "./SupportedClients.js";
|
||||
|
||||
export const MANAGED_SKILL_FILES = [
|
||||
@@ -23,14 +28,119 @@ export const isManagedSkillManifest = (content: string): boolean =>
|
||||
content.startsWith(`---\r\nname: ${PRODUCT_IDENTITY.skillName}\r\n`);
|
||||
|
||||
export const readSkillFile = (path: string): Promise<string> =>
|
||||
readRegularFileText(path, { symlinks: "reject" });
|
||||
readSkillFileState(path).then(({ content }) => content);
|
||||
|
||||
interface SkillFileState {
|
||||
readonly content: string;
|
||||
readonly mode: number;
|
||||
}
|
||||
|
||||
const readSkillFileState = async (path: string): Promise<SkillFileState> =>
|
||||
withRegularFile(
|
||||
path,
|
||||
async (handle, stats) => {
|
||||
const bytes = await readBoundedFileBytes(
|
||||
handle,
|
||||
stats.size,
|
||||
undefined,
|
||||
stats.size,
|
||||
);
|
||||
if (bytes === undefined || bytes.length !== stats.size)
|
||||
throw new RegularFileChangedError(path);
|
||||
return { content: bytes.toString("utf8"), mode: stats.mode & 0o7777 };
|
||||
},
|
||||
{ symlinks: "reject" },
|
||||
);
|
||||
|
||||
interface CanonicalSkillFile {
|
||||
readonly content: string;
|
||||
readonly destination: string;
|
||||
readonly original: string | undefined;
|
||||
readonly original: SkillFileState | undefined;
|
||||
}
|
||||
|
||||
export interface SkillInstallFileOperations {
|
||||
readonly mkdir: (path: string) => Promise<void>;
|
||||
readonly backup: (source: string, destination: string) => Promise<void>;
|
||||
readonly write: (
|
||||
path: string,
|
||||
content: string,
|
||||
mode: number,
|
||||
) => Promise<void>;
|
||||
readonly remove: (path: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface SkillInstallRollbackFailure {
|
||||
readonly path: string;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
/** Expected failure while replacing a managed skill bundle. */
|
||||
export class SetupSkillInstallError extends Error {
|
||||
readonly _tag = "SetupSkillInstallError";
|
||||
readonly path: string;
|
||||
readonly stage: "prepare" | "backup" | "write" | "readback";
|
||||
readonly reason: string;
|
||||
readonly rollbackFailures: readonly SkillInstallRollbackFailure[];
|
||||
readonly recoveryBackupPaths: readonly string[];
|
||||
|
||||
constructor(input: {
|
||||
readonly path: string;
|
||||
readonly stage: "prepare" | "backup" | "write" | "readback";
|
||||
readonly reason: string;
|
||||
readonly rollbackFailures: readonly SkillInstallRollbackFailure[];
|
||||
readonly recoveryBackupPaths: readonly string[];
|
||||
readonly cause: unknown;
|
||||
}) {
|
||||
const message = [
|
||||
`REA skill ${input.stage} failed at ${input.path}: ${input.reason}.`,
|
||||
...(input.rollbackFailures.length === 0
|
||||
? []
|
||||
: [
|
||||
`Rollback also failed for ${input.rollbackFailures.map(({ path, reason }) => `${path} (${reason})`).join(", ")}.`,
|
||||
...(input.recoveryBackupPaths.length === 0
|
||||
? []
|
||||
: [
|
||||
`Existing-file backups remain at ${input.recoveryBackupPaths.join(", ")}.`,
|
||||
]),
|
||||
]),
|
||||
].join(" ");
|
||||
super(message, { cause: input.cause });
|
||||
this.path = input.path;
|
||||
this.stage = input.stage;
|
||||
this.reason = input.reason;
|
||||
this.rollbackFailures = input.rollbackFailures;
|
||||
this.recoveryBackupPaths = input.recoveryBackupPaths;
|
||||
}
|
||||
|
||||
get remediation(): string {
|
||||
return `${this.message} Check permissions and rerun setup.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type SkillInstallValue = "installed" | "unchanged";
|
||||
export type SkillInstallResult = Result<
|
||||
SkillInstallValue,
|
||||
SetupSkillInstallError
|
||||
>;
|
||||
|
||||
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;
|
||||
}
|
||||
},
|
||||
write: (path, content, mode) =>
|
||||
writeFileAtomic(path, content, { encoding: "utf8", mode }),
|
||||
remove: (path) => rm(path, { force: true }),
|
||||
};
|
||||
|
||||
/** Managed skill location selected for a client family. */
|
||||
export interface SkillDestination {
|
||||
readonly client: string;
|
||||
@@ -87,9 +197,11 @@ export const existingSkillDestinations = async (
|
||||
return existing;
|
||||
};
|
||||
|
||||
const readOptionalText = async (path: string): Promise<string | undefined> => {
|
||||
const readOptionalSkillState = async (
|
||||
path: string,
|
||||
): Promise<SkillFileState | undefined> => {
|
||||
try {
|
||||
return await readSkillFile(path);
|
||||
return await readSkillFileState(path);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return undefined;
|
||||
@@ -117,7 +229,7 @@ const canonicalSkillFiles = async (
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
original: await readOptionalText(destination),
|
||||
original: await readOptionalSkillState(destination),
|
||||
};
|
||||
}),
|
||||
),
|
||||
@@ -133,7 +245,7 @@ export const canonicalSkillNeedsInstall = async (
|
||||
try {
|
||||
return (
|
||||
await canonicalSkillFiles(home, clientIds, environment, platform)
|
||||
).some(({ content, original }) => original !== content);
|
||||
).some(({ content, original }) => original?.content !== content);
|
||||
} catch (cause: unknown) {
|
||||
// Unreadable skill state fails open to install so setup can repair it.
|
||||
void cause;
|
||||
@@ -141,39 +253,42 @@ export const canonicalSkillNeedsInstall = async (
|
||||
}
|
||||
};
|
||||
|
||||
const writeText = (path: string, content: string): Promise<void> =>
|
||||
writeFileAtomic(path, content, { encoding: "utf8", mode: 0o600 });
|
||||
const causeReason = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
const preserveSkillBackup = async (
|
||||
source: string,
|
||||
destination: string,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await copyFile(source, destination, fsConstants.COPYFILE_EXCL);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
|
||||
return;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
const causePath = (cause: unknown): string | undefined =>
|
||||
cause instanceof Error && "path" in cause && typeof cause.path === "string"
|
||||
? cause.path
|
||||
: undefined;
|
||||
|
||||
const restoreSkillFiles = async (
|
||||
changed: readonly CanonicalSkillFile[],
|
||||
): Promise<void> => {
|
||||
for (const { destination, original } of [...changed].reverse()) {
|
||||
if (original === undefined) await rm(destination, { force: true });
|
||||
else await writeText(destination, original);
|
||||
attempted: readonly CanonicalSkillFile[],
|
||||
operations: SkillInstallFileOperations,
|
||||
): Promise<readonly SkillInstallRollbackFailure[]> => {
|
||||
const failures: SkillInstallRollbackFailure[] = [];
|
||||
for (const { destination, original } of [...attempted].reverse()) {
|
||||
try {
|
||||
if (original === undefined) await operations.remove(destination);
|
||||
else await operations.write(destination, original.content, original.mode);
|
||||
} catch (cause: unknown) {
|
||||
failures.push({ path: destination, reason: causeReason(cause) });
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
};
|
||||
|
||||
/** Transactionally install or upgrade the canonical REA skill and references. */
|
||||
/** Transactionally install the canonical skill bundle and optional references. */
|
||||
export const installCanonicalSkill = async (
|
||||
home: string,
|
||||
clientIds: readonly string[] = [],
|
||||
environment: Readonly<NodeJS.ProcessEnv> = {},
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Promise<"installed" | "unchanged" | "failed"> => {
|
||||
let changed: readonly CanonicalSkillFile[] = [];
|
||||
operations: SkillInstallFileOperations = systemSkillInstallFileOperations,
|
||||
): Promise<SkillInstallResult> => {
|
||||
let attempted: CanonicalSkillFile[] = [];
|
||||
let stage: "prepare" | "backup" | "write" | "readback" = "prepare";
|
||||
let failingPath = "skill bundle";
|
||||
try {
|
||||
const canonical = await canonicalSkillFiles(
|
||||
home,
|
||||
@@ -181,30 +296,52 @@ export const installCanonicalSkill = async (
|
||||
environment,
|
||||
platform,
|
||||
);
|
||||
changed = canonical.filter(({ content, original }) => original !== content);
|
||||
if (changed.length === 0) return "unchanged";
|
||||
const changed = canonical.filter(
|
||||
({ content, original }) => original?.content !== content,
|
||||
);
|
||||
if (changed.length === 0) return ok("unchanged");
|
||||
|
||||
stage = "backup";
|
||||
for (const { destination, original } of changed) {
|
||||
await mkdir(dirname(destination), { recursive: true });
|
||||
failingPath = destination;
|
||||
await operations.mkdir(dirname(destination));
|
||||
if (original !== undefined)
|
||||
await preserveSkillBackup(destination, `${destination}.rea.backup`);
|
||||
await operations.backup(destination, `${destination}.rea.backup`);
|
||||
}
|
||||
for (const { destination, content } of changed)
|
||||
await writeText(destination, content);
|
||||
for (const { destination, content } of changed)
|
||||
stage = "write";
|
||||
for (const file of changed) {
|
||||
failingPath = file.destination;
|
||||
// An atomic writer can publish and then reject; include the target before
|
||||
// entering it so rollback covers that ambiguous outcome.
|
||||
attempted.push(file);
|
||||
await operations.write(
|
||||
file.destination,
|
||||
file.content,
|
||||
file.original?.mode ?? 0o600,
|
||||
);
|
||||
}
|
||||
stage = "readback";
|
||||
for (const { destination, content } of changed) {
|
||||
failingPath = destination;
|
||||
if ((await readSkillFile(destination)) !== content)
|
||||
throw new Error(`skill readback mismatch: ${destination}`);
|
||||
return "installed";
|
||||
} catch (cause: unknown) {
|
||||
// Install failure preserves the original error outcome; report cause inline.
|
||||
void cause;
|
||||
try {
|
||||
await restoreSkillFiles(changed);
|
||||
} catch (restoreCause: unknown) {
|
||||
// Per-file backups remain beside changed files for operator recovery.
|
||||
void restoreCause;
|
||||
}
|
||||
return "failed";
|
||||
return ok("installed");
|
||||
} catch (cause: unknown) {
|
||||
failingPath = causePath(cause) ?? failingPath;
|
||||
const rollbackFailures = await restoreSkillFiles(attempted, operations);
|
||||
return err(
|
||||
new SetupSkillInstallError({
|
||||
path: failingPath,
|
||||
stage,
|
||||
reason: causeReason(cause),
|
||||
rollbackFailures,
|
||||
recoveryBackupPaths: attempted.flatMap(({ destination, original }) =>
|
||||
original === undefined ? [] : [`${destination}.rea.backup`],
|
||||
),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user