import { createHash } from "node:crypto"; import { cp, lstat, mkdtemp, mkdir, open, readFile, readdir, realpath, rm, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { canonicalDigest, captureFailure, runCommand } from "./pack-test-support.mjs"; import { installPublishedFoundation } from "./published-foundation-install.mjs"; import { publishedFoundationIntegrity } from "./published-foundation-imports.ts"; import { executePublishedFoundationOperation } from "./published-foundation-operations.ts"; const version = "0.11.0"; const expectedIntegrity = publishedFoundationIntegrity(version); const repositoryRoot = fileURLToPath(new URL("..", import.meta.url)); const packageName = "@agent-teams/engineering-foundation"; function compareStrings(left, right) { return left < right ? -1 : left > right ? 1 : 0; } function jsonErrorCode(failure) { return failure?.stdout.length === 0 ? undefined : JSON.parse(failure.stdout).error?.code; } function pnpmLockSource() { const packageKey = `${packageName}@${version}`; return [ "lockfileVersion: '9.0'", "", "settings:", " autoInstallPeers: true", " excludeLinksFromLockfile: false", "", "importers:", "", " .:", " devDependencies:", ` ${JSON.stringify(packageName)}:`, ` specifier: ${JSON.stringify(version)}`, ` version: ${JSON.stringify(version)}`, "", "packages:", "", ` ${JSON.stringify(packageKey)}:`, ` resolution: {integrity: ${JSON.stringify(expectedIntegrity)}}`, "", "snapshots:", "", ` ${JSON.stringify(packageKey)}: {}`, "", ].join("\n"); } async function prepareConsumer(consumerRoot, installedPackageRoot) { await cp(dirname(dirname(installedPackageRoot)), join(consumerRoot, "node_modules"), { recursive: true, }); await writeFile( join(consumerRoot, "package.json"), `${JSON.stringify( { name: "old-foundation-transaction-consumer", packageManager: "pnpm@11.18.0", private: true, type: "module", devDependencies: { [packageName]: version }, }, null, 2, )}\n`, "utf8", ); const lockSource = pnpmLockSource(); await writeFile(join(consumerRoot, "pnpm-lock.yaml"), lockSource, "utf8"); await mkdir(join(consumerRoot, "node_modules", ".pnpm"), { recursive: true, }); await writeFile(join(consumerRoot, "node_modules", ".pnpm", "lock.yaml"), lockSource, "utf8"); } function digestBytes(bytes) { return createHash("sha256").update(bytes).digest("hex"); } async function treeEvidence(root, relativePath = "") { const directory = join(root, relativePath); const evidence = []; for (const entry of (await readdir(directory, { withFileTypes: true })).toSorted((left, right) => compareStrings(left.name, right.name), )) { const entryRelativePath = join(relativePath, entry.name); const entryPath = join(root, entryRelativePath); if (entry.isDirectory()) { evidence.push(`d:${entryRelativePath}`); evidence.push(...(await treeEvidence(root, entryRelativePath))); } else if (entry.isFile()) { const bytes = await readFile(entryPath); evidence.push(`f:${entryRelativePath}:${bytes.byteLength}:${digestBytes(bytes)}`); } else { evidence.push(`o:${entryRelativePath}`); } } return evidence; } async function mutationEvidence(consumerRoot) { const stateRoot = join(consumerRoot, ".agent-teams-local"); const installedPackageRoot = join( consumerRoot, "node_modules", "@agent-teams", "engineering-foundation", ); const installedMetadata = await lstat(installedPackageRoot); return JSON.stringify({ installedIsRealDirectory: installedMetadata.isDirectory() && !installedMetadata.isSymbolicLink(), installedRealpath: await realpath(installedPackageRoot), installedTree: await treeEvidence(installedPackageRoot), manifestDigest: digestBytes(await readFile(join(consumerRoot, "package.json"))), rootLockDigest: digestBytes(await readFile(join(consumerRoot, "pnpm-lock.yaml"))), stateTree: await treeEvidence(stateRoot), virtualLockDigest: digestBytes( await readFile(join(consumerRoot, "node_modules", ".pnpm", "lock.yaml")), ), }); } async function assertOldMutationBlocked({ operation, packageRoot, consumerRoot, expected, targetRoot, }) { const observation = await executePublishedFoundationOperation({ packageRoot, version, consumerRoot, operation, ...(targetRoot === undefined ? {} : { targetRoot }), }); if ( observation.outcome !== "threw" || observation.error.code !== "LOCAL_STATE_INVALID" || !/^(?:Foundation operation lock path must be a real local directory|Another foundation operation is active or its lock is not safely recoverable)\.$/u.test( observation.error.message, ) ) { throw new Error(`Published Foundation ${version} operation ${operation} did not fail closed.`, { cause: observation, }); } if ((await mutationEvidence(consumerRoot)) !== expected) { throw new Error( `Published Foundation ${version} mutated consumer state while ${operation} was blocked.`, ); } } async function assertPersistentBarrier(consumerRoot) { const lockPath = join(consumerRoot, ".agent-teams-local", "foundation-operation.lock"); const lockHandle = await open(lockPath, "r"); let lockEvidence; let lockMetadata; try { lockMetadata = await lockHandle.stat(); lockEvidence = JSON.parse(await lockHandle.readFile("utf8")); } finally { await lockHandle.close(); } if ( !lockMetadata.isFile() || lockMetadata.isSymbolicLink() || lockEvidence.schemaVersion !== 1 || lockEvidence.kind !== "transaction-barrier" ) { throw new Error("Current Foundation did not persist a valid downgrade barrier."); } } async function assertOldCommandsBlocked({ packageRoot, consumerRoot, targetRoot }) { const beforeOldCommands = await mutationEvidence(consumerRoot); await assertOldMutationBlocked({ operation: "recover", packageRoot, consumerRoot, expected: beforeOldCommands, }); await assertOldMutationBlocked({ operation: "attach", targetRoot, packageRoot, consumerRoot, expected: beforeOldCommands, }); await assertOldMutationBlocked({ operation: "detach", packageRoot, consumerRoot, expected: beforeOldCommands, }); } async function verifyOrphanTemporaryBarrier({ currentCliPath, installed, temporaryRoot }) { const consumerRoot = join(temporaryRoot, "temporary-consumer"); await prepareConsumer(consumerRoot, installed.packageRoot); const transactionPath = join( consumerRoot, ".agent-teams-local", "scaffolding-transaction.json.tmp", ); await mkdir(dirname(transactionPath), { recursive: true }); const evidence = Buffer.from("partial transaction evidence\n", "utf8"); await writeFile(transactionPath, evidence); const failure = await captureFailure(() => runCommand( process.execPath, [currentCliPath, "scaffold-recover", "--consumer", consumerRoot, "--json"], consumerRoot, ), ); if ( failure?.code !== 1 || failure.stderr !== "" || jsonErrorCode(failure) !== "SCAFFOLD_RECOVERY_REQUIRED" ) { throw new Error( "Current Foundation did not establish a downgrade barrier for orphan temporary evidence.", ); } await assertPersistentBarrier(consumerRoot); if (!(await readFile(transactionPath)).equals(evidence)) { throw new Error("Current Foundation changed orphan temporary evidence."); } await assertOldCommandsBlocked({ packageRoot: installed.packageRoot, consumerRoot, targetRoot: join(temporaryRoot, "unreachable-temporary-target"), }); if (!(await readFile(transactionPath)).equals(evidence)) { throw new Error(`Published Foundation ${version} changed orphan temporary evidence.`); } } export async function verifyOldFoundationTransactionBarrier({ currentCliPath, installPackage }) { const temporaryRoot = await mkdtemp(join(tmpdir(), "foundation-old-version-e2e-")); try { const installed = await installPublishedFoundation({ expectedIntegrity, installPackage, root: join(temporaryRoot, "published-package"), version, }); const consumerRoot = join(temporaryRoot, "consumer"); await prepareConsumer(consumerRoot, installed.packageRoot); const transactionPath = join( consumerRoot, ".agent-teams-local", "scaffolding-transaction.json", ); await mkdir(join(consumerRoot, ".agent-teams-local"), { recursive: true }); const documentFixture = JSON.parse( await readFile( join(repositoryRoot, "tests", "fixtures", "document-authoring-contracts", "valid-v1.json"), "utf8", ), ); const journal = { ...documentFixture.documentEnvelope.journal, plan: documentFixture.plan, }; const envelopeBody = { ...documentFixture.documentEnvelope, journal, payloadDigest: canonicalDigest(journal), }; delete envelopeBody.envelopeDigest; const envelope = { ...envelopeBody, envelopeDigest: canonicalDigest(envelopeBody), }; const transactionBytes = Buffer.from(`${JSON.stringify(envelope, null, 2)}\n`, "utf8"); await writeFile(transactionPath, transactionBytes); const currentFailure = await captureFailure(() => runCommand( process.execPath, [currentCliPath, "scaffold-recover", "--consumer", consumerRoot, "--json"], consumerRoot, ), ); if ( currentFailure?.code !== 1 || currentFailure.stderr !== "" || jsonErrorCode(currentFailure) !== "SCAFFOLD_RECOVERY_REQUIRED" ) { throw new Error("Current Foundation did not establish the persistent downgrade barrier."); } await assertPersistentBarrier(consumerRoot); if (!(await readFile(transactionPath)).equals(transactionBytes)) { throw new Error("Current Foundation changed the blocked envelope v2 evidence."); } const statusFailure = await captureFailure(() => runCommand( process.execPath, [currentCliPath, "status", "--consumer", consumerRoot, "--json"], consumerRoot, ), ); const status = JSON.parse(statusFailure?.stdout ?? "null"); if ( statusFailure?.code !== 1 || statusFailure.stderr !== "" || status.transaction?.state !== "manual-recovery-required" || status.transaction.reason !== "recovery-handler-unavailable" || status.transaction.foundationVersion !== documentFixture.documentEnvelope.foundation.version || status.transaction.foundationBuildIdentity !== documentFixture.documentEnvelope.foundation.buildIdentity ) { throw new Error("Current status omitted preserved envelope v2 identity evidence."); } await assertOldCommandsBlocked({ packageRoot: installed.packageRoot, consumerRoot, targetRoot: join(temporaryRoot, "unreachable-foundation-target"), }); if (!(await readFile(transactionPath)).equals(transactionBytes)) { throw new Error(`Published Foundation ${version} changed envelope v2 evidence.`); } await verifyOrphanTemporaryBarrier({ currentCliPath, installed, temporaryRoot, }); process.stdout.write( `Published operation-boundary downgrade barrier qualification PASS: ${version} recover/attach/detach for canonical and temporary transaction evidence; integrity ${expectedIntegrity}.\n`, ); } finally { await rm(temporaryRoot, { force: true, recursive: true }); } }