Files
reverse-engineering-anything/src/application/UpdateMaintenance.ts
T
Harsh Asalkarandmorluto 63c50ecfc0 feat(setup): discover project-scoped MCP registrations in doctor and … (#7283)
* feat(setup): discover project-scoped MCP registrations in doctor and uninstall

* fix(setup): preserve OpenCode layer fields, user launcher provenance, and user fallback

* fix(setup): restore working directory in tests and refine replacement and launcher provenance

* fix(setup): bound OpenCode discovery to worktree and enforce Pi project trust

* fix(setup): preserve Pi project trust failures in doctor and prevent skipping project registrations in uninstall

* fix(setup): defer cross-setting environment validation and decouple OpenCode launcher ownership

* fix(setup): separate OpenCode readiness schema from launcher ownership and fix cross-setting test

* fix(doctor): include project remediation when disabled project registration inherits outdated user launcher

* fix(setup): scope status properties to project-scoped registrations

Omit scope and launcher_scope when no project-level configuration was discovered or evaluated, ensuring user-level registrations retain their exact unextended status contract in isolated environments without project files.

* fix(setup): prevent activating unowned launchers during uninstall and align array normalization

Prevent activating unowned or foreign launchers hidden in lower-precedence configurations during project-scoped uninstall, normalize array command arguments uniformly in OpenCode ownership parsing without appending separate args, and clarify field inheritance in client configuration documentation.

* fix(setup): check effective remaining launcher on uninstall and preserve cleanup failure

* fix(uninstall): preserve user configuration path in project client to check fallback ownership

* fix(uninstall): scope fallback configuration paths only to project-scoped clients

* fix(doctor): validate effective merged Pi flags and preserve MSIX selection during uninstall

* fix(uninstall): preserve surviving OpenCode project registrations across complete configuration layers

* fix(uninstall): require surviving OpenCode server to carry a launcher when checking layered activation

* fix(uninstall): rely on full layered check for OpenCode instead of lower-only fallback

* fix(doctor): preserve source paths for inherited environment failures

When a trusted Pi project partial override or an OpenCode project registration inherits an invalid REA environment value from user configuration (or an ancestor configuration), attribute the resulting doctor invalid registration error to the contributing configuration source rather than the winning project file. Preserves source evidence provenance across merged configuration layers so doctor remediation points the user to the file that actually requires repair.

* test(doctor): exercise effective cross-setting merge failure in inherited environment tests

Replace scalar validation errors with cross-setting constraints (REA_GHIDRA_PROGRAM_NAME without REA_GHIDRA_PROJECT_PATH) in inherited environment regression tests so individual fragments pass and the failure is only triggered during effective layer merge, directly protecting contributingEnvironmentSource provenance lookup.

* fix(uninstall): allow cleaning up owned entries in untrusted Pi projects

Evaluate Pi project trust in unownedLowerLayerFallback so owned entries in untrusted Pi projects can be cleanly removed without falsely claiming that removal would activate an unowned user launcher.

* fix(uninstall): require confirmed untrusted decision to skip Pi fallback check

Only skip the unowned lower-layer fallback check when Pi project trust is confirmed untrusted (trust.ok && !trust.value). When Pi trust reading or parsing fails (!trust.ok), preserve the unresolved state and conservatively inspect the lower layer so that an unowned user launcher is not inadvertently exposed if the project was trusted.

* fix(doctor): track activation provenance across layers and normalize platform path identity

- Track activation source provenance (activationScope, activationConfigPath) across Pi and OpenCode configuration layers so activation drift remediation points to the exact file contributing the disable/enable flag rather than nearest fragment.
- Normalize path identity case-insensitively on Windows and macOS when deduplicating user configuration from OpenCode hierarchy and Pi project candidates.
- Qualify Pi project registration docs with trusted projects prerequisite and fallback semantics.

* fix(doctor): isolate platform casing tests and restore cwd mocks

* fix(doctor): use filesystem identity for path normalization and verify present files in case tests

* fix(doctor): preserve inherited schema provenance and include activation in project package remediation

* fix(doctor): report the contributing registration and activation sources

* test(doctor): exercise combined Pi activation and launcher repairs

* fix(doctor): honor OpenCode activation by config dialect

* fix(doctor): share project registration activation and provenance

* fix(setup): plan project removals before writes and isolate provider probes

* fix(doctor): preserve OpenCode registration and launcher provenance

* fix(doctor): use shared registration error and path provenance

* fix(doctor): gate desktop probes on registration authority

* fix(uninstall): skip absent project configuration candidates

* fix(uninstall): compare effective project registration before removal

* fix(doctor): guide project package launcher migration

* test(doctor): verify OpenCode project launcher migration advice

* fix(uninstall): separate project load order from write targets

* fix(doctor): preserve OpenCode directory alias precedence

* fix(uninstall): preserve unchanged remote project registrations

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-21 22:19:56 +00:00

303 lines
11 KiB
TypeScript

import { z } from "zod";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { currentClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import {
readClientRegistrationInspections,
type ClientRegistrationStatus,
} from "./ClientRegistrationStatus.js";
import { clientRefreshRefusal } from "./SetupClientConfiguration.js";
import { explicitSetupRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
import {
existingSkillDestinations,
type SkillPathIssue,
} from "./SetupSkill.js";
import type { SetupAction } from "./SetupTypes.js";
import type { Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../resources/index.js";
import type { ClientSystemPaths } from "./SupportedClients.js";
import { errorMessage } from "../kernel/errorMessage.js";
/**
* A client maintenance left alone: its registration as inspected, and why REA
* cannot update it (unresolved identity, or setup's preflight refusal).
*/
export type UnresolvedMaintenanceClient = Pick<
ClientRegistrationStatus,
"client" | "config_path" | "state"
> & { readonly remediation: string };
/** Existing REA integrations selected for maintenance, without discovering new targets. */
export interface MaintenanceScope {
readonly clients: readonly string[];
readonly skill: boolean;
readonly unresolved?: readonly UnresolvedMaintenanceClient[];
readonly skillIssues?: readonly SkillPathIssue[];
readonly skillDestinations?: readonly {
readonly client: string;
readonly path: string;
}[];
}
/** Unapplied maintenance evidence produced by the updated setup executable. */
export type IntegrationMaintenance =
| {
readonly status: "current";
readonly plannedActions: readonly [];
/** Clients left unmaintained because REA cannot identify or update their registration. */
readonly unresolved?: readonly UnresolvedMaintenanceClient[];
}
| {
readonly status: "planned";
readonly scope: MaintenanceScope;
readonly command: readonly string[];
readonly plannedActions: readonly SetupAction[];
}
| {
readonly status: "unavailable";
readonly remediation: string;
readonly scope?: MaintenanceScope;
};
const setupPlanSchema = z.object({
status: z.literal("planned"),
plannedActions: z.array(
z.object({
id: z.string(),
kind: z.enum(["configure_client", "install_skill"]),
label: z.string(),
target: z.string(),
detail: z.string(),
external: z.literal(false),
operation: z.enum(["create", "update", "install"]),
backupPath: z.string().optional(),
commands: z.array(z.string()).optional(),
}),
),
});
const unresolvedRegistrationDetail = ({
client,
config_path,
remediation,
}: UnresolvedMaintenanceClient): string =>
`${client} (${config_path}): ${remediation}`;
/** Clients a maintenance result left alone because REA cannot identify or update their registration. */
export const unresolvedMaintenanceClients = (
maintenance: IntegrationMaintenance,
): readonly UnresolvedMaintenanceClient[] =>
(maintenance.status === "current"
? maintenance.unresolved
: maintenance.scope?.unresolved) ?? [];
/** One sentence naming each unknown client and its own recovery. */
export const unresolvedMaintenanceRemediation = (
unresolved: readonly UnresolvedMaintenanceClient[],
): string =>
`REA did not maintain ${unresolved.length === 1 ? "one client" : `${String(unresolved.length)} clients`} whose registration it cannot update: ${unresolved.map(unresolvedRegistrationDetail).join(" ")}`;
/** A maintenance failure that still reports the unknown clients it found. */
const unavailableMaintenance = (
remediation: string,
scope: MaintenanceScope | undefined,
): IntegrationMaintenance => {
const unresolved = scope?.unresolved ?? [];
return {
status: "unavailable",
remediation:
unresolved.length === 0
? remediation
: `${remediation} ${unresolvedMaintenanceRemediation(unresolved)}`,
...(scope === undefined ? {} : { scope }),
};
};
/** Where maintenance reads: the caller's resource scope and system layers. */
export interface MaintenanceInputs {
/** The platform whose client layout and environment identity apply. */
readonly platform: NodeJS.Platform;
readonly resources?: ArtifactResourceScope;
/** System configuration files; tests point them inside their own home. */
readonly systemPaths?: ClientSystemPaths;
}
/** Discover owned registrations and REA skills without writes. */
export const existingMaintenanceScope = async (
home: string,
entryPoint: string,
environment: Readonly<NodeJS.ProcessEnv>,
{ platform, resources, systemPaths }: MaintenanceInputs,
): Promise<MaintenanceScope> => {
const registrations = await readClientRegistrationInspections(
home,
entryPoint,
{
platform,
environment,
// A registration REA wrote must be refreshed even when the product
// profile is absent, so maintenance reads ownership evidence instead of
// product applicability. Owned rows stay the only ones selected below.
evidence: "ownership",
scope: "user",
...(resources === undefined ? {} : { resources }),
...(systemPaths === undefined ? {} : { systemPaths }),
},
);
const clients: string[] = [];
const unresolved: UnresolvedMaintenanceClient[] = [];
// The launcher and explicitly selected settings the maintenance setup run
// registers; provider defaults doctor discovers there are not known here.
const command = currentClientRegistrationCommand({
platform,
entrypointPath: entryPoint,
environment,
});
const settings = explicitSetupRegistrationEnvironment(environment);
for (const { status: registration, activation, client } of registrations) {
if (registration.state === "unknown" || registration.state === "invalid") {
unresolved.push(registration);
continue;
}
if (
activation !== "enabled" ||
(registration.state !== "aligned" && registration.state !== "stale") ||
registration.command_identity !== "owned"
)
continue;
// One client setup refuses (a client policy, or a read-only inline layer
// that would override the refreshed entry) blocks the whole setup plan,
// so ask setup's own refusal check first and report that client instead
// of selecting it. An aligned registration is checked too: setup still
// preflights it. When the conflict involves only provider settings setup
// discovers, alignment is unknown here, not aligned or refused.
const refusal = await clientRefreshRefusal(client, settings, command, {
platform,
currentCommandPath: entryPoint,
launcherEnvironment: environment,
...(resources === undefined ? {} : { resources }),
});
if (refusal !== undefined) {
unresolved.push({
...registration,
...(refusal.alignment === "unknown" ? { state: "unknown" } : {}),
remediation: refusal.remediation,
});
continue;
}
clients.push(registration.client);
}
// Each setup action rewrites only that client's own configuration path, so
// maintenance keeps every selected client instead of deferring one view of
// a registration to another client's inspection: ZCode writes
// ~/.zcode/cli/config.json and deliberately leaves the ~/.agents/mcp.json
// fallback untouched (docs/getting-started/client-configuration.md), while FreeBuff writes
// the shared file itself. Dropping FreeBuff because ZCode reads that
// fallback would leave the row both products load pinned to the old
// version.
const skills = await existingSkillDestinations(
home,
environment,
platform,
resources,
);
return {
clients,
skill: skills.destinations.length > 0,
skillDestinations: skills.destinations,
...(skills.issues.length === 0 ? {} : { skillIssues: skills.issues }),
...(unresolved.length === 0 ? {} : { unresolved }),
};
};
/** Ask the verified new executable to plan only existing REA integrations. */
export const planIntegrationMaintenance = async (
home: string,
entryPoint: string,
environment: Readonly<NodeJS.ProcessEnv>,
execute: (command: readonly string[]) => Promise<Result<string, string>>,
inputs: MaintenanceInputs,
): Promise<IntegrationMaintenance> => {
const { resources } = inputs;
let scope: MaintenanceScope | undefined;
try {
scope = await existingMaintenanceScope(
home,
entryPoint,
environment,
inputs,
);
// An unresolved client fails closed on its own: it stays out of the
// maintained clients and is reported, while every resolved client is
// still maintained. Skill destinations are one shared selection.
if ((scope.skillIssues?.length ?? 0) > 0)
return unavailableMaintenance(
`Integration maintenance is unresolved: ${(scope.skillIssues ?? [])
.map(
({ client, path, detail }) =>
`${client ?? "skill"} (${path}): ${detail}`,
)
.join(" ")}`,
scope,
);
const current: IntegrationMaintenance = {
status: "current",
plannedActions: [],
...(scope.unresolved === undefined
? {}
: { unresolved: scope.unresolved }),
};
const skillDestinations = scope.skillDestinations ?? [];
if (scope.clients.length === 0 && !scope.skill) return current;
const command = [
process.execPath,
entryPoint,
"setup",
...scope.clients.flatMap((client) => ["--client", client]),
...skillDestinations.flatMap(({ client }) => ["--skill-client", client]),
`--skill=${String(scope.skill)}`,
];
const execution = await execute([...command, "--dry-run", "--json"]);
if (!execution.ok) return unavailableMaintenance(execution.error, scope);
const plan = setupPlanSchema.safeParse(JSON.parse(execution.value));
if (!plan.success)
return unavailableMaintenance(
`The updated setup executable returned an invalid maintenance plan: ${plan.error.message}`,
scope,
);
if (plan.data.plannedActions.length === 0) return current;
const allowedIds = new Set(
scope.clients.map((client) => `configure_client:${client}`),
);
const skillTargets = new Set(skillDestinations.map(({ path }) => path));
if (
plan.data.plannedActions.some((action) =>
action.kind === "install_skill"
? !skillTargets.has(action.target)
: !allowedIds.has(action.id),
)
)
return unavailableMaintenance(
"The updated setup plan included an integration outside the existing REA maintenance scope.",
scope,
);
return {
status: "planned",
scope,
command,
plannedActions: plan.data.plannedActions.map(
({ backupPath, commands, ...action }) => ({
...action,
...(backupPath === undefined ? {} : { backupPath }),
...(commands === undefined ? {} : { commands }),
}),
),
};
} catch (cause: unknown) {
// Without a supplied scope, the typed failure is the caller's cleanup capability.
if (resources === undefined && cause instanceof RegularFileCleanupFailure)
throw cause;
return unavailableMaintenance(errorMessage(cause), scope);
}
};