Files
rea/src/desktop/DesktopBuildSetupHost.ts
T
morluto b138f52e12 refactor: prune internal seams and preserve configuration ownership (#10430)
* refactor: prune internal seams and preserve configuration ownership

* fix(setup): keep YAML aliases and inherited registration settings on refresh

- Reuse an unchanged YAML collection only while every alias in it still
  resolves after the edit; otherwise rebuild it so the alias becomes its
  value. A sibling anchor replaced or moved in the same refresh no longer
  leaves an unresolved alias in Hermes or Goose output.
- Keep a connection selector whose existing value already chooses stdio
  (for example an inherited Hermes transport: stdio) instead of superseding
  it; remote selectors are still replaced. Explicit stdio selectors are
  therefore no longer rewritten (Kimi expectation updated).
- When the whole Hermes registration is inherited through a merge,
  override it with that merge and write only the changed fields.

* fix(setup): edit registration fields whose YAML key is an alias

A key written as an alias to a string scalar (for example *field with
field: &field env) was treated as a source-only key, so any change to
its value was refused in Hermes and Goose. Resolve such keys to their
string, keep the aliased spelling while its anchor survives the edit,
and write the plain key when the same edit rebuilds the anchor.

* test(process): bound cleanup-boundary waits and always release gates

Both cancellation tests awaited a bare started promise and released
their gates only on success, so a missed boundary waited for the outer
deadline and could leave cleanup parked. Use awaitAcknowledgement and
release and join the cleanup in finally.

* fix(setup): repair only aliases an edit leaves unresolved

Replace the pre-edit alias survival guess, which expanded aliases to
sibling anchors that survive unchanged, with an exact repair: record
what each alias in the replaced value resolves to, write the edit, then
replace only aliases left without a preceding anchor by that value.

- Keep an aliased key's source position, so its anchor stays ahead of
  later aliases.
- Treat an aliased key as its string only when no other key in the map
  resolves to the same string; an ambiguous one stays guarded.
- Override an inherited Hermes registration only when the requested
  entry keeps every inherited field, so an explicit replacement can drop
  remote selectors.

* fix(setup): repair aliases whose binding an edit changes, keeping comments

An alias whose own anchor was removed could resolve to an earlier anchor
with the same name and silently change value. Record the node each alias
resolved to and repair any alias that no longer resolves to that node.
Carry the alias's comments and spacing onto the repaired value.

* test(setup): split the Hermes anchor and merge refresh cases

* fix(setup): refuse removing an overridden key its merge would restore

The merge-retention check skipped keys the mapping also overrides, so
dropping such a key (for example a remote url during an explicit stdio
replacement) let the retained merge restore it. Check removal before
skipping overridden keys, so the edit is refused with the existing
message instead of producing a registration that cannot be applied.
2026-11-14 04:08:37 -05:00

314 lines
11 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { access, mkdir, mkdtemp, rename, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { DoctorHost } from "../application/Doctor.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { assertSetupActive } from "../application/SetupCancellation.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import type {
DesktopBuildSetupFacts,
DesktopBuildSetupHost,
} from "../application/SetupDesktopBuild.js";
import { DESKTOP_EXPORT_FRAMEWORK_VERSION } from "../domain/desktop/appExport.js";
import {
execFileOutput,
execFileOutputFailure,
} from "../process/ExecFileOutput.js";
import {
agentEnvReportedVersion,
buildComputerArchiveDirectory,
defaultBuildComputerArchive,
programOnPath,
} from "./BuildComputerEnvironment.js";
import { BUILD_COMPUTER_SETTINGS } from "../domain/desktop/buildComputerSettings.js";
import {
desktopBuildOwnedCommandReason,
runDesktopBuildOwnedCommand,
} from "./DesktopBuildOwnedCommand.js";
const PACK_SCRIPT = fileURLToPath(
new URL("../../scripts/pack-build-computer-runtime.mjs", import.meta.url),
);
const CHECKOUT_LOCKFILE = fileURLToPath(
new URL("../../package-lock.json", import.meta.url),
);
const PROBE = { timeout: 10_000, maxBuffer: 64 * 1024 } as const;
const PACK = { timeout: 30 * 60_000, maxBuffer: 16 * 1024 * 1024 } as const;
const INSTALL = { timeout: 10 * 60_000, maxBuffer: 4 * 1024 * 1024 } as const;
const ARCHIVE = "REA_BUILD_COMPUTER_REA_ARCHIVE";
/** What setup's fact readers share: the caller's environment and registration reader. */
interface SetupContext {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly platform: NodeJS.Platform;
readonly registrations: DoctorHost["clientRegistrations"];
probe(
command: string,
arguments_: readonly string[],
): Promise<{ readonly stdout: string }>;
}
const exists = (path: string): Promise<boolean> =>
access(path).then(
() => true,
() => false,
);
const failureReason = (cause: unknown): string => {
const stderr = execFileOutputFailure(cause)?.stderr.trim() ?? "";
const message = cause instanceof Error ? cause.message : String(cause);
return stderr === "" ? message : `${message}: ${stderr.slice(-2000)}`;
};
/** Setup's desktop build effects on this host. */
export const systemDesktopBuildSetupHost = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
registrations: DoctorHost["clientRegistrations"],
resources: ArtifactResourceScope,
): DesktopBuildSetupHost => {
const run = (
command: string,
arguments_: readonly string[],
limits: typeof PROBE,
env = environment,
) =>
execFileOutput(command, arguments_, {
...limits,
env,
stopSignal: "SIGTERM",
});
return {
facts: (clientIds) =>
readSetupFacts(
{
environment,
platform,
registrations,
probe: (command, arguments_) => run(command, arguments_, PROBE),
},
clientIds,
),
async packRuntime(archive, signal) {
const partial = join(dirname(archive), `.rea-${randomUUID()}.tar.xz`);
let commandFinished = false;
return resources.run(async () => {
try {
assertSetupActive(signal);
await mkdir(dirname(archive), { recursive: true });
const workspace = await mkdtemp(join(tmpdir(), "rea-desktop-pack-"));
await runDesktopBuildOwnedCommand({
command: process.execPath,
arguments: [PACK_SCRIPT, partial],
timeoutMs: PACK.timeout,
maxOutputBytes: PACK.maxBuffer,
resources,
partialPath: partial,
workspace,
...(signal === undefined ? {} : { signal }),
environment: {
...environment,
TMPDIR: workspace,
TMP: workspace,
TEMP: workspace,
npm_config_loglevel: "error",
npm_config_progress: "false",
npm_config_fund: "false",
npm_config_audit: "false",
},
});
commandFinished = true;
try {
await rm(workspace, { recursive: true, force: true });
} catch (cause: unknown) {
resources.retain({
kind: "lease",
resource: workspace,
lease: {
release: () => rm(workspace, { recursive: true, force: true }),
},
});
throw cause;
}
assertSetupActive(signal);
await rename(partial, archive);
return undefined;
} catch (cause: unknown) {
if (commandFinished) {
try {
await rm(partial, { force: true });
} catch (cleanup: unknown) {
const lease = new AnalysisCleanupLease(
() => rm(partial, { force: true }),
[partial],
);
resources.retain({ kind: "lease", resource: partial, lease });
if (cause instanceof AnalysisError) {
const cleanupFailure = new ProviderCleanupError(
"rea-desktop",
[partial],
{ reason: failureReason(cleanup) },
{ operation: "setup", cause: cleanup },
);
cleanupFailure.bindCleanupResourceOwner(lease);
lease.bindCleanupError(cleanupFailure);
throw analysisErrorWithCleanupFailure(
cause,
cleanupFailure,
"setup",
).bindCleanupDependencies([cause, cleanupFailure]);
}
return `${desktopBuildOwnedCommandReason(cause)}; partial archive cleanup failed: ${failureReason(cleanup)}`;
}
}
if (cause instanceof AnalysisError) throw cause;
return desktopBuildOwnedCommandReason(cause);
}
});
},
async installAgentenv(uv, signal) {
return resources.run(async () => {
try {
assertSetupActive(signal);
await runDesktopBuildOwnedCommand({
command: uv,
arguments: [
"tool",
"install",
`agentenv-framework==${DESKTOP_EXPORT_FRAMEWORK_VERSION}`,
],
timeoutMs: INSTALL.timeout,
maxOutputBytes: INSTALL.maxBuffer,
resources,
environment,
...(signal === undefined ? {} : { signal }),
});
return undefined;
} catch (cause: unknown) {
if (cause instanceof AnalysisError) throw cause;
return desktopBuildOwnedCommandReason(cause);
}
});
},
};
};
const readSetupFacts = async (
context: SetupContext,
clientIds: readonly string[],
): Promise<DesktopBuildSetupFacts> => {
const { environment, platform, probe } = context;
const archive = defaultBuildComputerArchive(environment, platform);
const selected = BUILD_COMPUTER_SETTINGS.filter(
(name) => (environment[name] ?? "") !== "",
);
const settings = await absoluteSettings(environment, archive, platform);
const agentEnv = settings.REA_AGENT_ENV_COMMAND;
const uv = await programOnPath("uv", environment);
const uvBin =
uv === undefined
? undefined
: await probe(uv, ["tool", "dir", "--bin"]).then(
({ stdout }) => stdout.trim(),
() => undefined,
);
return {
settings,
selected,
archive,
archivePacked: await stat(archive).then(
(entry) => entry.isFile(),
() => false,
),
...((await exists(PACK_SCRIPT)) && (await exists(CHECKOUT_LOCKFILE))
? {}
: {
packBlocker:
"Packing REA's build-computer runtime needs a REA checkout: run rea setup --desktop-build from one (see docs/installation.md#run-rea-from-a-checkout), or pack an archive yourself and set REA_BUILD_COMPUTER_REA_ARCHIVE.",
}),
...(agentEnv === undefined
? {}
: await probe(agentEnv, ["--version"]).then(
({ stdout }) => ({
agentEnvVersion: agentEnvReportedVersion(stdout),
}),
() => ({}),
)),
...(uv === undefined || uvBin === undefined || uvBin === ""
? {}
: { uv: { path: uv, agentEnv: join(uvBin, "agent-env") } }),
recorded: await recordedSettings(context, clientIds, settings),
};
};
/** Each build setting as an absolute path: the caller's selection, else its default. */
const absoluteSettings = async (
environment: Readonly<NodeJS.ProcessEnv>,
archive: string,
platform: NodeJS.Platform,
): Promise<Record<string, string>> => {
const settings: Record<string, string> = {};
for (const [name, program] of [
["REA_AGENT_ENV_COMMAND", "agent-env"],
["REA_DOCKER_COMMAND", "docker"],
] as const) {
const value = environment[name] ?? "";
const path =
value === ""
? await programOnPath(program, environment)
: isAbsolute(value)
? value
: await programOnPath(value, environment);
if (path !== undefined) settings[name] = path;
}
const selectedArchive = environment[ARCHIVE] ?? "";
settings[ARCHIVE] =
selectedArchive === ""
? archive
: absoluteCallerPath(selectedArchive, { platform });
return settings;
};
/**
* Per client, the build settings its registration records with a value of its
* own: an archive REA packed for another version is setup's, not the user's,
* whether or not it is still on disk.
*/
const recordedSettings = async (
{ environment, platform, registrations }: SetupContext,
clientIds: readonly string[],
settings: Readonly<Record<string, string>>,
): Promise<Record<string, readonly string[]>> => {
if (registrations === undefined || clientIds.length === 0) return {};
const directory = buildComputerArchiveDirectory(environment, platform);
const setupArchive = (name: string, value: string) =>
name === ARCHIVE &&
value !== settings[ARCHIVE] &&
dirname(resolve(value)) === directory &&
/^rea-.+\.tar\.xz$/u.test(basename(value));
// Every name is compared, so a runner not installed yet still reads as unrecorded.
const compared = {
...Object.fromEntries(BUILD_COMPUTER_SETTINGS.map((name) => [name, ""])),
...settings,
};
const statuses = await registrations(clientIds, compared, setupArchive);
const recorded: Record<string, string[]> = {};
for (const status of statuses) {
if (!clientIds.includes(status.client) || status.command.length === 0)
continue;
const gaps = status.provider_settings;
const replaced = [...(gaps?.unrecorded ?? []), ...(gaps?.owned ?? [])];
recorded[status.client] = BUILD_COMPUTER_SETTINGS.filter(
(name) => !replaced.includes(name),
);
}
return recorded;
};