fix(setup): preserve cleanup ownership and resource reports (#6920)

* fix(setup): report host-owned cleanup resources alongside the primary's

SetupHost.close documents that it reports the resources a setup host still
owns, but its contract returned only a string. runSetup therefore built the
ProviderCleanupError from the primary failure's cleanupResources alone, so a
resource the host failed to release reached the projection only inside a
free-text reason while the error asks the caller to review the reported local
resources.

Return a SetupCloseReport instead. closeSetupResources absorbs the structured
resources of any cause that reports them, through
ArtifactReaderFailure.cleanupObservation, and leaves opaque failures
message-only so no resource name is invented. runSetup then unions the host's
resources with the primary's before building the typed cleanup error.

Two boundary tests read the close result directly: the skill-cleanup case now
asserts the retained backup path in the report reason rather than in a bare
string, and the shared ownership helper takes an opaque close result because it
only ever awaits undefined from either host it is given.

Validation: RED then green in src/application/Setup.recovery.test.ts, where
the new case previously received only the primary resource; 116 tests across
the seven Setup and cleanup-ownership suites pass; tsc --noEmit over the
changed set, its setup callers, and both boundary tests exits 0; oxlint
reports 0 errors; oxfmt --check is clean; verify:module-boundaries passes.
The two failures in src/setupEnvironment.test.ts reproduce identically on
pristine bded9c628 with this change stashed.

* fix(setup): preserve cleanup ownership through host reports

* fix(setup): bind finalization reports to cleanup owners

* fix(setup): retain live resources in returned cleanup views

* fix(setup): preserve completed cleanup and exact installer resources

* fix(setup): retain delegated cleanup across authority changes

* fix(setup): compose callback and source cleanup authorities

* fix(setup): retain producer cleanup failure reasons

* fix(cli): render structured setup cleanup resources

* fix(setup): separate failure evidence from cleanup ownership

* fix(setup): normalize close failures and unify lease binding

* fix(setup): preserve direct lease resource attribution

---------

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
Dery Ferdikaandgensokyo-dev authored and GitHub committed 2026-10-24 15:08:10 +08:00
1 parent bdf15b9bd5
commit 98ec00f406
23 files changed
+1543 -188

No files matched your search

+110 -116
View File
@@ -24,7 +24,6 @@ import {
installLinuxHopper,
LinuxHopperTemporaryCleanupOwner,
systemLinuxHopperInstallHost,
type LinuxHopperInstallHost,
} from "./LinuxHopper.js";
import { installMacHopper, systemMacHopperInstallHost } from "./MacHopper.js";
import { linuxHopperReleaseCacheDirectory } from "./LinuxHopperCacheDirectory.js";
@@ -46,7 +45,10 @@ import {
inspectClientConfiguration,
} from "./SetupClientConfiguration.js";
import { failedConfigurationMessage } from "./SetupClients.js";
import { setupInstallFailure } from "./SetupInstallFailure.js";
import {
setupInstallFailure,
type SetupHopperInstallResult,
} from "./SetupInstallFailure.js";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import {
explicitSetupRegistrationEnvironment,
@@ -62,6 +64,12 @@ import type {
SetupProviderEnvironment,
} from "./SetupTypes.js";
import type { DoctorScope } from "./Doctor.js";
import { SetupCleanupOwner } from "./SetupCleanupOwner.js";
import {
AnalysisCleanupLeaseGroup,
type AnalysisCleanupLease,
} from "../artifacts/AnalysisCleanupLease.js";
import { bindRegularFileCleanup } from "./RegularFileRead.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
import { analysisProviderSelectorSchema } from "../contracts/providerSelection.js";
@@ -151,6 +159,30 @@ export const systemSetupHost = (
linuxDistribution,
);
const pendingLinuxHopperCleanup = new LinuxHopperTemporaryCleanupOwner();
const macCleanup = {
rejectedPrefix: "Hopper host cleanup failed",
close: async () => macHopperHost?.close?.(),
};
const temporaryCleanup = {
rejectedPrefix: "Linux Hopper cleanup retry failed",
close: () => pendingLinuxHopperCleanup.retry(linuxHopperHost.cleanup),
};
const publisherCleanup = {
rejectedPrefix: "Linux Hopper publisher cleanup failed",
close: async () => {
await linuxHopperHost.close?.();
},
};
const cleanup = new SetupCleanupOwner([
macCleanup,
{
rejectedPrefix: "Doctor host cleanup failed",
close: async () => doctorHost.close?.(),
},
temporaryCleanup,
publisherCleanup,
{ close: () => resources.close() },
]);
return {
platform,
homeDirectory,
@@ -166,10 +198,7 @@ export const systemSetupHost = (
nodeVersion: process.versions.node,
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution,
close: () =>
closeSetupResources(resources, macHopperHost, doctorHost, () =>
closeLinuxHopperInstallHost(linuxHopperHost, pendingLinuxHopperCleanup),
),
close: () => cleanup.close(),
initialSetupState: async (
scope?: DoctorScope,
): Promise<SetupInitialState> => {
@@ -205,62 +234,74 @@ export const systemSetupHost = (
doctor: diagnosis,
};
},
installHopper: async (replaceExisting) => {
if (platform === "linux") {
const result = await installLinuxHopper(linuxHopperHost);
if (result.cleanupFailure !== undefined)
pendingLinuxHopperCleanup.retain(result.cleanupFailure);
if (result.status === "installed")
return { status: "installed", launcherPath: result.launcherPath };
const failure = setupInstallFailure(
result.reason,
result.packageFailure,
"linux",
);
const detail =
result.verificationFailure?.message ??
result.pythonRuntimeFailure?.message ??
(result.operationFailure === undefined
? undefined
: `${result.operationFailure.operation}${result.operationFailure.path === undefined ? "" : ` at ${result.operationFailure.path}`}: ${result.operationFailure.systemCode === undefined ? "" : `${result.operationFailure.systemCode}: `}${result.operationFailure.detail}`);
return detail !== undefined
? {
...failure,
remediation: `${detail} ${failure.remediation}`,
installHopper: (replaceExisting) =>
resources.run<SetupHopperInstallResult>(async () => {
const publisher = platform === "linux" ? publisherCleanup : macCleanup;
cleanup.admit(publisher);
try {
if (platform === "linux") {
const result = await installLinuxHopper(linuxHopperHost);
if (result.cleanupFailure !== undefined) {
pendingLinuxHopperCleanup.retain(result.cleanupFailure);
cleanup.admit(temporaryCleanup);
}
: failure;
}
if (macHopperHost === undefined)
return setupInstallFailure("unsupported_host");
const result = await installMacHopper({ replaceExisting }, macHopperHost);
if (result.status === "installed")
return {
status: "installed",
launcherPath: result.launcherPath,
...(result.openFailure === undefined
? {}
: {
warning: `Hopper was installed, but macOS could not open it: ${result.openFailure}. Open ${result.launcherPath} manually to complete first-run setup.`,
}),
...(result.cleanupFailure === undefined
? {}
: { cleanupFailure: result.cleanupFailure }),
};
const failure = setupInstallFailure(result.reason);
const diagnostic = setupInstallerDiagnostic(result.diagnostic);
return {
...failure,
remediation: [
failure.remediation,
...(diagnostic === undefined
? []
: [`Installer detail: ${diagnostic}`]),
...(result.cleanupFailure === undefined
? []
: [result.cleanupFailure]),
].join(" "),
};
},
if (result.status === "installed")
return { status: "installed", launcherPath: result.launcherPath };
const failure = setupInstallFailure(
result.reason,
result.packageFailure,
"linux",
);
const detail =
result.verificationFailure?.message ??
result.pythonRuntimeFailure?.message ??
(result.operationFailure === undefined
? undefined
: `${result.operationFailure.operation}${result.operationFailure.path === undefined ? "" : ` at ${result.operationFailure.path}`}: ${result.operationFailure.systemCode === undefined ? "" : `${result.operationFailure.systemCode}: `}${result.operationFailure.detail}`);
return detail !== undefined
? {
...failure,
remediation: `${detail} ${failure.remediation}`,
}
: failure;
}
if (macHopperHost === undefined)
return setupInstallFailure("unsupported_host");
const result = await installMacHopper(
{ replaceExisting },
macHopperHost,
);
if (result.status === "installed")
return {
status: "installed",
launcherPath: result.launcherPath,
...(result.openFailure === undefined
? {}
: {
warning: `Hopper was installed, but macOS could not open it: ${result.openFailure}. Open ${result.launcherPath} manually to complete first-run setup.`,
}),
...(result.cleanupFailure === undefined
? {}
: { cleanupFailure: result.cleanupFailure }),
};
const failure = setupInstallFailure(result.reason);
const diagnostic = setupInstallerDiagnostic(result.diagnostic);
return {
...failure,
remediation: [
failure.remediation,
...(diagnostic === undefined
? []
: [`Installer detail: ${diagnostic}`]),
...(result.cleanupFailure === undefined
? []
: [result.cleanupFailure]),
].join(" "),
};
} finally {
cleanup.admit(publisher);
}
}),
detectedClients: () => detectClients(homeDirectory, platform, environment),
supportedClients: () =>
Promise.resolve(supportedClients(homeDirectory, platform, environment)),
@@ -360,42 +401,6 @@ const clientConfigurationOperations = (
),
});
const closeSetupResources = async (
resources: ArtifactResourceScope,
macHopperHost: ReturnType<typeof systemMacHopperInstallHost> | undefined,
doctorHost: DoctorHost,
retryLinuxHopperCleanup: () => Promise<string | undefined>,
): Promise<string | undefined> => {
const [resourceCleanup, hopperCleanup, doctorCleanup, linuxCleanup] =
await Promise.allSettled([
resources.close(),
Promise.resolve().then(() => macHopperHost?.close()),
Promise.resolve().then(() => doctorHost.close?.()),
retryLinuxHopperCleanup(),
]);
const failures: string[] = [];
if (hopperCleanup.status === "rejected")
failures.push(
`Hopper host cleanup failed: ${errorMessage(hopperCleanup.reason)}`,
);
else if (hopperCleanup.value !== undefined)
failures.push(hopperCleanup.value);
if (doctorCleanup.status === "rejected")
failures.push(
`Doctor host cleanup failed: ${errorMessage(doctorCleanup.reason)}`,
);
else if (doctorCleanup.value !== undefined)
failures.push(doctorCleanup.value);
if (linuxCleanup.status === "rejected")
failures.push(
`Linux Hopper cleanup retry failed: ${errorMessage(linuxCleanup.reason)}`,
);
else if (linuxCleanup.value !== undefined) failures.push(linuxCleanup.value);
if (resourceCleanup.status === "rejected")
failures.push(errorMessage(resourceCleanup.reason));
return failures.length === 0 ? undefined : failures.join("; ");
};
const runClientConfigurationOperation = async <Value>(
resources: ArtifactResourceScope,
operation: () => Promise<Value>,
@@ -419,6 +424,7 @@ const runClientConfigurationOperation = async <Value>(
`Could not safely access client configuration at ${cause.path}: ${errorMessage(cleanup.primary)}.${rollbackMessage}`,
cause,
cleanup.cleanup,
cleanup.cleanupLeases,
);
}
});
@@ -435,33 +441,21 @@ const configurationCleanupError = (
cleanup:
| { readonly reason: string; readonly resources: readonly string[] }
| undefined,
): ConfigurationError =>
new ConfigurationError(message, {
leases?: readonly AnalysisCleanupLease[],
): ConfigurationError => {
const error = new ConfigurationError(message, {
cause,
settings: [{ setting: "client configuration", constraint: message }],
...(cleanup === undefined ? {} : { cleanup }),
});
if (leases !== undefined) new AnalysisCleanupLeaseGroup(error, leases);
else bindRegularFileCleanup(cause, error);
return error;
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
const closeLinuxHopperInstallHost = async (
host: LinuxHopperInstallHost,
temporaryOwner: LinuxHopperTemporaryCleanupOwner,
): Promise<string | undefined> => {
const reasons: string[] = [];
const temporary = await temporaryOwner.retry(host.cleanup);
if (temporary !== undefined) reasons.push(temporary);
try {
await host.close?.();
} catch (cause: unknown) {
reasons.push(
`Linux Hopper publisher cleanup failed: ${errorMessage(cause)}`,
);
}
return reasons.length === 0 ? undefined : reasons.join("; ");
};
/** Detect supported agents from their config files or stable installation markers. */
export const detectClients = async (
home: string,