import { execFile, spawnSync } from "node:child_process";
import {
  cp,
  link,
  lstat,
  mkdir,
  mkdtemp,
  readFile,
  readdir,
  realpath,
  readlink,
  rm,
  symlink,
  utimes,
  writeFile,
} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";

import * as EffectVitest from "@effect/vitest";

import { hashJsonContent, hashManagedFileContent } from "../../scaffold/json";

const execFileAsync = promisify(execFile);
const { describe: suite, expect: assertThat, it: test } = EffectVitest;
const nodePath = process.env.HI_TEST_NODE_PATH ?? "node";
const mkfifoPath = process.env.HI_TEST_MKFIFO_PATH ?? "mkfifo";
const mkfifoAvailable = spawnSync(mkfifoPath, ["--help"], { stdio: "ignore" }).error === undefined;

const requireDefined = <Value>(value: Value | undefined): Value => {
  if (value === undefined) {
    throw new Error("Expected value to be defined");
  }
  return value;
};

const repositoryInventory = (root: string): Promise<readonly string[]> => {
  const visit = async (directory: string): Promise<readonly string[]> => {
    const directoryEntries = await readdir(directory);
    const names = directoryEntries.toSorted();
    const nestedEntries = await Promise.all(
      names.map(async (name) => {
        const absolutePath = path.join(directory, name);
        const relativePath = path.relative(root, absolutePath).split(path.sep).join("/");
        const stat = await lstat(absolutePath);
        if (stat.isSymbolicLink()) {
          const linkTarget = await readlink(absolutePath);
          return [`${relativePath}:symlink:${linkTarget}`];
        }
        if (stat.isDirectory()) {
          return [`${relativePath}:directory`, ...(await visit(absolutePath))];
        }
        if (stat.isFile()) {
          const content = await readFile(absolutePath);
          return [`${relativePath}:file:${content.toString("base64")}`];
        }
        return [`${relativePath}:special:${stat.mode}`];
      }),
    );
    return nestedEntries.flat();
  };
  return visit(root);
};

const pathExists = async (targetPath: string): Promise<boolean> => {
  try {
    await lstat(targetPath);
    return true;
  } catch (error) {
    if (error instanceof Error && "code" in error && error.code === "ENOENT") {
      return false;
    }
    throw error;
  }
};

const scriptSourcePath = path.resolve(import.meta.dirname, "sync-subagents.mjs");
const projectionSourcePath = path.resolve(import.meta.dirname, "harness-projection");

const receiptRelativePath = ".devpunks/harness-projection-receipt.json";
const scaffoldManifest = (
  receiptEntries: readonly Record<string, unknown>[] = [
    { kind: "projection-receipt", path: receiptRelativePath, sha256: "b".repeat(64) },
  ],
) => ({
  finalPacks: ["quality", "subagents"],
  managedFiles: [
    { kind: "hook", path: ".agents/hooks/existing.mjs", sha256: "a".repeat(64) },
    ...receiptEntries,
  ],
  projectionReceiptFile: receiptRelativePath,
  projectionStatus: "partial",
  unrelated: { retained: true },
  version: "3.1.5",
});

const writeScaffoldManifest = async (root: string, manifest: unknown): Promise<string> => {
  const manifestPath = path.join(root, ".devpunks/scaffold-manifest.json");
  await writeFile(manifestPath, `${JSON.stringify(manifest, null, 4)}\n`, "utf-8");
  return manifestPath;
};

const writeHarnessHooks = async (root: string): Promise<void> => {
  await mkdir(path.join(root, ".agents/hooks"), { recursive: true });
  await writeFile(path.join(root, ".agents/hooks/format-edited-file.mjs"), "", "utf-8");
  await writeFile(path.join(root, ".agents/hooks/scaffold-update-check.mjs"), "", "utf-8");
};

const canonicalContextPlan = {
  scopes: [
    {
      contributions: [
        {
          compatibility: [],
          identity: { id: ".agents:shared-agents", version: "2026.07.17" },
          kind: "scoped-prompt",
          order: 0,
          provenance: { revision: "2026.07.17", source: "bundled" },
          references: [],
        },
      ],
      id: ".agents",
      packs: [{ id: "subagents", order: 0 }],
    },
    {
      contributions: [
        {
          compatibility: [],
          identity: { id: "simplify", version: "2026.07.17" },
          kind: "skill",
          order: 0,
          provenance: { revision: "2026.07.17", source: "bundled" },
          references: [],
        },
        {
          compatibility: [],
          identity: { id: "format-edited-file", version: "2026.07.17" },
          kind: "lifecycle-hook",
          order: 1,
          provenance: { revision: "2026.07.17", source: "bundled" },
          references: [],
        },
        {
          compatibility: [],
          identity: { id: "scaffold-update-check", version: "2026.07.17" },
          kind: "lifecycle-hook",
          order: 2,
          provenance: { revision: "2026.07.17", source: "bundled" },
          references: [],
        },
        {
          compatibility: [],
          identity: { id: "opensrc", version: "2026.07.17" },
          kind: "tool-configuration",
          order: 3,
          provenance: { revision: "2026.07.17", source: "bundled" },
          references: [],
        },
        {
          compatibility: [],
          identity: { id: "frontend-worker", version: "2026.07.17" },
          kind: "subagent-template",
          order: 4,
          provenance: { revision: "2026.07.17", source: "bundled" },
          references: ["simplify"],
        },
      ],
      id: "root",
      packs: [
        { id: "quality", order: 0 },
        { id: "subagents", order: 1 },
      ],
    },
  ],
  version: "1",
};

const writeFixture = async ({
  guidanceFile,
  projectionTransforms = {},
  scriptSource,
  writeContextPlan = true,
  writeGuidance = true,
}: {
  readonly guidanceFile: string;
  readonly projectionTransforms?: Readonly<Record<string, (source: string) => string>>;
  readonly scriptSource?: string;
  readonly writeContextPlan?: boolean;
  readonly writeGuidance?: boolean;
}): Promise<string> => {
  const root = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-"));
  await mkdir(path.join(root, "app/backend"), { recursive: true });
  await mkdir(path.join(root, "app/frontend"), { recursive: true });
  await mkdir(path.join(root, "app/lambda"), { recursive: true });
  await mkdir(path.join(root, "app/wiki"), { recursive: true });
  await mkdir(path.join(root, "infra"), { recursive: true });
  await mkdir(path.join(root, ".agents/scripts"), { recursive: true });
  await mkdir(path.join(root, ".agents/skills/simplify"), { recursive: true });
  await mkdir(path.join(root, ".agents/subagents"), { recursive: true });
  await mkdir(path.join(root, ".devpunks"), { recursive: true });
  if (writeGuidance) {
    await mkdir(path.dirname(path.join(root, guidanceFile)), { recursive: true });
  }

  await writeFile(
    path.join(root, ".agents/scripts/sync-subagents.mjs"),
    scriptSource ?? (await readFile(scriptSourcePath, "utf-8")),
    "utf-8",
  );
  await writeFile(path.join(root, ".agents/skills/simplify/SKILL.md"), "# Simplify\n", "utf-8");
  await writeFile(path.join(root, ".agents/AGENTS.md"), "Shared neutral guidance\n", "utf-8");
  if (writeContextPlan) {
    await writeFile(
      path.join(root, ".devpunks/context-plan.json"),
      `${JSON.stringify(canonicalContextPlan, null, 2)}\n`,
      "utf-8",
    );
  }
  await cp(projectionSourcePath, path.join(root, ".agents/scripts/harness-projection"), {
    recursive: true,
  });
  await Promise.all(
    Object.entries(projectionTransforms).map(async ([relativePath, transform]) => {
      const targetPath = path.join(root, ".agents/scripts/harness-projection", relativePath);
      const source = await readFile(targetPath, "utf-8");
      await writeFile(targetPath, transform(source), "utf-8");
    }),
  );
  await writeFile(
    path.join(root, ".agents/subagents/manifest.mjs"),
    [
      "const capabilityPacks = {",
      '  quality: { description: "Quality guidance pack.", skills: ["simplify"] },',
      "};",
      "const agents = [",
      "  {",
      '    name: "frontend-worker",',
      '    description: "Own frontend changes.",',
      '    ownedPaths: ["app/frontend", "app/frontend/**"],',
      `    guidanceFiles: [${JSON.stringify(guidanceFile)}],`,
      '    activationInstructions: ["Read scoped guidance before editing."],',
      '    packs: ["quality"],',
      '    skills: ["simplify"],',
      '    boundaries: ["Stay inside src unless parent expands scope."],',
      "  },",
      "];",
      "export { agents, capabilityPacks };",
      "",
    ].join("\n"),
    "utf-8",
  );
  if (writeGuidance) {
    await writeFile(
      path.join(root, guidanceFile),
      [
        "## Consumer App Guidance",
        "",
        "Primary skills here: `simplify`.",
        "",
        "Only this consumer-authored guidance should name local product boundaries.",
        "",
      ].join("\n"),
      "utf-8",
    );
  }

  return root;
};

const publicationWriterSource = (
  source: string,
  boundary: string,
  placement: "before" | "after",
  indent: string,
): string => {
  const gate = [
    `${indent}await writeTestMarker(process.env.HI_TEST_READY, "ready\\n");`,
    `${indent}await readFile(process.env.HI_TEST_GATE);`,
  ];
  return source
    .replace(
      'import { lstat, readFile, realpath, readdir, readlink } from "node:fs/promises";',
      'import { lstat, readFile, realpath, readdir, readlink, writeFile as writeTestMarker } from "node:fs/promises";',
    )
    .replace(
      '    const receipt = {\n      version: "1",',
      '    const receipt = {\n      version: "1",\n      writer: process.env.HI_TEST_WRITER,',
    )
    .replace(
      boundary,
      [
        ...(placement === "before" ? gate : []),
        boundary,
        ...(placement === "after" ? gate : []),
      ].join("\n"),
    );
};

const providerWriterSource = (source: string): string => {
  const writeBoundary = "    await writeConfinedTextFile(targetPath, content);";
  return source
    .replace(
      'import { lstat, readFile, realpath, readdir, readlink } from "node:fs/promises";',
      'import { lstat, readFile, realpath, readdir, readlink, writeFile as writeTestMarker } from "node:fs/promises";',
    )
    .replace(
      "function buildPrompt(agent, guidance) {\n",
      // oxlint-disable-next-line eslint/no-template-curly-in-string -- Inject literal provider source.
      "function buildPrompt(agent, guidance) {\n  guidance = `${guidance}\\n\\nTest writer: ${process.env.HI_TEST_WRITER}`;\n",
    )
    .replace(
      '    const receipt = {\n      version: "1",',
      '    const receipt = {\n      version: "1",\n      writer: process.env.HI_TEST_WRITER,',
    )
    .replace(
      writeBoundary,
      [
        writeBoundary,
        "    if (globalThis.__hiProviderRaceGated !== true) {",
        "      globalThis.__hiProviderRaceGated = true;",
        '      await writeTestMarker(process.env.HI_TEST_READY, "ready\\n");',
        "      await readFile(process.env.HI_TEST_GATE);",
        "    }",
      ].join("\n"),
    );
};

const expectCoherentReceiptEvidence = async (
  root: string,
  manifestPath: string,
  writer?: string,
): Promise<void> => {
  const receiptBytes = await readFile(path.join(root, receiptRelativePath));
  const receipt = JSON.parse(receiptBytes.toString("utf-8")) as {
    readonly status: string;
    readonly writer?: string;
  };
  const manifest = JSON.parse(await readFile(manifestPath, "utf-8")) as {
    readonly managedFiles: readonly { readonly kind: string; readonly sha256: string }[];
    readonly projectionStatus: string;
  };
  assertThat(receipt.writer).toBe(writer);
  assertThat(manifest.projectionStatus).toBe(receipt.status);
  assertThat(manifest.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256).toBe(
    hashManagedFileContent(receiptRelativePath, receiptBytes),
  );
};

