diff --git a/README.md b/README.md index 8dfbdcee..79764d4c 100644 --- a/README.md +++ b/README.md @@ -643,6 +643,7 @@ agentwheel mutation list agentwheel mutation show agentwheel mutation finalize agentwheel mutation recover-runtime +agentwheel mutation recover-runtime --dry-run --json ``` See [the v1 revision-provider specification](docs/specs/revision-provider-v1.md) for configuration, @@ -1064,3 +1065,10 @@ Built-in runtime targets: ## License See [`LICENSE`](LICENSE). + +For a partial guarded metadata transaction with zero runtime operations, `mutation recover-runtime --dry-run` +observes the linked journal, runtime block/file hashes, exact snapshots, and inventory without locks, +receipt/journal updates, files, or revision-provider calls. `mutation recover --dry-run` and +`mutation finalize --dry-run` show the same preview and identify `recover-runtime` as the required next +command; ordinary finalize/recover still refuse partial handlers. The preview is advisory: execution +revalidates repository leases and all guards under locks. Other runtime recovery shapes are refused. diff --git a/src/cli/index.ts b/src/cli/index.ts index 7acac5bf..f01338a6 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -75,7 +75,7 @@ import { pruneGitCache, releaseGitSnapshotLease } from "../source/cache.js"; import { listRegisteredFleets, registerFleet, resolveWorkspaceOwnershipScope, resolveWorkspaceScope, showRegisteredFleet } from "../model/fleet.js"; import { applyFleetNormalization, planFleetNormalization, recoverFleetNormalization, type FleetNormalizationSource } from "../lifecycle/fleet-normalize.js"; import { declareMutationPath } from "../mutation/declarations.js"; -import { GovernedMutation, checkMutationProvider, mutationPolicyForWorkspace, recoverMutationRuntime, resumeMutation } from "../mutation/coordinator.js"; +import { GovernedMutation, checkMutationProvider, mutationPolicyForWorkspace, recoverMutationRuntime, resumeMutation, previewMutationRecovery } from "../mutation/coordinator.js"; import { listMutationReceipts, readMutationReceipt, type MutationReceipt } from "../mutation/receipts.js"; import { isGovernedCommand, requiresCleanMutationPreflight } from "../mutation/commands.js"; @@ -1823,7 +1823,9 @@ for (const action of ["finalize", "recover"] as const) { .description(`${action} one verified successful governed mutation idempotently`) .argument("", "mutation operation id") .option("--json", "print the updated receipt as JSON", false) + .option("--dry-run", "inspect zero-operation metadata recovery without writing", false) .action(async (operationId, options) => { + if (options.dryRun) return printRecoveryPreview(await previewMutationRecovery(operationId, action), options.json); const receipt = await resumeMutation(operationId, action); if (options.json) return console.log(JSON.stringify(receipt, null, 2)); printMutationReceipt(receipt); @@ -1835,7 +1837,9 @@ mutationCommand .description("resume linked runtime apply journals, verify them, and finalize revisioning") .argument("", "mutation operation id") .option("--json", "print the updated receipt as JSON", false) + .option("--dry-run", "inspect zero-operation metadata recovery without writing", false) .action(async (operationId, options) => { + if (options.dryRun) return printRecoveryPreview(await previewMutationRecovery(operationId), options.json); const receipt = await recoverMutationRuntime(operationId); if (options.json) return console.log(JSON.stringify(receipt, null, 2)); printMutationReceipt(receipt); @@ -5497,3 +5501,16 @@ try { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } + +function printRecoveryPreview(preview: Awaited>, json: boolean): void { + if (json) return console.log(JSON.stringify(preview, null, 2)); + console.log(`DRY RUN ${preview.operationId}: ${preview.status}; zero runtime operations`); + for (const journal of preview.journals) { + console.log(` ${journal.removesManifest ? "Remove" : "Write"} metadata: ${journal.manifestPath}`); + for (const path of journal.auditPaths) console.log(` Ensure audit intent: ${path}`); + console.log(` Resolve journal: ${journal.path}`); + } + for (const step of preview.steps) console.log(` ${step}`); + console.log(`Next: ${preview.nextCommand}`); + console.log("Advisory only; execution revalidates all guards. No revision provider was invoked."); +} diff --git a/src/install/apply.ts b/src/install/apply.ts index eed2efbc..bb99b893 100644 --- a/src/install/apply.ts +++ b/src/install/apply.ts @@ -582,15 +582,33 @@ async function assertCommittedJournalState( return actualManifest; } +/** Observe a zero-operation metadata recovery without locks, providers, or durable writes. */ +export async function previewMetadataJournal(journal: ApplyJournal, transport: TargetTransport = localTransport): Promise<{ + manifestPath: string; auditPaths: string[]; removesManifest: boolean; +}> { + if (journal.operations.length || journal.completed.length || (!journal.metadataGuards && !journal.metadataAudit)) { + throw new Error("Read-only recovery preview requires a guarded metadata journal with zero runtime operations."); + } + const manifest = withManifestRevision({ ...journal.manifest, generatedAt: journal.createdAt }); + if (journal.metadataGuards) await assertMetadataStateGuards(journal, manifest, journal.metadataGuards, transport, false, true); + if (journal.metadataAudit) await assertMetadataAuditGuards(journal, manifest, transport, false, true); + return { + manifestPath: installManifestPath(journal.targetRoot, journal.adapter, { installationType: journal.installationType, stateKey: journal.stateKey }), + auditPaths: journal.metadataAudit?.auditFiles.map((file) => metadataAuditPath(journal.metadataAudit!, file.path)) ?? [], + removesManifest: manifest.entries.length === 0 && !journal.metadataAudit, + }; +} + /** Both initial commit and recovery accept only the exact reviewed before/after manifest states. */ async function assertMetadataAuditGuards( journal: ApplyJournal, after: InstallManifestV2, transport: TargetTransport, requireAfter = false, + readOnly = false, ): Promise { const audit = journal.metadataAudit!; - await assertOwnershipMetadataAuditPaths(journal, transport); + if (!readOnly) await assertOwnershipMetadataAuditPaths(journal, transport); const sha = /^[a-f0-9]{64}$/; if (transport.kind === "ssh" || (audit.kind !== "ownership-release" && audit.kind !== "ownership-handoff") || after.adapter !== journal.adapter || after.targetRoot !== journal.targetRoot @@ -602,7 +620,7 @@ async function assertMetadataAuditGuards( || audit.auditFiles.length !== 1 || audit.runtime.length !== 1 || !audit.inventory.length) { throw new Error("Invalid metadata-audit transaction; no state was committed."); } - await assertMetadataStateGuards(journal, after, audit, transport, requireAfter); + await assertMetadataStateGuards(journal, after, audit, transport, requireAfter, readOnly); for (const file of audit.auditFiles) { const path = metadataAuditPath(audit, file.path); await assertNoSymlinkPath(path); @@ -623,6 +641,7 @@ async function assertMetadataStateGuards( guards: MetadataStateGuards, transport: TargetTransport, requireAfter = false, + readOnly = false, ): Promise { const sha = /^[a-f0-9]{64}$/; if (transport.kind === "ssh" || (journal.metadataAudit && journal.metadataGuards) @@ -635,7 +654,7 @@ async function assertMetadataStateGuards( || !guards.inventory.length || !guards.runtime.length) { throw new Error("Invalid guarded metadata transaction; no state was committed."); } - assertOwnershipMetadataTransportSupported(transport, journal); + if (!readOnly) assertOwnershipMetadataTransportSupported(transport, journal); if (transport.kind === "local") { await assertNoSymlinkPath(journal.targetRoot); await assertNoSymlinkPath(metadataDir(journal.targetRoot)); @@ -658,13 +677,35 @@ async function assertMetadataStateGuards( } for (const guard of guards.runtime) { const path = metadataRuntimePath(journal.targetRoot, guard.path); + // Older metadata journals record the block hash but not its selector. Resolve it + // from the exact CAS-verified inventory, never from arbitrary live marker text. + const selectors = new Set(inventory.flatMap(({ manifest }) => { + if (manifest.version === 2) { + return manifest.entries + .filter((entry) => entry.path === guard.path && entry.mode === "managed-block" && entry.hash === guard.hash) + .map((entry) => managedInstructionSelector(entry.logicalSelector, entry.artifactType, entry.artifactName)); + } + return manifest.entries + .filter((entry) => entry.path === guard.path && entry.mode === "managed-block" && entry.hash === guard.hash) + .map((entry) => managedInstructionSelector(undefined, entry.artifactType, entry.artifactName)); + })); + if (!guard.managedBlock && selectors.size > 1) throw new Error(`Ambiguous metadata managed block at ${guard.path}.`); + const selector = guard.managedBlock?.selector ?? [...selectors][0]; + const current = selector + ? exactManagedInstructionBlockSnapshot(await transport.readFile(path), selector) + : undefined; + const runtimeHash = current ? current.hash : await transport.hashPath(path); + const expectedHash = guard.managedBlock?.hash ?? guard.hash; + // Legacy journals may pin a whole-file hash alongside an exact block snapshot. + // Preserve that file guard as well as comparing the live block with its recorded hash. + const legacyFileGuard = guard.managedBlock && guard.hash !== expectedHash; if (!sha.test(guard.hash) || !sha.test(guard.snapshotDigest) || (await observeOwnershipRuntime(path, transport)).snapshotDigest !== guard.snapshotDigest - || await transport.hashPath(path) !== guard.hash) { + || runtimeHash !== expectedHash + || (legacyFileGuard && await transport.hashPath(path) !== guard.hash)) { throw new Error(`Metadata runtime CAS failed at ${guard.path}; runtime was preserved.`); } if (guard.managedBlock) { - const current = exactManagedInstructionBlockSnapshot(await transport.readFile(path), guard.managedBlock.selector); if (canonicalJson(current) !== canonicalJson(guard.managedBlock)) { throw new Error(`Managed instruction snapshot CAS failed at ${guard.path}.`); } diff --git a/src/lifecycle/ownership-adopt-legacy.ts b/src/lifecycle/ownership-adopt-legacy.ts index 3d84fee1..eaaa541d 100644 --- a/src/lifecycle/ownership-adopt-legacy.ts +++ b/src/lifecycle/ownership-adopt-legacy.ts @@ -401,7 +401,7 @@ async function observe(request: AdoptLegacyOwnershipRequest, transport: TargetTr desiredCoverage: desiredCoverageIdentity(request.desiredCoverage, selectedPaths), ...(guardedInventory ? { metadataGuards: { inventory: guardedInventory.map((item) => ({ stateKey: item.stateKey, revision: item.manifest.revision })), - runtime: selected.map((entry) => ({ path: entry.path, hash: entry.runtimeHash!, snapshotDigest: entry.runtimeSnapshotDigest!, + runtime: selected.map((entry) => ({ path: entry.path, hash: entry.managedBlock?.hash ?? entry.runtimeHash!, snapshotDigest: entry.runtimeSnapshotDigest!, ...(entry.managedBlock ? { managedBlock: entry.managedBlock } : {}) })), } } : {}), }; diff --git a/src/mutation/coordinator.ts b/src/mutation/coordinator.ts index d0d762fc..658c3f28 100644 --- a/src/mutation/coordinator.ts +++ b/src/mutation/coordinator.ts @@ -397,6 +397,54 @@ async function transitionMutationRuntimeJournal( } +export interface MutationRecoveryPreview { + dryRun: true; + operationId: string; + status: MutationReceipt["status"]; + requestedAction: "finalize" | "recover" | "recover-runtime"; + nextCommand: string; + runtimeOperations: 0; + journals: Array<{ path: string; manifestPath: string; auditPaths: string[]; removesManifest: boolean }>; + steps: string[]; +} + +/** Advisory observation only: execution must reacquire locks and revalidate all leases and guards. */ +export async function previewMutationRecovery( + operationId: string, + requestedAction: MutationRecoveryPreview["requestedAction"] = "recover-runtime", +): Promise { + const receipt = await readMutationReceipt(operationId); + assertRuntimeRecoveryReceipt(receipt); + const { readLinkedLocalApplyJournal } = await import("../install/transaction.js"); + const { previewMetadataJournal } = await import("../install/apply.js"); + const journals: MutationRecoveryPreview["journals"] = []; + for (const entry of receipt.runtimeJournals.filter((link) => link.status !== "resolved")) { + if (entry.transport === "ssh") throw new Error("Read-only recovery preview does not support SSH journals."); + let transport = localTransport; + if (entry.transport === "local-run-as") { + const pinned = entry.runAsIdentity!; + const current = resolveRunAsIdentity(pinned.user, pinned.root); + if (!sameRunAsIdentity(pinned, current)) throw new Error("Runtime recovery run-as identity changed."); + transport = createRunAsTransport(current); + } + const journal = await readLinkedLocalApplyJournal(entry.path, receipt.operationId, entry.journalDigest, entry.transportDescription, transport); + if (journal.mutation?.reason !== receipt.reason || journal.mutation.noCommit !== receipt.noCommit) { + throw new Error("Runtime apply journal mutation metadata does not match its durable receipt."); + } + journals.push({ path: entry.path, ...await previewMetadataJournal(journal, transport) }); + } + return { + dryRun: true, operationId: receipt.operationId, status: receipt.status, requestedAction, + nextCommand: `agentwheel mutation recover-runtime ${receipt.operationId}`, + runtimeOperations: 0, journals, + steps: [ + "Acquire mutation and runtime locks and revalidate receipt, journal, repository, inventory and runtime guards", + "Roll forward guarded metadata and audit intent without runtime operations", + "Resolve linked journals and verify revisioning under the recorded policy", + ], + }; +} + export async function resumeMutation(operationId: string, action: "finalize" | "recover"): Promise { let receipt = await readMutationReceipt(operationId); if (["succeeded", "revisioning-skipped", "no-repository-delta"].includes(receipt.status)) return receipt; diff --git a/test/managed-block-metadata-cas.test.ts b/test/managed-block-metadata-cas.test.ts new file mode 100644 index 00000000..70526a62 --- /dev/null +++ b/test/managed-block-metadata-cas.test.ts @@ -0,0 +1,121 @@ +import { createHash } from "node:crypto"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { commitManifestMetadataJournal, previewMetadataJournal } from "../src/install/apply.js"; +import { exactManagedInstructionBlockSnapshot } from "../src/install/instructions-block.js"; +import { readInstallManifest, withManifestRevision, writeInstallManifest } from "../src/install/manifest.js"; +import { observeOwnershipRuntime, readApplyJournal, writeApplyJournal, type ApplyJournal } from "../src/install/transaction.js"; +import { applyJournalPath } from "../src/install/transaction.js"; +import { installManifestPath } from "../src/install/paths.js"; +import { localTransport } from "../src/transport/index.js"; + +const roots: string[] = []; +const scope = { installationType: "local", stateKey: "fixture.local" }; +const hash = (text: string) => createHash("sha256").update(text).digest("hex"); +afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); }); + +async function fixture(managedBlock = true, legacyGuard = false) { + const root = await mkdtemp(join(tmpdir(), "agentwheel-metadata-cas-")); roots.push(root); + const path = join(root, "instructions.md"), body = "Managed guidance.\n"; + const prefix = "x".repeat(8592) + "\n"; + const content = managedBlock + ? `${prefix}\n${body}\nLocal suffix.\n` + : "Entire managed file.\n"; + await writeFile(path, content); + await writeInstallManifest({ version: 2, adapter: "fixture", ...scope, targetRoot: root, + generatedAt: "2026-01-01T00:00:00.000Z", revision: "pending-fixture-revision", legacy: false, entries: legacyGuard ? [{ + path: "instructions.md", artifactType: "instructions", artifactName: "fixture", logicalSelector: "fixture", + kind: "file", hash: hash(body), sourceHash: hash(body), updatedAt: "2026-01-01T00:00:00.000Z", + mode: "managed-block", installName: "fixture", owners: ["fixture"], refCount: 1, + channel: "managed", dependencyRole: "root", workspaceOwner: "legacy:unowned", + }] : [] }); + const before = (await readInstallManifest(root, "fixture", localTransport, scope))!; + if (before.version !== 2) throw new Error("Expected v2 manifest"); + const exact = managedBlock ? exactManagedInstructionBlockSnapshot(content, "fixture") : undefined; + const journal: ApplyJournal = { + version: 1, adapter: "fixture", ...scope, targetRoot: root, mode: "uninstall", baseRevision: before.revision, + createdAt: "2026-01-02T00:00:00.000Z", updatedAt: "2026-01-02T00:00:00.000Z", operations: [], completed: [], + manifest: withManifestRevision({ ...before, generatedAt: "2026-01-02T00:00:00.000Z" }), + metadataGuards: { inventory: [{ stateKey: scope.stateKey, revision: before.revision }], + runtime: [{ path: "instructions.md", hash: exact?.hash ?? hash(content), + snapshotDigest: (await observeOwnershipRuntime(path)).snapshotDigest, ...(exact && !legacyGuard ? { managedBlock: exact } : {}) }] }, + }; + return { root, path, content, body, prefix, journal, manifest: installManifestPath(root, "fixture", scope) }; +} + +describe("metadata runtime CAS hash domains", () => { + it.each([true, false])("commits using the correct hash domain (managed block=%s)", async (block) => { + const f = await fixture(block); + if (block) { + expect(Buffer.byteLength(f.prefix)).toBe(8593); + expect(f.journal.metadataGuards!.runtime[0]!.hash).toBe(hash(f.body)); + expect(hash(f.content)).not.toBe(hash(f.body)); + } + await expect(commitManifestMetadataJournal(f.journal)).resolves.toMatchObject({ adapter: "fixture" }); + expect(await readFile(f.path, "utf8")).toBe(f.content); + }); + + it("resolves a legacy zero-operation block guard from the verified inventory", async () => { + const f = await fixture(true, true); + await expect(previewMetadataJournal(f.journal)).resolves.toMatchObject({ manifestPath: f.manifest }); + await expect(commitManifestMetadataJournal(f.journal)).resolves.toMatchObject({ adapter: "fixture" }); + expect(await readFile(f.path, "utf8")).toBe(f.content); + }); + + it.each(["unchanged", "body", "prefix", "file-hash", "snapshot", "inventory"])("loads a legacy whole-file hash plus managedBlock journal (%s)", async (change) => { + const f = await fixture(); + const guard = f.journal.metadataGuards!.runtime[0]!; + guard.hash = hash(f.content); + expect(guard.managedBlock!.hash).toBe(hash(f.body)); + expect(guard.hash).not.toBe(guard.managedBlock!.hash); + await writeApplyJournal(f.journal); + const journalPath = applyJournalPath(f.root, "fixture", scope); + const persisted = await readFile(journalPath); + const loaded = (await readApplyJournal(f.root, "fixture", localTransport, scope))!; + expect(loaded.metadataGuards!.runtime[0]).toEqual(guard); + if (change === "body") await writeFile(f.path, f.content.replace(f.body, "Changed guidance.\n")); + if (change === "prefix") await writeFile(f.path, "Changed prefix.\n" + f.content); + if (change === "file-hash") loaded.metadataGuards!.runtime[0]!.hash = "b".repeat(64); + if (change === "snapshot") loaded.metadataGuards!.runtime[0]!.snapshotDigest = "b".repeat(64); + if (change === "inventory") loaded.metadataGuards!.inventory.push({ stateKey: "other.local", revision: "b".repeat(64) }); + const before = await readFile(f.manifest); + if (change === "unchanged") { + await expect(previewMetadataJournal(loaded)).resolves.toMatchObject({ manifestPath: f.manifest }); + expect(await readFile(f.manifest)).toEqual(before); + expect(await readFile(journalPath)).toEqual(persisted); + await expect(commitManifestMetadataJournal(loaded)).resolves.toMatchObject({ adapter: "fixture" }); + expect(await readFile(f.path, "utf8")).toBe(f.content); + } else { + await expect(previewMetadataJournal(loaded)).rejects.toThrow(/CAS|drift|marker/i); + await expect(commitManifestMetadataJournal(loaded)).rejects.toThrow(/CAS|drift|marker/i); + expect(await readFile(f.manifest)).toEqual(before); + } + expect(await readFile(journalPath)).toEqual(persisted); + }); + + it("refuses a preview with any runtime completion record", async () => { + const f = await fixture(); + f.journal.completed.push({ index: 0, destPath: f.path, kind: "file", hadExisting: true, completed: true }); + await expect(previewMetadataJournal(f.journal)).rejects.toThrow(/zero runtime operations/); + }); + + it.each(["body", "marker", "missing", "prefix", "hash", "snapshot", "inventory", "full-file"])("refuses changed %s without committing metadata", async (change) => { + const f = await fixture(change !== "full-file"); + const before = await readFile(f.manifest); + const guard = f.journal.metadataGuards!.runtime[0]!; + if (change === "body") await writeFile(f.path, f.content.replace(f.body, "Changed guidance.\n")); + if (change === "marker") await writeFile(f.path, f.content.replace(hash(f.body), "b".repeat(64))); + if (change === "missing" || change === "full-file") await writeFile(f.path, "Replaced file.\n"); + if (change === "prefix") await writeFile(f.path, "Changed prefix.\n" + f.content); + // Keep the full-file snapshot current to prove the block/hash CAS independently rejects drift. + if (["body", "marker", "missing", "prefix", "full-file"].includes(change)) guard.snapshotDigest = (await observeOwnershipRuntime(f.path)).snapshotDigest; + if (change === "hash") guard.hash = "b".repeat(64); + if (change === "snapshot") guard.snapshotDigest = "b".repeat(64); + if (change === "inventory") f.journal.metadataGuards!.inventory.push({ stateKey: "other.local", revision: "b".repeat(64) }); + await expect(commitManifestMetadataJournal(f.journal)).rejects.toThrow(/CAS|drift|marker/i); + await expect(previewMetadataJournal(f.journal)).rejects.toThrow(/CAS|drift|marker/i); + expect(await readFile(f.manifest)).toEqual(before); + }); +}); diff --git a/test/ownership-adopt-legacy.test.ts b/test/ownership-adopt-legacy.test.ts index 759189b9..42985076 100644 --- a/test/ownership-adopt-legacy.test.ts +++ b/test/ownership-adopt-legacy.test.ts @@ -883,7 +883,7 @@ async function managedFixture() { await seedPlan(seeded, legacyKey, legacyLock); const source = await readV2({ target }, legacyKey); const entry = source.entries[0]!; const file = join(target, entry.path); const block = await readFile(file, "utf8"); - const prefix = "# Existing local guidance\r\n\r\nKeep every prefix byte.\r\n\n"; + const prefix = "x".repeat(8592) + "\n"; const suffix = "\nKeep every suffix byte.\r\n"; await writeFile(file, prefix + block + suffix); await chmod(file, 0o640); await writeConfig(parent, { schemaVersion: 3, fleetId: "delivery", packages: [fleetPackage()] }); diff --git a/test/ownership-handoff-audit.test.ts b/test/ownership-handoff-audit.test.ts index 8f36ebe7..f3610769 100644 --- a/test/ownership-handoff-audit.test.ts +++ b/test/ownership-handoff-audit.test.ts @@ -2,15 +2,17 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { promisify } from "node:util"; +import { watch, type FSWatcher } from "node:fs"; import { afterEach, describe, expect, it } from "vitest"; import { applyArtifactOwnershipHandoff, planArtifactOwnershipHandoff, workspaceOwnerForRoot, type OwnershipHandoffRequest } from "../src/lifecycle/ownership.js"; import { readInstallManifest, writeInstallManifest } from "../src/install/manifest.js"; import { installManifestPath } from "../src/install/paths.js"; import { applyJournalPath, ownershipRuntimeSnapshot } from "../src/install/transaction.js"; -import { recoverMutationRuntime, resumeMutation } from "../src/mutation/coordinator.js"; +import { recoverMutationRuntime, resumeMutation, previewMutationRecovery } from "../src/mutation/coordinator.js"; import { listMutationReceipts } from "../src/mutation/receipts.js"; +import { ensureCliBuild } from "./helpers/ensure-cli-build.js"; import { localTransport, type TargetTransport } from "../src/transport/index.js"; const execute = promisify(execFile), roots: string[] = []; @@ -71,6 +73,25 @@ describe.sequential("native audited ownership handoff", () => { } }; await expect(applyArtifactOwnershipHandoff({ ...f.request, transport })).rejects.toThrow(/interrupted/); expect((JSON.parse(await readFile(f.journal, "utf8"))).operations).toEqual([]); + const before = await snapshotTree(f.root); + const observation = await observeFilesystemChanges(f.root); + try { + const preview = await previewMutationRecovery("fixture-handoff"); + expect(preview).toMatchObject({ dryRun: true, runtimeOperations: 0, status: "partial", + nextCommand: "agentwheel mutation recover-runtime fixture-handoff" }); + expect(preview.journals).toEqual([expect.objectContaining({ path: f.journal, manifestPath: f.manifest, auditPaths: [f.audit] })]); + expect(await snapshotTree(f.root)).toEqual(before); + const cli = resolve("dist/index.js"); + await ensureCliBuild(cli); + for (const action of ["recover", "finalize", "recover-runtime"]) { + const result = await execute(process.execPath, [cli, "mutation", action, "fixture-handoff", "--dry-run", "--json"], + { cwd: f.workspace, env: { ...process.env, HOME: f.home } }); + expect(JSON.parse(result.stdout)).toMatchObject({ dryRun: true, runtimeOperations: 0, requestedAction: action }); + expect(await snapshotTree(f.root)).toEqual(before); + } + await new Promise((resolveWait) => setTimeout(resolveWait, 20)); + expect(observation.events).toEqual([]); + } finally { observation.close(); } const recovered = await recoverMutationRuntime("fixture-handoff"); expect(recovered.status).toBe("succeeded"); expect((await resumeMutation("fixture-handoff", "recover")).status).toBe("succeeded"); @@ -133,3 +154,27 @@ async function source(f: Awaited>) { const m = await readInstallManifest(f.target, "claude", localTransport, scope); if (!m || m.version !== 2) throw new Error("missing fixture"); return m; } + +async function snapshotTree(root: string): Promise> { + const result: Record = {}; + async function visit(path: string): Promise { + for (const entry of await readdir(path, { withFileTypes: true })) { + const child = join(path, entry.name); + if (entry.isDirectory()) { result[child] = "directory"; await visit(child); } + else result[child] = (await readFile(child)).toString("base64"); + } + } + await visit(root); return result; +} + +async function observeFilesystemChanges(root: string): Promise<{ events: string[]; close(): void }> { + const events: string[] = [], watchers: FSWatcher[] = []; + async function visit(path: string): Promise { + watchers.push(watch(path, (event, name) => events.push(`${path}:${event}:${name ?? ""}`))); + for (const entry of await readdir(path, { withFileTypes: true })) { + if (entry.isDirectory()) await visit(join(path, entry.name)); + } + } + try { await visit(root); } catch (error) { for (const watcher of watchers) watcher.close(); throw error; } + return { events, close: () => { for (const watcher of watchers) watcher.close(); } }; +} diff --git a/test/run-as-metadata.test.ts b/test/run-as-metadata.test.ts index e839e878..d5eccac0 100644 --- a/test/run-as-metadata.test.ts +++ b/test/run-as-metadata.test.ts @@ -215,6 +215,7 @@ describe.skipIf(process.getuid?.() === 0)("confined run-as ownership metadata", await writeFile(f.runtimePath, content); const value = await journal(f); const exact = exactManagedInstructionBlockSnapshot(content, "fixture"); + value.metadataAudit!.runtime[0]!.hash = hash; value.metadataAudit!.runtime[0]!.managedBlock = valid ? exact : { ...exact, prefixHash: "b".repeat(64) }; await writeApplyJournal(value, f.transport); if (valid) await expect(commitManifestMetadataJournal(value, f.transport)).resolves.toMatchObject({ adapter: "openclaw" });