src/apply.js
// Applies a plan built by src/engine.js. This is the only module that changes files. Rules:
// - every operation is re-checked immediately before it runs (paths, links, and that sources and
// overwrite/append targets still match what the plan saw; otherwise it stops with plan_changed);
// - new files are created with the exclusive "wx" flag, so an existing file is never replaced by
// a create; copies use COPYFILE_EXCL; a move first checks that the destination does not exist;
// - overwrites (only with if_exists "overwrite") write a temporary file next to the target and
// rename it over the target, so a failure never leaves a half-written file;
// - nothing is ever deleted: there is no delete operation, and the only removal is of this run's
// own temporary file after a failed overwrite;
// - folders are created one level at a time, never through links.
import { writeFileSync, appendFileSync, renameSync, copyFileSync, mkdirSync, lstatSync, rmSync, readFileSync, constants } from "node:fs";
import { join, dirname, basename } from "node:path";
import { createHash, randomBytes } from "node:crypto";
import { ToolError } from "./errors.js";
import { inspectTarget, inspectSource, folderChain, absOf, pathKey, checkWritableName } from "./fsguard.js";
const sha256 = (b) => createHash("sha256").update(b).digest("hex");
function ensureFolder(root, rel, field) {
const segs = rel.split("/");
const missingParents = folderChain(root, segs.slice(0, -1), field); // every existing parent must be a real folder, not a link
if (missingParents.length) throw new ToolError("plan_changed", `${field}: the folder ${missingParents[0]} should exist by now but does not.`);
const abs = absOf(root, rel);
let st = null;
try {
st = lstatSync(abs);
} catch {
/* missing */
}
if (st?.isSymbolicLink()) throw new ToolError("unsafe_path", `${field}: ${rel} is now a link; nothing is written through links.`);
if (st && !st.isDirectory()) throw new ToolError("plan_changed", `${field}: ${rel} now exists and is not a folder.`);
if (!st) mkdirSync(abs);
return st ? "already existed" : "created";
}
function removeOwnTemp(path) {
try {
rmSync(path, { force: true });
} catch {
/* best effort: the temporary file has a .workflow-<random>.tmp name next to the target */
}
}
function runOne(root, op) {
const field = `operation ${op.index} (${op.op} ${op.path})`;
switch (op.op) {
case "create_folder":
return ensureFolder(root, op.path, field);
case "write_file": {
checkWritableName(op.path, field); // re-checked at apply time
const t = inspectTarget(root, op.path, field);
if (t.missingFolders.length) throw new ToolError("plan_changed", `${field}: the folder ${t.missingFolders[0]} does not exist.`);
if (op.mode === "create") {
if (t.exists) throw new ToolError("plan_changed", `${field}: ${op.path} appeared after the plan was made; it was not replaced.`);
writeFileSync(t.abs, op._content, { flag: "wx" });
return "created";
}
if (op.mode === "overwrite") {
if (!t.exists) throw new ToolError("plan_changed", `${field}: ${op.path} no longer exists.`);
const now = readFileSync(t.abs);
if (sha256(now) !== op.before_sha256) throw new ToolError("plan_changed", `${field}: ${op.path} changed after the plan was made; it was not overwritten.`);
const temp = join(dirname(t.abs), `.${basename(t.abs)}.workflow-${randomBytes(6).toString("hex")}.tmp`);
try {
writeFileSync(temp, op._content, { flag: "wx" });
renameSync(temp, t.abs);
} catch (e) {
removeOwnTemp(temp);
throw e;
}
return "overwritten";
}
// append
if (!t.exists) {
if (!op.after_planned_write && op.before_bytes !== undefined) throw new ToolError("plan_changed", `${field}: ${op.path} no longer exists.`);
writeFileSync(t.abs, op._content, { flag: "wx" });
return "created";
}
if (!op.after_planned_write) {
if (t.size !== op.before_bytes || t.mtimeMs !== op.before_mtime_ms) throw new ToolError("plan_changed", `${field}: ${op.path} changed after the plan was made; nothing was appended.`);
if (t.nlink > 1) throw new ToolError("unsafe_path", `${field}: ${op.path} has several hard links; nothing was appended.`);
}
appendFileSync(t.abs, op._content, { flag: "a" });
return "appended";
}
case "move_file":
case "copy_file": {
checkWritableName(op.path, field);
const s = inspectSource(root, op.from, field);
if (s.size !== op.bytes) throw new ToolError("plan_changed", `${field}: ${op.from} changed after the plan was made.`);
const t = inspectTarget(root, op.path, field);
if (t.missingFolders.length) throw new ToolError("plan_changed", `${field}: the folder ${t.missingFolders[0]} does not exist.`);
if (op.op === "copy_file") {
copyFileSync(s.abs, t.abs, constants.COPYFILE_EXCL);
return "copied";
}
if (t.exists && !(op.case_only && pathKey(op.from) === pathKey(op.path))) throw new ToolError("plan_changed", `${field}: ${op.path} appeared after the plan was made; it was not replaced.`);
renameSync(s.abs, t.abs);
return "moved";
}
default:
throw new ToolError("internal_error", `Unknown operation ${op.op}.`);
}
}
/** Applies planned operations in order. Stops at the first failure (nothing is rolled back or deleted). */
export function applyOperations(root, ops, tick) {
const results = [];
for (const op of ops) {
if (op.status !== "planned") {
results.push({ index: op.index, op: op.op, path: op.path, from: op.from ?? null, status: op.status === "unchanged" ? "unchanged" : "skipped", detail: op.reason ?? null });
continue;
}
try {
tick();
const detail = runOne(root, op);
results.push({ index: op.index, op: op.op, path: op.path, from: op.from ?? null, status: "done", detail });
} catch (e) {
const done = results.filter((r) => r.status === "done");
const list = done.slice(0, 15).map((r) => `${r.op} ${r.from ? `${r.from} -> ` : ""}${r.path}`).join("; ");
const reason = e instanceof ToolError ? e.message : `${e.code ?? "error"}: ${e.message}`;
throw new ToolError(e instanceof ToolError && e.code === "plan_changed" ? "plan_changed" : "apply_failed", `Stopped at operation ${op.index} of ${ops.length} (${op.op} ${op.from ? `${op.from} -> ` : ""}${op.path}): ${reason} ${done.length} operation(s) completed before this${done.length ? `: ${list}${done.length > 15 ? "; ..." : ""}` : ""}. Nothing was rolled back or deleted; run plan_recipe again to see the current state.`);
}
}
return results;
}