mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* test(architecture): fail on a stale layer baseline and document the declared layers verify:module-boundaries reported a layer baseline entry whose imports were gone but still passed, so main kept process -> artifacts at 20 after it fell to 17 and a later change could add three imports back unnoticed. A stale entry now fails like growth; --shrink-layer-baseline lowers it in the change that removes the imports. The architecture map and CONTRIBUTING name scripts/lib/module-layers.mjs as the per-directory layer declaration. * test(architecture): refuse to lower the layer baseline after an inspection failure A file that cannot be parsed contributes no imports, so a shrink run would record counts that fail as growth once the file is fixed. Whole-command tests cover stale rejection, shrinking, refused growth and the inspection failure. * refactor(ports): move the progress, work-scope and inspection-scope ports to src/ports (#11214) * refactor(ports): move the progress, work-scope and inspection-scope ports to src/ports Pure move with git mv and import specifier updates. * test(architecture): declare the ports layer and lower the layer baseline src/ports sits between the foundation and the providers. Moving the three ports removes 11 provider -> application imports. * refactor(ports): move AnalysisProvider to src/ports (#11217) * refactor(ports): move AnalysisProvider to src/ports Pure move with git mv and import specifier updates in its importers, the built-fixture path, the CI scope glob and the lint-rule test spellings. * test(architecture): lower the layer baseline after moving AnalysisProvider * refactor(ports): move the per-feature provider ports to src/ports (#11226) * refactor(ports): move the per-feature provider ports to src/ports Pure move with git mv and import specifier updates: the 47 *Port.ts and *Ports.ts files that providers implement, plus OptionalObservationProviders, which only composes the observation ports. * test(architecture): lower the layer baseline after moving the feature ports * refactor(providers): move closeAnalysisClient and the Frida session input errors to their owners (#11233) * refactor(providers): move closeAnalysisClient to src/providers and the Frida session input errors to src/frida Pure move with git mv and import specifier updates. * test(architecture): drop the application-providers and application-frida cycles from the layer baseline * fix(ci): keep provider lanes selecting the ports moved to src/ports Each lane glob that matched a moved port under src/application gains its src/ports counterpart; the change-scope test pins one moved port per lane. * refactor(domain): declare the localPath host exception and read HOST_PLATFORM there (#11256) absoluteLocalPathStringSchema decides which paths are absolute on the running host, so it reads HOST_PLATFORM instead of process.platform. Domain may not import outside domain/contracts; module-layers now declares LAYER_EXCEPTIONS, exact file-to-file imports with a reason, and both the layer count and the pure-layer boundary skip only that import. Any other domain -> platform import still fails. * refactor(ports): move the doctor check and provider inspection types to src/ports (#11246) * refactor(ports): move the doctor check and provider inspection types to src/ports Declaration move from application/Doctor.ts (unchanged text) and import updates; no re-export from Doctor.ts. * test(architecture): lower the layer baseline after moving the doctor provider types * refactor(ports): move the packet capture and signal recording ports to src/ports (#11249) * refactor(ports): move the packet capture and signal recording ports to src/ports Declaration move (unchanged text) out of the two application services, with import updates. * test(architecture): lower the layer baseline after moving the capture and signal ports * refactor(domain): move the analysis error projection schema from contracts to domain (#11251) * refactor(domain): move the analysis error projection schema from contracts to domain Declaration move (unchanged text) of the projection schemas that domain modules embed; contracts/errorSchemas.ts keeps the CLI envelope and the published JSON Schema. Import updates only. * test(architecture): drop the contracts-domain cycle from the layer baseline * refactor(ports): drop the imports the moved capture, signal and doctor types left behind Also give the packet capture and signal recording lanes the new port paths, with change-scope cases. * refactor(resources): add src/resources and move AnalysisCleanupLease and ArtifactReader there (#11259) * refactor(resources): move AnalysisCleanupLease to src/resources Pure move: git mv plus import specifier rewrites (source, tests, and the dist paths the verifier scripts load). * refactor(resources): declare src/resources as a foundation unit src/resources owns the shared analysis resource modules that process, windows and providers hold; AnalysisCleanupLease is the first. Its tests join the adapters project, the apk signature lane selects it beside src/artifacts, and the layer baseline drops the process and windows imports of the lease. * test(ci): pin the apk signature lane on the moved cleanup lease * refactor(resources): move ArtifactReader to src/resources Pure move: git mv plus import specifier rewrites (source, tests, and the dist path a verifier script loads). * test(architecture): lower the layer baseline after moving ArtifactReader windows no longer imports src/artifacts; process -> artifacts 11 -> 9. The CI lanes that selected src/artifacts/ArtifactReader.ts select its new path, pinned in the change-scope test. * refactor(resources): move ArtifactResourceScope to src/resources (#11265) * refactor(artifacts): name the output tree and private root capabilities the resource scope releases ArtifactResourceScope typed its output-tree and private-runtime-root owners with SafeOutputTree (src/artifacts) and PrivateRuntimeRoot (src/process). It only calls rollback() and close(), so it now declares those capabilities itself and names neither unit, which lets it move to src/resources without a resources <-> process cycle. The withheld-export test narrows to SafeOutputTree where it reads the published flag. * refactor(resources): move ArtifactResourceScope to src/resources Pure move: git mv plus import specifier rewrites (source, tests, the dist paths verifier scripts load, and the FIFO probe's module-relative URL). * test(architecture): lower the layer baseline after moving ArtifactResourceScope process -> artifacts 9 -> 5, and the artifacts <-> dotnet mutual pair is gone. The sqlite and agentenv lanes select the scope at its new path, pinned in the change-scope test. * refactor(resources): move ArtifactFileOperation to src/resources (#11269) * refactor(resources): move ArtifactFileOperation to src/resources Pure move: git mv plus import specifier rewrites (source, tests, and the dist paths verifier scripts load). * test(architecture): lower the layer baseline after moving ArtifactFileOperation process -> artifacts 5 -> 1. * refactor(resources): move readStableArtifact to src/resources (#11271) * refactor(resources): move readStableArtifact to src/resources Pure move: git mv plus import specifier rewrites. * test(architecture): lower the layer baseline after moving readStableArtifact process no longer imports src/artifacts: process -> artifacts 1 -> 0 and the artifacts <-> process mutual pair is gone. The seven lanes that selected readStableArtifact select its new path, pinned in the change-scope test; the architecture map lists what src/resources owns. * refactor(hopper): take Linux launcher verification from composition through a port (#11278) The Hopper launcher imported inspectLinuxHopperLauncher and retryLinuxHopperPublisherCleanup from src/application (the two hopper -> application imports). src/ports/LinuxHopperLauncherVerification.ts now names that capability; src/application/LinuxHopper.ts provides LINUX_HOPPER_LAUNCHER_VERIFICATION, binary composition passes it to HopperProvider, and the provider hands it to the launcher. A launcher built without one refuses a Linux demo launch with reason verification_unavailable before running the launcher. Layer baseline: hopper -> application 2 -> 0. * refactor(config): move Hopper launcher discovery to a src/hopperPaths foundation unit (#11292) * refactor(hopper): move the launcher discovery and macOS Hopper paths to src/hopperPaths Pure move: git mv plus import specifier rewrites. * refactor(hopper): declare src/hopperPaths as a foundation unit with the Linux launcher candidates Hopper install paths and launcher discovery are pure path facts that the Hopper provider, doctor and setup all read. Declare src/hopperPaths in the foundation layer, add it to the adapters test project, the architecture map and the package-baseline CI lane, and move the Linux launcher candidates out of src/application/LinuxHopper.ts into src/hopperPaths/LinuxHopperPaths.ts so discovery no longer imports application code. * refactor(config): leave Hopper launcher discovery to the Hopper provider parseConfig resolved an unset HOPPER_LAUNCHER_PATH by probing the filesystem through application-owned discovery, so config imported application (config -> application 2, application <-> config cycle) and read process.platform ambiently. AppConfig.hopperLauncherPath is now the caller's HOPPER_LAUNCHER_PATH unchanged (string | undefined). src/hopperPaths/HopperLauncherDiscovery.ts owns the selection (selectedHopperLauncherPath: the configured spelling, else discovery from the caller environment's home on the provider's platform); HopperProvider and the two real-Hopper verifiers read it. Discovery tests move from config.test.ts to src/hopperPaths; a provider test covers discovery from the provider's own platform and home. Module layers: config -> application 2 -> 0; application <-> config removed. Architecture guards: ambient platform reads in parseConfig.ts 2 -> 0. * refactor(providers): move owned-process prerequisite availability out of application (#11294) * refactor(providers): move the owned-process prerequisite availability mapping to src/providers Pure move: git mv plus import specifier rewrites. * test(architecture): lower the layer baseline after moving owned-process availability android -> application 1 -> 0; apktool -> application 1 -> 0. * refactor(process): move the regular-file read owner out of application (#11299) * refactor(process): move the regular-file read owner from src/application to src/process Pure move: git mv plus import specifier rewrites. * test(architecture): lower the layer baseline after moving the regular-file read owner desktop -> application 5 -> 4; dotnet -> application 2 -> 1. The agentenv lane listed src/application/RegularFileRead.ts. At its new path it is a src/process/ shared boundary: fast qualification selects the code and runtime checks (and the single owning lane, web_source_map, via src/process/**), and full qualification selects every lane, as for every other src/process/ module. A second owner entry would only suppress the web_source_map selection, so the agentenv entry is removed, not renamed. * refactor(resources): give atomic text writes their own owner (#11302) * refactor(resources): give atomic text writes their own owner in src/resources src/application/JsonFiles.ts owned both JSON input reads and the atomic text write (writeTextFile / writeTextParts and their staged-output publication). The write side depends only on domain, filesystem and resource owners, but il2cpp's Ghidra seed writer had to import application to reach it (il2cpp -> application). Move the write side verbatim to src/resources/TextFileWrite.ts (TextWriteCancellation, writeTextFile, writeTextParts and their private staging, publication and failure classification helpers). JsonFiles keeps the JSON read owner and reads the shared errno-to-reason classifier (fileAccessFailureReason) from the write owner instead of a copy. Importers (il2cpp seed writer, evidence bundle files, desktop build solves, analysis snapshot files and four boundary tests) read the new path; no re-export is left in JsonFiles. * test(architecture): lower the layer baseline after moving the text write owner il2cpp -> application 1 -> 0. * refactor(ports): move the desktop build host contract to src/ports (#11303) * refactor(domain): move the setup cancellation check from src/application to src/domain Pure move: git mv plus import specifier rewrites. * refactor(ports): move the desktop build host contract to src/ports The desktop provider implements doctor's desktop build facts reader and setup's desktop build host, but the contract it implements lived in application (DesktopBuildDoctor, SetupDesktopBuild, Doctor's clientRegistrations signature, ClientRegistrationEnvironment's setting types), so desktop imported application four times and the two units were a recorded mutual pair. src/ports/DesktopBuildHost.ts now holds that contract, moved verbatim: DesktopBuildCommand, DesktopBuildFacts, DesktopBuildFactsInput, DesktopBuildSetupFacts, DesktopBuildSetupHost, RecordedProviderSettings and OwnedProviderSetting. Two names are new: DesktopBuildRegistration, the registration facts the host reads (client, command and the recorded-settings names; client registration status satisfies it), and DesktopBuildRegistrationReader, which replaces DoctorHost["clientRegistrations"] in the setup host. The facts input's registration reader returns DesktopBuildRegistration instead of the full application status; the setup facts' settings are spelled Readonly<Record<string, string>> (SetupProviderEnvironment's definition). Application imports the types from the port; no re-export is left. * test(architecture): lower the layer baseline after the desktop build host port desktop -> application 4 -> 0; the application <-> desktop mutual pair is gone. * refactor(domain): define the resolved app bundle resource root beside its schema (#11304) * refactor(domain): define the resolved app bundle resource root beside its provenance schema ResolvedAppBundleResourceRoot (an app directory's resource-only identity) is a pure type over BundleResourceRoot's layout, but it lived in src/application/AppBundleExecutable.ts, so the native and artifact providers that receive it imported application. Move the interface verbatim to src/domain/apple/bundleResourceRoot.ts, which owns BundleResourceRoot, and point its eight readers there (native macOS provider and plist source, artifact provider, binary composition, and the binary session, status, port and bundle-resource session). The resolver that produces it stays in application. * test(architecture): lower the layer baseline after moving the resource root type native -> application 2 -> 0; artifacts -> application 2 -> 1 (the artifact provider still constructs BundleResourceSession). * refactor(config): move the pwntools input bound parser to src/config (#11306) * refactor(config): move the pwntools input bound parser from src/native to src/config Pure move: git mv plus import specifier rewrites, and the module path in docs/design/rea-limit-inventory.md (table realigned by oxfmt). * test(architecture): lower the layer baseline after moving the pwntools input bound config -> native 1 -> 0. The binary_layout and recorded_crash lanes, which select src/native/pwntools/**, also select src/config/pwntoolsInputLimit*.ts; ciChangeScope.test.ts pins both. * refactor(filesystem): move REA cache directory helpers out of config (#11309) * refactor(filesystem): move the REA cache directory and lexical directory helpers from src/config to src/filesystem Pure move: git mv plus import specifier rewrites. * test(architecture): drop the config and filesystem cycle from the layer baseline config no longer imports filesystem; filesystem still reads the Windows ChangeTime settle budget from config. * refactor(windows): break the process and windows import cycle (#11317) * refactor(domain): move the runtime-control and private-runtime-root refusals from src/process to src/domain Pure move: git mv plus import specifier rewrites (including the dist path scripts/verify-windows-native.mjs loads). * refactor(windows): type Job Object cleanup by what a Windows job reports WindowsOwnedProcess.cleanup() returned process-ownership's ProcessCleanupResult, so src/windows imported src/process for a type while process imports windows to supervise Windows trees. A Job Object stop only ever reports settled-and-signalled or a reason it did not settle; name that subset WindowsJobCleanupResult in windows. It stays assignable to ProcessCleanupResult, so the process supervisor reads it unchanged. * test(architecture): drop the process and windows cycle from the layer baseline * test(architecture): ratchet cross-provider imports and imports past a provider entry (#11386) * test(architecture): ratchet cross-provider imports and imports past a provider entry A provider folder may import the domain, contracts, foundation and ports layers, the shared provider core (src/providers) and its own files; an import of another provider folder is a recorded exception. Application, composition and the CLI/MCP adapters reach a provider only through src/<provider>/index.ts. verify:module-boundaries counts both kinds of import per unit pair in the layer baseline (crossProvider, providerEntry); like the upward counts they may only shrink, and a pair missing from the baseline fails. * refactor(resources): move StableArtifactFailure and StableArtifactObservation into src/resources (#11387) * refactor(resources): move StableArtifactFailure and StableArtifactObservation into src/resources Providers project stable-read failures through StableArtifactFailure next to the other shared provider toolkit owners (ArtifactReader, ArtifactResourceScope, ArtifactFileOperation, AnalysisCleanupLease, readStableArtifact) that already live in src/resources. Under src/artifacts it made every provider that reads a stable artifact import the artifacts provider. Pure move: git mv plus import specifier and baseline updates; the layer baseline drops the provider-boundary counts the move removes. * refactor(resources): reach the shared provider toolkit through src/resources/index.ts (#11390) * refactor(resources): import the shared provider toolkit through src/resources/index.ts Adds src/resources/index.ts, which exports the toolkit names that production code outside src/resources uses, and rewrites those importers (420 files) to import from it, merging each importer's toolkit imports into one declaration. Mechanical: import declarations only. * test(architecture): reach src/resources only through its entry file verify:module-boundaries now counts any production import of a src/resources file other than src/resources/index.ts, from any unit, with the imports past a provider entry. The count is renamed from providerEntry to entry ("import past the entry file"); it may only shrink, and src/resources starts at zero. * test(architecture): cover provider boundary counts through the verifier command * refactor(resources): move the safe output tree and artifact path owners into src/resources (#11398) * refactor(resources): move the safe output tree and artifact path owners into src/resources SafeOutputTree (with its admission, creation failure, readback, cleanup and identity files), StreamBytes, ArtifactPaths and readArtifactFileChunks depend only on domain, filesystem, platform and the toolkit, and browser, firmware, ghidra, javascript, android and apktool use them to publish outputs. Under src/artifacts every such provider imported the artifacts provider. Pure move: git mv, importers moved onto src/resources/index.ts (names added to the entry), the moved files import toolkit modules directly, path keys in the CI scopes and guard baseline follow the move, and the layer baseline drops the removed imports. * test(architecture): give the shared provider core its own layer below the providers (#11401) src/providers (deferred client owners and failure attribution) now imports only domain, ports, process, filesystem and the resources toolkit. Declaring it as the providerCore layer, between ports and providers, makes any import from it into a provider folder an upward import that verify:module-boundaries rejects, and lets every unit in the providers layer be a provider folder. * test(architecture): declare each provider's entry files instead of a provider barrel (#11407) * chore: ignore the source map parser move (#11348) in blame * test(architecture): declare inspector's use of the browser CDP client as a provider dependency (#11420)
1902 lines
69 KiB
TypeScript
1902 lines
69 KiB
TypeScript
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
|
import { appendCallerPath } from "../filesystem/callerPath.js";
|
|
import {
|
|
isClientConfigurationCleanupFailure,
|
|
retryClientConfigurationCleanup,
|
|
} from "./ClientConfigurationCleanup.js";
|
|
import {
|
|
ClientConfigurationShapeError,
|
|
clientConfigurationServersKey,
|
|
clientConfigurationSyntaxName,
|
|
parseClientConfiguration,
|
|
serializeClientConfiguration,
|
|
clientServerPath,
|
|
legacyClientServerPath,
|
|
shadowedClientServers,
|
|
withClientServers,
|
|
type ClientConfigurationDocument,
|
|
} from "./ClientConfigurationDocument.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import { ConfigurationError } from "../domain/configurationErrors.js";
|
|
import {
|
|
AnalysisError,
|
|
type AnalysisCleanupObservation,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import { copyFile, lstat, realpath, rm, rmdir } from "node:fs/promises";
|
|
import { constants as fsConstants } from "node:fs";
|
|
import { isDeepStrictEqual } from "node:util";
|
|
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
|
|
import { basename, dirname } from "node:path";
|
|
import {
|
|
defaultKunaCacheDirectory,
|
|
hasParentTraversal,
|
|
sameLexicalDirectory,
|
|
withinLexicalDirectory,
|
|
} from "../filesystem/cacheDirectory.js";
|
|
import { defaultDarwinHelperCacheDirectory } from "../process/DarwinHelperCache.js";
|
|
import { linuxHopperReleaseCacheDirectory } from "./LinuxHopperCacheDirectory.js";
|
|
|
|
import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js";
|
|
import {
|
|
effectiveClientConfiguration,
|
|
type ClientConfigurationSource,
|
|
} from "./ClientConfigurationFiles.js";
|
|
import { clientRegistrationOwnership } from "./ClientRegistration.js";
|
|
|
|
import { PRODUCT_IDENTITY } from "../identity.js";
|
|
import {
|
|
isManagedSkillManifest,
|
|
MANAGED_SKILL_FILES,
|
|
readSkillFile,
|
|
skillDestinationSelection,
|
|
} from "./SetupSkill.js";
|
|
import { dshDocument } from "./DshCordisPatch.js";
|
|
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
|
import {
|
|
preserveCurrentRecoveryBackup,
|
|
type RecoveryBackupPreservationOptions,
|
|
} from "./SetupRecoveryBackup.js";
|
|
import { preservePrivateRecoveryBackup } from "./ClientRegistrationBackup.js";
|
|
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
|
|
import {
|
|
InvalidUtf8FileError,
|
|
readRegularFileText,
|
|
bindRegularFileCleanup,
|
|
} from "../process/RegularFileRead.js";
|
|
import {
|
|
ArtifactReaderFailure,
|
|
ArtifactResourceScope,
|
|
} from "../resources/index.js";
|
|
import {
|
|
appDataRedirection,
|
|
clientOwnershipEvidencePaths,
|
|
clientSharedRegistrationPaths,
|
|
manualRegistrationRemediation,
|
|
registrationWriteBlocker,
|
|
resolveSupportedClients,
|
|
type ClientSystemPaths,
|
|
type SetupClient,
|
|
} from "./SupportedClients.js";
|
|
import {
|
|
redirectedWriteBlocker,
|
|
type MsixPackageView,
|
|
} from "./MsixPackageStorage.js";
|
|
|
|
interface ManagedPathStats {
|
|
readonly uid?: number;
|
|
isFile?(): boolean;
|
|
isDirectory?(): boolean;
|
|
isSymbolicLink(): boolean;
|
|
}
|
|
|
|
/** Injectable filesystem operations used to prove uninstall failure recovery. */
|
|
export interface UninstallFileSystem {
|
|
readText(path: string): Promise<string>;
|
|
readRegularText?(path: string): Promise<string>;
|
|
/** Preserve the first backup; reject an existing destination with EEXIST. */
|
|
copy(source: string, destination: string): Promise<void>;
|
|
publishConfiguration(
|
|
path: string,
|
|
contents: string,
|
|
original: string,
|
|
): Promise<
|
|
Pick<
|
|
ClientConfigurationPublication,
|
|
"path" | "verify" | "assertCurrent" | "restore"
|
|
>
|
|
>;
|
|
stat(path: string): Promise<ManagedPathStats>;
|
|
realpath?(path: string): Promise<string>;
|
|
remove(path: string, recursive?: boolean): Promise<void>;
|
|
/** Remove a directory only if it is empty; a non-empty one is kept. */
|
|
removeEmptyDirectory?(path: string): Promise<void>;
|
|
}
|
|
|
|
const systemFileSystem = (
|
|
resources: ArtifactResourceScope,
|
|
): UninstallFileSystem => ({
|
|
readText: (path) => readRegularFileText(path, { resources }),
|
|
readRegularText: (path) => readSkillFile(path, resources),
|
|
copy: (source, destination) =>
|
|
copyFile(source, destination, fsConstants.COPYFILE_EXCL),
|
|
publishConfiguration: (path, contents, original) =>
|
|
ClientConfigurationPublication.write(path, contents, original),
|
|
stat: (path) => lstat(path),
|
|
realpath: (path) => realpath(path),
|
|
remove: (path, recursive = true) => rm(path, { recursive }),
|
|
removeEmptyDirectory: (path) => rmdir(path),
|
|
});
|
|
|
|
/** One completed or refused action, preserving its candidate configuration path. */
|
|
export interface UninstallAction {
|
|
readonly status: "removed" | "retained" | "skipped" | "failed";
|
|
readonly detail: string;
|
|
readonly configuration_path?: string;
|
|
}
|
|
|
|
/** One client summary with its constituent actions when multiple paths apply. */
|
|
export interface UninstallItem extends UninstallAction {
|
|
readonly name: string;
|
|
readonly actions?: readonly UninstallAction[];
|
|
}
|
|
|
|
/** Structured, idempotent result of removing REA-owned state. */
|
|
export interface UninstallResult {
|
|
readonly status: "complete" | "failed";
|
|
readonly items: readonly UninstallItem[];
|
|
readonly cleanup?: AnalysisCleanupObservation | undefined;
|
|
}
|
|
|
|
/** Applicability established once from product-specific discovery evidence. */
|
|
export interface UninstallClient extends SetupClient {
|
|
readonly applicability?: "unverified";
|
|
/** Clients that load this same registration table as a fallback report the
|
|
* owner's outcome without inspecting or editing the file again. */
|
|
readonly sharedWith?: readonly string[];
|
|
}
|
|
|
|
/** Filesystem boundary used by the contained uninstall workflow. */
|
|
export interface UninstallHost {
|
|
clients(): Promise<readonly UninstallClient[]>;
|
|
/** Report a configuration that cannot be read safely, before any removal. */
|
|
inspectClient(client: UninstallClient): Promise<UninstallItem | undefined>;
|
|
removeClient(client: UninstallClient): Promise<UninstallItem>;
|
|
inspectSkill?(): Promise<UninstallItem | undefined>;
|
|
removeSkill(): Promise<UninstallItem>;
|
|
purgeData(): Promise<readonly UninstallItem[]>;
|
|
close?(): Promise<AnalysisError | undefined>;
|
|
}
|
|
|
|
/** Preserve the resource owner's explicit retry capabilities through uninstall reporting. */
|
|
const uninstallCleanupError = (cause: unknown): AnalysisError => {
|
|
if (cause instanceof AnalysisError && cause.carriesCleanup) return cause;
|
|
const cleanup = ArtifactReaderFailure.cleanupObservation(cause, []);
|
|
const error = new ProviderCleanupError(
|
|
"uninstall",
|
|
cleanup.resources,
|
|
{ reason: cleanup.reason },
|
|
{ cause, cleanup, operation: "uninstall" },
|
|
);
|
|
bindRegularFileCleanup(cause, error);
|
|
return error;
|
|
};
|
|
|
|
/**
|
|
* Remove only REA-owned registrations and managed files, optionally including
|
|
* local state. A client configuration that cannot be read safely stops the
|
|
* operation before anything is removed; one that fails during removal stops
|
|
* the remaining removals.
|
|
*/
|
|
export const runUninstall = async (
|
|
purgeData: boolean,
|
|
host: UninstallHost,
|
|
): Promise<UninstallResult> => {
|
|
let result: UninstallResult | undefined;
|
|
let primaryFailure: unknown;
|
|
let failed = false;
|
|
try {
|
|
const clients = await host.clients();
|
|
const blocked: UninstallItem[] = [];
|
|
for (const client of clients) {
|
|
const blocking = await host.inspectClient(client);
|
|
if (blocking !== undefined)
|
|
blocked.push({ ...blocking, configuration_path: client.configPath });
|
|
}
|
|
const skillBlocker = await host.inspectSkill?.();
|
|
if (skillBlocker !== undefined) blocked.push(skillBlocker);
|
|
const items: UninstallItem[] =
|
|
blocked.length > 0
|
|
? [
|
|
...blocked,
|
|
item(
|
|
"uninstall",
|
|
"skipped",
|
|
"No REA registration, skill, or data was removed. Repair each failed configuration, then rerun uninstall.",
|
|
),
|
|
]
|
|
: await removeAll(clients, purgeData, host);
|
|
items.push({
|
|
name: "analysis_engine",
|
|
status: "retained",
|
|
detail: "Hopper is not owned by REA uninstall.",
|
|
});
|
|
const reported = collapseUninstallItems(
|
|
projectSharedRegistrations(items, clients),
|
|
);
|
|
result = {
|
|
status: reported.some(({ status }) => status === "failed")
|
|
? "failed"
|
|
: "complete",
|
|
items: reported,
|
|
};
|
|
} catch (cause: unknown) {
|
|
failed = true;
|
|
primaryFailure = cause;
|
|
}
|
|
let cleanupFailure: AnalysisError | undefined;
|
|
try {
|
|
const report = await host.close?.();
|
|
cleanupFailure =
|
|
report === undefined ? undefined : uninstallCleanupError(report);
|
|
} catch (cause: unknown) {
|
|
cleanupFailure = uninstallCleanupError(cause);
|
|
}
|
|
if (cleanupFailure !== undefined && !cleanupFailure.cleanupIncomplete)
|
|
cleanupFailure = undefined;
|
|
if (failed) {
|
|
if (cleanupFailure !== undefined) {
|
|
if (primaryFailure instanceof AnalysisError)
|
|
throw analysisErrorWithCleanupFailure(
|
|
primaryFailure,
|
|
cleanupFailure,
|
|
"uninstall",
|
|
).bindCleanupDependencies([primaryFailure, cleanupFailure]);
|
|
throw new AggregateError(
|
|
[primaryFailure, cleanupFailure],
|
|
"Uninstall failed and its resource cleanup remains incomplete.",
|
|
{ cause: primaryFailure },
|
|
);
|
|
}
|
|
throw primaryFailure;
|
|
}
|
|
if (result === undefined)
|
|
throw new Error("Uninstall result was not produced.");
|
|
if (cleanupFailure === undefined) return result;
|
|
const items = collapseUninstallItems([
|
|
...result.items,
|
|
item(
|
|
"uninstall_cleanup",
|
|
"failed",
|
|
`Uninstall resource cleanup failed: ${cleanupFailure.cleanup?.reason ?? cleanupFailure.message}${cleanupFailure.cleanupResources.length === 0 ? "" : ` (${cleanupFailure.cleanupResources.join(", ")})`}`,
|
|
),
|
|
]);
|
|
const retained = cleanupFailure;
|
|
return {
|
|
status: "failed",
|
|
items,
|
|
get cleanup() {
|
|
return retained.cleanupIncomplete
|
|
? {
|
|
reason: retained.cleanup?.reason ?? retained.message,
|
|
resources: retained.cleanupResources,
|
|
}
|
|
: undefined;
|
|
},
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Reread each client when editing and refuse detected changes before publication.
|
|
* A client that fails still stops the remaining removals.
|
|
*/
|
|
const removeAll = async (
|
|
clients: readonly UninstallClient[],
|
|
purgeData: boolean,
|
|
host: UninstallHost,
|
|
): Promise<UninstallItem[]> => {
|
|
const items: UninstallItem[] = [];
|
|
const stopped = (): UninstallItem[] => [
|
|
...items,
|
|
item(
|
|
"uninstall",
|
|
"skipped",
|
|
"Uninstall stopped at this failure; the items above report what changed. Repair the failed removal, then rerun uninstall.",
|
|
),
|
|
];
|
|
for (const client of clients) {
|
|
const removed = await host.removeClient(client);
|
|
items.push({ ...removed, configuration_path: client.configPath });
|
|
if (removed.status === "failed") return stopped();
|
|
}
|
|
const skill = await host.removeSkill();
|
|
items.push(skill);
|
|
if (skill.status === "failed") return stopped();
|
|
if (purgeData) items.push(...(await host.purgeData()));
|
|
return items;
|
|
};
|
|
|
|
/**
|
|
* Report a shared file's single outcome under every client that loads it. The
|
|
* owner edits the file once, so a fallback reader reports what happened to its
|
|
* registration instead of finding it already absent.
|
|
*/
|
|
const projectSharedRegistrations = (
|
|
items: readonly UninstallItem[],
|
|
clients: readonly UninstallClient[],
|
|
): UninstallItem[] => {
|
|
const readersByRegistration = new Map<string, readonly string[]>();
|
|
for (const client of clients)
|
|
if (client.sharedWith !== undefined && client.sharedWith.length > 0)
|
|
readersByRegistration.set(
|
|
JSON.stringify([client.name, client.configPath]),
|
|
client.sharedWith,
|
|
);
|
|
if (readersByRegistration.size === 0) return [...items];
|
|
return items.flatMap((next) => {
|
|
const readers =
|
|
next.configuration_path === undefined
|
|
? undefined
|
|
: readersByRegistration.get(
|
|
JSON.stringify([next.name, next.configuration_path]),
|
|
);
|
|
if (readers === undefined) return [next];
|
|
const { name, ...action } = next;
|
|
return [name, ...readers].map((reader) => ({ ...action, name: reader }));
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Ownership is a readable, recognizable REA-owned row, never the shared
|
|
* file's existence. An unrelated malformed file must not establish ownership;
|
|
* it stays retained without blocking other removals.
|
|
*/
|
|
const hasOwnershipEvidence = async (
|
|
client: UninstallClient,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<boolean> => {
|
|
for (const path of clientOwnershipEvidencePaths(client)) {
|
|
let original: string;
|
|
try {
|
|
original = await fileSystem.readText(path);
|
|
} catch (cause: unknown) {
|
|
// A close failure after a completed read still carries the exact text
|
|
// in its retained outcome, and that text is the ownership fact: only a
|
|
// read that never completed proves nothing. Preserve it, so later read
|
|
// failures stay blocking instead of softening to retained.
|
|
if (!(cause instanceof RegularFileCleanupFailure)) continue;
|
|
if (cause.outcome.kind !== "completed") continue;
|
|
const completed: unknown = cause.outcome.value;
|
|
if (typeof completed !== "string") continue;
|
|
original = completed;
|
|
}
|
|
let parsed: ClientConfigurationDocument;
|
|
try {
|
|
parsed = parseClientConfiguration(original, client.format);
|
|
} catch {
|
|
// Malformed shared data is retained, never ownership evidence.
|
|
continue;
|
|
}
|
|
const removal = clientRegistrationRemoval(parsed, original, client);
|
|
// Refusing the edit never retracts the owned-row fact: an effective
|
|
// REA-owned row shadowed by a foreign duplicate still proves ownership,
|
|
// so later read failures stay blocking instead of softening to retained.
|
|
const owned = removal.ok ? removal.value : removal.error.owned;
|
|
if (owned.removeNative || owned.legacyPath !== undefined) return true;
|
|
}
|
|
return false;
|
|
};
|
|
|
|
/** Installation evidence for one probed path, never inferred from absence. */
|
|
interface DiscoveryProbe {
|
|
readonly applicable: boolean;
|
|
readonly unresolved: boolean;
|
|
}
|
|
|
|
/** A client's shared-storage applicability from its discovery paths: a hit
|
|
* proves installation, a miss leaves it unproven, and any other probe failure
|
|
* leaves it unresolved — never absence. */
|
|
const discoveryApplicability = async (
|
|
discoveryPaths: readonly string[] | undefined,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<DiscoveryProbe> => {
|
|
if (discoveryPaths === undefined)
|
|
return { applicable: true, unresolved: false };
|
|
let applicable = false;
|
|
let unresolved = false;
|
|
for (const path of discoveryPaths) {
|
|
try {
|
|
// The product's own directory proves installation, not a leftover link
|
|
// to it: `stat` is `lstat`, so a dangling profile link passes here even
|
|
// though setup and doctor, which follow the target, reject it. Resolve
|
|
// the link for the same answer, keeping `lstat` for removal safety.
|
|
const stats = await fileSystem.stat(path);
|
|
if (stats.isSymbolicLink() && fileSystem.realpath !== undefined)
|
|
await fileSystem.realpath(path);
|
|
return { applicable: true, unresolved: false };
|
|
} catch (cause: unknown) {
|
|
// Absence keeps scanning until one discovery path exists; any
|
|
// other probe failure leaves applicability unresolved.
|
|
if (!isMissing(cause)) unresolved = true;
|
|
}
|
|
}
|
|
return { applicable, unresolved };
|
|
};
|
|
|
|
/** One physical configuration path a client claims. */
|
|
interface ClientConfigClaim {
|
|
readonly client: SetupClient;
|
|
readonly configPath: string;
|
|
/** The path is another product's storage this client falls back to. */
|
|
readonly fallback: boolean;
|
|
}
|
|
|
|
/** One physical file, the client whose configuration it is, and the other
|
|
* clients that load it as a fallback. */
|
|
interface SharedConfigPath {
|
|
readonly owner: ClientConfigClaim;
|
|
readonly readers: readonly ClientConfigClaim[];
|
|
}
|
|
|
|
/**
|
|
* Resolve each physical configuration file to the clients that edit it. A
|
|
* client's own configuration owns its registration row; a fallback view only
|
|
* reports the owner's decision instead of racing it to "absent". Two clients
|
|
* that each declare the same path as their own configuration keep their own
|
|
* row, because they write different tables.
|
|
*/
|
|
const sharedConfigPaths = (
|
|
clients: readonly SetupClient[],
|
|
): readonly SharedConfigPath[] => {
|
|
const claimsByPath = new Map<string, ClientConfigClaim[]>();
|
|
for (const client of clients)
|
|
for (const claim of [
|
|
...uninstallConfigPaths(client).map((configPath) => ({
|
|
client,
|
|
configPath,
|
|
fallback: false,
|
|
})),
|
|
...(client.zcodeFallbackPath === undefined
|
|
? []
|
|
: [
|
|
{
|
|
client,
|
|
configPath: client.zcodeFallbackPath,
|
|
fallback: true,
|
|
},
|
|
]),
|
|
])
|
|
claimsByPath.set(claim.configPath, [
|
|
...(claimsByPath.get(claim.configPath) ?? []),
|
|
claim,
|
|
]);
|
|
return [...claimsByPath.values()].flatMap((claims): SharedConfigPath[] => {
|
|
const fallbacks = claims.filter((claim) => claim.fallback);
|
|
const owners = claims.filter((claim) => !claim.fallback);
|
|
// A fallback view can only report one client's row. OpenCode can be pointed
|
|
// at FreeBuff's file through `OPENCODE_CONFIG`, and both then own the path
|
|
// while writing different tables, so each keeps its own decision.
|
|
if (owners.length > 0)
|
|
return owners.map((owner) => {
|
|
const format = owner.client.format;
|
|
// ZCode's fallback reads mcpServers, never another table in the same
|
|
// file (for example OpenCode's mcp table). Use the format owner's
|
|
// mapping instead of reinterpreting table names here.
|
|
const readers =
|
|
format !== undefined &&
|
|
format !== "unsupported" &&
|
|
format !== "dsh" &&
|
|
clientConfigurationServersKey(format) ===
|
|
clientConfigurationServersKey("zcode_fallback")
|
|
? fallbacks
|
|
: [];
|
|
return { owner, readers };
|
|
});
|
|
const [only] = fallbacks;
|
|
if (only === undefined)
|
|
throw new Error("A configuration path has no claiming client.");
|
|
return [{ owner: only, readers: [] }];
|
|
});
|
|
};
|
|
|
|
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
|
|
export const systemUninstallHost = (
|
|
selectedHome: string | undefined = undefined,
|
|
selectedFileSystem: UninstallFileSystem | undefined = undefined,
|
|
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
|
platform: NodeJS.Platform = HOST_PLATFORM.platform,
|
|
systemPaths: ClientSystemPaths = {},
|
|
): UninstallHost => {
|
|
const home =
|
|
selectedHome ?? homeDirectoryFromEnvironment(environment, platform);
|
|
const resources = new ArtifactResourceScope();
|
|
// Whole-operation admission must not share a gate with its nested file reads:
|
|
// a peer's pending cleanup otherwise waits for the operation requesting it.
|
|
const configurationOperations = new ArtifactResourceScope();
|
|
const fileSystem = selectedFileSystem ?? systemFileSystem(resources);
|
|
const preflightOwnedClients = new WeakSet<UninstallClient>();
|
|
// REA's registration that only layers REA does not edit define: uninstall
|
|
// cannot remove it, so it is reported instead of being treated as absent.
|
|
const retainedLowerOnly = new WeakMap<UninstallClient, UninstallItem>();
|
|
// One report per client although uninstall visits each of its files.
|
|
const inlineReported = new Set<string>();
|
|
/**
|
|
* The effective REA entry across the read-only lower layers, and the user
|
|
* layer above them when given.
|
|
*/
|
|
const lowerLayerRegistration = async (
|
|
client: UninstallClient,
|
|
ownershipEstablished: boolean,
|
|
upper?: ClientConfigurationSource,
|
|
): Promise<
|
|
| { readonly kind: "item"; readonly item: UninstallItem }
|
|
| { readonly kind: "entry"; readonly entry: unknown }
|
|
> => {
|
|
const lowerLayers: ClientConfigurationSource[] = [];
|
|
for (const configPath of client.configPaths ?? []) {
|
|
if (configPath === client.configPath) continue;
|
|
const layer = await readClientConfiguration(
|
|
{ ...client, configPath },
|
|
fileSystem,
|
|
resources,
|
|
ownershipEstablished,
|
|
"read_only",
|
|
);
|
|
if (layer.kind === "item") {
|
|
if (layer.item.status !== "skipped") return layer;
|
|
continue;
|
|
}
|
|
lowerLayers.push({ ...layer.parsed, sourcePath: configPath });
|
|
}
|
|
if (upper !== undefined) lowerLayers.push(upper);
|
|
return {
|
|
kind: "entry",
|
|
entry: effectiveClientConfiguration(lowerLayers, undefined, platform)
|
|
?.servers[PRODUCT_IDENTITY.mcpServerKey],
|
|
};
|
|
};
|
|
/**
|
|
* Record REA's enabled registration that a read-only layer keeps in effect
|
|
* when uninstall removes nothing from the user layer: absent there, or a
|
|
* partial user entry inheriting REA's launcher. An unreadable layer leaves
|
|
* that unknown, so it stops uninstall before any removal.
|
|
*/
|
|
const retainLowerOnlyRegistration = async (
|
|
client: UninstallClient,
|
|
ownershipEstablished: boolean,
|
|
upper?: ClientConfigurationSource,
|
|
): Promise<UninstallItem | undefined> => {
|
|
// An inline layer (KILO_CONFIG_CONTENT) that alone sets REA's enabled
|
|
// entry keeps it in effect whatever uninstall removes from the files, as
|
|
// doctor reports; any file entry is refused by the layered check instead.
|
|
const inline = client.inlineConfiguration;
|
|
const inlineEntry =
|
|
inline === undefined
|
|
? undefined
|
|
: effectiveClientConfiguration(
|
|
[{ ...inline.parsed, inlineOrigin: inline.origin }],
|
|
undefined,
|
|
platform,
|
|
)?.servers[PRODUCT_IDENTITY.mcpServerKey];
|
|
if (
|
|
inline !== undefined &&
|
|
enabledRegistration(inlineEntry) &&
|
|
clientRegistrationOwnership(inlineEntry, client) === "owned"
|
|
) {
|
|
if (!inlineReported.has(client.name)) {
|
|
inlineReported.add(client.name);
|
|
const name = client.displayName ?? client.name;
|
|
retainedLowerOnly.set(
|
|
client,
|
|
item(
|
|
client.name,
|
|
"failed",
|
|
`${inline.origin} sets REA's enabled ${name} registration, and REA does not edit it, so the registration stays in effect after uninstall. Remove the ${PRODUCT_IDENTITY.mcpServerKey} entry from ${inline.origin}, then restart ${name}.`,
|
|
),
|
|
);
|
|
}
|
|
return undefined;
|
|
}
|
|
if (client.readOnlyLowerLayers !== true) return undefined;
|
|
const lower = await lowerLayerRegistration(
|
|
client,
|
|
ownershipEstablished,
|
|
upper,
|
|
);
|
|
if (lower.kind === "item") return lower.item;
|
|
if (
|
|
enabledRegistration(lower.entry) &&
|
|
clientRegistrationOwnership(lower.entry, client) === "owned"
|
|
)
|
|
retainedLowerOnly.set(
|
|
client,
|
|
item(
|
|
client.name,
|
|
"failed",
|
|
"REA's enabled registration is defined in a read-only configuration layer REA does not change, so it stays in effect after uninstall. Remove it with that layer's owner.",
|
|
),
|
|
);
|
|
return undefined;
|
|
};
|
|
// Set with the client list: the package view that redirects this
|
|
// process's AppData writes, if any.
|
|
let redirection: MsixPackageView | undefined;
|
|
const clientWriteBlocker = (client: SetupClient): string | undefined =>
|
|
registrationWriteBlocker(client, "uninstall") ??
|
|
redirectedWriteBlocker(redirection, [client.configPath], "uninstall");
|
|
const skillWriteBlocker = (path: string): string | undefined =>
|
|
redirectedWriteBlocker(redirection, [path], "uninstall");
|
|
return {
|
|
clients: async () => {
|
|
const supported = await resolveSupportedClients(
|
|
home,
|
|
platform,
|
|
environment,
|
|
systemPaths,
|
|
);
|
|
redirection = appDataRedirection(supported);
|
|
// Shared configuration alone cannot establish product applicability.
|
|
// Definitive absence leaves the shared paths unverified while owned
|
|
// rows in a readable configuration can still be removed independently;
|
|
// an unresolved probe is unknown, never absence.
|
|
const probes = new Map<string, DiscoveryProbe>();
|
|
for (const client of supported)
|
|
probes.set(
|
|
client.name,
|
|
await discoveryApplicability(client.discoveryPaths, fileSystem),
|
|
);
|
|
const paths = sharedConfigPaths(supported);
|
|
const clients: UninstallClient[] = [];
|
|
for (const client of supported)
|
|
for (const path of paths) {
|
|
if (path.owner.client !== client) continue;
|
|
// A fallback reader constrains this file only while it may load it:
|
|
// definitive absence leaves the file to its owner. A reader that may
|
|
// load the owner's registration makes applicability one fact per
|
|
// physical file, so its installed proof applies and its unresolved
|
|
// probe keeps the file fail-closed.
|
|
const readers = path.readers.filter(({ client: reader }) => {
|
|
const probe = probes.get(reader.name);
|
|
return probe?.applicable === true || probe?.unresolved === true;
|
|
});
|
|
const probesForPath = [path.owner, ...readers].map(
|
|
({ client: participant }) =>
|
|
probes.get(participant.name) ?? {
|
|
applicable: false,
|
|
unresolved: false,
|
|
},
|
|
);
|
|
// Only definitive absence may soften failures for storage REA does
|
|
// not own: a denied or failed probe leaves applicability unresolved,
|
|
// and unresolved applicability must not downgrade shared-config
|
|
// failures to retained. A denied product-local path means an unknown
|
|
// registration state, which must stop uninstall instead of reporting
|
|
// success.
|
|
const applicability: Pick<UninstallClient, "applicability"> =
|
|
probesForPath.some(({ applicable }) => applicable) ||
|
|
probesForPath.some(({ unresolved }) => unresolved) ||
|
|
!clientSharedRegistrationPaths(client).has(path.owner.configPath)
|
|
? {}
|
|
: { applicability: "unverified" };
|
|
clients.push({
|
|
...client,
|
|
configPath: path.owner.configPath,
|
|
...(path.owner.fallback
|
|
? { format: "zcode_fallback" as const }
|
|
: {}),
|
|
...applicability,
|
|
...(readers.length === 0
|
|
? {}
|
|
: {
|
|
sharedWith: readers.map(({ client: reader }) => reader.name),
|
|
}),
|
|
});
|
|
}
|
|
return clients;
|
|
},
|
|
inspectClient: (client) =>
|
|
configurationOperations.run(async () => {
|
|
const ownershipEstablished =
|
|
client.sharedRegistration === true &&
|
|
clientOwnershipEvidencePaths(client).length > 0 &&
|
|
(await hasOwnershipEvidence(client, fileSystem));
|
|
const read = await readClientConfiguration(
|
|
client,
|
|
fileSystem,
|
|
resources,
|
|
ownershipEstablished,
|
|
);
|
|
if (read.kind === "item") {
|
|
if (read.item.status === "failed") return read.item;
|
|
return read.item.status === "skipped"
|
|
? retainLowerOnlyRegistration(client, ownershipEstablished)
|
|
: undefined;
|
|
}
|
|
const removal = clientRegistrationRemoval(
|
|
read.parsed,
|
|
read.original,
|
|
client,
|
|
);
|
|
if (!removal.ok)
|
|
return item(client.name, "failed", removal.error.detail);
|
|
if (!removal.value.removeNative) {
|
|
const unknown = await retainLowerOnlyRegistration(
|
|
client,
|
|
ownershipEstablished,
|
|
{ ...read.parsed, sourcePath: client.configPath },
|
|
);
|
|
if (unknown !== undefined) return unknown;
|
|
}
|
|
// ZCode switches the entire server table to its shared fallback once
|
|
// the last native server disappears. Inspect the table it would load,
|
|
// not just the REA row: unrelated servers may otherwise become active.
|
|
if (
|
|
client.format === "zcode" &&
|
|
removal.value.removeNative &&
|
|
Object.keys(read.parsed.servers).length === 1 &&
|
|
client.zcodeFallbackPath !== undefined
|
|
) {
|
|
const fallbackClient: UninstallClient = {
|
|
...client,
|
|
configPath: client.zcodeFallbackPath,
|
|
configPaths: [client.zcodeFallbackPath],
|
|
format: "zcode_fallback",
|
|
};
|
|
const fallback = await readClientConfiguration(
|
|
fallbackClient,
|
|
fileSystem,
|
|
resources,
|
|
true,
|
|
);
|
|
if (fallback.kind === "item") {
|
|
if (fallback.item.status !== "skipped") return fallback.item;
|
|
} else {
|
|
const fallbackRemoval = clientRegistrationRemoval(
|
|
fallback.parsed,
|
|
fallback.original,
|
|
fallbackClient,
|
|
);
|
|
if (!fallbackRemoval.ok)
|
|
return item(client.name, "failed", fallbackRemoval.error.detail);
|
|
const remaining = Object.keys(fallback.parsed.servers).filter(
|
|
(name) =>
|
|
name !== PRODUCT_IDENTITY.mcpServerKey ||
|
|
!fallbackRemoval.value.removeNative,
|
|
);
|
|
if (remaining.length > 0)
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
"Removing REA's last native ZCode server would activate retained fallback servers; no change was made. Review the fallback configuration, then rerun uninstall.",
|
|
);
|
|
}
|
|
}
|
|
// OpenCode and Kilo merge every layer, so removing REA's entries can
|
|
// expose or change an entry another layer keeps.
|
|
if (
|
|
(client.format === "opencode" || client.format === "kilo") &&
|
|
(removal.value.removeNative || removal.value.legacyPath !== undefined)
|
|
) {
|
|
const originalLayers: ClientConfigurationSource[] = [];
|
|
const remainingLayers: ClientConfigurationSource[] = [];
|
|
for (const configPath of client.configPaths ?? [client.configPath]) {
|
|
const layer =
|
|
configPath === client.configPath
|
|
? read
|
|
: await readClientConfiguration(
|
|
{ ...client, configPath },
|
|
fileSystem,
|
|
resources,
|
|
ownershipEstablished,
|
|
);
|
|
if (layer.kind === "item") {
|
|
if (layer.item.status !== "skipped") return layer.item;
|
|
continue;
|
|
}
|
|
const layerRemoval = clientRegistrationRemoval(
|
|
layer.parsed,
|
|
layer.original,
|
|
client,
|
|
);
|
|
if (!layerRemoval.ok)
|
|
return item(client.name, "failed", layerRemoval.error.detail);
|
|
originalLayers.push({ ...layer.parsed, sourcePath: configPath });
|
|
const servers = { ...layer.parsed.servers };
|
|
const legacyServers = { ...layer.parsed.legacyServers };
|
|
const name = PRODUCT_IDENTITY.mcpServerKey;
|
|
if (layerRemoval.value.removeNative) delete servers[name];
|
|
if (layerRemoval.value.legacyPath !== undefined)
|
|
delete legacyServers[name];
|
|
remainingLayers.push({
|
|
...layer.parsed,
|
|
servers,
|
|
legacyServers,
|
|
sourcePath: configPath,
|
|
});
|
|
}
|
|
// REA never edits the inline layer, so it survives removal.
|
|
const inline = client.inlineConfiguration;
|
|
if (inline !== undefined) {
|
|
const layer = { ...inline.parsed, inlineOrigin: inline.origin };
|
|
originalLayers.push(layer);
|
|
remainingLayers.push(layer);
|
|
}
|
|
const selected = effectiveClientConfiguration(
|
|
originalLayers,
|
|
undefined,
|
|
platform,
|
|
)?.servers[PRODUCT_IDENTITY.mcpServerKey];
|
|
const remaining = effectiveClientConfiguration(
|
|
remainingLayers,
|
|
undefined,
|
|
platform,
|
|
)?.servers[PRODUCT_IDENTITY.mcpServerKey];
|
|
const altersEffectiveRegistration =
|
|
clientRegistrationOwnership(selected, client) === "owned"
|
|
? remaining !== undefined
|
|
: !isDeepStrictEqual(selected, remaining);
|
|
if (altersEffectiveRegistration)
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
client.format === "opencode"
|
|
? "Removing REA's registration would activate or change an unowned OpenCode registration in another configuration layer, including a possible V1 fallback; no change was made. Remove or replace that registration manually, then rerun uninstall."
|
|
: `Removing REA's registration would activate or change a registration that another Kilo configuration layer${inline === undefined ? "" : ` or ${inline.origin}, which REA does not edit,`} keeps in effect; no change was made. Remove or replace that registration manually, then rerun uninstall.`,
|
|
);
|
|
}
|
|
// REA writes only the user layer. If the read-only lower layers alone
|
|
// still define an entry that is not disabled, removal would leave it
|
|
// (or expose it) in effect, so nothing changes.
|
|
if (client.readOnlyLowerLayers === true && removal.value.removeNative) {
|
|
const lower = await lowerLayerRegistration(
|
|
client,
|
|
ownershipEstablished,
|
|
);
|
|
if (lower.kind === "item") return lower.item;
|
|
if (enabledRegistration(lower.entry))
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
"A read-only configuration layer REA does not change also defines an enabled REA registration, which would stay in effect after removal; no change was made. Remove that registration with its owner, then rerun uninstall.",
|
|
);
|
|
}
|
|
if (
|
|
!removal.value.removeNative &&
|
|
removal.value.legacyPath === undefined
|
|
)
|
|
return undefined;
|
|
preflightOwnedClients.add(client);
|
|
// A removal the running package would revert, or redirect into its
|
|
// private storage, would leave the registration in place.
|
|
const blocker = clientWriteBlocker(client);
|
|
return blocker === undefined
|
|
? undefined
|
|
: item(client.name, "failed", blocker);
|
|
}),
|
|
removeClient: (client) =>
|
|
configurationOperations.run(
|
|
async () =>
|
|
retainedLowerOnly.get(client) ??
|
|
removeClient(
|
|
client,
|
|
fileSystem,
|
|
resources,
|
|
platform,
|
|
() => clientWriteBlocker(client),
|
|
preflightOwnedClients.has(client),
|
|
),
|
|
),
|
|
inspectSkill: async () => {
|
|
const selection = skillDestinationSelection(
|
|
home,
|
|
undefined,
|
|
environment,
|
|
platform,
|
|
);
|
|
if (selection.issues.length > 0)
|
|
return item(
|
|
"skill",
|
|
"failed",
|
|
selection.issues
|
|
.map(({ path, detail }) => `${detail} (${path})`)
|
|
.join(" "),
|
|
);
|
|
for (const destination of selection.destinations) {
|
|
const inspected = await inspectManagedSkill(
|
|
destination.path,
|
|
destination.client,
|
|
fileSystem,
|
|
);
|
|
if (inspected?.status === "failed") return inspected;
|
|
if (inspected !== undefined) continue;
|
|
const blocker = skillWriteBlocker(destination.path);
|
|
if (blocker !== undefined) return item("skill", "failed", blocker);
|
|
}
|
|
return undefined;
|
|
},
|
|
removeSkill: () =>
|
|
removeManagedSkills(
|
|
home,
|
|
fileSystem,
|
|
environment,
|
|
platform,
|
|
skillWriteBlocker,
|
|
),
|
|
purgeData: () => purgeSelectedData(home, environment, platform, fileSystem),
|
|
close: async () => {
|
|
try {
|
|
await configurationOperations.close();
|
|
await resources.close();
|
|
return undefined;
|
|
} catch (cause: unknown) {
|
|
return uninstallCleanupError(cause);
|
|
}
|
|
},
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Every user file that can hold REA's registration for one client. An MSIX
|
|
* package can read either its private copy or the AppData file, and earlier
|
|
* setups wrote the AppData file, so both lose REA's entry.
|
|
*/
|
|
const uninstallConfigPaths = (client: SetupClient): readonly string[] => [
|
|
...new Set([
|
|
...(client.readOnlyLowerLayers === true
|
|
? [client.configPath]
|
|
: (client.configPaths ?? [client.configPath])),
|
|
...(client.msixPackage === undefined
|
|
? []
|
|
: [
|
|
client.msixPackage.privateConfigPath,
|
|
client.msixPackage.appDataConfigPath,
|
|
]),
|
|
]),
|
|
];
|
|
|
|
/** Whether a client loads this entry: present and not disabled. */
|
|
const enabledRegistration = (entry: unknown): boolean =>
|
|
entry !== undefined &&
|
|
!(
|
|
typeof entry === "object" &&
|
|
entry !== null &&
|
|
"enabled" in entry &&
|
|
entry.enabled === false
|
|
);
|
|
|
|
/** Whether removal would change this configuration. */
|
|
const registrationPresent = (parsed: ClientConfigurationDocument): boolean => {
|
|
const name = PRODUCT_IDENTITY.mcpServerKey;
|
|
return (
|
|
Object.hasOwn(parsed.servers, name) ||
|
|
// Beside a native OpenCode V2 table, OpenCode also loads a V1 `mcp.rea`.
|
|
legacyClientServerPath(parsed, name) !== undefined ||
|
|
// Harness ownership is the stable entry id. A stale or malformed launcher
|
|
// still belongs to that id, and so does a direct patch that projects no row.
|
|
(parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry)
|
|
);
|
|
};
|
|
|
|
type ClientConfigurationRead =
|
|
| { readonly kind: "item"; readonly item: UninstallItem }
|
|
| {
|
|
readonly kind: "configuration";
|
|
readonly transactionPath: string;
|
|
readonly original: string;
|
|
readonly parsed: ClientConfigurationDocument;
|
|
};
|
|
|
|
/** The configuration text, or the outcome to report for a failed read. A
|
|
* completed physical read is retained even when its handle fails to close:
|
|
* that exact text still drives removal, so an owned row it proves stays
|
|
* actionable instead of softening to retained. */
|
|
const readClientConfigurationText = async (
|
|
client: UninstallClient,
|
|
transactionPath: string,
|
|
io: {
|
|
readonly fileSystem: UninstallFileSystem;
|
|
readonly resources: ArtifactResourceScope;
|
|
readonly configurationFailure: (detail: string) => ClientConfigurationRead;
|
|
},
|
|
): Promise<string | ClientConfigurationRead> => {
|
|
try {
|
|
return await io.fileSystem.readText(transactionPath);
|
|
} catch (cause: unknown) {
|
|
if (isClientConfigurationCleanupFailure(cause)) {
|
|
const cleanup = await retryClientConfigurationCleanup(
|
|
cause,
|
|
io.resources,
|
|
);
|
|
const detail =
|
|
cleanup.primary instanceof InvalidUtf8FileError
|
|
? "Configuration is not valid UTF-8 and was not changed; its resources could not be released. Repair it, then rerun uninstall."
|
|
: "Configuration could not be read or its resources could not be released. Check file permissions, then rerun uninstall.";
|
|
// An unreleased handle is REA's own incomplete cleanup, never foreign-
|
|
// storage uncertainty: it must stop removal outright, so later removals
|
|
// and purge cannot outrun the failure that close() reports afterwards.
|
|
if (cleanup.cleanup !== undefined)
|
|
return itemRead(item(client.name, "failed", detail));
|
|
const completed: unknown =
|
|
cause.outcome.kind === "completed" ? cause.outcome.value : undefined;
|
|
if (typeof completed !== "string") return io.configurationFailure(detail);
|
|
return completed;
|
|
}
|
|
return isMissing(cause)
|
|
? itemRead(item(client.name, "skipped", "Configuration does not exist."))
|
|
: io.configurationFailure(
|
|
cause instanceof InvalidUtf8FileError
|
|
? "Configuration is not valid UTF-8 and was not changed. Repair it, then rerun uninstall."
|
|
: "Configuration could not be read. Check file permissions, then rerun uninstall.",
|
|
);
|
|
}
|
|
};
|
|
|
|
const readClientConfiguration = async (
|
|
client: UninstallClient,
|
|
fileSystem: UninstallFileSystem,
|
|
resources: ArtifactResourceScope,
|
|
ownershipEstablished: boolean,
|
|
/**
|
|
* `read_only` is a lower layer REA never changes: it is read where the
|
|
* client reads it, without the write target's ownership check.
|
|
*/
|
|
access: "write_target" | "read_only" = "write_target",
|
|
): Promise<ClientConfigurationRead> => {
|
|
const applicabilityUnverified =
|
|
client.applicability === "unverified" && !ownershipEstablished;
|
|
const configurationFailure = (detail: string): ClientConfigurationRead =>
|
|
itemRead(
|
|
item(
|
|
client.name,
|
|
applicabilityUnverified ? "retained" : "failed",
|
|
applicabilityUnverified
|
|
? `Product applicability could not be established. Shared configuration was retained without blocking other REA removals. ${detail}`
|
|
: detail,
|
|
),
|
|
);
|
|
if (client.configPathError !== undefined)
|
|
return configurationFailure(client.configPathError);
|
|
const { format } = client;
|
|
if (format === "unsupported")
|
|
return itemRead(
|
|
item(
|
|
client.name,
|
|
"skipped",
|
|
manualRegistrationRemediation(client.name) ??
|
|
"This client has no documented local MCP configuration boundary.",
|
|
),
|
|
);
|
|
const resolved =
|
|
access === "read_only"
|
|
? client.configPath
|
|
: await resolveUninstallConfigPath(client, fileSystem);
|
|
if (typeof resolved !== "string")
|
|
return resolved.status === "failed"
|
|
? configurationFailure(resolved.detail)
|
|
: itemRead(resolved);
|
|
const transactionPath = resolved;
|
|
const original = await readClientConfigurationText(client, transactionPath, {
|
|
fileSystem,
|
|
resources,
|
|
configurationFailure,
|
|
});
|
|
if (typeof original !== "string") return original;
|
|
try {
|
|
const parsed = parseClientConfiguration(original, format);
|
|
return { kind: "configuration", transactionPath, original, parsed };
|
|
} catch (cause: unknown) {
|
|
return configurationFailure(
|
|
cause instanceof ClientConfigurationShapeError ||
|
|
cause instanceof ConfigurationError
|
|
? `Configuration was not changed: ${cause.message}. Repair it, then rerun uninstall.`
|
|
: format === undefined
|
|
? "This client's configuration syntax is unknown, so its configuration was not changed."
|
|
: `Configuration is not valid ${clientConfigurationSyntaxName(format)} and was not changed. Repair it, then rerun uninstall.`,
|
|
);
|
|
}
|
|
};
|
|
|
|
const itemRead = (result: UninstallItem): ClientConfigurationRead => ({
|
|
kind: "item",
|
|
item: result,
|
|
});
|
|
|
|
/**
|
|
* Share the exact ownership and applicability decision with preflight. A
|
|
* removable legacy entry carries its document path, so removal edits exactly
|
|
* the entry this decision admitted.
|
|
*/
|
|
type RegistrationRemoval = {
|
|
readonly removeNative: boolean;
|
|
readonly legacyPath: readonly string[] | undefined;
|
|
};
|
|
type RegistrationRemovalRefusal = {
|
|
readonly kind: "shadowed_unowned_member" | "foreign_legacy_fallback";
|
|
readonly detail: string;
|
|
/** The owned rows that motivated removal; refusing the edit keeps them. */
|
|
readonly owned: RegistrationRemoval;
|
|
};
|
|
|
|
const clientRegistrationRemoval = (
|
|
parsed: ClientConfigurationDocument,
|
|
original: string,
|
|
client: SetupClient,
|
|
): Result<RegistrationRemoval, RegistrationRemovalRefusal> => {
|
|
const name = PRODUCT_IDENTITY.mcpServerKey;
|
|
if (
|
|
parsed.dialect === "dsh" &&
|
|
dshDocument(parsed.document).hasUnknownStructure
|
|
)
|
|
return ok({ removeNative: false, legacyPath: undefined });
|
|
const removeNative =
|
|
(parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry) ||
|
|
(Object.hasOwn(parsed.servers, name) &&
|
|
clientRegistrationOwnership(parsed.servers[name], client) === "owned");
|
|
const legacyPath = legacyClientServerPath(parsed, name);
|
|
const removeLegacy =
|
|
legacyPath !== undefined &&
|
|
clientRegistrationOwnership(parsed.legacyServers[name], client) === "owned";
|
|
const ownership: RegistrationRemoval = {
|
|
removeNative,
|
|
legacyPath: removeLegacy ? legacyPath : undefined,
|
|
};
|
|
if (removeNative || removeLegacy) {
|
|
const shadowed = shadowedClientServers(original, parsed, name);
|
|
if (
|
|
(removeNative &&
|
|
shadowed.servers.some(
|
|
(member) => clientRegistrationOwnership(member, client) !== "owned",
|
|
)) ||
|
|
(removeLegacy &&
|
|
shadowed.legacyServers.some(
|
|
(member) => clientRegistrationOwnership(member, client) !== "owned",
|
|
))
|
|
)
|
|
return err({
|
|
kind: "shadowed_unowned_member",
|
|
detail: SHADOWED_UNOWNED_MEMBER_DETAIL,
|
|
owned: ownership,
|
|
});
|
|
}
|
|
if (removeNative && legacyPath !== undefined && !removeLegacy)
|
|
return err({
|
|
kind: "foreign_legacy_fallback",
|
|
detail: UNOWNED_LEGACY_FALLBACK_DETAIL,
|
|
owned: ownership,
|
|
});
|
|
return ok(ownership);
|
|
};
|
|
|
|
const SHADOWED_UNOWNED_MEMBER_DETAIL = `Configuration repeats the "${PRODUCT_IDENTITY.mcpServerKey}" member, and an earlier duplicate is not REA-owned; removing the registration the client reads would activate an earlier duplicate, so no change was made. Remove the duplicate members manually, then rerun uninstall.`;
|
|
|
|
const UNOWNED_LEGACY_FALLBACK_DETAIL = `OpenCode falls back to the V1 "mcp.${PRODUCT_IDENTITY.mcpServerKey}" entry, which is not REA-owned; removing REA's native registration would activate it, so no change was made. Remove or replace that V1 entry manually, then rerun uninstall.`;
|
|
|
|
/** Preserve the bytes uninstall is about to edit and return the backup holding them. */
|
|
const backupClientConfiguration = async (
|
|
client: SetupClient,
|
|
transactionPath: string,
|
|
original: string,
|
|
options: RecoveryBackupPreservationOptions,
|
|
): Promise<string | UninstallItem> => {
|
|
const failed = (detail: string) =>
|
|
item(
|
|
client.name,
|
|
"failed",
|
|
`Configuration could not be backed up, so no change was made. ${detail}`,
|
|
);
|
|
try {
|
|
const preserved =
|
|
client.privateProfile === undefined
|
|
? await preserveCurrentRecoveryBackup(
|
|
`${client.configPath}.rea.backup`,
|
|
transactionPath,
|
|
original,
|
|
options,
|
|
)
|
|
: // A private profile's backup stays owner-only (0600).
|
|
await preservePrivateRecoveryBackup(
|
|
`${client.configPath}.rea.backup`,
|
|
transactionPath,
|
|
original,
|
|
options.resources,
|
|
);
|
|
if (preserved.ok) return preserved.value;
|
|
if (preserved.error.kind === "occupied")
|
|
return failed(
|
|
`${preserved.error.detail}. Move that file aside, then rerun uninstall.`,
|
|
);
|
|
} catch (cause: unknown) {
|
|
// The resource scope retains a backup handle whose close failed.
|
|
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
|
|
}
|
|
return failed("Check file permissions, then rerun uninstall.");
|
|
};
|
|
|
|
const removeClient = async (
|
|
client: UninstallClient,
|
|
fileSystem: UninstallFileSystem,
|
|
resources: ArtifactResourceScope,
|
|
platform: NodeJS.Platform,
|
|
writeBlocker?: () => string | undefined,
|
|
preflightOwned = false,
|
|
): Promise<UninstallItem> => {
|
|
const read = await readClientConfiguration(
|
|
client,
|
|
fileSystem,
|
|
resources,
|
|
preflightOwned,
|
|
);
|
|
if (read.kind === "item") return read.item;
|
|
const { transactionPath, original, parsed } = read;
|
|
const name = PRODUCT_IDENTITY.mcpServerKey;
|
|
if (
|
|
parsed.dialect === "dsh" &&
|
|
dshDocument(parsed.document).hasUnknownStructure
|
|
)
|
|
return item(
|
|
client.name,
|
|
"retained",
|
|
"A Cordis expression may produce registration rows, so the patch was retained without changes.",
|
|
);
|
|
if (!registrationPresent(parsed))
|
|
return item(client.name, "skipped", "REA registration is absent.");
|
|
const removal = clientRegistrationRemoval(parsed, original, client);
|
|
if (!removal.ok) return item(client.name, "failed", removal.error.detail);
|
|
const { removeNative, legacyPath } = removal.value;
|
|
const removeLegacy = legacyPath !== undefined;
|
|
if (!removeNative && !removeLegacy)
|
|
return item(
|
|
client.name,
|
|
"retained",
|
|
"The rea-named registration is not REA-owned.",
|
|
);
|
|
const blocker = writeBlocker?.();
|
|
if (blocker !== undefined) return item(client.name, "failed", blocker);
|
|
const remaining = { ...parsed.servers };
|
|
if (removeNative) delete remaining[name];
|
|
const document = withClientServers(
|
|
parsed,
|
|
remaining,
|
|
platform,
|
|
removeLegacy ? name : undefined,
|
|
);
|
|
const editedPaths = [
|
|
...(removeNative ? [clientServerPath(parsed, name)] : []),
|
|
...(legacyPath === undefined ? [] : [legacyPath]),
|
|
];
|
|
let serialized: ReturnType<typeof serializeClientConfiguration>;
|
|
try {
|
|
serialized = serializeClientConfiguration(
|
|
document,
|
|
client.format,
|
|
original,
|
|
editedPaths,
|
|
// clientRegistrationRemoval admitted only names whose repeats REA owns.
|
|
{ removeShadowedMembersAt: editedPaths },
|
|
);
|
|
} catch (cause: unknown) {
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
cause instanceof ConfigurationError
|
|
? `Configuration could not be updated, so no change was made. ${cause.message}.`
|
|
: "Configuration could not be updated, so no change was made. Repair the configuration, then rerun uninstall.",
|
|
);
|
|
}
|
|
if (!serialized.ok)
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
`Configuration repeats the member at ${JSON.stringify(serialized.error.path)}; removing the registration the client reads would activate an earlier duplicate, so no change was made. Remove the duplicate members manually, then rerun uninstall.`,
|
|
);
|
|
const backupPath = await backupClientConfiguration(
|
|
client,
|
|
transactionPath,
|
|
original,
|
|
{
|
|
copy: (source, destination) => fileSystem.copy(source, destination),
|
|
resources,
|
|
},
|
|
);
|
|
if (typeof backupPath !== "string") return backupPath;
|
|
const manualRecovery = () =>
|
|
item(
|
|
client.name,
|
|
"failed",
|
|
`Configuration could not be updated or restored. Restore the backup at ${backupPath} manually, then rerun uninstall.`,
|
|
);
|
|
let publication: Awaited<
|
|
ReturnType<UninstallFileSystem["publishConfiguration"]>
|
|
>;
|
|
try {
|
|
publication = await fileSystem.publishConfiguration(
|
|
transactionPath,
|
|
serialized.value,
|
|
original,
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (isClientConfigurationCleanupFailure(cause))
|
|
await retryClientConfigurationCleanup(cause, resources);
|
|
return manualRecovery();
|
|
}
|
|
try {
|
|
return await publication.verify(async () => {
|
|
try {
|
|
const text = await fileSystem.readText(publication.path);
|
|
await publication.assertCurrent(text);
|
|
const readback = parseClientConfiguration(text, client.format);
|
|
if (
|
|
(removeNative && Object.hasOwn(readback.servers, name)) ||
|
|
(readback.dialect === "dsh" &&
|
|
dshDocument(readback.document).carriesEntry) ||
|
|
(removeLegacy && Object.hasOwn(readback.legacyServers, name))
|
|
)
|
|
throw new Error("registration readback mismatch");
|
|
return item(
|
|
client.name,
|
|
"removed",
|
|
`Removed registration from ${client.configPath}.`,
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (isClientConfigurationCleanupFailure(cause))
|
|
await retryClientConfigurationCleanup(cause, resources);
|
|
try {
|
|
await publication.restore(original);
|
|
} catch {
|
|
return manualRecovery();
|
|
}
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
`Configuration could not be updated. The original was restored and its backup at ${backupPath} was retained. Repair the configuration or restore that backup, then rerun uninstall.`,
|
|
);
|
|
}
|
|
});
|
|
} catch (cause: unknown) {
|
|
if (isClientConfigurationCleanupFailure(cause))
|
|
await retryClientConfigurationCleanup(cause, resources);
|
|
return item(
|
|
client.name,
|
|
"failed",
|
|
`Configuration verification or resource cleanup failed. The backup at ${backupPath} was retained. Check the configuration and rerun uninstall.`,
|
|
);
|
|
}
|
|
};
|
|
|
|
const resolveUninstallConfigPath = async (
|
|
client: SetupClient,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<string | UninstallItem> => {
|
|
const path = await resolveClientConfigTransactionPath(
|
|
client.configPath,
|
|
fileSystem.realpath === undefined
|
|
? { lstat: fileSystem.stat }
|
|
: { lstat: fileSystem.stat, realpath: fileSystem.realpath },
|
|
);
|
|
return (
|
|
path ??
|
|
item(
|
|
client.name,
|
|
"failed",
|
|
"Configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun uninstall.",
|
|
)
|
|
);
|
|
};
|
|
|
|
/** Purge the same default cache namespaces selected by their producers. */
|
|
const purgeSelectedData = async (
|
|
home: string,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<readonly UninstallItem[]> => {
|
|
const items: UninstallItem[] = [];
|
|
const directories: string[] = [];
|
|
let custom: string | undefined;
|
|
if (platform === "darwin" || platform === "linux") {
|
|
const defaultCache = defaultKunaCacheDirectory(home, environment, platform);
|
|
directories.push(defaultCache);
|
|
custom = environment.REA_KUNA_CACHE_DIR;
|
|
// Lexical spellings identify the default namespace for reporting.
|
|
// Removal still uses the owned-path checks below. Other selections
|
|
// remain separately reported without resolving symbolic links.
|
|
if (
|
|
custom !== undefined &&
|
|
custom !== defaultCache &&
|
|
!sameLexicalDirectory(custom, defaultCache, platform)
|
|
)
|
|
items.push(
|
|
item(
|
|
"kuna-custom-cache",
|
|
"retained",
|
|
`Caller-selected Kuna cache ${custom} was retained because purge does not establish ownership of that entire directory.`,
|
|
),
|
|
);
|
|
else custom = undefined;
|
|
}
|
|
// The ownership helper cache has no caller-selected location to retain.
|
|
if (platform === "darwin")
|
|
directories.push(defaultDarwinHelperCacheDirectory(home));
|
|
if (platform === "linux") {
|
|
const hopper = linuxHopperReleaseCacheDirectory(environment, home);
|
|
if (hopper.ok) directories.push(hopper.value);
|
|
else items.push(item("hopper-releases", "failed", hopper.error.message));
|
|
}
|
|
// Resolve selections before a managed namespace removal can delete cwd.
|
|
// A namespace that contains the caller-selected cache is kept whole, so
|
|
// the retained report is true.
|
|
const reaRoot = appendCallerPath(home, ".rea");
|
|
// A spelling with `..` is judged only where the filesystem resolves it,
|
|
// because collapsing it lexically is wrong after a symbolic link.
|
|
// `undefined` means the location could not be established.
|
|
const resolve = async (path: string): Promise<string[] | undefined> => {
|
|
const resolved = await existingRealpath(fileSystem, path);
|
|
return resolved === undefined
|
|
? undefined
|
|
: [...(hasParentTraversal(path) ? [] : [path]), ...resolved];
|
|
};
|
|
const selections = custom === undefined ? [] : await resolve(custom);
|
|
const purge = async (root: string, names: readonly string[]) => {
|
|
const kept: { readonly name: string; readonly unknown: boolean }[] = [];
|
|
for (const name of names) {
|
|
const targets = await resolve(appendCallerPath(root, name));
|
|
// An unestablished selection or namespace may contain the selection,
|
|
// so it is kept rather than treated as absent.
|
|
const contains =
|
|
custom !== undefined &&
|
|
(selections === undefined ||
|
|
targets === undefined ||
|
|
targets.some((target) =>
|
|
selections.some((selection) =>
|
|
withinLexicalDirectory(selection, target, platform),
|
|
),
|
|
));
|
|
if (contains)
|
|
kept.push({
|
|
name,
|
|
unknown: selections === undefined || targets === undefined,
|
|
});
|
|
}
|
|
const keptItems = kept.map(({ name, unknown }) =>
|
|
item(
|
|
name,
|
|
"retained",
|
|
unknown
|
|
? `${appendCallerPath(root, name)} was retained because purge could not establish whether it contains the caller-selected Kuna cache ${custom}.`
|
|
: `${appendCallerPath(root, name)} was retained because it contains the caller-selected Kuna cache ${custom}, which purge does not remove.`,
|
|
),
|
|
);
|
|
const owned = names.filter(
|
|
(name) => !kept.some((entry) => entry.name === name),
|
|
);
|
|
return async () => [
|
|
...keptItems,
|
|
...(await purgeManagedData(root, fileSystem, owned)),
|
|
];
|
|
};
|
|
const reaPlan = await purge(reaRoot, ["cache", "state"]);
|
|
const plans: (() => Promise<readonly UninstallItem[]>)[] = [];
|
|
for (const directory of directories)
|
|
plans.push(await purge(dirname(directory), [basename(directory)]));
|
|
items.unshift(...(await reaPlan()));
|
|
for (const plan of plans) items.push(...(await plan()));
|
|
return items;
|
|
};
|
|
|
|
/**
|
|
* Canonical spelling of an existing path, nothing when the path is absent,
|
|
* or `undefined` when its location cannot be established (for example an
|
|
* inaccessible parent, or `..` without a realpath to judge it).
|
|
*/
|
|
const existingRealpath = async (
|
|
fileSystem: UninstallFileSystem,
|
|
path: string,
|
|
): Promise<string[] | undefined> => {
|
|
if (fileSystem.realpath === undefined)
|
|
return hasParentTraversal(path) ? undefined : [];
|
|
try {
|
|
return [await fileSystem.realpath(path)];
|
|
} catch (error) {
|
|
const code = (error as NodeJS.ErrnoException).code;
|
|
return code === "ENOENT" || code === "ENOTDIR" ? [] : undefined;
|
|
}
|
|
};
|
|
|
|
const purgeManagedData = async (
|
|
root: string,
|
|
fileSystem: UninstallFileSystem,
|
|
names: readonly string[],
|
|
): Promise<readonly UninstallItem[]> => {
|
|
try {
|
|
const stats = await fileSystem.stat(root);
|
|
const linked = stats.isSymbolicLink();
|
|
if (linked || stats.isDirectory?.() !== true)
|
|
return names.map((name) =>
|
|
item(
|
|
name,
|
|
"retained",
|
|
`REA did not remove this item because its managed data root ${root} is ${linked ? "a symbolic link" : "not a directory"}. Verify the root before removing its data manually.`,
|
|
),
|
|
);
|
|
} catch (cause: unknown) {
|
|
return names.map((name) =>
|
|
isMissing(cause)
|
|
? item(
|
|
name,
|
|
"skipped",
|
|
`${appendCallerPath(root, name)} does not exist.`,
|
|
)
|
|
: item(
|
|
name,
|
|
"failed",
|
|
`The managed data root ${root} could not be verified. Check its permissions, then rerun uninstall.`,
|
|
),
|
|
);
|
|
}
|
|
const items: UninstallItem[] = [];
|
|
for (const name of names)
|
|
items.push(
|
|
await removeManagedPath(appendCallerPath(root, name), name, fileSystem),
|
|
);
|
|
return items;
|
|
};
|
|
|
|
const removeManagedPath = async (
|
|
path: string,
|
|
name: string,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<UninstallItem> => {
|
|
try {
|
|
const stats = await fileSystem.stat(path);
|
|
if (stats.isSymbolicLink())
|
|
return item(
|
|
name,
|
|
"retained",
|
|
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
|
|
);
|
|
await fileSystem.remove(path);
|
|
return item(name, "removed", `Removed ${path}.`);
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(name, "skipped", `${path} does not exist.`)
|
|
: item(
|
|
name,
|
|
"failed",
|
|
"This item could not be removed. Check file permissions, then rerun uninstall.",
|
|
);
|
|
}
|
|
};
|
|
|
|
const removeManagedSkills = async (
|
|
home: string,
|
|
fileSystem: UninstallFileSystem,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
writeBlocker?: (path: string) => string | undefined,
|
|
): Promise<UninstallItem> => {
|
|
const selection = skillDestinationSelection(
|
|
home,
|
|
undefined,
|
|
environment,
|
|
platform,
|
|
);
|
|
if (selection.issues.length > 0)
|
|
return item(
|
|
"skill",
|
|
"failed",
|
|
selection.issues
|
|
.map(({ path, detail }) => `${detail} (${path})`)
|
|
.join(" "),
|
|
);
|
|
// Every destination shares one summary item; preserve both client and path.
|
|
const results = await Promise.all(
|
|
selection.destinations.map(({ client, path }) =>
|
|
removeManagedSkill(path, `${client} (${path})`, fileSystem, writeBlocker),
|
|
),
|
|
);
|
|
const failed = results.find(({ status }) => status === "failed");
|
|
if (failed !== undefined)
|
|
return item(
|
|
"skill",
|
|
"failed",
|
|
results
|
|
.map(({ name, status, detail }) => `${name}: ${status} (${detail})`)
|
|
.join(" "),
|
|
);
|
|
const status = results.some(
|
|
({ status: resultStatus }) => resultStatus === "removed",
|
|
)
|
|
? "removed"
|
|
: results.some(({ status: resultStatus }) => resultStatus === "retained")
|
|
? "retained"
|
|
: "skipped";
|
|
return item(
|
|
"skill",
|
|
status,
|
|
results
|
|
.map(
|
|
({ name, status: resultStatus, detail }) =>
|
|
`${name}: ${resultStatus} (${detail})`,
|
|
)
|
|
.join(" "),
|
|
);
|
|
};
|
|
|
|
const inspectManagedSkill = async (
|
|
path: string,
|
|
name: string,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<UninstallItem | undefined> => {
|
|
let root: ManagedPathStats;
|
|
try {
|
|
root = await fileSystem.stat(path);
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(name, "skipped", "Skill directory does not exist.")
|
|
: item(name, "failed", "Skill directory could not be inspected.");
|
|
}
|
|
if (root.isSymbolicLink())
|
|
return item(name, "retained", "Skill directory is a symbolic link.");
|
|
if (root.isDirectory?.() !== true)
|
|
return item(name, "retained", "Skill path is not a directory.");
|
|
|
|
const manifestPath = appendCallerPath(path, "SKILL.md");
|
|
try {
|
|
const manifest = await fileSystem.stat(manifestPath);
|
|
if (manifest.isSymbolicLink())
|
|
return item(name, "retained", "Skill manifest is a symbolic link.");
|
|
if (manifest.isFile?.() !== true)
|
|
return item(name, "retained", "Skill manifest is not a regular file.");
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(name, "retained", "Skill ownership could not be established.")
|
|
: item(name, "failed", "Skill manifest could not be inspected.");
|
|
}
|
|
let content: string;
|
|
try {
|
|
content = await (fileSystem.readRegularText?.(manifestPath) ??
|
|
fileSystem.readText(manifestPath));
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(name, "retained", "Skill ownership could not be established.")
|
|
: item(name, "failed", "Skill manifest could not be read.");
|
|
}
|
|
if (!isManagedSkillManifest(content))
|
|
return item(name, "retained", "Skill manifest is not REA-owned.");
|
|
|
|
return undefined;
|
|
};
|
|
|
|
const removeManagedSkill = async (
|
|
path: string,
|
|
name: string,
|
|
fileSystem: UninstallFileSystem,
|
|
writeBlocker?: (path: string) => string | undefined,
|
|
): Promise<UninstallItem> => {
|
|
const inspection = await inspectManagedSkill(path, name, fileSystem);
|
|
if (inspection !== undefined) return inspection;
|
|
const blocker = writeBlocker?.(path);
|
|
if (blocker !== undefined) return item(name, "failed", blocker);
|
|
|
|
const manifestName = "SKILL.md";
|
|
const otherFiles = MANAGED_SKILL_FILES.filter(
|
|
(relativePath) => relativePath !== manifestName,
|
|
);
|
|
const results: UninstallItem[] = [];
|
|
for (const relativePath of otherFiles)
|
|
results.push(
|
|
await removeManagedSkillFile(path, relativePath, name, fileSystem),
|
|
);
|
|
if (
|
|
results.some(({ status }) => status === "failed" || status === "retained")
|
|
)
|
|
results.push(
|
|
item(
|
|
name,
|
|
"retained",
|
|
"REA ownership manifest was retained because a managed file could not be safely removed.",
|
|
),
|
|
);
|
|
else {
|
|
const manifest = await removeManagedSkillFile(
|
|
path,
|
|
manifestName,
|
|
name,
|
|
fileSystem,
|
|
);
|
|
results.push(manifest);
|
|
const directories =
|
|
manifest.status === "removed"
|
|
? await removeEmptyManagedDirectories(path, name, fileSystem)
|
|
: undefined;
|
|
if (directories !== undefined) results.push(directories);
|
|
}
|
|
const failed = results.find(({ status }) => status === "failed");
|
|
if (failed !== undefined)
|
|
return item(name, "failed", results.map(({ detail }) => detail).join(" "));
|
|
if (results.some(({ status }) => status === "retained"))
|
|
return item(
|
|
name,
|
|
"retained",
|
|
[...new Set(results.map(({ detail }) => detail))].join(" "),
|
|
);
|
|
const removed = results.some(({ status }) => status === "removed");
|
|
return item(
|
|
name,
|
|
removed ? "removed" : "skipped",
|
|
"REA-managed skill files were removed; other files were preserved.",
|
|
);
|
|
};
|
|
|
|
/** Directories setup creates for managed files, deepest first, then the root. */
|
|
const MANAGED_SKILL_DIRECTORIES = [
|
|
...new Set(
|
|
MANAGED_SKILL_FILES.map((relativePath) =>
|
|
relativePath.split("/").slice(0, -1).join("/"),
|
|
).filter((directory) => directory.length > 0),
|
|
),
|
|
].sort((left, right) => right.split("/").length - left.split("/").length);
|
|
|
|
/** Remove managed directories left empty; any remaining user file keeps them. */
|
|
const removeEmptyManagedDirectories = async (
|
|
root: string,
|
|
name: string,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<UninstallItem | undefined> => {
|
|
if (fileSystem.removeEmptyDirectory === undefined) return undefined;
|
|
for (const directory of [
|
|
...MANAGED_SKILL_DIRECTORIES.map((relative) =>
|
|
appendCallerPath(root, relative),
|
|
),
|
|
root,
|
|
]) {
|
|
try {
|
|
await fileSystem.removeEmptyDirectory(directory);
|
|
} catch (cause: unknown) {
|
|
// User files, an absent directory, or a non-directory keep it as is.
|
|
if (!isKeptDirectory(cause))
|
|
return item(
|
|
name,
|
|
"failed",
|
|
`Managed skill directory could not be removed: ${directory}.`,
|
|
);
|
|
}
|
|
}
|
|
return undefined;
|
|
};
|
|
|
|
const isKeptDirectory = (cause: unknown): boolean =>
|
|
cause instanceof Error &&
|
|
"code" in cause &&
|
|
["ENOTEMPTY", "EEXIST", "ENOENT", "ENOTDIR"].includes(String(cause.code));
|
|
|
|
const removeManagedSkillFile = async (
|
|
root: string,
|
|
relativePath: string,
|
|
name: string,
|
|
fileSystem: UninstallFileSystem,
|
|
): Promise<UninstallItem> => {
|
|
const segments = relativePath.split(/[\\/]/u);
|
|
let parent = root;
|
|
for (const segment of segments.slice(0, -1)) {
|
|
parent = appendCallerPath(parent, segment);
|
|
try {
|
|
const stats = await fileSystem.stat(parent);
|
|
if (stats.isSymbolicLink() || stats.isDirectory?.() !== true)
|
|
return item(
|
|
name,
|
|
"retained",
|
|
`Managed path parent was retained: ${parent}.`,
|
|
);
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(
|
|
name,
|
|
"skipped",
|
|
`${appendCallerPath(parent, segments.at(-1) ?? "")} does not exist.`,
|
|
)
|
|
: item(
|
|
name,
|
|
"failed",
|
|
`Managed path parent could not be inspected: ${parent}.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
const target = appendCallerPath(root, relativePath);
|
|
let stats: ManagedPathStats;
|
|
try {
|
|
stats = await fileSystem.stat(target);
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(name, "skipped", `${target} does not exist.`)
|
|
: item(name, "failed", `Managed file could not be inspected: ${target}.`);
|
|
}
|
|
if (stats.isSymbolicLink())
|
|
return item(
|
|
name,
|
|
"retained",
|
|
`Managed file is a symbolic link: ${target}.`,
|
|
);
|
|
if (stats.isFile?.() !== true)
|
|
return item(
|
|
name,
|
|
"retained",
|
|
`Managed path is not a regular file: ${target}.`,
|
|
);
|
|
try {
|
|
await fileSystem.remove(target, false);
|
|
return item(name, "removed", `Removed ${target}.`);
|
|
} catch (cause: unknown) {
|
|
return isMissing(cause)
|
|
? item(name, "skipped", `${target} does not exist.`)
|
|
: item(name, "failed", `Managed file could not be removed: ${target}.`);
|
|
}
|
|
};
|
|
|
|
const item = (
|
|
name: string,
|
|
status: UninstallItem["status"],
|
|
detail: string,
|
|
): UninstallItem => ({ name, status, detail });
|
|
|
|
/**
|
|
* Layered clients are removed file by file, but callers look up one status by
|
|
* client name. Aggregate status does not invalidate any constituent outcome.
|
|
*/
|
|
const collapseUninstallItems = (
|
|
items: readonly UninstallItem[],
|
|
): UninstallItem[] => {
|
|
const grouped = new Map<string, UninstallAction[]>();
|
|
for (const next of items) {
|
|
const { name, actions, ...action } = next;
|
|
const group = grouped.get(name) ?? [];
|
|
group.push(
|
|
...(actions !== undefined && actions.length > 0 ? actions : [action]),
|
|
);
|
|
grouped.set(name, group);
|
|
}
|
|
return [...grouped].map(([name, actions]) => {
|
|
const first = actions[0];
|
|
if (first === undefined)
|
|
throw new Error("Uninstall outcome group has no actions.");
|
|
if (actions.length === 1) return { name, ...first };
|
|
const status = actions.reduce(
|
|
(selected, action) =>
|
|
uninstallStatusPriority(action.status) >
|
|
uninstallStatusPriority(selected)
|
|
? action.status
|
|
: selected,
|
|
first.status,
|
|
);
|
|
return {
|
|
name,
|
|
status,
|
|
detail: [...new Set(actions.map(({ detail }) => detail))].join(" "),
|
|
actions,
|
|
};
|
|
});
|
|
};
|
|
|
|
const uninstallStatusPriority = (status: UninstallItem["status"]): number => {
|
|
switch (status) {
|
|
case "failed":
|
|
return 3;
|
|
case "removed":
|
|
return 2;
|
|
case "retained":
|
|
return 1;
|
|
case "skipped":
|
|
return 0;
|
|
default: {
|
|
const exhaustive: never = status;
|
|
throw new TypeError(
|
|
`Unhandled uninstall item status: ${String(exhaustive)}`,
|
|
);
|
|
}
|
|
}
|
|
};
|
|
const isMissing = (cause: unknown): boolean =>
|
|
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|