suite("sync-subagents script", () => {
  test.runIf(process.platform !== "win32" && mkfifoAvailable)(
    "rejects an original-schedule contender before it can replace the held receipt",
    async () => {
      const baseSource = await readFile(scriptSourcePath, "utf-8");
      const boundary = "  try {\n    await publishReceiptEvidence(";
      const scriptSource = publicationWriterSource(baseSource, boundary, "before", "  ");
      assertThat(scriptSource).not.toBe(baseSource);
      assertThat(scriptSource).toContain("HI_TEST_WRITER");
      assertThat(scriptSource).toContain("HI_TEST_READY");

      const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
      await writeHarnessHooks(root);
      const manifestPath = await writeScaffoldManifest(root, scaffoldManifest());
      const raceDirectory = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-race-"));
      const writerAPath = path.join(root, ".agents/scripts/sync-subagents-a.mjs");
      const writerBPath = path.join(root, ".agents/scripts/sync-subagents-b.mjs");
      const gateA = path.join(raceDirectory, "gate-a");
      const gateB = path.join(raceDirectory, "gate-b");
      const readyA = path.join(raceDirectory, "ready-a");
      const readyB = path.join(raceDirectory, "ready-b");
      await Promise.all([
        writeFile(writerAPath, scriptSource, "utf-8"),
        writeFile(writerBPath, scriptSource, "utf-8"),
        execFileAsync(mkfifoPath, [gateA]),
        execFileAsync(mkfifoPath, [gateB]),
        execFileAsync(mkfifoPath, [readyA]),
      ]);

      try {
        const writerA = execFileAsync(nodePath, [writerAPath], {
          cwd: root,
          env: {
            ...process.env,
            HI_TEST_GATE: gateA,
            HI_TEST_READY: readyA,
            HI_TEST_WRITER: "a",
          },
          timeout: 10_000,
        });
        await readFile(readyA, { signal: AbortSignal.timeout(5000) });
        const writerBResult = await Promise.allSettled([
          execFileAsync(nodePath, [writerBPath], {
            cwd: root,
            env: {
              ...process.env,
              HI_TEST_GATE: gateB,
              HI_TEST_READY: readyB,
              HI_TEST_WRITER: "b",
            },
            timeout: 2000,
          }),
        ]);

        assertThat(writerBResult[0]?.status).toBe("rejected");
        if (writerBResult[0]?.status === "rejected") {
          assertThat(String(writerBResult[0].reason)).toContain(
            "projection publication is already active; retry sync-subagents",
          );
        }
        assertThat(await pathExists(readyB)).toBe(false);
        const heldReceipt = JSON.parse(
          await readFile(path.join(root, receiptRelativePath), "utf-8"),
        ) as { readonly writer: string };
        assertThat(heldReceipt.writer).toBe("a");

        await writeFile(gateA, "continue\n", {
          encoding: "utf-8",
          signal: AbortSignal.timeout(5000),
        });
        await assertThat(writerA).resolves.toBeDefined();
        await expectCoherentReceiptEvidence(root, manifestPath, "a");
        const publishedManifest = JSON.parse(await readFile(manifestPath, "utf-8")) as {
          readonly unrelated: { readonly retained: boolean };
        };
        assertThat(publishedManifest.unrelated).toStrictEqual({ retained: true });
        assertThat(await readdir(path.join(root, ".devpunks-cache"))).toStrictEqual([]);

        await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        });
        await expectCoherentReceiptEvidence(root, manifestPath);
        const cacheInventory = await readdir(path.join(root, ".devpunks-cache"));
        assertThat(cacheInventory).toStrictEqual([]);

        const providerSource = providerWriterSource(baseSource);
        const providerAPath = path.join(root, ".agents/scripts/sync-subagents-provider-a.mjs");
        const providerBPath = path.join(root, ".agents/scripts/sync-subagents-provider-b.mjs");
        const providerGate = path.join(raceDirectory, "provider-gate");
        const providerReadyA = path.join(raceDirectory, "provider-ready-a");
        const providerReadyB = path.join(raceDirectory, "provider-ready-b");
        await Promise.all([
          writeFile(providerAPath, providerSource, "utf-8"),
          writeFile(providerBPath, providerSource, "utf-8"),
          execFileAsync(mkfifoPath, [providerGate]),
          execFileAsync(mkfifoPath, [providerReadyA]),
        ]);

        const providerA = execFileAsync(nodePath, [providerAPath], {
          cwd: root,
          env: {
            ...process.env,
            HI_TEST_GATE: providerGate,
            HI_TEST_READY: providerReadyA,
            HI_TEST_WRITER: "a",
          },
          timeout: 10_000,
        });
        await readFile(providerReadyA, { signal: AbortSignal.timeout(5000) });
        const claudeProviderPath = path.join(root, ".claude/agents/frontend-worker.md");
        const heldProviderBytes = await readFile(claudeProviderPath);
        assertThat(heldProviderBytes.toString("utf-8")).toContain("Test writer: a");

        const providerBResult = await Promise.allSettled([
          execFileAsync(nodePath, [providerBPath], {
            cwd: root,
            env: {
              ...process.env,
              HI_TEST_GATE: path.join(raceDirectory, "unused-provider-gate-b"),
              HI_TEST_READY: providerReadyB,
              HI_TEST_WRITER: "b",
            },
            timeout: 5000,
          }),
        ]);
        assertThat(providerBResult[0]?.status).toBe("rejected");
        if (providerBResult[0]?.status === "rejected") {
          assertThat(String(providerBResult[0].reason)).toContain(
            "projection publication is already active; retry sync-subagents",
          );
        }
        assertThat(await pathExists(providerReadyB)).toBe(false);
        assertThat(await readFile(claudeProviderPath)).toStrictEqual(heldProviderBytes);

        await writeFile(providerGate, "continue\n", {
          encoding: "utf-8",
          signal: AbortSignal.timeout(5000),
        });
        await assertThat(providerA).resolves.toBeDefined();

        const rendered = {
          claude: {
            "frontend-worker": await readFile(claudeProviderPath, "utf-8"),
          },
          codex: {
            "frontend-worker": await readFile(
              path.join(root, ".codex/agents/frontend-worker.toml"),
              "utf-8",
            ),
          },
          cursor: {
            "frontend-worker": await readFile(
              path.join(root, ".cursor/agents/frontend-worker.md"),
              "utf-8",
            ),
          },
          opencode: {
            "frontend-worker": await readFile(
              path.join(root, ".opencode/agents/frontend-worker.md"),
              "utf-8",
            ),
          },
        };
        for (const providerBytes of Object.values(rendered).flatMap((files) =>
          Object.values(files),
        )) {
          assertThat(providerBytes).toContain("Test writer: a");
          assertThat(providerBytes).not.toContain("Test writer: b");
        }
        const receipt = JSON.parse(
          await readFile(path.join(root, receiptRelativePath), "utf-8"),
        ) as { readonly renderedOutputSha256: string; readonly writer: string };
        const reconstructedRenderedOutputSha256 = hashJsonContent(
          JSON.stringify({
            availableHooks: { hasFormatHook: true, hasUpdateCheckHook: true },
            rendered,
          }),
        );
        assertThat(receipt).toMatchObject({
          renderedOutputSha256: reconstructedRenderedOutputSha256,
          writer: "a",
        });
        await expectCoherentReceiptEvidence(root, manifestPath, "a");
        assertThat(await readdir(path.join(root, ".devpunks-cache"))).toStrictEqual([]);
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(raceDirectory, { force: true, recursive: true });
      }
    },
  );

  test.runIf(process.platform !== "win32" && mkfifoAvailable)(
    "rejects a later writer while the successful writer still holds its publication boundary",
    async () => {
      const baseSource = await readFile(scriptSourcePath, "utf-8");
      const boundary = [
        "    await assertPublishedReceiptEvidence(",
        "      manifestPreflight,",
        "      committedReceipt.status,",
        "      committedReceiptHash,",
        "    );",
      ].join("\n");
      const scriptSource = publicationWriterSource(baseSource, boundary, "after", "    ");
      assertThat(scriptSource).not.toBe(baseSource);
      assertThat(scriptSource).toContain("HI_TEST_READY");

      const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
      await writeHarnessHooks(root);
      const manifestPath = await writeScaffoldManifest(root, scaffoldManifest());
      const raceDirectory = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-late-race-"));
      const writerAPath = path.join(root, ".agents/scripts/sync-subagents-a.mjs");
      const writerBPath = path.join(root, ".agents/scripts/sync-subagents-b.mjs");
      const gateA = path.join(raceDirectory, "gate-a");
      const readyA = path.join(raceDirectory, "ready-a");
      const readyB = path.join(raceDirectory, "ready-b");
      await Promise.all([
        writeFile(writerAPath, scriptSource, "utf-8"),
        writeFile(writerBPath, scriptSource, "utf-8"),
        execFileAsync(mkfifoPath, [gateA]),
        execFileAsync(mkfifoPath, [readyA]),
      ]);

      try {
        const writerA = execFileAsync(nodePath, [writerAPath], {
          cwd: root,
          env: {
            ...process.env,
            HI_TEST_GATE: gateA,
            HI_TEST_READY: readyA,
            HI_TEST_WRITER: "a",
          },
          timeout: 10_000,
        });
        await readFile(readyA, { signal: AbortSignal.timeout(5000) });
        const writerBResult = await Promise.allSettled([
          execFileAsync(nodePath, [writerBPath], {
            cwd: root,
            env: {
              ...process.env,
              HI_TEST_GATE: path.join(raceDirectory, "unused-gate-b"),
              HI_TEST_READY: readyB,
              HI_TEST_WRITER: "b",
            },
            timeout: 5000,
          }),
        ]);

        assertThat(writerBResult[0]?.status).toBe("rejected");
        if (writerBResult[0]?.status === "rejected") {
          assertThat(String(writerBResult[0].reason)).toContain(
            "projection publication is already active; retry sync-subagents",
          );
        }
        assertThat(await pathExists(readyB)).toBe(false);
        await expectCoherentReceiptEvidence(root, manifestPath, "a");

        await writeFile(gateA, "continue\n", {
          encoding: "utf-8",
          signal: AbortSignal.timeout(5000),
        });
        await assertThat(writerA).resolves.toBeDefined();
        await expectCoherentReceiptEvidence(root, manifestPath, "a");
        const cacheInventory = await readdir(path.join(root, ".devpunks-cache"));
        assertThat(cacheInventory).toStrictEqual([]);
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(raceDirectory, { force: true, recursive: true });
      }
    },
  );

  test.runIf(process.platform !== "win32" && mkfifoAvailable)(
    "rejects a stale preflight after waiting for publication before touching the receipt",
    async () => {
      const baseSource = await readFile(scriptSourcePath, "utf-8");
      const boundary =
        "  const publicationLease = await acquireProjectionPublicationLock(publicationLock);";
      const staleWriterSource = publicationWriterSource(baseSource, boundary, "before", "  ");
      assertThat(staleWriterSource).not.toBe(baseSource);

      const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
      await writeHarnessHooks(root);
      const manifestPath = await writeScaffoldManifest(root, scaffoldManifest());
      const raceDirectory = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-preflight-race-"));
      const staleWriterPath = path.join(root, ".agents/scripts/sync-subagents-stale.mjs");
      const gate = path.join(raceDirectory, "gate");
      const ready = path.join(raceDirectory, "ready");
      await Promise.all([
        writeFile(staleWriterPath, staleWriterSource, "utf-8"),
        execFileAsync(mkfifoPath, [gate]),
        execFileAsync(mkfifoPath, [ready]),
      ]);

      try {
        const staleWriter = execFileAsync(nodePath, [staleWriterPath], {
          cwd: root,
          env: {
            ...process.env,
            HI_TEST_GATE: gate,
            HI_TEST_READY: ready,
            HI_TEST_WRITER: "stale",
          },
          timeout: 10_000,
        });
        await readFile(ready, { signal: AbortSignal.timeout(5000) });

        await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        });
        const publishedReceipt = await readFile(path.join(root, receiptRelativePath));
        const publishedManifest = await readFile(manifestPath);

        await writeFile(gate, "continue\n", {
          encoding: "utf-8",
          signal: AbortSignal.timeout(5000),
        });
        const staleWriterResult = await Promise.allSettled([staleWriter]);
        assertThat(staleWriterResult[0]?.status).toBe("rejected");
        if (staleWriterResult[0]?.status === "rejected") {
          assertThat(String(staleWriterResult[0].reason)).toContain(
            "Scaffold manifest changed after preflight; retry sync-subagents",
          );
        }
        assertThat(await readFile(path.join(root, receiptRelativePath))).toStrictEqual(
          publishedReceipt,
        );
        assertThat(await readFile(manifestPath)).toStrictEqual(publishedManifest);
        await expectCoherentReceiptEvidence(root, manifestPath);
        assertThat(await readdir(path.join(root, ".devpunks-cache"))).toStrictEqual([]);
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(raceDirectory, { force: true, recursive: true });
      }
    },
  );

  test("atomically recovers a stale publication lock and leaves no lock residue", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const scriptSource = baseSource.replace(
      "  await main();",
      "  await main({ publicationLock: { now: () => 1000, staleAfterMs: 50 } });",
    );
    assertThat(scriptSource).not.toBe(baseSource);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
    });
    await writeHarnessHooks(root);
    const manifestPath = await writeScaffoldManifest(root, scaffoldManifest());
    const cacheDirectory = path.join(root, ".devpunks-cache");
    const lockDirectory = path.join(cacheDirectory, "sync-subagents-publication.lock");
    await mkdir(lockDirectory, { recursive: true });
    await writeFile(
      path.join(lockDirectory, "owner.json"),
      `${JSON.stringify({ acquiredAt: 900, token: "stale-owner" }, null, 2)}\n`,
      "utf-8",
    );

    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
      await expectCoherentReceiptEvidence(root, manifestPath);
      assertThat(await readdir(cacheDirectory)).toStrictEqual([]);
    } finally {
      await rm(root, { force: true, recursive: true });
    }

    const futureOwnerSource = baseSource.replace(
      "  await main();",
      "  await main({ publicationLock: { now: () => 1000, staleAfterMs: 50 } });",
    );
    const futureRoot = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: futureOwnerSource,
    });
    await writeHarnessHooks(futureRoot);
    const futureManifestPath = await writeScaffoldManifest(futureRoot, scaffoldManifest());
    const futureCacheDirectory = path.join(futureRoot, ".devpunks-cache");
    const futureLockDirectory = path.join(futureCacheDirectory, "sync-subagents-publication.lock");
    await mkdir(futureLockDirectory, { recursive: true });
    await writeFile(
      path.join(futureLockDirectory, "owner.json"),
      `${JSON.stringify({ acquiredAt: 1100, token: "future-owner" }, null, 2)}\n`,
      "utf-8",
    );

    try {
      await execFileAsync(nodePath, [path.join(futureRoot, ".agents/scripts/sync-subagents.mjs")], {
        cwd: futureRoot,
      });
      await expectCoherentReceiptEvidence(futureRoot, futureManifestPath);
      assertThat(await readdir(futureCacheDirectory)).toStrictEqual([]);
    } finally {
      await rm(futureRoot, { force: true, recursive: true });
    }

    const backwardClockSource = providerWriterSource(baseSource).replace(
      "  await main();",
      "  await main({ publicationLock: { now: () => 1000, staleAfterMs: 50 } });",
    );
    const backwardClockRoot = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: backwardClockSource,
    });
    await writeHarnessHooks(backwardClockRoot);
    await writeScaffoldManifest(backwardClockRoot, scaffoldManifest());
    const backwardClockCacheDirectory = path.join(backwardClockRoot, ".devpunks-cache");
    const backwardClockLockDirectory = path.join(
      backwardClockCacheDirectory,
      "sync-subagents-publication.lock",
    );
    const backwardClockOwnerPath = path.join(backwardClockLockDirectory, "owner.json");
    const backwardClockOwnerBytes = `${JSON.stringify(
      { acquiredAt: 1010, token: "active-owner" },
      null,
      2,
    )}\n`;
    const providerGate = path.join(backwardClockRoot, "provider-gate");
    const providerReady = path.join(backwardClockRoot, "provider-ready");
    await mkdir(backwardClockLockDirectory, { recursive: true });
    await writeFile(backwardClockOwnerPath, backwardClockOwnerBytes, "utf-8");
    await utimes(backwardClockLockDirectory, 1.01, 1.01);
    await writeFile(providerGate, "continue\n", "utf-8");
    const activeLockIdentity = await lstat(backwardClockLockDirectory);

    try {
      const contenderResult = await Promise.allSettled([
        execFileAsync(
          nodePath,
          [path.join(backwardClockRoot, ".agents/scripts/sync-subagents.mjs")],
          {
            cwd: backwardClockRoot,
            env: {
              ...process.env,
              HI_TEST_GATE: providerGate,
              HI_TEST_READY: providerReady,
              HI_TEST_WRITER: "backward-clock-contender",
            },
          },
        ),
      ]);
      assertThat(contenderResult[0]?.status).toBe("rejected");
      if (contenderResult[0]?.status === "rejected") {
        assertThat(String(contenderResult[0].reason)).toContain(
          "projection publication is already active; retry sync-subagents",
        );
      }
      assertThat(await pathExists(providerReady)).toBe(false);
      assertThat(
        await pathExists(path.join(backwardClockRoot, ".claude/agents/frontend-worker.md")),
      ).toBe(false);
      const preservedLockIdentity = await lstat(backwardClockLockDirectory);
      assertThat({
        device: preservedLockIdentity.dev,
        inode: preservedLockIdentity.ino,
      }).toStrictEqual({ device: activeLockIdentity.dev, inode: activeLockIdentity.ino });
      assertThat(await readFile(backwardClockOwnerPath, "utf-8")).toBe(backwardClockOwnerBytes);
    } finally {
      await rm(backwardClockRoot, { force: true, recursive: true });
    }
  });

  test.runIf(process.platform !== "win32" && mkfifoAvailable)(
    "preserves a replacement owner during delayed stale-lock recovery",
    async () => {
      const baseSource = await readFile(scriptSourcePath, "utf-8");
      const boundary = "    try {\n      await removeConfinedPath(publicationLockPath, {";
      const scriptSource = publicationWriterSource(baseSource, boundary, "before", "    ");
      assertThat(scriptSource).not.toBe(baseSource);

      const root = await writeFixture({
        guidanceFile: "app/frontend/AGENTS.md",
        scriptSource,
      });
      await writeHarnessHooks(root);
      await writeScaffoldManifest(root, scaffoldManifest());
      const cacheDirectory = path.join(root, ".devpunks-cache");
      const lockDirectory = path.join(cacheDirectory, "sync-subagents-publication.lock");
      const ownerPath = path.join(lockDirectory, "owner.json");
      await mkdir(lockDirectory, { recursive: true });
      await writeFile(
        ownerPath,
        `${JSON.stringify({ acquiredAt: 0, token: "stale-owner" }, null, 2)}\n`,
        "utf-8",
      );
      const raceDirectory = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-stale-aba-"));
      const gate = path.join(raceDirectory, "gate");
      const ready = path.join(raceDirectory, "ready");
      await Promise.all([execFileAsync(mkfifoPath, [gate]), execFileAsync(mkfifoPath, [ready])]);

      try {
        const delayedRecovery = execFileAsync(
          nodePath,
          [path.join(root, ".agents/scripts/sync-subagents.mjs")],
          {
            cwd: root,
            env: {
              ...process.env,
              HI_TEST_GATE: gate,
              HI_TEST_READY: ready,
              HI_TEST_WRITER: "delayed",
            },
            timeout: 10_000,
          },
        );
        await readFile(ready, { signal: AbortSignal.timeout(5000) });
        const replacementOwner = { acquiredAt: Date.now(), token: "replacement-owner" };
        await writeFile(ownerPath, `${JSON.stringify(replacementOwner, null, 2)}\n`, "utf-8");
        await writeFile(gate, "continue\n", {
          encoding: "utf-8",
          signal: AbortSignal.timeout(5000),
        });

        const result = await Promise.allSettled([delayedRecovery]);
        assertThat(result[0]?.status).toBe("rejected");
        if (result[0]?.status === "rejected") {
          assertThat(String(result[0].reason)).toContain(
            "projection publication is already active; retry sync-subagents",
          );
        }
        assertThat(JSON.parse(await readFile(ownerPath, "utf-8"))).toStrictEqual(replacementOwner);
        assertThat(await readdir(cacheDirectory)).toStrictEqual([
          "sync-subagents-publication.lock",
        ]);
        assertThat(await pathExists(path.join(root, receiptRelativePath))).toBe(false);
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(raceDirectory, { force: true, recursive: true });
      }
    },
  );

  test("does not release a publication lock whose owner token changed", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const releaseBoundary =
      "  } finally {\n    await releaseProjectionPublicationLock(publicationLease);";
    const scriptSource = baseSource.replace(
      releaseBoundary,
      [
        "  } finally {",
        "    await writeConfinedTextFile(",
        "      path.join(publicationLockPath, publicationLockOwnerFile),",
        '      encodeJson({ acquiredAt: Date.now(), token: "replacement-owner" }),',
        "    );",
        "    await releaseProjectionPublicationLock(publicationLease);",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(baseSource);
    assertThat(scriptSource).toContain("replacement-owner");
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
    });
    await writeHarnessHooks(root);
    await writeScaffoldManifest(root, scaffoldManifest());
    const cacheDirectory = path.join(root, ".devpunks-cache");
    const lockDirectory = path.join(cacheDirectory, "sync-subagents-publication.lock");

    try {
      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        }),
      ).rejects.toThrow();
      const owner = JSON.parse(await readFile(path.join(lockDirectory, "owner.json"), "utf-8")) as {
        readonly token: string;
      };
      assertThat(owner.token).toBe("replacement-owner");
      assertThat(await readdir(cacheDirectory)).toStrictEqual(["sync-subagents-publication.lock"]);
    } finally {
      await rm(root, { force: true, recursive: true });
    }
  });

  test("rejects a semantically distinct receipt replacement between publication and reread", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const scriptSource = baseSource.replace(
      "  const committedReceiptBytes = await readConfinedRegularFile(projectionReceiptPath);",
      [
        "  await writeConfinedTextFile(",
        "    projectionReceiptPath,",
        '    encodeJson({ ...receipt, status: "failure", outOfBand: true }),',
        "  );",
        "  const committedReceiptBytes = await readConfinedRegularFile(projectionReceiptPath);",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(baseSource);
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md", scriptSource });
    await writeHarnessHooks(root);
    const initialManifest = scaffoldManifest();
    const manifestPath = await writeScaffoldManifest(root, initialManifest);

    let failure = "";
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
    } catch (error) {
      failure = String(error);
    }

    const replacedReceipt = JSON.parse(
      await readFile(path.join(root, receiptRelativePath), "utf-8"),
    ) as { readonly outOfBand: boolean };
    assertThat(replacedReceipt.outOfBand).toBe(true);
    assertThat(failure).toContain("receipt changed after publication; retry sync-subagents");
    assertThat(JSON.parse(await readFile(manifestPath, "utf-8"))).toStrictEqual(initialManifest);
  });

  test("retains truthful receipt and concurrent manifest bytes on CAS conflict, then retry converges", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const scriptSource = baseSource.replace(
      "  try {\n    await publishReceiptEvidence(",
      [
        "  const concurrentManifestBytes = await readConfinedRegularFile(scaffoldManifestPath);",
        '  const concurrentManifest = JSON.parse(concurrentManifestBytes.toString("utf8"));',
        "  await writeConfinedTextFile(scaffoldManifestPath, encodeJson({ ...concurrentManifest, concurrent: true }));",
        "  try {",
        "    await publishReceiptEvidence(",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(baseSource);
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md", scriptSource });
    await writeHarnessHooks(root);
    const originalManifest = scaffoldManifest();
    const manifestPath = await writeScaffoldManifest(root, originalManifest);

    let failure = "";
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
    } catch (error) {
      failure = String(error);
    }
    const committedReceipt = await readFile(path.join(root, receiptRelativePath));
    const conflictedManifest = JSON.parse(await readFile(manifestPath, "utf-8")) as {
      readonly concurrent: boolean;
      readonly managedFiles: readonly { readonly kind: string; readonly sha256: string }[];
    };
    assertThat(failure).toContain("retry sync-subagents");
    assertThat(conflictedManifest.concurrent).toBe(true);
    assertThat(
      conflictedManifest.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256,
    ).toBe("b".repeat(64));

    await writeFile(
      path.join(root, ".agents/scripts/sync-subagents.mjs"),
      await readFile(scriptSourcePath, "utf-8"),
      "utf-8",
    );
    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });
    const converged = JSON.parse(
      await readFile(manifestPath, "utf-8"),
    ) as typeof conflictedManifest;
    assertThat(converged.concurrent).toBe(true);
    assertThat(
      converged.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256,
    ).toBe(hashManagedFileContent(receiptRelativePath, committedReceipt));
  });

  test("preserves a concurrent manifest recreation after the atomic claim", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const originalManifest = scaffoldManifest();
    const concurrentManifest = { ...originalManifest, concurrent: "path recreation" };
    const publicationBoundary = "      linkSync(request.temporary, request.target);";
    const scriptSource = baseSource.replace(
      publicationBoundary,
      [
        '    if (request.target === "scaffold-manifest.json") {',
        `      writeFileSync(request.target, ${JSON.stringify(`${JSON.stringify(concurrentManifest, null, 4)}\n`)});`,
        "    }",
        publicationBoundary,
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(baseSource);
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md", scriptSource });
    await writeHarnessHooks(root);
    const manifestPath = await writeScaffoldManifest(root, originalManifest);
    let failure = "";
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
    } catch (error) {
      failure = String(error);
    }

    const receipt = JSON.parse(await readFile(path.join(root, receiptRelativePath), "utf-8")) as {
      readonly status: string;
    };
    assertThat(JSON.parse(await readFile(manifestPath, "utf-8"))).toStrictEqual(concurrentManifest);
    assertThat(receipt.status).toBe("success");
    assertThat(failure).toContain("retry sync-subagents");
    const conflictedInventory = await readdir(path.dirname(manifestPath));
    const retainedClaims = conflictedInventory.filter((entry) =>
      entry.startsWith(".hi-manifest-claim-"),
    );
    assertThat(retainedClaims).toHaveLength(1);
    assertThat(
      JSON.parse(
        await readFile(
          path.join(path.dirname(manifestPath), requireDefined(retainedClaims[0])),
          "utf-8",
        ),
      ),
    ).toStrictEqual(originalManifest);
    assertThat(conflictedInventory.filter((entry) => entry.startsWith(".hi-"))).toStrictEqual(
      retainedClaims,
    );

    await writeFile(path.join(root, ".agents/scripts/sync-subagents.mjs"), baseSource, "utf-8");
    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });
    const committedReceipt = await readFile(path.join(root, receiptRelativePath));
    const converged = JSON.parse(await readFile(manifestPath, "utf-8")) as {
      readonly concurrent: string;
      readonly managedFiles: readonly { readonly kind: string; readonly sha256: string }[];
    };
    assertThat(converged.concurrent).toBe("path recreation");
    assertThat(
      converged.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256,
    ).toBe(hashManagedFileContent(receiptRelativePath, committedReceipt));
  });

  test("withdraws publication when a stale descriptor modifies the claimed manifest", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const originalManifest = scaffoldManifest();
    const concurrentManifest = { ...originalManifest, concurrent: "stale descriptor" };
    const scriptSource = baseSource
      .replace(" let descriptor;", " let descriptor;\n let staleManifestDescriptor;")
      .replace(
        "      renameSync(request.target, request.claim);",
        [
          '      if (request.target === "scaffold-manifest.json") {',
          "        staleManifestDescriptor = openSync(request.target, constants.O_WRONLY);",
          "      }",
          "      renameSync(request.target, request.claim);",
        ].join("\n"),
      )
      .replace(
        "      // Supported publication boundary.",
        [
          "      if (staleManifestDescriptor !== undefined) {",
          `        writeFileSync(staleManifestDescriptor, ${JSON.stringify(`${JSON.stringify(concurrentManifest, null, 4)}\n`)});`,
          "        closeSync(staleManifestDescriptor);",
          "        staleManifestDescriptor = undefined;",
          "      }",
          "      // Supported publication boundary.",
        ].join("\n"),
      );
    assertThat(scriptSource).not.toBe(baseSource);
    assertThat(scriptSource).toContain("staleManifestDescriptor = openSync");
    assertThat(scriptSource).toContain("stale descriptor");
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md", scriptSource });
    await writeHarnessHooks(root);
    const manifestPath = await writeScaffoldManifest(root, originalManifest);

    let failure = "";
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
    } catch (error) {
      failure = String(error);
    }

    const receipt = JSON.parse(await readFile(path.join(root, receiptRelativePath), "utf-8")) as {
      readonly status: string;
    };
    assertThat(JSON.parse(await readFile(manifestPath, "utf-8"))).toStrictEqual(concurrentManifest);
    assertThat(receipt.status).toBe("success");
    assertThat(failure).toContain("retry sync-subagents");
    const conflictedInventory = await readdir(path.dirname(manifestPath));
    assertThat(conflictedInventory.filter((entry) => entry.startsWith(".hi-"))).toStrictEqual([]);

    await writeFile(path.join(root, ".agents/scripts/sync-subagents.mjs"), baseSource, "utf-8");
    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });
    const committedReceipt = await readFile(path.join(root, receiptRelativePath));
    const converged = JSON.parse(await readFile(manifestPath, "utf-8")) as {
      readonly concurrent: string;
      readonly managedFiles: readonly { readonly kind: string; readonly sha256: string }[];
    };
    assertThat(converged.concurrent).toBe("stale descriptor");
    assertThat(
      converged.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256,
    ).toBe(hashManagedFileContent(receiptRelativePath, committedReceipt));
  });

  test("withdraws a published manifest modified before the publication boundary", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const originalManifest = scaffoldManifest();
    const modifiedPublication = { ...originalManifest, concurrent: "published inode" };
    const scriptSource = baseSource.replace(
      "      // Supported publication boundary.",
      [
        '      if (request.target === "scaffold-manifest.json") {',
        `        writeFileSync(request.target, ${JSON.stringify(`${JSON.stringify(modifiedPublication, null, 4)}\n`)});`,
        "      }",
        "      // Supported publication boundary.",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(baseSource);
    assertThat(scriptSource).toContain("published inode");
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md", scriptSource });
    await writeHarnessHooks(root);
    const manifestPath = await writeScaffoldManifest(root, originalManifest);

    let failure = "";
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
    } catch (error) {
      failure = String(error);
    }

    const receipt = JSON.parse(await readFile(path.join(root, receiptRelativePath), "utf-8")) as {
      readonly status: string;
    };
    assertThat(JSON.parse(await readFile(manifestPath, "utf-8"))).toStrictEqual(originalManifest);
    assertThat(receipt.status).toBe("success");
    assertThat(failure).toContain("retry sync-subagents");
    const conflictedInventory = await readdir(path.dirname(manifestPath));
    assertThat(conflictedInventory.filter((entry) => entry.startsWith(".hi-"))).toStrictEqual([]);

    await writeFile(path.join(root, ".agents/scripts/sync-subagents.mjs"), baseSource, "utf-8");
    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });
    const committedReceipt = await readFile(path.join(root, receiptRelativePath));
    const converged = JSON.parse(await readFile(manifestPath, "utf-8")) as {
      readonly managedFiles: readonly { readonly kind: string; readonly sha256: string }[];
    };
    assertThat(
      converged.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256,
    ).toBe(hashManagedFileContent(receiptRelativePath, committedReceipt));
  });

  test("bounds validation when the claimed manifest grows before publication", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const maximumBytes = 16 * 1024 * 1024;
    const readBoundary =
      "      const bytesRead = readSync(contentDescriptor, buffer, 0, buffer.length, null);";
    const scriptSource = baseSource
      .replace(
        readBoundary,
        [
          "      if (fstatSync(contentDescriptor).size > 16 * 1024 * 1024) {",
          '        writeFileSync("unbounded-read-reached", "reached\\n");',
          "      }",
          readBoundary,
        ].join("\n"),
      )
      .replace(
        "      // Supported publication boundary.",
        [
          '      if (request.target === "scaffold-manifest.json") {',
          "        writeFileSync(request.claim, Buffer.alloc(16 * 1024 * 1024 + 1, 0x20));",
          "      }",
          "      // Supported publication boundary.",
        ].join("\n"),
      );
    assertThat(scriptSource).not.toBe(baseSource);
    assertThat(scriptSource).toContain("unbounded-read-reached");
    const originalManifest = scaffoldManifest();
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md", scriptSource });
    await writeHarnessHooks(root);
    const manifestPath = await writeScaffoldManifest(root, originalManifest);
    const markerPath = path.join(root, ".devpunks/unbounded-read-reached");

    let failure = "";
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      });
    } catch (error) {
      failure = String(error);
    }

    assertThat(await pathExists(markerPath)).toBe(false);
    const conflictedManifest = await lstat(manifestPath);
    assertThat(conflictedManifest.size).toBe(maximumBytes + 1);
    assertThat(failure).toContain("retry sync-subagents");
    assertThat(failure).toContain("EFBIG");

    await writeScaffoldManifest(root, originalManifest);
    await writeFile(path.join(root, ".agents/scripts/sync-subagents.mjs"), baseSource, "utf-8");
    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });
    const committedReceipt = await readFile(path.join(root, receiptRelativePath));
    const converged = JSON.parse(await readFile(manifestPath, "utf-8")) as {
      readonly managedFiles: readonly { readonly kind: string; readonly sha256: string }[];
    };
    assertThat(
      converged.managedFiles.find(({ kind }) => kind === "projection-receipt")?.sha256,
    ).toBe(hashManagedFileContent(receiptRelativePath, committedReceipt));
  });

  test("atomically writes managed agents with a long valid basename", async () => {
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      writeContextPlan: false,
    });
    const longAgentName = "a".repeat(230);
    const manifestPath = path.join(root, ".agents/subagents/manifest.mjs");
    const manifest = await readFile(manifestPath, "utf-8");
    await writeFile(manifestPath, manifest.replaceAll("frontend-worker", longAgentName), "utf-8");

    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });

    assertThat(
      await readFile(path.join(root, ".codex/agents", `${longAgentName}.toml`), "utf-8"),
    ).toContain(`name = ${JSON.stringify(longAgentName)}`);
  });

  test("atomically replaces a hard-linked Codex config without changing the shared inode", async () => {
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      writeContextPlan: false,
    });
    const outsideDirectory = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-shared-"));
    const outsidePath = path.join(outsideDirectory, "config.toml");
    const configPath = path.join(root, ".codex/config.toml");
    await mkdir(path.dirname(configPath), { recursive: true });
    await writeFile(outsidePath, "shared config\n", "utf-8");
    await link(outsidePath, configPath);

    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });

    assertThat(await readFile(outsidePath, "utf-8")).toBe("shared config\n");
    assertThat(await readFile(configPath, "utf-8")).toContain("[agents]");
    const configStat = await lstat(configPath);
    const outsideStat = await lstat(outsidePath);
    assertThat(configStat.ino).not.toBe(outsideStat.ino);
  });

  test("atomically replaces a hard-linked managed agent without changing the shared inode", async () => {
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      writeContextPlan: false,
    });
    const outsideDirectory = await mkdtemp(path.join(os.tmpdir(), "sync-subagents-agent-"));
    const outsidePath = path.join(outsideDirectory, "frontend-worker.toml");
    const agentPath = path.join(root, ".codex/agents/frontend-worker.toml");
    await mkdir(path.dirname(agentPath), { recursive: true });
    await writeFile(outsidePath, "shared agent\n", "utf-8");
    await link(outsidePath, agentPath);

    await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
      cwd: root,
    });

    assertThat(await readFile(outsidePath, "utf-8")).toBe("shared agent\n");
    assertThat(await readFile(agentPath, "utf-8")).toContain('name = "frontend-worker"');
    const agentStat = await lstat(agentPath);
    const outsideStat = await lstat(outsidePath);
    assertThat(agentStat.ino).not.toBe(outsideStat.ino);
  });

  test.each([
    ["claude", ".claude/hooks"],
    ["codex", ".codex/hooks"],
    ["cursor", ".cursor/hooks"],
    ["opencode", ".opencode/plugins"],
  ] as const)(
    "rejects a symlinked %s hook mirror directory before deleting outside the repository",
    async (adapterId, hookDirectory) => {
      const outside = await mkdtemp(path.join(os.tmpdir(), `ip317-${adapterId}-hooks-outside-`));
      const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
      const scriptPath = path.join(root, ".agents/scripts/sync-subagents.mjs");
      const outsideFormatHook = path.join(outside, "format-edited-file.mjs");
      const outsideUpdateHook = path.join(outside, "scaffold-update-check.mjs");
      const withoutFormatter = structuredClone(canonicalContextPlan);
      const hookScope = requireDefined(withoutFormatter.scopes[1]);
      hookScope.contributions = hookScope.contributions.filter(
        ({ identity }) => identity.id !== "format-edited-file",
      );

      try {
        await mkdir(path.join(root, ".agents/hooks"), { recursive: true });
        await writeFile(
          path.join(root, ".agents/hooks/scaffold-update-check.mjs"),
          "canonical update hook\n",
          "utf-8",
        );
        await writeFile(outsideFormatHook, "outside format sentinel\n", "utf-8");
        await writeFile(outsideUpdateHook, "outside update sentinel\n", "utf-8");
        await mkdir(path.dirname(path.join(root, hookDirectory)), { recursive: true });
        await symlink(outside, path.join(root, hookDirectory));
        await writeFile(
          path.join(root, ".devpunks/context-plan.json"),
          `${JSON.stringify(withoutFormatter, null, 2)}\n`,
          "utf-8",
        );

        await assertThat(execFileAsync(nodePath, [scriptPath], { cwd: root })).rejects.toThrow();
        assertThat(await readFile(outsideFormatHook, "utf-8")).toBe("outside format sentinel\n");
        assertThat(await readFile(outsideUpdateHook, "utf-8")).toBe("outside update sentinel\n");

        const receipt = JSON.parse(
          await readFile(path.join(root, ".devpunks/harness-projection-receipt.json"), "utf-8"),
        ) as {
          readonly status: string;
          readonly projections: readonly {
            readonly adapter: { readonly id: string };
            readonly actions: readonly {
              readonly id: string;
              readonly operation: string;
              readonly managedHookFiles?: readonly string[];
            }[];
            readonly failures: readonly {
              readonly _tag: string;
              readonly action: string;
            }[];
          }[];
        };
        const projection = receipt.projections.find(({ adapter }) => adapter.id === adapterId);
        const reconciliation = projection?.actions.find(
          ({ operation }) => operation === "reconcile-lifecycle-hooks",
        );

        assertThat(receipt.status).toBe("failure");
        assertThat(reconciliation?.managedHookFiles).toEqual([
          `${hookDirectory}/format-edited-file.mjs`,
          `${hookDirectory}/scaffold-update-check.mjs`,
        ]);
        assertThat(projection?.failures).toContainEqual(
          assertThat.objectContaining({
            _tag: "HarnessApplicationFailureError",
            action: `${adapterId}:reconcile-lifecycle-hooks`,
          }),
        );
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(outside, { force: true, recursive: true });
      }
    },
  );

  test("rejects projection paths that escape the consumer repository", async () => {
    const escapeRoot = path.join(os.tmpdir(), "ip317-path-escape");
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
    const unsafeContextPlan = {
      ...canonicalContextPlan,
      scopes: canonicalContextPlan.scopes.map((scope, index) =>
        index === 0 ? { ...scope, id: "../ip317-path-escape" } : scope,
      ),
    };

    await mkdir(escapeRoot);
    try {
      await writeFile(path.join(escapeRoot, "AGENTS.md"), "outside fixture source\n", "utf-8");
      await mkdir(path.join(root, ".agents/hooks"), { recursive: true });
      await writeFile(path.join(root, ".agents/hooks/format-edited-file.mjs"), "", "utf-8");
      await writeFile(path.join(root, ".agents/hooks/scaffold-update-check.mjs"), "", "utf-8");
      await writeFile(
        path.join(root, ".devpunks/context-plan.json"),
        `${JSON.stringify(unsafeContextPlan, null, 2)}\n`,
        "utf-8",
      );

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        }),
      ).rejects.toThrow();
      await assertThat(readFile(path.join(escapeRoot, "CLAUDE.md"), "utf-8")).rejects.toMatchObject(
        {
          code: "ENOENT",
        },
      );

      const receipt = JSON.parse(
        await readFile(path.join(root, ".devpunks/harness-projection-receipt.json"), "utf-8"),
      ) as {
        readonly status: string;
        readonly projections: readonly {
          readonly adapter: { readonly id: string };
          readonly failures: readonly { readonly _tag: string; readonly action: string }[];
        }[];
      };
      assertThat(receipt.status).toBe("failure");
      assertThat(
        receipt.projections.find(({ adapter }) => adapter.id === "claude")?.failures,
      ).toContainEqual(
        assertThat.objectContaining({
          _tag: "HarnessApplicationFailureError",
          action: assertThat.stringContaining("claude:scoped-prompt"),
        }),
      );
      assertThat(
        await readFile(path.join(root, ".codex/agents/frontend-worker.toml"), "utf-8"),
      ).toContain("Only this consumer-authored guidance");
    } finally {
      await rm(escapeRoot, { force: true, recursive: true });
    }
  });

  test("rejects projection targets beneath symlinked parents while continuing safe actions", async () => {
    const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-symlink-outside-"));
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
    const unsafeContextPlan = {
      ...canonicalContextPlan,
      scopes: [
        ...canonicalContextPlan.scopes,
        {
          contributions: [
            {
              compatibility: [],
              identity: { id: "linked-agents", version: "2026.07.17" },
              kind: "scoped-prompt",
              order: 0,
              provenance: { revision: "2026.07.17", source: "bundled" },
              references: [],
            },
          ],
          id: "linked",
          packs: [],
        },
      ],
    };

    try {
      await symlink(outside, path.join(root, "linked"));
      await writeFile(path.join(outside, "AGENTS.md"), "outside source\n", "utf-8");
      await mkdir(path.join(root, ".agents/hooks"), { recursive: true });
      await writeFile(path.join(root, ".agents/hooks/format-edited-file.mjs"), "", "utf-8");
      await writeFile(path.join(root, ".agents/hooks/scaffold-update-check.mjs"), "", "utf-8");
      await writeFile(
        path.join(root, ".devpunks/context-plan.json"),
        `${JSON.stringify(unsafeContextPlan, null, 2)}\n`,
        "utf-8",
      );

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        }),
      ).rejects.toThrow();
      await assertThat(readFile(path.join(outside, "CLAUDE.md"), "utf-8")).rejects.toMatchObject({
        code: "ENOENT",
      });
      assertThat(
        await readFile(path.join(root, ".codex/agents/frontend-worker.toml"), "utf-8"),
      ).toContain("Only this consumer-authored guidance");
      const receipt = JSON.parse(
        await readFile(path.join(root, ".devpunks/harness-projection-receipt.json"), "utf-8"),
      ) as {
        readonly status: string;
        readonly projections: readonly {
          readonly adapter: { readonly id: string };
          readonly failures: readonly { readonly _tag: string; readonly action: string }[];
        }[];
      };
      assertThat(receipt.status).toBe("failure");
      assertThat(
        receipt.projections.find(({ adapter }) => adapter.id === "claude")?.failures,
      ).toContainEqual(
        assertThat.objectContaining({
          _tag: "HarnessApplicationFailureError",
          action: assertThat.stringContaining("claude:scoped-prompt:linked"),
        }),
      );
    } finally {
      await rm(root, { force: true, recursive: true });
      await rm(outside, { force: true, recursive: true });
    }
  });

  test("rejects a symlinked Cursor configuration leaf before writing outside the repository", async () => {
    const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-cursor-config-outside-"));
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
    const outsideConfig = path.join(outside, "hooks.json");

    try {
      await mkdir(path.join(root, ".agents/hooks"), { recursive: true });
      await writeFile(path.join(root, ".agents/hooks/format-edited-file.mjs"), "", "utf-8");
      await writeFile(path.join(root, ".agents/hooks/scaffold-update-check.mjs"), "", "utf-8");
      await mkdir(path.join(root, ".cursor"), { recursive: true });
      await writeFile(outsideConfig, "outside config\n", "utf-8");
      await symlink(outsideConfig, path.join(root, ".cursor/hooks.json"));

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        }),
      ).rejects.toThrow();
      assertThat(await readFile(outsideConfig, "utf-8")).toBe("outside config\n");
      assertThat(
        await readFile(path.join(root, ".codex/agents/frontend-worker.toml"), "utf-8"),
      ).toContain("Only this consumer-authored guidance");
      const receipt = JSON.parse(
        await readFile(path.join(root, ".devpunks/harness-projection-receipt.json"), "utf-8"),
      ) as {
        readonly status: string;
        readonly projections: readonly {
          readonly adapter: { readonly id: string };
          readonly failures: readonly { readonly _tag: string; readonly action: string }[];
        }[];
      };
      assertThat(receipt.status).toBe("failure");
      assertThat(
        receipt.projections.find(({ adapter }) => adapter.id === "cursor")?.failures,
      ).toContainEqual(
        assertThat.objectContaining({
          _tag: "HarnessApplicationFailureError",
          action: assertThat.stringContaining("cursor:lifecycle-hook"),
        }),
      );
    } finally {
      await rm(root, { force: true, recursive: true });
      await rm(outside, { force: true, recursive: true });
    }
  });

  test("rejects a symlinked projection receipt without changing its external target", async () => {
    const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-receipt-outside-"));
    const root = await writeFixture({ guidanceFile: "app/frontend/AGENTS.md" });
    const outsideReceipt = path.join(outside, "receipt.json");
    const originalContent = "{}\n";

    try {
      await writeFile(outsideReceipt, originalContent, "utf-8");
      await rm(path.join(root, ".devpunks/harness-projection-receipt.json"), { force: true });
      await symlink(outsideReceipt, path.join(root, ".devpunks/harness-projection-receipt.json"));

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        }),
      ).rejects.toThrow();
      const outsideContent = await readFile(outsideReceipt, "utf-8");
      assertThat(outsideContent).toBe(originalContent);
    } finally {
      await rm(root, { force: true, recursive: true });
      await rm(outside, { force: true, recursive: true });
    }
  });

  test.runIf(process.platform !== "win32")(
    "rejects a repo-root swap before parent capture without changing outside inventory",
    async () => {
      const sourceFile = await readFile(scriptSourcePath, "utf-8");
      const captureBoundary =
        "async function captureConfinedDirectoryIdentity(directoryPath, operation, repoRootIdentity) {";
      const scriptSource = sourceFile
        .replace("{ lstat, readFile,", "{ lstat, readFile, rename, symlink,")
        .replace(
          captureBoundary,
          [
            captureBoundary,
            "  if (!globalThis.__HI_TEST_ROOT_SWAPPED) {",
            "    globalThis.__HI_TEST_ROOT_SWAPPED = true;",
            "    await rename(repoRoot, process.env.HI_TEST_DISPLACED_ROOT);",
            "    await symlink(process.env.HI_TEST_OUTSIDE_ROOT, repoRoot);",
            "  }",
          ].join("\n"),
        );
      assertThat(scriptSource).not.toBe(sourceFile);
      const root = await writeFixture({
        guidanceFile: "app/frontend/AGENTS.md",
        scriptSource,
      });
      const displacedRoot = `${root}-displaced`;
      const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-root-swap-outside-"));
      await writeFile(path.join(outside, "sentinel.txt"), "outside sentinel\n", "utf-8");

      try {
        await assertThat(
          execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
            cwd: root,
            env: {
              ...process.env,
              HI_TEST_DISPLACED_ROOT: displacedRoot,
              HI_TEST_OUTSIDE_ROOT: outside,
            },
          }),
        ).rejects.toThrow();

        assertThat(await readdir(outside)).toStrictEqual(["sentinel.txt"]);
        assertThat(await readFile(path.join(outside, "sentinel.txt"), "utf-8")).toBe(
          "outside sentinel\n",
        );
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(displacedRoot, { force: true, recursive: true });
        await rm(outside, { force: true, recursive: true });
      }
    },
  );

  test.runIf(process.platform !== "win32")(
    "keeps one repo-root identity across sequential sync mutations",
    async () => {
      const sourceFile = await readFile(scriptSourcePath, "utf-8");
      const completedWriteBoundary = [
        "  await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);",
        "}",
        "",
        "async function readConfinedRegularFile",
      ].join("\n");
      const scriptSource = sourceFile
        .replace("{ lstat, readFile,", "{ lstat, mkdir, readFile, rename, writeFile,")
        .replace(
          completedWriteBoundary,
          [
            "  await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);",
            "  if (!globalThis.__HI_TEST_ROOT_REPLACED) {",
            "    globalThis.__HI_TEST_ROOT_REPLACED = true;",
            "    await rename(repoRoot, process.env.HI_TEST_DISPLACED_ROOT);",
            "    await mkdir(repoRoot);",
            '    await writeFile(path.join(repoRoot, "replacement.txt"), "replacement\\n");',
            "  }",
            "}",
            "",
            "async function readConfinedRegularFile",
          ].join("\n"),
        );
      assertThat(scriptSource).not.toBe(sourceFile);
      assertThat(scriptSource).toContain("__HI_TEST_ROOT_REPLACED");
      const root = await writeFixture({
        guidanceFile: "app/frontend/AGENTS.md",
        scriptSource,
        writeContextPlan: false,
      });
      const displacedRoot = `${root}-displaced`;
      const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-root-session-outside-"));
      await writeFile(path.join(outside, "sentinel.txt"), "outside\n");

      try {
        await assertThat(
          execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
            cwd: root,
            env: { ...process.env, HI_TEST_DISPLACED_ROOT: displacedRoot },
          }),
        ).rejects.toThrow();
        assertThat(await readdir(root)).toStrictEqual(["replacement.txt"]);
        assertThat(await readdir(outside)).toStrictEqual(["sentinel.txt"]);
        assertThat(await pathExists(path.join(displacedRoot, ".codex"))).toBe(true);
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(displacedRoot, { force: true, recursive: true });
        await rm(outside, { force: true, recursive: true });
      }
    },
  );

  test.runIf(process.platform !== "win32")(
    "binds sync directory creation to its validated parent",
    async () => {
      const sourceFile = await readFile(scriptSourcePath, "utf-8");
      const mkdirBoundary = [
        "      await runStableMutation(parentDirectory, {",
        '        operation: "mkdir",',
      ].join("\n");
      const scriptSource = sourceFile
        .replace("{ lstat,", "{ lstat, rename, symlink,")
        .replace(
          mkdirBoundary,
          [
            "      await rename(parentDirectory, process.env.HI_TEST_DISPLACED_PARENT);",
            "      await symlink(process.env.HI_TEST_OUTSIDE_PARENT, parentDirectory);",
            mkdirBoundary,
          ].join("\n"),
        );
      assertThat(scriptSource).not.toBe(sourceFile);
      const root = await writeFixture({
        guidanceFile: "app/frontend/AGENTS.md",
        scriptSource,
        writeContextPlan: false,
      });
      const displacedRoot = `${root}-displaced`;
      const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-mkdir-session-outside-"));
      await writeFile(path.join(outside, "sentinel.txt"), "outside\n");

      try {
        await assertThat(
          execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
            cwd: root,
            env: {
              ...process.env,
              HI_TEST_DISPLACED_PARENT: displacedRoot,
              HI_TEST_OUTSIDE_PARENT: outside,
            },
          }),
        ).rejects.toThrow();
        assertThat(await readdir(outside)).toStrictEqual(["sentinel.txt"]);
        assertThat(await pathExists(path.join(displacedRoot, ".codex"))).toBe(false);
      } finally {
        await rm(root, { force: true, recursive: true });
        await rm(displacedRoot, { force: true, recursive: true });
        await rm(outside, { force: true, recursive: true });
      }
    },
  );

  test("settles worker shutdown promptly when spawn cwd is missing", async () => {
    const sourceFile = await readFile(scriptSourcePath, "utf-8");
    const workerBoundary = "function createMutationWorker(parentDirectory, parentIdentity, key) {";
    const scriptSource = sourceFile.replace(
      workerBoundary,
      [workerBoundary, '  parentDirectory = path.join(repoRoot, "removed-worker-cwd");'].join("\n"),
    );
    assertThat(scriptSource).not.toBe(sourceFile);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
      writeContextPlan: false,
    });
    const startedAt = Date.now();
    let failure: unknown;
    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
        timeout: 2000,
      });
    } catch (error) {
      failure = error;
    } finally {
      await rm(root, { force: true, recursive: true });
    }

    assertThat(failure).toBeDefined();
    assertThat(Date.now() - startedAt).toBeLessThan(2000);
    assertThat(String(failure)).toContain("ENOENT");
  });

  test("bounds mutation workers across many unique parents", async () => {
    const sourceFile = await readFile(scriptSourcePath, "utf-8");
    const spawnBoundary = ["  const child = spawn(", "    process.execPath,"].join("\n");
    const sessionBoundary =
      '  operationRepoRootIdentity = await captureRepoRootIdentity("synchronize scaffold output");';
    const closeBoundary = ["} finally {", "  await closeMutationWorkers();", "}"].join("\n");
    const scriptSource = sourceFile
      .replace("{ lstat, readFile,", "{ lstat, readFile, writeFile,")
      .replace(
        "const mutationWorkers = new Map();",
        [
          "let activeWorkerCount = 0;",
          "let peakWorkerCount = 0;",
          "const instrumentedSpawn = (...args) => {",
          "  const child = spawn(...args);",
          "  activeWorkerCount += 1;",
          "  peakWorkerCount = Math.max(peakWorkerCount, activeWorkerCount);",
          '  child.once("exit", () => { activeWorkerCount -= 1; });',
          "  return child;",
          "};",
          "const mutationWorkers = new Map();",
        ].join("\n"),
      )
      .replace(spawnBoundary, spawnBoundary.replace("spawn", "instrumentedSpawn"))
      .replace(
        sessionBoundary,
        [
          sessionBoundary,
          "  for (let index = 0; index < 24; index += 1) {",
          '    const parentDirectory = path.join(repoRoot, "worker-parents", String(index));',
          "    await ensureConfinedDirectory(parentDirectory);",
          '    await writeConfinedTextFile(path.join(parentDirectory, "value.txt"), "parent-" + index + "\\n");',
          "  }",
        ].join("\n"),
      )
      .replace(
        closeBoundary,
        [
          "} finally {",
          "  await closeMutationWorkers();",
          "  await writeFile(",
          "    process.env.HI_TEST_WORKER_STATS,",
          "    JSON.stringify({ active: activeWorkerCount, peak: peakWorkerCount }),",
          "  );",
          "}",
        ].join("\n"),
      );
    assertThat(scriptSource).not.toBe(sourceFile);
    assertThat(scriptSource).not.toContain(spawnBoundary);
    assertThat(scriptSource).not.toContain(closeBoundary);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
      writeContextPlan: false,
    });
    const statsPath = path.join(root, "worker-stats.json");

    try {
      await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
        env: { ...process.env, HI_TEST_WORKER_STATS: statsPath },
      });
      const stats = JSON.parse(await readFile(statsPath, "utf-8")) as {
        readonly active: number;
        readonly peak: number;
      };
      assertThat(stats).toMatchObject({ active: 0 });
      assertThat(stats.peak).toBeLessThanOrEqual(8);
      const parentContents = await Promise.all(
        Array.from({ length: 24 }, (_, index) =>
          readFile(path.join(root, "worker-parents", String(index), "value.txt"), "utf-8"),
        ),
      );
      assertThat(parentContents).toStrictEqual(
        Array.from({ length: 24 }, (_, index) => `parent-${index}\n`),
      );
    } finally {
      await rm(root, { force: true, recursive: true });
    }
  });

  test.runIf(process.platform !== "win32" && mkfifoAvailable)(
    "rejects FIFO, device, and symlink receipt leaves before their first read",
    async () => {
      const sourceFile = await readFile(scriptSourcePath, "utf-8");
      const scriptSource = sourceFile
        .replace("{ lstat, readFile,", "{ lstat, readFile as nodeReadFile, writeFile,")
        .replace(
          'const projectionReceiptPath = path.join(repoRoot, ".devpunks/harness-projection-receipt.json");',
          [
            'const projectionReceiptPath = path.join(repoRoot, ".devpunks/harness-projection-receipt.json");',
            "const readFile = async (filePath, ...args) => {",
            "  if (path.resolve(filePath) === projectionReceiptPath) {",
            '    await writeFile(process.env.HI_TEST_RECEIPT_READ_MARKER, "read reached\\n");',
            '    throw new Error("Unsafe receipt read reached");',
            "  }",
            "  return nodeReadFile(filePath, ...args);",
            "};",
          ].join("\n"),
        );

      await Promise.all(
        (["fifo", "device", "symlink"] as const).map(async (leafType) => {
          const outside = await mkdtemp(path.join(os.tmpdir(), `ip317-receipt-${leafType}-`));
          const root = await writeFixture({
            guidanceFile: "app/frontend/AGENTS.md",
            scriptSource,
          });
          const receiptPath = path.join(root, ".devpunks/harness-projection-receipt.json");
          const markerPath = path.join(outside, "read-marker.txt");
          const outsideReceipt = path.join(outside, "receipt.json");

          try {
            await rm(receiptPath, { force: true });
            if (leafType === "fifo") {
              await execFileAsync(mkfifoPath, [receiptPath]);
            } else if (leafType === "device") {
              await symlink("/dev/null", receiptPath);
            } else {
              await writeFile(outsideReceipt, "outside sentinel\n", "utf-8");
              await symlink(outsideReceipt, receiptPath);
            }
            const before = await repositoryInventory(root);

            await assertThat(
              execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
                cwd: root,
                env: { ...process.env, HI_TEST_RECEIPT_READ_MARKER: markerPath },
                timeout: 3000,
              }),
            ).rejects.toThrow();

            assertThat(await pathExists(markerPath), leafType).toBe(false);
            assertThat(await repositoryInventory(root), leafType).toStrictEqual(before);
            if (leafType === "symlink") {
              const outsideContent = await readFile(outsideReceipt, "utf-8");
              assertThat(outsideContent).toBe("outside sentinel\n");
            }
          } finally {
            await rm(root, { force: true, recursive: true });
            await rm(outside, { force: true, recursive: true });
          }
        }),
      );
    },
  );

  test.runIf(process.platform !== "win32")(
    "rejects receipt leaf and parent swaps between preflight and descriptor read",
    async () => {
      const sourceFile = await readFile(scriptSourcePath, "utf-8");
      const boundary = "  await assertConfinedRegularFile(projectionReceiptPath);";
      const returnBoundary = '    return Buffer.from(result.content, "base64");';
      const scriptSource = sourceFile
        .replace("{ lstat, readFile,", "{ lstat, readFile, rename, symlink, writeFile,")
        .replace(
          boundary,
          [
            boundary,
            '  if (process.env.HI_TEST_RECEIPT_SWAP === "leaf") {',
            '    await rename(projectionReceiptPath, projectionReceiptPath + "-displaced");',
            "    await symlink(process.env.HI_TEST_OUTSIDE_RECEIPT, projectionReceiptPath);",
            "  } else {",
            "    const receiptParent = path.dirname(projectionReceiptPath);",
            '    await rename(receiptParent, receiptParent + "-displaced");',
            "    await symlink(process.env.HI_TEST_OUTSIDE_PARENT, receiptParent);",
            "  }",
          ].join("\n"),
        )
        .replace(
          returnBoundary,
          [
            '    await writeFile(process.env.HI_TEST_RECEIPT_READ_MARKER, "read reached\\n");',
            returnBoundary,
          ].join("\n"),
        );
      assertThat(scriptSource).not.toBe(sourceFile);
      assertThat(scriptSource).toContain("HI_TEST_RECEIPT_READ_MARKER");

      await Promise.all(
        (["leaf", "parent"] as const).map(async (swap) => {
          const outside = await mkdtemp(path.join(os.tmpdir(), `ip317-receipt-${swap}-outside-`));
          const root = await writeFixture({
            guidanceFile: "app/frontend/AGENTS.md",
            scriptSource,
          });
          const receiptPath = path.join(root, ".devpunks/harness-projection-receipt.json");
          const displacedPath =
            swap === "leaf" ? `${receiptPath}-displaced` : path.join(root, ".devpunks-displaced");
          const outsideReceipt = path.join(outside, "harness-projection-receipt.json");
          const markerPath = path.join(outside, "read-marker.txt");
          const originalReceipt = "{}\n";
          await writeFile(receiptPath, originalReceipt, "utf-8");
          await writeFile(outsideReceipt, "{}\n", "utf-8");

          try {
            await assertThat(
              execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
                cwd: root,
                env: {
                  ...process.env,
                  HI_TEST_OUTSIDE_PARENT: outside,
                  HI_TEST_OUTSIDE_RECEIPT: outsideReceipt,
                  HI_TEST_RECEIPT_READ_MARKER: markerPath,
                  HI_TEST_RECEIPT_SWAP: swap,
                },
                timeout: 3000,
              }),
            ).rejects.toThrow();

            assertThat(await pathExists(markerPath), swap).toBe(false);
            assertThat(await readFile(outsideReceipt, "utf-8"), swap).toBe("{}\n");
            const displacedReceipt =
              swap === "leaf"
                ? displacedPath
                : path.join(displacedPath, "harness-projection-receipt.json");
            assertThat(await readFile(displacedReceipt, "utf-8"), swap).toBe(originalReceipt);
            const outsideEntries = await readdir(outside);
            const outsideInventory = outsideEntries.toSorted();
            assertThat(outsideInventory, swap).toStrictEqual(["harness-projection-receipt.json"]);
          } finally {
            await rm(root, { force: true, recursive: true });
            await rm(displacedPath, { force: true, recursive: true });
            await rm(outside, { force: true, recursive: true });
          }
        }),
      );
    },
  );

  test.runIf(process.platform !== "win32")(
    "checks receipt descriptor identity before read when no-follow is unavailable",
    async () => {
      await Promise.all(
        (["symlink", "descriptor"] as const).map(async (substitution) => {
          const outside = await mkdtemp(
            path.join(os.tmpdir(), `ip317-receipt-descriptor-${substitution}-`),
          );
          const outsideReceipt = path.join(outside, "outside-receipt.json");
          const markerPath = path.join(outside, "read-marker.txt");
          const sourceFile = await readFile(scriptSourcePath, "utf-8");
          const boundary =
            "  const target = await assertConfinedRegularFile(targetPath, repoRootIdentity);";
          const scriptSource = sourceFile
            .replace("{ lstat, readFile,", "{ link, lstat, readFile, rename, symlink,")
            .replace("(constants.O_NOFOLLOW ?? 0)", "0")
            .replace(
              "      const bytesRead = readSync(descriptor, chunk, 0, chunk.length, null);",
              `      writeFileSync(${JSON.stringify(markerPath)}, "read reached\\n");\n      const bytesRead = readSync(descriptor, chunk, 0, chunk.length, null);`,
            )
            .replace(
              boundary,
              [
                boundary,
                '  if (path.basename(targetPath) === "harness-projection-receipt.json") {',
                '    await rename(targetPath, targetPath + "-displaced");',
                substitution === "symlink"
                  ? `    await symlink(${JSON.stringify(outsideReceipt)}, targetPath);`
                  : `    await link(${JSON.stringify(outsideReceipt)}, targetPath);`,
                "  }",
              ].join("\n"),
            );
          assertThat(scriptSource).not.toBe(sourceFile);
          const root = await writeFixture({
            guidanceFile: "app/frontend/AGENTS.md",
            scriptSource,
          });
          const receiptPath = path.join(root, ".devpunks/harness-projection-receipt.json");
          const displacedReceipt = `${receiptPath}-displaced`;
          await writeFile(receiptPath, "inside receipt\n", "utf-8");
          await writeFile(outsideReceipt, "outside sentinel\n", "utf-8");

          try {
            await assertThat(
              execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
                cwd: root,
              }),
            ).rejects.toThrow();
            assertThat({
              displaced: await readFile(displacedReceipt, "utf-8"),
              markerExists: await pathExists(markerPath),
              outside: await readFile(outsideReceipt, "utf-8"),
            }).toStrictEqual({
              displaced: "inside receipt\n",
              markerExists: false,
              outside: "outside sentinel\n",
            });
          } finally {
            await rm(root, { force: true, recursive: true });
            await rm(outside, { force: true, recursive: true });
          }
        }),
      );
    },
  );

  test("rejects a parent swap immediately before rename without changing an outside sentinel", async () => {
    const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-parent-swap-outside-"));
    const scriptSource = await readFile(scriptSourcePath, "utf-8");
    const source = scriptSource.replace("{ lstat,", "{ lstat, rename, symlink,");
    const mutationBoundary = [
      "  await runStableMutation(",
      "    parentDirectory,",
      "    {",
      '      operation: "write",',
    ].join("\n");
    const injectedBoundary = [
      '  if (targetPath === projectionReceiptPath && process.env.HI_TEST_SWAP_PARENT === "1") {',
      "      delete process.env.HI_TEST_SWAP_PARENT;",
      '      await rename(parentDirectory, parentDirectory + "-displaced");',
      "      await symlink(process.env.HI_TEST_OUTSIDE_PARENT, parentDirectory);",
      "  }",
      mutationBoundary,
    ].join("\n");
    const transformed = source.replace(mutationBoundary, injectedBoundary);
    assertThat(transformed).not.toBe(source);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: transformed,
    });
    const outsideReceipt = path.join(outside, "harness-projection-receipt.json");

    try {
      await writeFile(outsideReceipt, "outside sentinel\n", "utf-8");
      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
          env: {
            ...process.env,
            HI_TEST_OUTSIDE_PARENT: outside,
            HI_TEST_SWAP_PARENT: "1",
          },
        }),
      ).rejects.toThrow();
      assertThat(await readFile(outsideReceipt, "utf-8")).toBe("outside sentinel\n");
      assertThat(await readdir(outside)).toEqual(["harness-projection-receipt.json"]);
    } finally {
      await rm(root, { force: true, recursive: true });
      await rm(outside, { force: true, recursive: true });
    }
  });

  test("preserves a concurrent target substitution before confined write publication", async () => {
    const sourceFile = await readFile(scriptSourcePath, "utf-8");
    const publicationBoundary = [
      "    closeSync(descriptor);",
      "    descriptor = undefined;",
      "    assertParentIdentity();",
    ].join("\n");
    const scriptSource = sourceFile.replace(
      publicationBoundary,
      [
        "    closeSync(descriptor);",
        "    descriptor = undefined;",
        '    if (request.target === "frontend-worker.toml") {',
        '      renameSync(request.target, request.target + ".displaced");',
        '      writeFileSync(request.target, "concurrent replacement\\n");',
        "    }",
        "    assertParentIdentity();",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(sourceFile);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
      writeContextPlan: false,
    });
    const target = path.join(root, ".codex/agents/frontend-worker.toml");
    const displaced = `${target}.displaced`;
    const original = "consumer-owned original\n";

    try {
      await mkdir(path.dirname(target), { recursive: true });
      await writeFile(target, original, "utf-8");

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
          env: process.env,
        }),
      ).rejects.toThrow();

      assertThat(await readFile(target, "utf-8")).toBe("concurrent replacement\n");
      assertThat(await readFile(displaced, "utf-8")).toBe(original);
      const targetEntries = await readdir(path.dirname(target));
      assertThat(targetEntries.some((name) => name.startsWith(".hi-"))).toBe(false);
    } finally {
      await rm(root, { force: true, recursive: true });
    }
  });

  test.runIf(process.platform !== "win32")(
    "binds adapter config and managed-agent reads to validated descriptors",
    async () => {
      const sourceFile = await readFile(scriptSourcePath, "utf-8");
      const readImport =
        'import { lstat, readFile, realpath, readdir, readlink } from "node:fs/promises";';
      const scriptSource = sourceFile
        .replace(
          readImport,
          'import { lstat, readFile as nodeReadFile, realpath, readdir, readlink, rename, symlink, writeFile } from "node:fs/promises";',
        )
        .replace(
          'const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");',
          [
            "const readFile = async (filePath, ...args) => {",
            "  if (path.relative(repoRoot, path.resolve(filePath)) === process.env.HI_TEST_READ_SWAP_TARGET) {",
            '    await writeFile(process.env.HI_TEST_PATH_READ_MARKER, "pathname read reached\\n");',
            "  }",
            "  return nodeReadFile(filePath, ...args);",
            "};",
            "",
            'const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");',
          ].join("\n"),
        )
        .replace(
          "    await assertConfinedRegularFile(claudeSettingsPath);",
          [
            "    await assertConfinedRegularFile(claudeSettingsPath);",
            "    if (path.relative(repoRoot, claudeSettingsPath) === process.env.HI_TEST_READ_SWAP_TARGET) {",
            '      await rename(claudeSettingsPath, claudeSettingsPath + ".displaced");',
            "      await symlink(process.env.HI_TEST_OUTSIDE_READ_TARGET, claudeSettingsPath);",
            "    }",
          ].join("\n"),
        )
        .replace(
          "    await assertConfinedRegularFile(opencodeConfigPath);",
          [
            "    await assertConfinedRegularFile(opencodeConfigPath);",
            "    if (path.relative(repoRoot, opencodeConfigPath) === process.env.HI_TEST_READ_SWAP_TARGET) {",
            '      await rename(opencodeConfigPath, opencodeConfigPath + ".displaced");',
            "      await symlink(process.env.HI_TEST_OUTSIDE_READ_TARGET, opencodeConfigPath);",
            "    }",
          ].join("\n"),
        )
        .replace(
          "    await assertConfinedRegularFile(filePath);",
          [
            "    await assertConfinedRegularFile(filePath);",
            "    if (path.relative(repoRoot, filePath) === process.env.HI_TEST_READ_SWAP_TARGET) {",
            '      await rename(filePath, filePath + ".displaced");',
            "      await symlink(process.env.HI_TEST_OUTSIDE_READ_TARGET, filePath);",
            "    }",
          ].join("\n"),
        );
      assertThat(scriptSource).not.toBe(sourceFile);
      assertThat(scriptSource).toContain("HI_TEST_PATH_READ_MARKER");

      await Promise.all(
        [
          { content: "{}\n", relativePath: ".claude/settings.json" },
          { content: "{}\n", relativePath: "opencode.json" },
          {
            content:
              "<!-- Generated by scripts/sync-subagents.mjs. Edit .agents/subagents/manifest.mjs instead. -->\n",
            relativePath: ".claude/agents/stale.md",
          },
        ].map(async (testCase) => {
          const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-confined-read-outside-"));
          const root = await writeFixture({
            guidanceFile: "app/frontend/AGENTS.md",
            scriptSource,
            writeContextPlan: false,
          });
          const target = path.join(root, testCase.relativePath);
          const displaced = `${target}.displaced`;
          const outsideTarget = path.join(outside, path.basename(target));
          const marker = path.join(outside, "pathname-read.txt");

          try {
            await mkdir(path.dirname(target), { recursive: true });
            await writeFile(target, testCase.content, "utf-8");
            await writeFile(outsideTarget, testCase.content, "utf-8");

            let failure: unknown;
            try {
              await execFileAsync(
                nodePath,
                [path.join(root, ".agents/scripts/sync-subagents.mjs")],
                {
                  cwd: root,
                  env: {
                    ...process.env,
                    HI_TEST_OUTSIDE_READ_TARGET: outsideTarget,
                    HI_TEST_PATH_READ_MARKER: marker,
                    HI_TEST_READ_SWAP_TARGET: testCase.relativePath,
                  },
                  timeout: 3000,
                },
              );
            } catch (error) {
              failure = error;
            }

            assertThat(await pathExists(displaced), testCase.relativePath).toBe(true);
            assertThat(failure, testCase.relativePath).toBeDefined();
            assertThat(await pathExists(marker), testCase.relativePath).toBe(false);
            assertThat(await readFile(displaced, "utf-8"), testCase.relativePath).toBe(
              testCase.content,
            );
            assertThat(await readFile(outsideTarget, "utf-8"), testCase.relativePath).toBe(
              testCase.content,
            );
          } finally {
            await rm(root, { force: true, recursive: true });
            await rm(outside, { force: true, recursive: true });
          }
        }),
      );
    },
  );

  test("rejects oversized adapter configs and managed agents before consuming their content", async () => {
    const oversizedJson = JSON.stringify({ padding: "x".repeat(16 * 1024 * 1024) });
    const oversizedManaged = `${[
      "# Generated by scripts/sync-subagents.mjs.",
      "# Do not edit by hand; update .agents/subagents/manifest.mjs and re-run sync.",
      "",
    ].join("\n")}${"x".repeat(16 * 1024 * 1024)}`;

    await Promise.all(
      [
        { content: oversizedJson, relativePath: ".claude/settings.json" },
        { content: oversizedJson, relativePath: "opencode.json" },
        { content: oversizedManaged, relativePath: ".claude/agents/stale.md" },
      ].map(async (testCase) => {
        const root = await writeFixture({
          guidanceFile: "app/frontend/AGENTS.md",
          writeContextPlan: false,
        });
        const target = path.join(root, testCase.relativePath);

        try {
          await mkdir(path.dirname(target), { recursive: true });
          await writeFile(target, testCase.content, "utf-8");

          await assertThat(
            execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
              cwd: root,
            }),
          ).rejects.toThrow();
          assertThat(await readFile(target, "utf-8"), testCase.relativePath).toBe(testCase.content);
        } finally {
          await rm(root, { force: true, recursive: true });
        }
      }),
    );
  });

  test.runIf(process.platform !== "win32" && mkfifoAvailable)(
    "rejects FIFO adapter configs and managed agents without opening them",
    async () => {
      await Promise.all(
        [".claude/settings.json", "opencode.json", ".claude/agents/stale.md"].map(
          async (relativePath) => {
            const root = await writeFixture({
              guidanceFile: "app/frontend/AGENTS.md",
              writeContextPlan: false,
            });
            const target = path.join(root, relativePath);

            try {
              await mkdir(path.dirname(target), { recursive: true });
              await execFileAsync(mkfifoPath, [target]);

              await assertThat(
                execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
                  cwd: root,
                  timeout: 3000,
                }),
              ).rejects.toThrow();
              const targetStat = await lstat(target);
              assertThat(targetStat.isFIFO(), relativePath).toBe(true);
            } finally {
              await rm(root, { force: true, recursive: true });
            }
          },
        ),
      );
    },
  );

  test("does not remove outside content when a parent swaps after removal validation", async () => {
    const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-remove-swap-outside-"));
    const scriptSource = await readFile(scriptSourcePath, "utf-8");
    const removalRequestBoundary =
      // oxlint-disable-next-line eslint/no-template-curly-in-string -- Match literal source.
      '  await runStableMutation(parentDirectory, {\n    claim: `.hi-remove-${randomUUID()}`,\n    expectedTarget,\n    operation: "remove",';
    const source = scriptSource
      .replace("{ lstat,", "{ lstat, rename, symlink,")
      .replace(
        removalRequestBoundary,
        [
          '  if (path.basename(targetPath) === "stale.md") {',
          '    await rename(parentDirectory, parentDirectory + "-displaced");',
          "    await symlink(process.env.HI_TEST_OUTSIDE_PARENT, parentDirectory);",
          "  }",
          removalRequestBoundary,
        ].join("\n"),
      );
    assertThat(source).not.toBe(scriptSource);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: source,
    });
    const staleAgent = path.join(root, ".claude/agents/stale.md");
    const outsideSentinel = path.join(outside, "stale.md");

    try {
      await mkdir(path.dirname(staleAgent), { recursive: true });
      await writeFile(
        staleAgent,
        "<!-- Generated by scripts/sync-subagents.mjs. Edit .agents/subagents/manifest.mjs instead. -->\n",
        "utf-8",
      );
      await writeFile(outsideSentinel, "outside sentinel\n", "utf-8");
      await writeFile(
        path.join(root, ".devpunks/context-plan.json"),
        '{"version":"1","scopes":[]}\n',
      );

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
          env: { ...process.env, HI_TEST_OUTSIDE_PARENT: outside },
        }),
      ).rejects.toThrow();
      assertThat(await readFile(outsideSentinel, "utf-8")).toBe("outside sentinel\n");
      assertThat(await readdir(outside)).toEqual(["stale.md"]);
    } finally {
      await rm(root, { force: true, recursive: true });
      await rm(outside, { force: true, recursive: true });
    }
  });

  test("preserves a directory substituted before recursive stale cleanup", async () => {
    const scriptSource = await readFile(scriptSourcePath, "utf-8");
    const boundary =
      // oxlint-disable-next-line eslint/no-template-curly-in-string -- Match literal source.
      '  await runStableMutation(parentDirectory, {\n    claim: `.hi-remove-${randomUUID()}`,\n    expectedTarget,\n    operation: "remove",';
    const source = scriptSource
      .replace("{ lstat, readFile,", "{ lstat, mkdir, readFile, rename, writeFile,")
      .replace(
        boundary,
        [
          '  if (path.basename(targetPath) === "stale.md") {',
          '    await rename(targetPath, targetPath + "-displaced");',
          "    await mkdir(targetPath);",
          '    await writeFile(path.join(targetPath, "sentinel.txt"), "concurrent directory\\n");',
          "  }",
          boundary,
        ].join("\n"),
      );
    assertThat(source).not.toBe(scriptSource);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: source,
    });
    const staleAgent = path.join(root, ".claude/agents/stale.md");
    const displacedAgent = `${staleAgent}-displaced`;

    try {
      await mkdir(path.dirname(staleAgent), { recursive: true });
      await writeFile(
        staleAgent,
        "<!-- Generated by scripts/sync-subagents.mjs. Edit .agents/subagents/manifest.mjs instead. -->\n",
        "utf-8",
      );
      await writeFile(
        path.join(root, ".devpunks/context-plan.json"),
        '{"version":"1","scopes":[]}\n',
      );

      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        }),
      ).rejects.toThrow();
      assertThat({
        displaced: await readFile(displacedAgent, "utf-8"),
        replacement: await readFile(path.join(staleAgent, "sentinel.txt"), "utf-8"),
      }).toStrictEqual({
        displaced:
          "<!-- Generated by scripts/sync-subagents.mjs. Edit .agents/subagents/manifest.mjs instead. -->\n",
        replacement: "concurrent directory\n",
      });
    } finally {
      await rm(root, { force: true, recursive: true });
    }
  });

  test.each([
    {
      kind: "managed agent",
      recursive: false,
      target: ".claude/agents/stale.md",
      writeContextPlan: true,
    },
    {
      kind: "hook mirror",
      recursive: true,
      target: ".codex/hooks/format-edited-file.mjs",
      writeContextPlan: false,
    },
  ] as const)(
    "preserves a $kind substituted inside the validated removal window",
    async ({ recursive, target, writeContextPlan }) => {
      const scriptSource = await readFile(scriptSourcePath, "utf-8");
      const validationBoundary = [
        '  } else if (request.operation === "remove") {',
        "    assertExpectedLeaf(request.target, request.expectedTarget);",
      ].join("\n");
      const source = scriptSource.replace(
        validationBoundary,
        [
          validationBoundary,
          `    if (request.target === ${JSON.stringify(path.basename(target))} && request.recursive === ${recursive}) {`,
          '      renameSync(request.target, request.target + ".displaced");',
          "      if (request.recursive) {",
          "        mkdirSync(request.target);",
          '        writeFileSync(request.target + "/sentinel.txt", "concurrent directory\\n");',
          "      } else {",
          '        writeFileSync(request.target, "concurrent file\\n");',
          "      }",
          "    }",
        ].join("\n"),
      );
      assertThat(source).not.toBe(scriptSource);
      const root = await writeFixture({
        guidanceFile: "app/frontend/AGENTS.md",
        scriptSource: source,
        writeContextPlan,
      });
      const targetPath = path.join(root, target);
      const displacedPath = `${targetPath}.displaced`;

      try {
        await mkdir(path.dirname(targetPath), { recursive: true });
        await writeFile(
          targetPath,
          recursive
            ? "obsolete hook mirror\n"
            : "<!-- Generated by scripts/sync-subagents.mjs. Edit .agents/subagents/manifest.mjs instead. -->\n",
          "utf-8",
        );

        await assertThat(
          execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
            cwd: root,
          }),
        ).rejects.toThrow();
        assertThat(
          recursive
            ? await readFile(path.join(targetPath, "sentinel.txt"), "utf-8")
            : await readFile(targetPath, "utf-8"),
        ).toBe(recursive ? "concurrent directory\n" : "concurrent file\n");
        assertThat(await readFile(displacedPath, "utf-8")).toContain(
          recursive ? "obsolete hook mirror" : "Generated by scripts/sync-subagents.mjs",
        );
        const parentEntries = await readdir(path.dirname(targetPath));
        assertThat(parentEntries.filter((entry) => entry.startsWith(".hi-remove-"))).toEqual([]);
      } finally {
        await rm(root, { force: true, recursive: true });
      }
    },
  );

  test("reports the retained claim when failed cleanup collides with target recreation", async () => {
    const scriptSource = await readFile(scriptSourcePath, "utf-8");
    const removalBoundary =
      "      rmSync(request.claim, { force: true, recursive: request.recursive });";
    const source = scriptSource.replace(
      removalBoundary,
      [
        '      if (request.target === "format-edited-file.mjs" && request.recursive === true) {',
        '        writeFileSync(request.target, "concurrent replacement\\n");',
        "        rmSync(request.claim, { force: true, recursive: false });",
        "      }",
        removalBoundary,
      ].join("\n"),
    );
    assertThat(source).not.toBe(scriptSource);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: source,
      writeContextPlan: false,
    });
    const targetPath = path.join(root, ".codex/hooks/format-edited-file.mjs");
    const originalBytes = Buffer.from("obsolete hook mirror\n");

    try {
      await mkdir(targetPath, { recursive: true });
      await writeFile(path.join(targetPath, "original.txt"), originalBytes);

      let failureMessage = "";
      try {
        await execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
        });
      } catch (error) {
        failureMessage = String(error);
      }

      const parentEntries = await readdir(path.dirname(targetPath));
      const claimName = requireDefined(
        parentEntries.find((entry) => entry.startsWith(".hi-remove-")),
      );
      const claimPath = path.join(path.dirname(targetPath), claimName);
      const surfacedClaimPath = await realpath(claimPath);
      assertThat(await readFile(path.join(claimPath, "original.txt"))).toStrictEqual(originalBytes);
      assertThat(await readFile(targetPath, "utf-8")).toBe("concurrent replacement\n");
      assertThat(failureMessage).toContain(
        `Confined removal could not restore its claimed target. Retained backup: ${surfacedClaimPath}.`,
      );
    } finally {
      await rm(root, { force: true, recursive: true });
    }
  });

  test("does not create an outside symlink when a parent swaps after symlink validation", async () => {
    const outside = await mkdtemp(path.join(os.tmpdir(), "ip317-symlink-swap-outside-"));
    const scriptSource = await readFile(scriptSourcePath, "utf-8");
    const source = scriptSource
      .replace("{ lstat,", "{ lstat, rename, symlink,")
      .replace(
        "    await runStableMutation(parentDirectory, {\n      linkTarget:",
        [
          '    if (path.basename(parentDirectory) === ".codex" && path.basename(linkPath) === "AGENTS.md") {',
          '      await rename(parentDirectory, parentDirectory + "-displaced");',
          "      await symlink(process.env.HI_TEST_OUTSIDE_PARENT, parentDirectory);",
          "    }",
          "    await runStableMutation(parentDirectory, {\n      linkTarget:",
        ].join("\n"),
      );
    assertThat(source).not.toBe(scriptSource);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource: source,
    });

    try {
      await assertThat(
        execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
          cwd: root,
          env: { ...process.env, HI_TEST_OUTSIDE_PARENT: outside },
        }),
      ).rejects.toThrow();
      assertThat(await readdir(outside)).toEqual([]);
    } finally {
      await rm(root, { force: true, recursive: true });
      await rm(outside, { force: true, recursive: true });
    }
  });

  test("preserves a target recreated before EPERM copy fallback publication", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const withEperm = baseSource.replace(
      "    symlinkSync(request.linkTarget, request.target, request.type);",
      [
        '    if (request.target === "AGENTS.md") {',
        '      const error = new Error("operation not permitted");',
        '      error.code = "EPERM";',
        "      throw error;",
        "    }",
        "    symlinkSync(request.linkTarget, request.target, request.type);",
      ].join("\n"),
    );
    const copyBoundary = [
      "    assertExpectedLeaf(request.target, request.expectedTarget);",
      "    if (request.recursive) {",
    ].join("\n");
    const scriptSource = withEperm.replace(
      copyBoundary,
      [
        "    assertExpectedLeaf(request.target, request.expectedTarget);",
        '    if (request.target === "AGENTS.md") {',
        '      writeFileSync(request.target, "concurrent replacement\\n");',
        "    }",
        "    if (request.recursive) {",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(withEperm);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
      writeContextPlan: false,
    });
    const targetPath = path.join(root, ".codex/AGENTS.md");

    await assertThat(
      execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      }),
    ).rejects.toThrow();
    assertThat(await readFile(targetPath, "utf-8")).toBe("concurrent replacement\n");
  });

  test("preserves a directory recreated before EPERM copy fallback publication", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const withEperm = baseSource.replace(
      "    symlinkSync(request.linkTarget, request.target, request.type);",
      [
        '    if (request.target === "skills") {',
        '      const error = new Error("operation not permitted");',
        '      error.code = "EPERM";',
        "      throw error;",
        "    }",
        "    symlinkSync(request.linkTarget, request.target, request.type);",
      ].join("\n"),
    );
    const claimBoundary = ["    if (request.recursive) {", "      mkdirSync(request.target);"].join(
      "\n",
    );
    const scriptSource = withEperm.replace(
      claimBoundary,
      [
        "    if (request.recursive) {",
        '      if (request.target === "skills") {',
        "        mkdirSync(request.target);",
        '        writeFileSync(request.target + "/sentinel.txt", "concurrent replacement\\n");',
        "      }",
        "      mkdirSync(request.target);",
      ].join("\n"),
    );
    assertThat(scriptSource).not.toBe(withEperm);
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
      writeContextPlan: false,
    });
    const sentinelPath = path.join(root, ".claude/skills/sentinel.txt");

    await assertThat(
      execFileAsync(nodePath, [path.join(root, ".agents/scripts/sync-subagents.mjs")], {
        cwd: root,
      }),
    ).rejects.toThrow();
    assertThat(await readFile(sentinelPath, "utf-8")).toBe("concurrent replacement\n");
  });

  test("refreshes unchanged EPERM prompt copies but preserves consumer edits", async () => {
    const baseSource = await readFile(scriptSourcePath, "utf-8");
    const scriptSource = baseSource.replace(
      "    symlinkSync(request.linkTarget, request.target, request.type);",
      [
        '    if (request.target === "AGENTS.md") {',
        '      const error = new Error("operation not permitted");',
        '      error.code = "EPERM";',
        "      throw error;",
        "    }",
        "    symlinkSync(request.linkTarget, request.target, request.type);",
      ].join("\n"),
    );
    const root = await writeFixture({
      guidanceFile: "app/frontend/AGENTS.md",
      scriptSource,
    });
    const scriptPath = path.join(root, ".agents/scripts/sync-subagents.mjs");
    const sourcePath = path.join(root, ".agents/AGENTS.md");
    const targetPath = path.join(root, ".codex/AGENTS.md");
    await mkdir(path.join(root, ".agents/hooks"), { recursive: true });
    await writeFile(path.join(root, ".agents/hooks/format-edited-file.mjs"), "", "utf-8");
    await writeFile(path.join(root, ".agents/hooks/scaffold-update-check.mjs"), "", "utf-8");

    await execFileAsync(nodePath, [scriptPath], { cwd: root });
    assertThat(await readFile(targetPath, "utf-8")).toBe("Shared neutral guidance\n");

    await writeFile(sourcePath, "Updated neutral guidance\n", "utf-8");
    await execFileAsync(nodePath, [scriptPath], { cwd: root });
    assertThat(await readFile(targetPath, "utf-8")).toBe("Updated neutral guidance\n");

    await writeFile(targetPath, "Consumer-owned guidance\n", "utf-8");
    await writeFile(sourcePath, "Newest neutral guidance\n", "utf-8");
    await execFileAsync(nodePath, [scriptPath], { cwd: root });
    assertThat(await readFile(targetPath, "utf-8")).toBe("Consumer-owned guidance\n");
  });
});
