




import { createHash, randomUUID } from "node:crypto";
import {
  copyFile,
  link,
  lstat,
  mkdir,
  open,
  readFile,
  readdir,
  realpath,
  rename,
  rm,
  stat,
  statfs,
  unlink,
} from "node:fs/promises";
import { constants as fsConstants, createReadStream } from "node:fs";
import { dirname, extname, isAbsolute, join, relative, sep } from "node:path";

const STORE_VERSION = 1;
const JOURNAL_FILE = "journal.json";
const DATABASE_FILE = "database.json";
const SOURCE_DIRECTORY = "source";
const OWNED_DIRECTORY = "owned";
const STEPS_DIRECTORY = "steps";
const RECEIPTS_DIRECTORY = "receipts";
const BUILDING_DIRECTORY_PATTERN = /^\.building-([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})$/;
const MAX_TRANSACTION_DIRECTORIES = 10;
const MAX_TERMINAL_RECEIPTS = 200;
const MAX_DATABASE_BYTES = 128 * 1024 * 1024;
const MAX_ATTACHMENTS = 20_000;
const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
const MAX_CREATE_BYTES = 2 * 1024 * 1024 * 1024;
const DEFAULT_DISK_RESERVE_BYTES = 256 * 1024 * 1024;
const MAX_JOURNAL_BYTES = 64 * 1024 * 1024;
const MAX_SEGMENT_LENGTH = 120;
const MAX_RELATIVE_PATH_LENGTH = 180;
const MAX_TARGET_PATH_LENGTH = 240;
const MAX_LOGICAL_DEPTH = 4;
const ACCOUNT_ID_PATTERN = /^[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/;
const TRANSACTION_ID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
const SHA256_PATTERN = /^[a-f0-9]{64}$/;
const REVERSE_PACKAGE_KIND = "central-to-employee";
const RESERVED_WINDOWS_NAME_PATTERN = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i;
const INVALID_WINDOWS_SEGMENT_PATTERN = /[<>:"\\|?*\u0000-\u001f]/;

const ERROR_MESSAGES = Object.freeze({
  PACKAGE_IMPORT_PENDING: "Najpierw dokończ poprzedni import paczki.",
  PACKAGE_IMPORT_NOT_FOUND: "Nie znaleziono oczekującego importu.",
  PACKAGE_IMPORT_ACCOUNT: "Ta transakcja nie należy do bieżącej agencji.",
  PACKAGE_IMPORT_BINDING: "Parametry transakcji nie są zgodne z zapisanym planem.",
  PACKAGE_IMPORT_STATE: "Import nie jest w stanie pozwalającym na tę operację.",
  PACKAGE_IMPORT_CONFLICT: "Nie można bezpiecznie zastosować plików tej paczki.",
  PACKAGE_IMPORT_DISK_SPACE: "Brakuje miejsca na bezpieczne zastosowanie paczki.",
  PACKAGE_IMPORT_INVALID: "Nie można bezpiecznie przygotować transakcji importu.",
  PACKAGE_IMPORT_STORE: "Nie można bezpiecznie odczytać magazynu importów.",
  PACKAGE_IMPORT_APPLY: "Nie udało się bezpiecznie zastosować paczki.",
  PACKAGE_IMPORT_PLAN_STALE: "Plan importu wymaga ponownego przygotowania paczki.",
  PACKAGE_IMPORT_VERIFY_BLOCKED: "Pliki importu wymagają bezpiecznego sprawdzenia.",
  PACKAGE_IMPORT_ROLLBACK_BLOCKED: "Nie można wycofać pliku zmienionego po imporcie.",
});

export class PackageImportTransactionError extends Error {
  constructor(code, { statusCode = 400, state = "" } = {}) {
    const safeCode = Object.hasOwn(ERROR_MESSAGES, code) ? code : "PACKAGE_IMPORT_STORE";
    super(ERROR_MESSAGES[safeCode]);
    this.name = "PackageImportTransactionError";
    this.code = safeCode;
    this.statusCode = statusCode;
    if (state === "rollback_blocked") this.state = state;
  }
}

function transactionError(code, options) {
  throw new PackageImportTransactionError(code, options);
}

function normalizeAccountId(value) {
  const normalized = String(value ?? "").trim().toUpperCase();
  return ACCOUNT_ID_PATTERN.test(normalized) ? normalized : "";
}

function pathKey(value) {
  return String(value ?? "").normalize("NFC").toUpperCase();
}

function pathIsInside(parent, candidate, allowEqual = false) {
  const value = relative(parent, candidate);
  if (!value) return allowEqual;
  return !isAbsolute(value) && value !== ".." && !value.startsWith(`..${sep}`);
}

function assertPathInside(parent, candidate, allowEqual = false) {
  if (!pathIsInside(parent, candidate, allowEqual)) {
    transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
  }
}

function normalizeLogicalAttachmentPath(pathValue, targetRoot = "") {
  if (typeof pathValue !== "string" || pathValue !== pathValue.normalize("NFC")) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  if (
    !pathValue
    || pathValue.startsWith("/")
    || pathValue.startsWith("\\")
    || pathValue.includes("\\")
    || pathValue.length > MAX_RELATIVE_PATH_LENGTH
  ) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  const segments = pathValue.split("/");
  if (
    segments.length < 2
    || segments.length > MAX_LOGICAL_DEPTH
    || segments[0] !== "Zalaczniki"
  ) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  for (const segment of segments) {
    if (
      !segment
      || segment === "."
      || segment === ".."
      || segment.length > MAX_SEGMENT_LENGTH
      || segment.endsWith(".")
      || segment.endsWith(" ")
      || INVALID_WINDOWS_SEGMENT_PATTERN.test(segment)
      || RESERVED_WINDOWS_NAME_PATTERN.test(segment)
    ) {
      transactionError("PACKAGE_IMPORT_INVALID");
    }
  }
  if (targetRoot && join(targetRoot, ...segments.slice(1)).length > MAX_TARGET_PATH_LENGTH) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  return { path: pathValue, segments };
}

function sha256(contents) {
  return createHash("sha256").update(contents).digest("hex");
}

function hashFile(filePath) {
  return new Promise((resolveHash, rejectHash) => {
    const hash = createHash("sha256");
    const input = createReadStream(filePath);
    input.on("data", (chunk) => hash.update(chunk));
    input.on("error", () => rejectHash(new PackageImportTransactionError("PACKAGE_IMPORT_APPLY")));
    input.on("end", () => resolveHash(hash.digest("hex")));
  });
}

function serializedJson(value) {
  return `${JSON.stringify(value, null, 2)}\n`;
}

export function assertPackageImportJournalSize(journal) {
  const bytes = Buffer.byteLength(serializedJson(journal), "utf8");
  if (bytes > MAX_JOURNAL_BYTES) transactionError("PACKAGE_IMPORT_INVALID");
  return bytes;
}

async function atomicWriteJson(filePath, value, { maximumBytes = 0 } = {}) {
  const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
  let handle;
  try {
    const contents = serializedJson(value);
    if (maximumBytes > 0 && Buffer.byteLength(contents, "utf8") > maximumBytes) {
      transactionError("PACKAGE_IMPORT_INVALID");
    }
    handle = await open(temporaryPath, "wx");
    await handle.writeFile(contents, "utf8");
    await handle.sync();
    await handle.close();
    handle = null;
    await rename(temporaryPath, filePath);
  } catch (error) {
    await handle?.close().catch(() => {});
    await unlink(temporaryPath).catch(() => {});
    throw error;
  }
}

async function readBoundedJson(filePath, maximumBytes, errorCode = "PACKAGE_IMPORT_STORE") {
  try {
    const fileStats = await stat(filePath);
    if (!fileStats.isFile() || fileStats.size > maximumBytes) {
      transactionError(errorCode);
    }
    return JSON.parse(await readFile(filePath, "utf8"));
  } catch (error) {
    if (error instanceof PackageImportTransactionError) throw error;
    transactionError(errorCode);
  }
}

async function ensureOrdinaryDirectory(directoryPath) {
  await mkdir(directoryPath, { recursive: true });
  const info = await lstat(directoryPath);
  if (!info.isDirectory() || info.isSymbolicLink()) {
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  return realpath(directoryPath);
}

async function findCasefoldEntry(directoryPath, desiredName) {
  let entries;
  try {
    entries = await readdir(directoryPath, { withFileTypes: true });
  } catch (error) {
    if (error?.code === "ENOENT") return null;
    transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
  }
  const desiredKey = pathKey(desiredName);
  const matches = entries.filter((entry) => pathKey(entry.name) === desiredKey);
  if (matches.length > 1) {
    transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
  }
  return matches[0] || null;
}

async function assertOrdinaryEntry(entryPath, expectedType) {
  let info;
  try {
    info = await lstat(entryPath);
  } catch (error) {
    if (error?.code === "ENOENT") return null;
    transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
  }
  if (
    info.isSymbolicLink()
    || (expectedType === "file" && !info.isFile())
    || (expectedType === "directory" && !info.isDirectory())
  ) {
    transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
  }
  return info;
}

async function resolveExistingParent(attachmentsRoot, desiredSegments) {
  let currentPath = attachmentsRoot;
  let parentExists = true;
  const actualSegments = [];
  for (const desiredSegment of desiredSegments) {
    if (!parentExists) {
      actualSegments.push(desiredSegment);
      currentPath = join(currentPath, desiredSegment);
      continue;
    }
    const entry = await findCasefoldEntry(currentPath, desiredSegment);
    if (!entry) {
      parentExists = false;
      actualSegments.push(desiredSegment);
      currentPath = join(currentPath, desiredSegment);
      continue;
    }
    const entryPath = join(currentPath, entry.name);
    await assertOrdinaryEntry(entryPath, "directory");
    const canonicalEntryPath = await realpath(entryPath);
    assertPathInside(attachmentsRoot, canonicalEntryPath, true);
    actualSegments.push(entry.name);
    currentPath = entryPath;
  }
  return {
    actualSegments,
    parentPath: currentPath,
    parentExists,
  };
}

function collisionFileName(originalName, contentHash, attempt, maximumLength) {
  const extension = extname(originalName);
  const safeExtension = extension.length <= 20 ? extension : "";
  const stem = safeExtension ? originalName.slice(0, -safeExtension.length) : originalName;
  const suffix = `--${contentHash.slice(0, 10)}${attempt > 1 ? `-${attempt}` : ""}`;
  const availableStemLength = maximumLength - suffix.length - safeExtension.length;
  if (availableStemLength < 1) transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
  return `${stem.slice(0, availableStemLength)}${suffix}${safeExtension}`;
}

function maximumCollisionNameLength(attachmentsRoot, parentSegments, parentPath) {
  const logicalPrefix = ["Zalaczniki", ...parentSegments].join("/");
  const maximumByRelative = MAX_RELATIVE_PATH_LENGTH - logicalPrefix.length - 1;
  const maximumByTarget = MAX_TARGET_PATH_LENGTH - parentPath.length - 1;
  return Math.min(MAX_SEGMENT_LENGTH, maximumByRelative, maximumByTarget);
}

async function inspectExistingFile(filePath, expectedSize, expectedHash) {
  const info = await assertOrdinaryEntry(filePath, "file");
  if (!info) return { exists: false, identical: false };
  if (info.size !== expectedSize) return { exists: true, identical: false };
  return {
    exists: true,
    identical: await hashFile(filePath) === expectedHash,
  };
}

async function chooseCollisionTarget({
  attachmentsRoot,
  parentPath,
  parentSegments,
  originalName,
  sourceHash,
  sourceSize,
  reservedTargetKeys,
  packageSourceKeys,
}) {
  const maximumLength = maximumCollisionNameLength(
    attachmentsRoot,
    parentSegments,
    parentPath,
  );
  for (let attempt = 1; attempt <= 100; attempt += 1) {
    const candidateName = collisionFileName(originalName, sourceHash, attempt, maximumLength);
    const candidateSegments = ["Zalaczniki", ...parentSegments, candidateName];
    const candidatePath = candidateSegments.join("/");
    const candidateKey = pathKey(candidatePath);
    if (reservedTargetKeys.has(candidateKey) || packageSourceKeys.has(candidateKey)) continue;
    const existingEntry = await findCasefoldEntry(parentPath, candidateName);
    if (!existingEntry) {
      return {
        action: "create",
        targetPath: candidatePath,
        renamed: true,
      };
    }
    const actualPath = join(parentPath, existingEntry.name);
    const inspection = await inspectExistingFile(actualPath, sourceSize, sourceHash);
    if (inspection.identical) {
      return {
        action: "reuse",
        targetPath: ["Zalaczniki", ...parentSegments, existingEntry.name].join("/"),
        renamed: true,
      };
    }
  }
  transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
}

function validateManifestAttachments(manifest, sourceRoot, attachmentsRoot) {
  if (!manifest || typeof manifest !== "object" || !Array.isArray(manifest.attachments)) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  if (manifest.attachments.length > MAX_ATTACHMENTS) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  const entries = [];
  const seen = new Set();
  for (const rawEntry of manifest.attachments) {
    const normalizedPath = normalizeLogicalAttachmentPath(rawEntry?.path, attachmentsRoot);
    const size = Number(rawEntry?.size);
    const contentHash = String(rawEntry?.sha256 || "");
    if (
      !Number.isSafeInteger(size)
      || size < 0
      || size > MAX_ATTACHMENT_BYTES
      || !SHA256_PATTERN.test(contentHash)
    ) {
      transactionError("PACKAGE_IMPORT_INVALID");
    }
    const key = pathKey(normalizedPath.path);
    if (seen.has(key)) transactionError("PACKAGE_IMPORT_INVALID");
    seen.add(key);
    entries.push({
      sourcePath: normalizedPath.path,
      sourceFilePath: join(sourceRoot, ...normalizedPath.segments),
      sourceSegments: normalizedPath.segments,
      size,
      sha256: contentHash,
    });
  }
  return entries;
}

async function buildFilePlan({
  sourceRoot,
  attachmentsRoot,
  manifest,
}) {
  const entries = validateManifestAttachments(manifest, sourceRoot, attachmentsRoot);
  const packageSourceKeys = new Set(entries.map((entry) => pathKey(entry.sourcePath)));
  const reservedTargetKeys = new Set();
  const plan = [];
  for (const sourceEntry of entries) {
    const sourceStats = await assertOrdinaryEntry(sourceEntry.sourceFilePath, "file");
    if (
      !sourceStats
      || sourceStats.size !== sourceEntry.size
      || await hashFile(sourceEntry.sourceFilePath) !== sourceEntry.sha256
    ) {
      transactionError("PACKAGE_IMPORT_INVALID");
    }
    const desiredTargetSegments = sourceEntry.sourceSegments.slice(1);
    const originalName = desiredTargetSegments.at(-1);
    const parent = await resolveExistingParent(
      attachmentsRoot,
      desiredTargetSegments.slice(0, -1),
    );
    const desiredParentSegments = parent.actualSegments;
    let targetDecision;
    if (!parent.parentExists) {
      targetDecision = {
        action: "create",
        targetPath: ["Zalaczniki", ...desiredParentSegments, originalName].join("/"),
        renamed: false,
      };
    } else {
      const existingEntry = await findCasefoldEntry(parent.parentPath, originalName);
      if (!existingEntry) {
        targetDecision = {
          action: "create",
          targetPath: ["Zalaczniki", ...desiredParentSegments, originalName].join("/"),
          renamed: false,
        };
      } else {
        const existingPath = join(parent.parentPath, existingEntry.name);
        const inspection = await inspectExistingFile(
          existingPath,
          sourceEntry.size,
          sourceEntry.sha256,
        );
        if (inspection.identical) {
          targetDecision = {
            action: "reuse",
            targetPath: ["Zalaczniki", ...desiredParentSegments, existingEntry.name].join("/"),
            renamed: false,
          };
        } else {
          targetDecision = await chooseCollisionTarget({
            attachmentsRoot,
            parentPath: parent.parentPath,
            parentSegments: desiredParentSegments,
            originalName,
            sourceHash: sourceEntry.sha256,
            sourceSize: sourceEntry.size,
            reservedTargetKeys,
            packageSourceKeys,
          });
        }
      }
    }
    normalizeLogicalAttachmentPath(targetDecision.targetPath, attachmentsRoot);
    const targetKey = pathKey(targetDecision.targetPath);
    if (reservedTargetKeys.has(targetKey)) {
      transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
    }
    reservedTargetKeys.add(targetKey);
    plan.push({
      action: targetDecision.action,
      sourcePath: sourceEntry.sourcePath,
      path: targetDecision.targetPath,
      size: sourceEntry.size,
      sha256: sourceEntry.sha256,
      renamed: targetDecision.renamed,
    });
  }
  return plan;
}

function rewriteDatabaseAttachmentPaths(database, plan) {
  let cloned;
  try {
    cloned = structuredClone(database);
  } catch {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  if (!cloned || typeof cloned !== "object" || !Array.isArray(cloned.policies)) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  const targetBySourceKey = new Map(plan.map((entry) => [
    pathKey(entry.sourcePath),
    entry.path,
  ]));
  let rewrittenReferences = 0;
  for (const policy of cloned.policies) {
    if (!policy || typeof policy !== "object" || !Array.isArray(policy.attachments ?? [])) {
      transactionError("PACKAGE_IMPORT_INVALID");
    }
    for (const attachment of policy.attachments || []) {
      if (attachment?.storage !== "file") continue;
      if (
        !Array.isArray(attachment.relativePath)
        || attachment.relativePath.some((segment) => (
          typeof segment !== "string" || segment.includes("/")
        ))
      ) {
        transactionError("PACKAGE_IMPORT_INVALID");
      }
      const sourcePath = attachment.relativePath.join("/");
      const targetPath = targetBySourceKey.get(pathKey(sourcePath));
      if (!targetPath) transactionError("PACKAGE_IMPORT_INVALID");
      attachment.relativePath = targetPath.split("/");
      rewrittenReferences += 1;
    }
  }
  if (plan.length > 0 && rewrittenReferences === 0) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  return cloned;
}

function journalPlanDigest(plan) {
  return sha256(JSON.stringify(plan.map((entry) => ({
    action: entry.action,
    sourcePath: entry.sourcePath,
    path: entry.path,
    size: entry.size,
    sha256: entry.sha256,
    renamed: entry.renamed,
  }))));
}

function logicalPackageDigest(manifest) {
  const databaseHash = String(manifest?.database?.sha256 || "");
  if (!SHA256_PATTERN.test(databaseHash) || !Array.isArray(manifest?.attachments)) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  const attachments = manifest.attachments.map((entry) => ({
    path: String(entry?.path || ""),
    size: Number(entry?.size),
    sha256: String(entry?.sha256 || ""),
  })).sort((left, right) => (
    left.path < right.path ? -1 : (left.path > right.path ? 1 : 0)
  ));
  if (attachments.some((entry) => (
    !entry.path
    || !Number.isSafeInteger(entry.size)
    || entry.size < 0
    || !SHA256_PATTERN.test(entry.sha256)
  ))) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  const digestContract = {
    databaseSha256: databaseHash,
    attachments,
  };
  if (manifest?.kind === REVERSE_PACKAGE_KIND) {
    const sourceAccountId = normalizeAccountId(manifest.sourceAccountId);
    const targetAccountId = normalizeAccountId(manifest.targetAccountId);
    if (
      !sourceAccountId
      || !targetAccountId
      || manifest.sourceAccountId !== sourceAccountId
      || manifest.targetAccountId !== targetAccountId
    ) {
      transactionError("PACKAGE_IMPORT_INVALID");
    }
    Object.assign(digestContract, {
      kind: REVERSE_PACKAGE_KIND,
      sourceAccountId,
      targetAccountId,
    });
  }
  return sha256(JSON.stringify(digestContract));
}

function validateJournal(journal, transactionId) {
  const reverseDirection = journal?.kind === REVERSE_PACKAGE_KIND;
  if (
    !journal
    || typeof journal !== "object"
    || Array.isArray(journal)
    || journal.version !== STORE_VERSION
    || journal.transactionId !== transactionId
    || !normalizeAccountId(journal.centralAccountId)
    || !normalizeAccountId(journal.sourceAccountId)
    || (journal.kind !== undefined && !reverseDirection)
    || (reverseDirection && (
      !normalizeAccountId(journal.targetAccountId)
      || journal.targetAccountId !== journal.centralAccountId
    ))
    || !SHA256_PATTERN.test(String(journal.baseDigest || ""))
    || !SHA256_PATTERN.test(String(journal.packageDigest || ""))
    || !SHA256_PATTERN.test(String(journal.planDigest || ""))
    || !SHA256_PATTERN.test(String(journal.rewrittenDatabaseDigest || ""))
    || !Array.isArray(journal.plan)
    || journal.plan.length > MAX_ATTACHMENTS
    || !["staged", "applying", "files_applied", "rolling_back", "apply_failed", "rollback_blocked", "confirmed", "rolled_back"].includes(journal.state)
  ) {
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  if (journalPlanDigest(journal.plan) !== journal.planDigest) {
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  return journal;
}

function transactionDirectory(storageDirectory, transactionId) {
  if (!TRANSACTION_ID_PATTERN.test(String(transactionId || ""))) {
    transactionError("PACKAGE_IMPORT_NOT_FOUND", { statusCode: 404 });
  }
  return join(storageDirectory, transactionId);
}

async function readJournal(storageDirectory, transactionId) {
  const directory = transactionDirectory(storageDirectory, transactionId);
  const journal = await readBoundedJson(
    join(directory, JOURNAL_FILE),
    MAX_JOURNAL_BYTES,
    "PACKAGE_IMPORT_NOT_FOUND",
  );
  return {
    directory,
    journal: validateJournal(journal, transactionId),
  };
}

async function listTransactionIds(storageDirectory) {
  let entries;
  try {
    entries = await readdir(storageDirectory, { withFileTypes: true });
  } catch (error) {
    if (error?.code === "ENOENT") return [];
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  const ids = entries
    .filter((entry) => entry.isDirectory() && TRANSACTION_ID_PATTERN.test(entry.name))
    .map((entry) => entry.name)
    .sort();
  if (ids.length > MAX_TRANSACTION_DIRECTORIES) {
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  return ids;
}

async function cleanupBuildingDirectories(storageDirectory) {
  let entries;
  try {
    entries = await readdir(storageDirectory, { withFileTypes: true });
  } catch {
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  for (const entry of entries) {
    if (!entry.isDirectory() || !BUILDING_DIRECTORY_PATTERN.test(entry.name)) continue;
    const directoryPath = join(storageDirectory, entry.name);
    const info = await lstat(directoryPath);
    if (!info.isDirectory() || info.isSymbolicLink()) {
      transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
    }
    await rm(directoryPath, { recursive: true, force: true });
  }
}

async function writeJournal(transactionDirectoryPath, journal, state = journal.state) {
  const updated = {
    ...journal,
    state,
    updatedAt: new Date().toISOString(),
  };
  assertPackageImportJournalSize(updated);
  await atomicWriteJson(
    join(transactionDirectoryPath, JOURNAL_FILE),
    updated,
    { maximumBytes: MAX_JOURNAL_BYTES },
  );
  return updated;
}

function receiptPath(storageDirectory, transactionId) {
  transactionDirectory(storageDirectory, transactionId);
  return join(storageDirectory, RECEIPTS_DIRECTORY, `${transactionId}.json`);
}

async function ensureReceiptsDirectory(storageDirectory) {
  const directory = join(storageDirectory, RECEIPTS_DIRECTORY);
  await mkdir(directory, { recursive: true });
  const info = await lstat(directory);
  if (!info.isDirectory() || info.isSymbolicLink()) {
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  const canonicalDirectory = await realpath(directory);
  assertPathInside(storageDirectory, canonicalDirectory, false);
  return canonicalDirectory;
}

async function rotateReceipts(receiptsDirectory) {
  const candidates = [];
  for (const entry of await readdir(receiptsDirectory, { withFileTypes: true })) {
    const match = entry.name.match(/^([a-f0-9-]{36})\.json$/);
    if (!match || !TRANSACTION_ID_PATTERN.test(match[1])) continue;
    const filePath = join(receiptsDirectory, entry.name);
    const info = await lstat(filePath);
    if (!info.isFile() || info.isSymbolicLink()) {
      transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
    }
    candidates.push({ filePath, mtimeMs: info.mtimeMs, name: entry.name });
  }
  candidates.sort((left, right) => (
    left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name)
  ));
  for (const candidate of candidates.slice(0, -MAX_TERMINAL_RECEIPTS)) {
    await unlink(candidate.filePath);
  }
}

async function writeReceipt(storageDirectory, journal, state) {
  const receiptsDirectory = await ensureReceiptsDirectory(storageDirectory);
  await atomicWriteJson(receiptPath(storageDirectory, journal.transactionId), {
    version: STORE_VERSION,
    transactionId: journal.transactionId,
    centralAccountId: journal.centralAccountId,
    sourceAccountId: journal.sourceAccountId,
    ...(journal.kind === REVERSE_PACKAGE_KIND
      ? {
        kind: REVERSE_PACKAGE_KIND,
        targetAccountId: journal.targetAccountId,
      }
      : {}),
    baseDigest: journal.baseDigest,
    packageDigest: journal.packageDigest,
    planDigest: journal.planDigest,
    rewrittenDatabaseDigest: journal.rewrittenDatabaseDigest,
    state,
    completedAt: new Date().toISOString(),
  });
  await rotateReceipts(receiptsDirectory);
}

async function readReceipt(storageDirectory, transactionId) {
  try {
    await ensureReceiptsDirectory(storageDirectory);
    const receipt = await readBoundedJson(
      receiptPath(storageDirectory, transactionId),
      16 * 1024,
      "PACKAGE_IMPORT_NOT_FOUND",
    );
    const reverseDirection = receipt?.kind === REVERSE_PACKAGE_KIND;
    if (
      receipt?.version !== STORE_VERSION
      || receipt?.transactionId !== transactionId
      || !normalizeAccountId(receipt?.centralAccountId)
      || !normalizeAccountId(receipt?.sourceAccountId)
      || (receipt?.kind !== undefined && !reverseDirection)
      || (reverseDirection && (
        !normalizeAccountId(receipt?.targetAccountId)
        || receipt.targetAccountId !== receipt.centralAccountId
      ))
      || !SHA256_PATTERN.test(String(receipt?.baseDigest || ""))
      || !SHA256_PATTERN.test(String(receipt?.packageDigest || ""))
      || !SHA256_PATTERN.test(String(receipt?.planDigest || ""))
      || !SHA256_PATTERN.test(String(receipt?.rewrittenDatabaseDigest || ""))
      || !["confirmed", "rolled_back"].includes(receipt?.state)
    ) {
      transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
    }
    return receipt;
  } catch (error) {
    if (error instanceof PackageImportTransactionError) throw error;
    transactionError("PACKAGE_IMPORT_NOT_FOUND", { statusCode: 404 });
  }
}

function stepMarkerPath(transactionDirectoryPath, index) {
  return join(
    transactionDirectoryPath,
    STEPS_DIRECTORY,
    `${String(index).padStart(5, "0")}.json`,
  );
}

function ownedFilePath(transactionDirectoryPath, index) {
  return join(
    transactionDirectoryPath,
    OWNED_DIRECTORY,
    `${String(index).padStart(5, "0")}.bin`,
  );
}

async function ensureOwnedCopy({
  transactionDirectoryPath,
  index,
  entry,
  sourcePath,
  copyFileOperation,
  allowRefresh = false,
}) {
  const ownedPath = ownedFilePath(transactionDirectoryPath, index);
  let ownedInfo = await assertOrdinaryEntry(ownedPath, "file");
  if (
    ownedInfo
    && allowRefresh
    && (
      ownedInfo.size !== entry.size
      || await hashFile(ownedPath) !== entry.sha256
    )
  ) {
    if (ownedInfo.nlink !== 1) {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    await unlink(ownedPath);
    ownedInfo = null;
  }
  if (!ownedInfo) {
    try {
      await copyFileOperation(sourcePath, ownedPath, fsConstants.COPYFILE_EXCL);
    } catch (error) {
      if (error?.code !== "EEXIST") throw error;
    }
    ownedInfo = await assertOrdinaryEntry(ownedPath, "file");
  }
  if (
    !ownedInfo
    || ownedInfo.size !== entry.size
    || await hashFile(ownedPath) !== entry.sha256
  ) {
    transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
  }
  const identity = await lstat(ownedPath, { bigint: true });
  if (!identity.isFile() || identity.isSymbolicLink()) {
    transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
  }
  return { ownedPath, identity };
}

async function writeStepMarker(
  transactionDirectoryPath,
  index,
  planEntry,
  { status = "complete", ownedIdentity = null } = {},
) {
  await atomicWriteJson(stepMarkerPath(transactionDirectoryPath, index), {
    version: STORE_VERSION,
    index,
    action: planEntry.action,
    status,
    path: planEntry.path,
    size: planEntry.size,
    sha256: planEntry.sha256,
    ...(ownedIdentity ? {
      ownedDevice: String(ownedIdentity.dev),
      ownedInode: String(ownedIdentity.ino),
    } : {}),
    completedAt: new Date().toISOString(),
  });
}

async function readStepMarker(transactionDirectoryPath, index, planEntry) {
  try {
    const marker = await readBoundedJson(stepMarkerPath(transactionDirectoryPath, index), 4096);
    const valid = marker?.version === STORE_VERSION
      && marker?.index === index
      && marker?.action === planEntry.action
      && marker?.path === planEntry.path
      && marker?.size === planEntry.size
      && marker?.sha256 === planEntry.sha256;
    if (!valid) return null;
    if (planEntry.action === "reuse" && marker.status === "complete") return marker;
    if (planEntry.action === "create" && marker.status === "checking") return marker;
    if (
      (
        (planEntry.action === "create" && ["intent", "linked"].includes(marker.status))
        || ["repair_intent", "repaired"].includes(marker.status)
      )
      && /^\d+$/.test(String(marker.ownedDevice || ""))
      && /^\d+$/.test(String(marker.ownedInode || ""))
    ) {
      return marker;
    }
    return null;
  } catch (error) {
    return null;
  }
}

async function hasStepMarker(transactionDirectoryPath, index, planEntry) {
  const marker = await readStepMarker(transactionDirectoryPath, index, planEntry);
  return planEntry.action === "reuse"
    ? ["complete", "repaired"].includes(marker?.status)
    : ["linked", "repaired"].includes(marker?.status);
}

function identitiesEqual(info, marker) {
  return Boolean(
    info
    && String(info.dev) === String(marker?.ownedDevice)
    && String(info.ino) === String(marker?.ownedInode)
  );
}

async function ensureLiveParent(attachmentsRoot, parentSegments) {
  let currentPath = attachmentsRoot;
  for (const segment of parentSegments) {
    const existing = await findCasefoldEntry(currentPath, segment);
    if (existing) {
      if (existing.name !== segment) {
        transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
      }
      currentPath = join(currentPath, existing.name);
      await assertOrdinaryEntry(currentPath, "directory");
      const canonicalDirectory = await realpath(currentPath);
      assertPathInside(attachmentsRoot, canonicalDirectory, true);
      continue;
    }
    const nextPath = join(currentPath, segment);
    try {
      await mkdir(nextPath);
    } catch (error) {
      if (error?.code !== "EEXIST") {
        transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
      }
    }
    await assertOrdinaryEntry(nextPath, "directory");
    currentPath = nextPath;
  }
  return currentPath;
}

async function verifyExactLiveTarget(attachmentsRoot, logicalPath, expectedSize, expectedHash) {
  const normalized = normalizeLogicalAttachmentPath(logicalPath, attachmentsRoot);
  let currentPath = attachmentsRoot;
  const targetSegments = normalized.segments.slice(1);
  for (let index = 0; index < targetSegments.length; index += 1) {
    const segment = targetSegments[index];
    const entry = await findCasefoldEntry(currentPath, segment);
    if (!entry || entry.name !== segment) return { exists: false, identical: false, path: "" };
    currentPath = join(currentPath, entry.name);
    if (index < targetSegments.length - 1) {
      await assertOrdinaryEntry(currentPath, "directory");
      const canonicalDirectory = await realpath(currentPath);
      assertPathInside(attachmentsRoot, canonicalDirectory, true);
    }
  }
  assertPathInside(attachmentsRoot, currentPath, false);
  const inspection = await inspectExistingFile(currentPath, expectedSize, expectedHash);
  if (inspection.exists) {
    const canonicalTarget = await realpath(currentPath);
    assertPathInside(attachmentsRoot, canonicalTarget, false);
  }
  return { ...inspection, path: currentPath };
}

async function availableDiskBytes(directoryPath) {
  try {
    const filesystemStats = await statfs(directoryPath, { bigint: true });
    return (filesystemStats.bavail ?? filesystemStats.bfree) * filesystemStats.bsize;
  } catch {
    transactionError("PACKAGE_IMPORT_DISK_SPACE", { statusCode: 507 });
  }
}

async function applyPlan({
  transactionDirectoryPath,
  attachmentsRoot,
  journal,
  linkOperation,
  copyFileOperation,
  diskReserveBytes,
}) {
  const createBytes = journal.plan
    .filter((entry) => entry.action === "create")
    .reduce((total, entry) => total + entry.size, 0);
  if (!Number.isSafeInteger(createBytes) || createBytes > MAX_CREATE_BYTES) {
    transactionError("PACKAGE_IMPORT_INVALID");
  }
  const requiredBytes = BigInt(createBytes) + BigInt(diskReserveBytes);
  if (await availableDiskBytes(attachmentsRoot) < requiredBytes) {
    transactionError("PACKAGE_IMPORT_DISK_SPACE", { statusCode: 507 });
  }

  let activeJournal = await writeJournal(transactionDirectoryPath, journal, "applying");
  try {
    for (let index = 0; index < activeJournal.plan.length; index += 1) {
      const entry = activeJournal.plan[index];
      if (await hasStepMarker(transactionDirectoryPath, index, entry)) continue;
      const sourcePath = join(
        transactionDirectoryPath,
        SOURCE_DIRECTORY,
        ...entry.sourcePath.split("/"),
      );
      const sourceStats = await assertOrdinaryEntry(sourcePath, "file");
      if (
        !sourceStats
        || sourceStats.size !== entry.size
        || await hashFile(sourcePath) !== entry.sha256
      ) {
        transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
      }
      if (entry.action === "reuse") {
        const target = await verifyExactLiveTarget(
          attachmentsRoot,
          entry.path,
          entry.size,
          entry.sha256,
        );
        if (!target.identical) transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
        await writeStepMarker(transactionDirectoryPath, index, entry);
        continue;
      }
      const normalizedTarget = normalizeLogicalAttachmentPath(entry.path, attachmentsRoot);
      const parentPath = await ensureLiveParent(
        attachmentsRoot,
        normalizedTarget.segments.slice(1, -1),
      );
      const targetName = normalizedTarget.segments.at(-1);
      
      
      await writeStepMarker(transactionDirectoryPath, index, entry, {
        status: "checking",
      });
      if (await findCasefoldEntry(parentPath, targetName)) {
        transactionError("PACKAGE_IMPORT_CONFLICT", { statusCode: 409 });
      }
      const targetPath = join(parentPath, targetName);
      const owned = await ensureOwnedCopy({
        transactionDirectoryPath,
        index,
        entry,
        sourcePath,
        copyFileOperation,
      });
      await writeStepMarker(transactionDirectoryPath, index, entry, {
        status: "intent",
        ownedIdentity: owned.identity,
      });
      await linkOperation(owned.ownedPath, targetPath);
      const targetIdentity = await lstat(targetPath, { bigint: true });
      if (!identitiesEqual(targetIdentity, {
        ownedDevice: owned.identity.dev,
        ownedInode: owned.identity.ino,
      })) {
        transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
      }
      const copied = await inspectExistingFile(targetPath, entry.size, entry.sha256);
      if (!copied.identical) transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
      await writeStepMarker(transactionDirectoryPath, index, entry, {
        status: "linked",
        ownedIdentity: owned.identity,
      });
    }
    activeJournal = await writeJournal(transactionDirectoryPath, activeJournal, "files_applied");
    return activeJournal;
  } catch (error) {
    activeJournal = await writeJournal(
      transactionDirectoryPath,
      activeJournal,
      "apply_failed",
    ).catch(() => ({ ...activeJournal, state: "apply_failed" }));
    const rollbackResult = await rollbackCreatedFiles({
      transactionDirectoryPath,
      attachmentsRoot,
      journal: activeJournal,
    }).catch(() => ({ blocked: true }));
    if (rollbackResult.blocked) {
      await writeJournal(
        transactionDirectoryPath,
        activeJournal,
        "rollback_blocked",
      ).catch(() => {});
      transactionError("PACKAGE_IMPORT_ROLLBACK_BLOCKED", {
        statusCode: 409,
        state: "rollback_blocked",
      });
    } else {
      await resetStepMarkers(transactionDirectoryPath).catch(() => {});
      await writeJournal(transactionDirectoryPath, activeJournal, "staged").catch(() => {});
    }
    if (
      error?.code === "EEXIST"
      || (
        error instanceof PackageImportTransactionError
        && error.code === "PACKAGE_IMPORT_CONFLICT"
      )
    ) {
      transactionError("PACKAGE_IMPORT_PLAN_STALE", { statusCode: 409 });
    }
    if (error instanceof PackageImportTransactionError) throw error;
    transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
  }
}

async function rollbackCreatedFiles({
  transactionDirectoryPath,
  attachmentsRoot,
  journal,
}) {
  
  
  
  let blocked = false;
  for (let index = journal.plan.length - 1; index >= 0; index -= 1) {
    const entry = journal.plan[index];
    const marker = await readStepMarker(transactionDirectoryPath, index, entry);
    const ownedPath = ownedFilePath(transactionDirectoryPath, index);
    let ownedEntry = null;
    let ownedLookupFailed = false;
    try {
      ownedEntry = await assertOrdinaryEntry(ownedPath, "file");
    } catch {
      ownedLookupFailed = true;
    }
    const transactionOwnsTarget = (entry.action === "create" && marker?.status !== "checking")
      || ["repair_intent", "repaired"].includes(marker?.status)
      || (entry.action === "reuse" && Boolean(ownedEntry || ownedLookupFailed));
    if (!transactionOwnsTarget) continue;
    const committedMarker = ["linked", "repaired"].includes(marker?.status);
    const markerHasIdentity = [
      "intent",
      "linked",
      "repair_intent",
      "repaired",
    ].includes(marker?.status);
    let target;
    try {
      target = await verifyExactLiveTarget(
        attachmentsRoot,
        entry.path,
        entry.size,
        entry.sha256,
      );
    } catch {
      
      
      blocked = true;
      continue;
    }
    if (!target.exists || !target.path) continue;
    let targetIdentity;
    let ownedIdentity = null;
    let ownedInspection = null;
    try {
      targetIdentity = await lstat(target.path, { bigint: true });
    } catch {
      blocked = true;
      continue;
    }
    if (ownedEntry) {
      try {
        ownedIdentity = await lstat(ownedPath, { bigint: true });
        ownedInspection = await inspectExistingFile(ownedPath, entry.size, entry.sha256);
      } catch {
        ownedLookupFailed = true;
      }
    }
    const markerIdentityProof = markerHasIdentity && identitiesEqual(targetIdentity, marker);
    const ownedIdentityProof = Boolean(ownedIdentity) && (
        String(targetIdentity.dev) === String(ownedIdentity.dev)
        && String(targetIdentity.ino) === String(ownedIdentity.ino)
      );
    if (!markerIdentityProof && !ownedIdentityProof) {
      
      
      
      if (
        committedMarker
        || (!markerHasIdentity && !ownedIdentity)
        || ownedLookupFailed
      ) {
        blocked = true;
      }
      continue;
    }
    if (
      !target.identical
      || (ownedIdentityProof && !ownedInspection?.identical)
    ) {
      blocked = true;
      continue;
    }
    await unlink(target.path).catch((error) => {
      if (error?.code !== "ENOENT") throw error;
    });
  }
  return { blocked };
}

async function resetStepMarkers(transactionDirectoryPath) {
  const stepsDirectory = join(transactionDirectoryPath, STEPS_DIRECTORY);
  const ownedDirectory = join(transactionDirectoryPath, OWNED_DIRECTORY);
  await rm(stepsDirectory, { recursive: true, force: true });
  await rm(ownedDirectory, { recursive: true, force: true });
  await mkdir(stepsDirectory);
  await mkdir(ownedDirectory);
}

async function revalidateAppliedTargets({
  transactionDirectoryPath,
  attachmentsRoot,
  journal,
  linkOperation,
  copyFileOperation,
}) {
  for (let index = 0; index < journal.plan.length; index += 1) {
    const entry = journal.plan[index];
    const marker = await readStepMarker(transactionDirectoryPath, index, entry);
    let target;
    try {
      target = await verifyExactLiveTarget(
        attachmentsRoot,
        entry.path,
        entry.size,
        entry.sha256,
      );
    } catch {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    if (target.exists) {
      if (!target.identical || !target.path) {
        transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
      }
      if (entry.action === "reuse" && marker?.status === "complete") continue;
      const ownedPath = ownedFilePath(transactionDirectoryPath, index);
      if (entry.action === "reuse" && !marker) {
        let ownedEntry;
        try {
          ownedEntry = await assertOrdinaryEntry(ownedPath, "file");
        } catch {
          transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
        }
        if (!ownedEntry) {
          await writeStepMarker(transactionDirectoryPath, index, entry);
          continue;
        }
      }
      let targetIdentity;
      let ownedIdentity;
      let ownedInspection;
      try {
        targetIdentity = await lstat(target.path, { bigint: true });
        ownedIdentity = await lstat(ownedPath, { bigint: true });
        ownedInspection = await inspectExistingFile(ownedPath, entry.size, entry.sha256);
      } catch {
        transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
      }
      const identityProof = marker
        ? identitiesEqual(targetIdentity, marker) && identitiesEqual(ownedIdentity, marker)
        : (
          String(targetIdentity.dev) === String(ownedIdentity.dev)
          && String(targetIdentity.ino) === String(ownedIdentity.ino)
        );
      if (!identityProof || !ownedInspection.identical) {
        transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
      }
      if (!marker) {
        await writeStepMarker(transactionDirectoryPath, index, entry, {
          status: entry.action === "reuse" ? "repaired" : "linked",
          ownedIdentity,
        });
      }
      continue;
    }

    const sourcePath = join(
      transactionDirectoryPath,
      SOURCE_DIRECTORY,
      ...entry.sourcePath.split("/"),
    );
    const sourceStats = await assertOrdinaryEntry(sourcePath, "file");
    if (
      !sourceStats
      || sourceStats.size !== entry.size
      || await hashFile(sourcePath) !== entry.sha256
    ) {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    const normalizedTarget = normalizeLogicalAttachmentPath(entry.path, attachmentsRoot);
    const parentPath = await ensureLiveParent(
      attachmentsRoot,
      normalizedTarget.segments.slice(1, -1),
    );
    const targetName = normalizedTarget.segments.at(-1);
    if (await findCasefoldEntry(parentPath, targetName)) {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    const owned = await ensureOwnedCopy({
      transactionDirectoryPath,
      index,
      entry,
      sourcePath,
      copyFileOperation,
      allowRefresh: true,
    });
    await writeStepMarker(transactionDirectoryPath, index, entry, {
      status: entry.action === "reuse" ? "repair_intent" : "intent",
      ownedIdentity: owned.identity,
    });
    const targetPath = join(parentPath, targetName);
    try {
      await linkOperation(owned.ownedPath, targetPath);
    } catch {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    const targetIdentity = await lstat(targetPath, { bigint: true });
    if (!identitiesEqual(targetIdentity, {
      ownedDevice: owned.identity.dev,
      ownedInode: owned.identity.ino,
    })) {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    const repaired = await inspectExistingFile(targetPath, entry.size, entry.sha256);
    if (!repaired.identical) {
      transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
    }
    await writeStepMarker(transactionDirectoryPath, index, entry, {
      status: entry.action === "reuse" ? "repaired" : "linked",
      ownedIdentity: owned.identity,
    });
  }
}

function bindJournal(journal, centralAccountId, {
  kind,
  sourceAccountId,
  targetAccountId,
} = {}) {
  if (
    journal.centralAccountId !== centralAccountId
    || (
      journal.kind === REVERSE_PACKAGE_KIND
      && journal.targetAccountId !== centralAccountId
    )
    || (
      kind !== undefined
      && (
        journal.kind !== kind
        || journal.sourceAccountId !== sourceAccountId
        || journal.targetAccountId !== targetAccountId
      )
    )
  ) {
    transactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
  }
}

function bindActionDigests(journal, {
  baseDigest,
  packageDigest,
  planDigest,
}) {
  if (
    !SHA256_PATTERN.test(String(baseDigest || ""))
    || !SHA256_PATTERN.test(String(packageDigest || ""))
    || !SHA256_PATTERN.test(String(planDigest || ""))
    || journal.baseDigest !== baseDigest
    || journal.packageDigest !== packageDigest
    || journal.planDigest !== planDigest
  ) {
    transactionError("PACKAGE_IMPORT_BINDING", { statusCode: 409 });
  }
}

async function readTransactionDatabase(transactionDirectoryPath, journal) {
  const databasePath = join(transactionDirectoryPath, DATABASE_FILE);
  let contents;
  try {
    const info = await stat(databasePath);
    if (!info.isFile() || info.size > MAX_DATABASE_BYTES) {
      transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
    }
    contents = await readFile(databasePath);
  } catch (error) {
    if (error instanceof PackageImportTransactionError) throw error;
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
  if (sha256(contents) !== journal.rewrittenDatabaseDigest) {
    transactionError("PACKAGE_IMPORT_VERIFY_BLOCKED", { statusCode: 409 });
  }
  try {
    const database = JSON.parse(contents.toString("utf8"));
    if (!database || typeof database !== "object" || !Array.isArray(database.policies)) {
      transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
    }
    return database;
  } catch (error) {
    if (error instanceof PackageImportTransactionError) throw error;
    transactionError("PACKAGE_IMPORT_STORE", { statusCode: 500 });
  }
}

async function publicTransaction(transactionDirectoryPath, journal) {
  const database = await readTransactionDatabase(transactionDirectoryPath, journal);
  const common = {
    transactionId: journal.transactionId,
    state: journal.state,
    accountId: journal.sourceAccountId,
    accountName: String(database.accountName || ""),
    centralAccountId: journal.centralAccountId,
    baseDigest: journal.baseDigest,
    packageDigest: journal.packageDigest,
    planDigest: journal.planDigest,
    policies: database.policies,
    ...(journal.kind === REVERSE_PACKAGE_KIND
      ? {
        kind: REVERSE_PACKAGE_KIND,
        sourceAccountId: journal.sourceAccountId,
        targetAccountId: journal.targetAccountId,
      }
      : {}),
  };
  const createCount = journal.plan.filter((entry) => entry.action === "create").length;
  const reuseCount = journal.plan.filter((entry) => entry.action === "reuse").length;
  const renameCount = journal.plan.filter((entry) => entry.renamed === true).length;
  if (journal.state === "staged") {
    return {
      ...common,
      attachmentsToCreate: createCount,
      attachmentsToReuse: reuseCount,
      attachmentsToRename: renameCount,
    };
  }
  return {
    ...common,
    requiresConfirmation: journal.state === "files_applied",
    attachmentsCopied: createCount,
    attachmentsReused: reuseCount,
    attachmentsRenamed: renameCount,
  };
}

export function createEmployeePackageImportTransactionStore({
  storageDirectory,
  attachmentsRoot,
  diskReserveBytes = DEFAULT_DISK_RESERVE_BYTES,
  linkOperation = link,
  copyFileOperation = copyFile,
} = {}) {
  if (!storageDirectory || !attachmentsRoot) {
    throw new Error("Transaction store paths are required.");
  }
  let mutationQueue = Promise.resolve();

  function serialize(operation) {
    const result = mutationQueue.catch(() => {}).then(operation);
    mutationQueue = result.then(() => undefined, () => undefined);
    return result;
  }

  async function initializeRoots() {
    const canonicalStorage = await ensureOrdinaryDirectory(storageDirectory);
    const canonicalAttachments = await ensureOrdinaryDirectory(attachmentsRoot);
    assertPathInside(canonicalStorage, canonicalStorage, true);
    assertPathInside(canonicalAttachments, canonicalAttachments, true);
    await cleanupBuildingDirectories(canonicalStorage);
    return { canonicalStorage, canonicalAttachments };
  }

  async function recoverTransactions(canonicalStorage, canonicalAttachments) {
    const transactionIds = await listTransactionIds(canonicalStorage);
    const pending = [];
    for (const transactionId of transactionIds) {
      const transaction = await readJournal(canonicalStorage, transactionId);
      let { journal } = transaction;
      if (["staged", "files_applied", "rollback_blocked"].includes(journal.state)) {
        pending.push(transaction);
        continue;
      }
      if (["applying", "apply_failed"].includes(journal.state)) {
        const rollbackResult = await rollbackCreatedFiles({
          transactionDirectoryPath: transaction.directory,
          attachmentsRoot: canonicalAttachments,
          journal,
        }).catch(() => ({ blocked: true }));
        if (rollbackResult.blocked) {
          journal = await writeJournal(
            transaction.directory,
            journal,
            "rollback_blocked",
          );
        } else {
          await resetStepMarkers(transaction.directory);
          journal = await writeJournal(transaction.directory, journal, "staged");
        }
        pending.push({ ...transaction, journal });
        continue;
      }
      if (journal.state === "rolling_back") {
        const rollbackResult = await rollbackCreatedFiles({
          transactionDirectoryPath: transaction.directory,
          attachmentsRoot: canonicalAttachments,
          journal,
        }).catch(() => ({ blocked: true }));
        if (rollbackResult.blocked) {
          journal = await writeJournal(
            transaction.directory,
            journal,
            "rollback_blocked",
          );
          pending.push({ ...transaction, journal });
          continue;
        }
        journal = await writeJournal(transaction.directory, journal, "rolled_back");
        await writeReceipt(canonicalStorage, journal, "rolled_back");
        await rm(transaction.directory, { recursive: true, force: true });
        continue;
      }
      if (["confirmed", "rolled_back"].includes(journal.state)) {
        await writeReceipt(canonicalStorage, journal, journal.state);
      }
      await rm(transaction.directory, { recursive: true, force: true });
    }
    return pending;
  }

  async function stage({
    centralAccountId,
    sourceAccountId,
    kind,
    targetAccountId,
    baseDigest,
    sourcePackageRoot,
    manifest,
    database,
  }) {
    return serialize(async () => {
      const normalizedCentralAccountId = normalizeAccountId(centralAccountId);
      const normalizedSourceAccountId = normalizeAccountId(sourceAccountId);
      const reverseDirection = kind === REVERSE_PACKAGE_KIND;
      const normalizedTargetAccountId = reverseDirection
        ? normalizeAccountId(targetAccountId)
        : "";
      if (
        !normalizedCentralAccountId
        || !normalizedSourceAccountId
        || (kind !== undefined && !reverseDirection)
        || (reverseDirection && (
          !normalizedTargetAccountId
          || normalizedTargetAccountId !== normalizedCentralAccountId
          || manifest?.kind !== REVERSE_PACKAGE_KIND
          || manifest?.sourceAccountId !== normalizedSourceAccountId
          || manifest?.targetAccountId !== normalizedTargetAccountId
        ))
        || !SHA256_PATTERN.test(String(baseDigest || ""))
      ) {
        transactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const { canonicalStorage, canonicalAttachments } = await initializeRoots();
      const pending = await recoverTransactions(canonicalStorage, canonicalAttachments);
      const packageDigest = logicalPackageDigest(manifest);
      if (pending.length > 0) {
        const existing = pending[0];
        if (
          existing.journal.centralAccountId === normalizedCentralAccountId
          && existing.journal.sourceAccountId === normalizedSourceAccountId
          && existing.journal.kind === (reverseDirection ? REVERSE_PACKAGE_KIND : undefined)
          && existing.journal.targetAccountId === (
            reverseDirection ? normalizedTargetAccountId : undefined
          )
          && existing.journal.baseDigest === baseDigest
          && existing.journal.packageDigest === packageDigest
        ) {
          return publicTransaction(existing.directory, existing.journal);
        }
        transactionError("PACKAGE_IMPORT_PENDING", { statusCode: 409 });
      }
      const transactionId = randomUUID();
      const directory = join(canonicalStorage, transactionId);
      const buildingDirectory = join(canonicalStorage, `.building-${transactionId}`);
      const sourceRoot = join(buildingDirectory, SOURCE_DIRECTORY);
      await mkdir(buildingDirectory);
      let published = false;
      try {
        await rename(sourcePackageRoot, sourceRoot);
        const plan = await buildFilePlan({
          sourceRoot,
          attachmentsRoot: canonicalAttachments,
          manifest,
        });
        if (database?.accountId !== normalizedSourceAccountId) {
          transactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
        }
        const rewrittenDatabase = rewriteDatabaseAttachmentPaths(database, plan);
        const databaseContents = `${JSON.stringify(rewrittenDatabase, null, 2)}\n`;
        if (Buffer.byteLength(databaseContents, "utf8") > MAX_DATABASE_BYTES) {
          transactionError("PACKAGE_IMPORT_INVALID");
        }
        await atomicWriteJson(join(buildingDirectory, DATABASE_FILE), rewrittenDatabase);
        await mkdir(join(buildingDirectory, STEPS_DIRECTORY));
        await mkdir(join(buildingDirectory, OWNED_DIRECTORY));
        const createdAt = new Date().toISOString();
        let journal = {
          version: STORE_VERSION,
          transactionId,
          centralAccountId: normalizedCentralAccountId,
          sourceAccountId: normalizedSourceAccountId,
          ...(reverseDirection
            ? {
              kind: REVERSE_PACKAGE_KIND,
              targetAccountId: normalizedTargetAccountId,
            }
            : {}),
          baseDigest,
          packageDigest,
          planDigest: journalPlanDigest(plan),
          rewrittenDatabaseDigest: sha256(Buffer.from(databaseContents, "utf8")),
          state: "staged",
          createdAt,
          updatedAt: createdAt,
          plan,
        };
        assertPackageImportJournalSize(journal);
        await atomicWriteJson(
          join(buildingDirectory, JOURNAL_FILE),
          journal,
          { maximumBytes: MAX_JOURNAL_BYTES },
        );
        await rename(buildingDirectory, directory);
        published = true;
        return publicTransaction(directory, journal);
      } catch (error) {
        if (!published) {
          await rm(buildingDirectory, { recursive: true, force: true }).catch(() => {});
        }
        if (error instanceof PackageImportTransactionError) throw error;
        transactionError("PACKAGE_IMPORT_APPLY", { statusCode: 500 });
      }
    });
  }

  async function apply({
    transactionId,
    centralAccountId,
    kind,
    sourceAccountId,
    targetAccountId,
    baseDigest,
    packageDigest,
    planDigest,
  }) {
    return serialize(async () => {
      const normalizedCentralAccountId = normalizeAccountId(centralAccountId);
      const { canonicalStorage, canonicalAttachments } = await initializeRoots();
      await recoverTransactions(canonicalStorage, canonicalAttachments);
      const { directory, journal } = await readJournal(canonicalStorage, transactionId);
      bindJournal(journal, normalizedCentralAccountId, {
        kind,
        sourceAccountId,
        targetAccountId,
      });
      bindActionDigests(journal, { baseDigest, packageDigest, planDigest });
      if (journal.state === "files_applied") {
        await readTransactionDatabase(directory, journal);
        await revalidateAppliedTargets({
          transactionDirectoryPath: directory,
          attachmentsRoot: canonicalAttachments,
          journal,
          linkOperation,
          copyFileOperation,
        });
        return publicTransaction(directory, journal);
      }
      if (journal.state !== "staged") {
        transactionError("PACKAGE_IMPORT_STATE", { statusCode: 409 });
      }
      await readTransactionDatabase(directory, journal);
      const appliedJournal = await applyPlan({
        transactionDirectoryPath: directory,
        attachmentsRoot: canonicalAttachments,
        journal,
        linkOperation,
        copyFileOperation,
        diskReserveBytes,
      });
      return publicTransaction(directory, appliedJournal);
    });
  }

  async function getPending({
    centralAccountId,
  }) {
    return serialize(async () => {
      const normalizedCentralAccountId = normalizeAccountId(centralAccountId);
      if (!normalizedCentralAccountId) {
        transactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const { canonicalStorage, canonicalAttachments } = await initializeRoots();
      const pending = await recoverTransactions(canonicalStorage, canonicalAttachments);
      const result = [];
      for (const transaction of pending) {
        if (transaction.journal.centralAccountId !== normalizedCentralAccountId) continue;
        result.push(await publicTransaction(transaction.directory, transaction.journal));
      }
      return result;
    });
  }

  async function confirm({
    transactionId,
    centralAccountId,
    kind,
    sourceAccountId,
    targetAccountId,
    baseDigest,
    packageDigest,
    planDigest,
  }) {
    return serialize(async () => {
      const normalizedCentralAccountId = normalizeAccountId(centralAccountId);
      const { canonicalStorage, canonicalAttachments } = await initializeRoots();
      await recoverTransactions(canonicalStorage, canonicalAttachments);
      let transaction;
      try {
        transaction = await readJournal(canonicalStorage, transactionId);
      } catch (error) {
        if (!(error instanceof PackageImportTransactionError) || error.code !== "PACKAGE_IMPORT_NOT_FOUND") {
          throw error;
        }
        const receipt = await readReceipt(canonicalStorage, transactionId);
        bindJournal(receipt, normalizedCentralAccountId, {
          kind,
          sourceAccountId,
          targetAccountId,
        });
        bindActionDigests(receipt, { baseDigest, packageDigest, planDigest });
        if (receipt.state !== "confirmed") {
          transactionError("PACKAGE_IMPORT_STATE", { statusCode: 409 });
        }
        return { transactionId, state: "confirmed" };
      }
      const { directory, journal } = transaction;
      bindJournal(journal, normalizedCentralAccountId, {
        kind,
        sourceAccountId,
        targetAccountId,
      });
      bindActionDigests(journal, { baseDigest, packageDigest, planDigest });
      if (journal.state !== "files_applied") {
        transactionError("PACKAGE_IMPORT_STATE", { statusCode: 409 });
      }
      await readTransactionDatabase(directory, journal);
      await revalidateAppliedTargets({
        transactionDirectoryPath: directory,
        attachmentsRoot: canonicalAttachments,
        journal,
        linkOperation,
        copyFileOperation,
      });
      const confirmed = await writeJournal(directory, journal, "confirmed");
      await writeReceipt(canonicalStorage, confirmed, "confirmed");
      await rm(directory, { recursive: true, force: true });
      return { transactionId, state: "confirmed" };
    });
  }

  async function rollback({
    transactionId,
    centralAccountId,
    kind,
    sourceAccountId,
    targetAccountId,
    baseDigest,
    packageDigest,
    planDigest,
  }) {
    return serialize(async () => {
      const normalizedCentralAccountId = normalizeAccountId(centralAccountId);
      const { canonicalStorage, canonicalAttachments } = await initializeRoots();
      await recoverTransactions(canonicalStorage, canonicalAttachments);
      let transaction;
      try {
        transaction = await readJournal(canonicalStorage, transactionId);
      } catch (error) {
        if (!(error instanceof PackageImportTransactionError) || error.code !== "PACKAGE_IMPORT_NOT_FOUND") {
          throw error;
        }
        const receipt = await readReceipt(canonicalStorage, transactionId);
        bindJournal(receipt, normalizedCentralAccountId, {
          kind,
          sourceAccountId,
          targetAccountId,
        });
        bindActionDigests(receipt, { baseDigest, packageDigest, planDigest });
        if (receipt.state !== "rolled_back") {
          transactionError("PACKAGE_IMPORT_STATE", { statusCode: 409 });
        }
        return { transactionId, state: "rolled_back" };
      }
      const { directory, journal } = transaction;
      bindJournal(journal, normalizedCentralAccountId, {
        kind,
        sourceAccountId,
        targetAccountId,
      });
      bindActionDigests(journal, { baseDigest, packageDigest, planDigest });
      if (!["staged", "files_applied", "rollback_blocked"].includes(journal.state)) {
        transactionError("PACKAGE_IMPORT_STATE", { statusCode: 409 });
      }
      
      
      
      if (journal.state === "staged") {
        const rolledBack = await writeJournal(directory, journal, "rolled_back");
        await writeReceipt(canonicalStorage, rolledBack, "rolled_back");
        await rm(directory, { recursive: true, force: true });
        return { transactionId, state: "rolled_back" };
      }
      const rollingBack = await writeJournal(directory, journal, "rolling_back");
      const rollbackResult = await rollbackCreatedFiles({
        transactionDirectoryPath: directory,
        attachmentsRoot: canonicalAttachments,
        journal: rollingBack,
      });
      if (rollbackResult.blocked) {
        await writeJournal(directory, rollingBack, "rollback_blocked");
        transactionError("PACKAGE_IMPORT_ROLLBACK_BLOCKED", {
          statusCode: 409,
          state: "rollback_blocked",
        });
      }
      const rolledBack = await writeJournal(directory, rollingBack, "rolled_back");
      await writeReceipt(canonicalStorage, rolledBack, "rolled_back");
      await rm(directory, { recursive: true, force: true });
      return { transactionId, state: "rolled_back" };
    });
  }

  return {
    stage,
    apply,
    getPending,
    confirm,
    rollback,
  };
}
