refactor!: enforce canonical evidence and provider boundaries
Deliver complete Evidence directly through MCP with required nullable analysis profiles and immutable per-server delivery settings. Bind selected environments at construction and require typed cleanup outcomes with retained retry ownership. Remove test-only routing, duplicate session and snapshot metadata, producer-field repairs, and ambiguous provider arguments. Separate artifact byte identity from occurrence classification and retain typed source-map and partial native facts across CLI, MCP, and verifier consumers. BREAKING CHANGE: obsolete Evidence envelopes, session aliases, incomplete snapshots, and missing normalized producer facts are no longer accepted.
This commit is contained in:
@@ -21,7 +21,6 @@ import {
|
||||
type LinuxPrivateDisplayRunnableStrategy,
|
||||
type LinuxPrivateDisplaySelection,
|
||||
} from "./LinuxPrivateDisplayProbe.js";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import {
|
||||
prepareHopperMachOImage,
|
||||
@@ -46,7 +45,12 @@ export interface BridgeSession {
|
||||
}
|
||||
|
||||
/** Process handle returned by a bridge launcher. */
|
||||
export type BridgeLaunch =
|
||||
export type BridgeLaunch = {
|
||||
/** Release application/target exclusivity only after verified document and process cleanup. */
|
||||
readonly releaseLease?: () => Promise<void>;
|
||||
/** Exact launch command retained in local ownership metadata. */
|
||||
readonly launcherCommand?: string;
|
||||
} & (
|
||||
| (ProviderProcessLaunch & {
|
||||
readonly shutdownMode: "bridge-request";
|
||||
readonly preparedImagePath?: string;
|
||||
@@ -58,7 +62,8 @@ export type BridgeLaunch =
|
||||
readonly preparedImagePath?: string;
|
||||
readonly providerLifetime: "launcher-process";
|
||||
readonly cleanup: NonNullable<ProviderProcessLaunch["cleanup"]>;
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
/** Application-owned capability that starts the in-Hopper bridge. */
|
||||
export interface BridgeLauncher {
|
||||
@@ -74,6 +79,7 @@ export interface BridgeLauncher {
|
||||
}
|
||||
|
||||
interface SharedHopperApplicationLauncherOptions {
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly launcherPath: string;
|
||||
readonly targetPath: string;
|
||||
readonly targetKind: "executable" | "database";
|
||||
@@ -101,6 +107,7 @@ export interface HopperApplicationLauncherDependencies {
|
||||
readonly acquireTargetLease?: typeof acquireHopperTargetLease;
|
||||
readonly acquireApplicationLease?: typeof acquireLinuxHopperApplicationLease;
|
||||
readonly selectPrivateDisplay?: (options: {
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly helperPath: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}) => Promise<LinuxPrivateDisplaySelection>;
|
||||
@@ -205,6 +212,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
if (!display.ok) return err(display.error);
|
||||
const prepared = await prepareHopperApplication(
|
||||
this.options.launcherPath,
|
||||
this.options.environment,
|
||||
signal,
|
||||
);
|
||||
if (!prepared) return err(new HopperCancelledError());
|
||||
@@ -224,28 +232,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
signal,
|
||||
});
|
||||
if (started === null) return err(new HopperCancelledError());
|
||||
const cleanup = () =>
|
||||
cleanupOwnedProcessGroup(started.ownership).finally(() =>
|
||||
lease?.release(),
|
||||
);
|
||||
const ownership = {
|
||||
run_id: session.runId,
|
||||
pid: started.ownership.leaderPid,
|
||||
process_group_id: started.ownership.leaderPid,
|
||||
parent_pid: process.pid,
|
||||
launcher: linuxDemo?.command ?? this.options.launcherPath,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
await writeFileAtomic(
|
||||
join(session.directory, "ownership.json"),
|
||||
`${JSON.stringify(ownership)}\n`,
|
||||
{ encoding: "utf8", mode: 0o600 },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
await cleanupOwnedProcessGroup(started.ownership);
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
const cleanup = () => cleanupOwnedProcessGroup(started.ownership);
|
||||
const ownedLauncher = {
|
||||
...(this.options.preparedImage === undefined
|
||||
? {}
|
||||
@@ -254,6 +241,8 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
ownsProcessLifetime: true as const,
|
||||
ownership: started.ownership,
|
||||
cleanup,
|
||||
launcherCommand: linuxDemo?.command ?? this.options.launcherPath,
|
||||
...(lease === undefined ? {} : { releaseLease: () => lease.release() }),
|
||||
};
|
||||
return ownsProcessLifetime
|
||||
? ok({
|
||||
@@ -352,6 +341,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
selectLinuxPrivateDisplayStrategy
|
||||
)({
|
||||
helperPath: this.options.demoHelperPath,
|
||||
environment: this.options.environment,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
if (signal?.aborted === true)
|
||||
@@ -401,6 +391,7 @@ const launchHopperProcess = async (input: {
|
||||
arguments: arguments_,
|
||||
runId: input.session.runId,
|
||||
expectedCommand: ownershipCommand,
|
||||
hostEnvironment: input.options.environment,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
});
|
||||
if (input.linuxDemo !== undefined)
|
||||
@@ -409,6 +400,7 @@ const launchHopperProcess = async (input: {
|
||||
arguments: input.linuxDemo.args,
|
||||
runId: input.session.runId,
|
||||
expectedCommand: ownershipCommand,
|
||||
hostEnvironment: input.options.environment,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
});
|
||||
return spawn(input.argumentsForTarget);
|
||||
@@ -480,20 +472,21 @@ export const usesLinuxDemo = (
|
||||
|
||||
const prepareHopperApplication = async (
|
||||
launcherPath: string,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<boolean> => {
|
||||
const appBundle = hopperApplicationBundle(launcherPath);
|
||||
if (appBundle === undefined) return signal?.aborted !== true;
|
||||
const executablePath = join(appBundle, "Contents/MacOS/Hopper Disassembler");
|
||||
if (await processIsRunning(executablePath)) return signal?.aborted !== true;
|
||||
if (await processIsRunning(executablePath, environment))
|
||||
return signal?.aborted !== true;
|
||||
// This reduces activation when Hopper is cold, but the vendor launcher that
|
||||
// follows may still activate its window. See HopperApplicationLauncher.
|
||||
await execFileAsync("/usr/bin/open", [
|
||||
"--hide",
|
||||
"--background",
|
||||
"-a",
|
||||
appBundle,
|
||||
]);
|
||||
await execFileAsync(
|
||||
"/usr/bin/open",
|
||||
["--hide", "--background", "-a", appBundle],
|
||||
{ env: environment },
|
||||
);
|
||||
return (
|
||||
(await waitForAbortableDelay(HOPPER_BACKGROUND_STARTUP_MS, signal)) ===
|
||||
"elapsed"
|
||||
@@ -506,13 +499,16 @@ const hopperApplicationBundle = (launcherPath: string): string | undefined => {
|
||||
return extname(candidate) === ".app" ? candidate : undefined;
|
||||
};
|
||||
|
||||
const processIsRunning = async (executablePath: string): Promise<boolean> => {
|
||||
const processIsRunning = async (
|
||||
executablePath: string,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const processes = await execFileOutput("/bin/ps", [
|
||||
"-ax",
|
||||
"-o",
|
||||
"command=",
|
||||
]);
|
||||
const processes = await execFileOutput(
|
||||
"/bin/ps",
|
||||
["-ax", "-o", "command="],
|
||||
{ env: environment },
|
||||
);
|
||||
return processes.stdout
|
||||
.split("\n")
|
||||
.some((command) => command.trim() === executablePath);
|
||||
|
||||
@@ -37,7 +37,7 @@ export const resolveHopperAnalysisProfile = async (
|
||||
options: HopperProfileOptions,
|
||||
): Promise<Result<AnalysisProfileResolution, AnalysisError>> => {
|
||||
if (target.kind !== "executable" && target.kind !== "database")
|
||||
return ok({ profile: null, compatibility: {} });
|
||||
return ok({ profile: null });
|
||||
let machoContainer: "thin" | "fat32" | "fat64" | undefined;
|
||||
if (target.kind === "executable" && target.format === "mach-o") {
|
||||
const header = await readMachoMagic(target.path, options.signal);
|
||||
@@ -67,11 +67,9 @@ export const resolveHopperAnalysisProfile = async (
|
||||
options.loaderArgsOverride.length === 0
|
||||
? derived.value
|
||||
: [...options.loaderArgsOverride];
|
||||
const compatibility = { loaderArgs: [...loaderArgs] };
|
||||
const launcherDigest = await sha256File(options.launcherPath, options.signal);
|
||||
if (!launcherDigest.ok) return launcherDigest;
|
||||
if (launcherDigest.value === undefined)
|
||||
return ok({ profile: null, compatibility });
|
||||
if (launcherDigest.value === undefined) return ok({ profile: null });
|
||||
const provider = {
|
||||
id: options.provider.id,
|
||||
name: options.provider.name,
|
||||
@@ -96,13 +94,9 @@ export const resolveHopperAnalysisProfile = async (
|
||||
options.loaderArgsOverride.length === 0
|
||||
? "derived"
|
||||
: "configured_override",
|
||||
argument_count: loaderArgs.length,
|
||||
arguments_sha256: createHash("sha256")
|
||||
.update(JSON.stringify(loaderArgs))
|
||||
.digest("hex"),
|
||||
arguments: [...loaderArgs],
|
||||
},
|
||||
}),
|
||||
compatibility,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -52,9 +52,12 @@ describe("Hopper shutdown rejection diagnostics", () => {
|
||||
const { logger, logs } = loggerHarness();
|
||||
const result = await cleanupHopperSession({
|
||||
socket: new Socket(),
|
||||
launch: undefined,
|
||||
processSupervisor: undefined,
|
||||
runtimeRoot: undefined,
|
||||
resources: {
|
||||
launch: undefined,
|
||||
processSupervisor: undefined,
|
||||
runtimeRoot: undefined,
|
||||
shutdownConfirmed: false,
|
||||
},
|
||||
activeRequest: null,
|
||||
retainDocument: false,
|
||||
progress: undefined,
|
||||
@@ -88,9 +91,12 @@ describe("Hopper shutdown rejection diagnostics", () => {
|
||||
const methods: string[] = [];
|
||||
const result = await cleanupHopperSession({
|
||||
socket: new Socket(),
|
||||
launch: processCleanupLaunch(),
|
||||
processSupervisor: undefined,
|
||||
runtimeRoot: undefined,
|
||||
resources: {
|
||||
launch: processCleanupLaunch(),
|
||||
processSupervisor: undefined,
|
||||
runtimeRoot: undefined,
|
||||
shutdownConfirmed: false,
|
||||
},
|
||||
activeRequest: null,
|
||||
retainDocument: false,
|
||||
progress: undefined,
|
||||
@@ -141,9 +147,12 @@ it("keeps a prepared backing image when native document closure cannot be confir
|
||||
};
|
||||
const result = await cleanupHopperSession({
|
||||
socket: new Socket(),
|
||||
launch,
|
||||
runtimeRoot,
|
||||
processSupervisor: undefined,
|
||||
resources: {
|
||||
launch,
|
||||
runtimeRoot,
|
||||
processSupervisor: undefined,
|
||||
shutdownConfirmed: false,
|
||||
},
|
||||
activeRequest: null,
|
||||
retainDocument: true,
|
||||
progress: undefined,
|
||||
|
||||
+69
-29
@@ -33,14 +33,20 @@ interface CleanupState {
|
||||
readonly issues: CleanupIssue[];
|
||||
readonly resources: Set<string>;
|
||||
cleanupResult: ProcessCleanupResult | undefined;
|
||||
processStopped: boolean;
|
||||
}
|
||||
|
||||
/** Owned capabilities survive failed cleanup until their release is verified. */
|
||||
export interface HopperOwnedResources {
|
||||
launch: BridgeLaunch | undefined;
|
||||
processSupervisor: ProviderProcessSupervisor | undefined;
|
||||
runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
shutdownConfirmed: boolean;
|
||||
}
|
||||
|
||||
export interface HopperCleanupInput {
|
||||
readonly socket: Socket | undefined;
|
||||
readonly launch: BridgeLaunch | undefined;
|
||||
readonly processSupervisor: ProviderProcessSupervisor | undefined;
|
||||
readonly runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
readonly resources: HopperOwnedResources;
|
||||
readonly activeRequest: HopperRequestActivity | null;
|
||||
readonly retainDocument: boolean;
|
||||
readonly progress: ProgressReporter | undefined;
|
||||
@@ -60,34 +66,55 @@ export const cleanupHopperSession = async (
|
||||
issues: [],
|
||||
resources: new Set(),
|
||||
cleanupResult: undefined,
|
||||
shutdownConfirmed: false,
|
||||
processStopped: input.resources.processSupervisor === undefined,
|
||||
};
|
||||
await report(
|
||||
input.progress,
|
||||
0,
|
||||
input.retainDocument && input.launch?.preparedImagePath === undefined
|
||||
input.retainDocument &&
|
||||
input.resources.launch?.preparedImagePath === undefined
|
||||
? "detaching REA from the Hopper document"
|
||||
: "requesting Hopper document shutdown",
|
||||
);
|
||||
await requestShutdown(input, state);
|
||||
await report(input.progress, 0.35, "releasing Hopper bridge transport");
|
||||
input.releaseTransport(input.socket);
|
||||
if (
|
||||
input.resources.shutdownConfirmed ||
|
||||
input.resources.launch?.providerLifetime !== "external-application"
|
||||
)
|
||||
input.releaseTransport(input.socket);
|
||||
await stopProcess(input, state);
|
||||
recordUnconfirmedDocument(input, state);
|
||||
await report(input.progress, 0.75, "removing Hopper private runtime files");
|
||||
if (
|
||||
input.launch?.preparedImagePath !== undefined &&
|
||||
!state.shutdownConfirmed
|
||||
input.resources.runtimeRoot !== undefined &&
|
||||
(!state.processStopped ||
|
||||
(!input.resources.shutdownConfirmed &&
|
||||
(input.resources.launch?.preparedImagePath !== undefined ||
|
||||
input.resources.launch?.providerLifetime === "external-application")))
|
||||
) {
|
||||
const resource = input.runtimeRoot?.path ?? input.launch.preparedImagePath;
|
||||
const resource = input.resources.runtimeRoot.path;
|
||||
state.resources.add(resource);
|
||||
state.issues.push({
|
||||
resource,
|
||||
reason:
|
||||
"Prepared image retained because native document closure was not confirmed",
|
||||
"Private runtime retained because process or native document closure was not confirmed",
|
||||
});
|
||||
} else {
|
||||
await closeRuntimeRoot(input.runtimeRoot, state);
|
||||
await closeRuntimeRoot(input, state);
|
||||
}
|
||||
if (state.processStopped && input.resources.shutdownConfirmed) {
|
||||
const launch = input.resources.launch;
|
||||
try {
|
||||
await launch?.releaseLease?.();
|
||||
input.resources.launch = undefined;
|
||||
} catch (cause: unknown) {
|
||||
state.resources.add("hopper-lease");
|
||||
state.issues.push({
|
||||
resource: "hopper-lease",
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
});
|
||||
}
|
||||
}
|
||||
return cleanupOutcome(input, state);
|
||||
};
|
||||
@@ -97,6 +124,7 @@ const requestShutdown = async (
|
||||
state: CleanupState,
|
||||
): Promise<void> => {
|
||||
if (
|
||||
input.resources.shutdownConfirmed ||
|
||||
input.socket === undefined ||
|
||||
input.socket.destroyed ||
|
||||
input.activeRequest !== null
|
||||
@@ -112,8 +140,9 @@ const requestShutdown = async (
|
||||
return;
|
||||
}
|
||||
const method =
|
||||
(input.retainDocument && input.launch?.preparedImagePath === undefined) ||
|
||||
input.launch?.shutdownMode === "process-cleanup"
|
||||
(input.retainDocument &&
|
||||
input.resources.launch?.preparedImagePath === undefined) ||
|
||||
input.resources.launch?.shutdownMode === "process-cleanup"
|
||||
? "shutdown"
|
||||
: "shutdown_document";
|
||||
const shutdown = await input
|
||||
@@ -122,23 +151,22 @@ const requestShutdown = async (
|
||||
if (
|
||||
shutdown.ok &&
|
||||
isHopperCleanupRequired(shutdown.value) &&
|
||||
input.launch?.shutdownMode === "process-cleanup"
|
||||
input.resources.launch?.shutdownMode === "process-cleanup"
|
||||
) {
|
||||
state.cleanupResult = await input.launch
|
||||
state.cleanupResult = await input.resources.launch
|
||||
.cleanup()
|
||||
.catch(providerCleanupFailure);
|
||||
if (!state.cleanupResult.cleaned) {
|
||||
state.shutdownConfirmed = await fallbackDocumentShutdown(input);
|
||||
state.cleanupResult = await input.launch
|
||||
.cleanup()
|
||||
.catch(providerCleanupFailure);
|
||||
input.resources.shutdownConfirmed = await fallbackDocumentShutdown(input);
|
||||
}
|
||||
} else if (shutdown.ok) {
|
||||
state.shutdownConfirmed = isHopperShutdownAcknowledgement(shutdown.value);
|
||||
input.resources.shutdownConfirmed = isHopperShutdownAcknowledgement(
|
||||
shutdown.value,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!shutdown.ok ||
|
||||
(!state.shutdownConfirmed && state.cleanupResult === undefined)
|
||||
(!input.resources.shutdownConfirmed && state.cleanupResult === undefined)
|
||||
)
|
||||
input.logger.warn(
|
||||
{
|
||||
@@ -220,7 +248,7 @@ const stopProcess = async (
|
||||
input: HopperCleanupInput,
|
||||
state: CleanupState,
|
||||
): Promise<void> => {
|
||||
const supervisor = input.processSupervisor;
|
||||
const supervisor = input.resources.processSupervisor;
|
||||
if (supervisor === undefined) return;
|
||||
const stopped = await supervisor.stop(
|
||||
state.cleanupResult === undefined
|
||||
@@ -241,10 +269,12 @@ const stopProcess = async (
|
||||
input.logger.info(diagnostic, "Owned Hopper launcher shutdown completed");
|
||||
if (stopped.status !== "incomplete") {
|
||||
if (
|
||||
input.launch?.shutdownMode === "process-cleanup" &&
|
||||
input.resources.launch?.shutdownMode === "process-cleanup" &&
|
||||
stopped.status !== "not-owned"
|
||||
)
|
||||
state.shutdownConfirmed = true;
|
||||
input.resources.shutdownConfirmed = true;
|
||||
state.processStopped = true;
|
||||
input.resources.processSupervisor = undefined;
|
||||
return;
|
||||
}
|
||||
const processGroupId = supervisor.launch.ownership?.processGroupId;
|
||||
@@ -265,8 +295,16 @@ const recordUnconfirmedDocument = (
|
||||
state: CleanupState,
|
||||
): void => {
|
||||
if (
|
||||
(input.socket === undefined && input.launch === undefined) ||
|
||||
state.shutdownConfirmed
|
||||
input.socket === undefined &&
|
||||
state.processStopped &&
|
||||
input.resources.launch?.providerLifetime === "launcher-process"
|
||||
) {
|
||||
// Startup never connected a document; the verified provider lifetime ended.
|
||||
input.resources.shutdownConfirmed = true;
|
||||
}
|
||||
if (
|
||||
(input.socket === undefined && input.resources.launch === undefined) ||
|
||||
input.resources.shutdownConfirmed
|
||||
)
|
||||
return;
|
||||
state.resources.add("hopper-document");
|
||||
@@ -280,11 +318,13 @@ const recordUnconfirmedDocument = (
|
||||
};
|
||||
|
||||
const closeRuntimeRoot = async (
|
||||
runtimeRoot: PrivateRuntimeRoot | undefined,
|
||||
input: HopperCleanupInput,
|
||||
state: CleanupState,
|
||||
): Promise<void> => {
|
||||
const runtimeRoot = input.resources.runtimeRoot;
|
||||
try {
|
||||
await runtimeRoot?.close();
|
||||
input.resources.runtimeRoot = undefined;
|
||||
} catch (cause: unknown) {
|
||||
const resource = runtimeRoot?.path ?? "hopper-runtime-root";
|
||||
state.resources.add(resource);
|
||||
@@ -306,9 +346,9 @@ const cleanupOutcome = (
|
||||
return err(
|
||||
new ProviderCleanupError("hopper", [...state.resources], {
|
||||
issues: cleanupIssueDetails(state.issues),
|
||||
...(input.runtimeRoot === undefined
|
||||
...(input.resources.runtimeRoot === undefined
|
||||
? {}
|
||||
: { runtime_root: input.runtimeRoot.path }),
|
||||
: { runtime_root: input.resources.runtimeRoot.path }),
|
||||
...(input.activeRequest === null
|
||||
? {}
|
||||
: { active_request: activityDetails(input.activeRequest) }),
|
||||
|
||||
+115
-72
@@ -3,7 +3,9 @@ import { access } from "node:fs/promises";
|
||||
import type { Socket } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import { analysisErrorWithCleanupFailure } from "../application/binary/AnalysisClientCleanup.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
HopperCancelledError,
|
||||
@@ -40,7 +42,10 @@ import {
|
||||
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
|
||||
import { hopperOperationStage } from "./HopperOperationStage.js";
|
||||
import type { HopperDiagnostic } from "./HopperDiagnostics.js";
|
||||
import { cleanupHopperSession } from "./HopperCleanup.js";
|
||||
import {
|
||||
cleanupHopperSession,
|
||||
type HopperOwnedResources,
|
||||
} from "./HopperCleanup.js";
|
||||
import {
|
||||
parseHopperServerInfo,
|
||||
type HopperServerInfo,
|
||||
@@ -92,9 +97,12 @@ export class HopperClient {
|
||||
readonly #responses: HopperResponseStream;
|
||||
readonly #logger: Logger;
|
||||
#socket: Socket | undefined;
|
||||
#launch: BridgeLaunch | undefined;
|
||||
#process: ProviderProcessSupervisor | undefined;
|
||||
#runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
readonly #resources: HopperOwnedResources = {
|
||||
launch: undefined,
|
||||
processSupervisor: undefined,
|
||||
runtimeRoot: undefined,
|
||||
shutdownConfirmed: false,
|
||||
};
|
||||
#token: string | undefined;
|
||||
readonly #lineage = new ProviderRunLineage();
|
||||
#nextId = 1;
|
||||
@@ -103,7 +111,7 @@ export class HopperClient {
|
||||
#launcherFailureDiagnostic: HopperStartupFailureDiagnostic | undefined;
|
||||
#operationFailure: OperationFailureRecord | undefined;
|
||||
#startupController: AbortController | undefined;
|
||||
#startPromise: Promise<Result<HopperServerInfo, HopperError>> | undefined;
|
||||
#startPromise: Promise<Result<HopperServerInfo, AnalysisError>> | undefined;
|
||||
#closePromise: Promise<Result<null, AnalysisError>> | undefined;
|
||||
readonly #onSocketData = (chunk: string): void => {
|
||||
this.#responses.push(chunk);
|
||||
@@ -121,7 +129,7 @@ export class HopperClient {
|
||||
};
|
||||
readonly #onSocketClose = (): void => {
|
||||
if (this.#closing) return;
|
||||
const launch = this.#launch;
|
||||
const launch = this.#resources.launch;
|
||||
if (
|
||||
launch?.providerLifetime === "launcher-process" &&
|
||||
this.#launcherExitCode !== undefined
|
||||
@@ -248,9 +256,13 @@ export class HopperClient {
|
||||
}
|
||||
|
||||
/** Launch the bridge once and complete its authenticated health handshake. */
|
||||
start(signal?: AbortSignal): Promise<Result<HopperServerInfo, HopperError>> {
|
||||
start(
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<HopperServerInfo, AnalysisError>> {
|
||||
if (this.#closePromise !== undefined) {
|
||||
return this.#closePromise.then(() => this.start(signal));
|
||||
return this.#closePromise.then((closed) =>
|
||||
closed.ok ? this.start(signal) : closed,
|
||||
);
|
||||
}
|
||||
if (this.#startPromise !== undefined) return this.#startPromise;
|
||||
|
||||
@@ -276,22 +288,7 @@ export class HopperClient {
|
||||
(result) => {
|
||||
release();
|
||||
if (!result.ok) {
|
||||
if (result.error instanceof HopperProcessError)
|
||||
this.#rememberProcessFailure(result.error, []);
|
||||
else if (
|
||||
this.#operationFailure === undefined &&
|
||||
(result.error instanceof HopperTimeoutError ||
|
||||
result.error instanceof HopperStartError)
|
||||
)
|
||||
this.#operationFailure = {
|
||||
state:
|
||||
result.error instanceof HopperTimeoutError
|
||||
? "not_started"
|
||||
: "unknown",
|
||||
exitCode: null,
|
||||
startupFailure: true,
|
||||
requests: [],
|
||||
};
|
||||
this.#rememberStartupFailure(result.error);
|
||||
reset();
|
||||
}
|
||||
},
|
||||
@@ -309,12 +306,17 @@ export class HopperClient {
|
||||
|
||||
async #start(
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<HopperServerInfo, HopperError>> {
|
||||
): Promise<Result<HopperServerInfo, AnalysisError>> {
|
||||
if (isAborted(signal)) return err(new HopperCancelledError());
|
||||
this.#operationFailure = undefined;
|
||||
if (this.#socket !== undefined || this.#runtimeRoot !== undefined) {
|
||||
if (
|
||||
this.#socket !== undefined ||
|
||||
this.#resources.launch !== undefined ||
|
||||
this.#resources.runtimeRoot !== undefined
|
||||
) {
|
||||
return err(new HopperProtocolError("Hopper client is already started"));
|
||||
}
|
||||
this.#resources.shutdownConfirmed = false;
|
||||
const deadline = new ProviderStartupDeadline(
|
||||
this.#options.startupTimeoutMs,
|
||||
signal,
|
||||
@@ -328,9 +330,9 @@ export class HopperClient {
|
||||
|
||||
async #startWithin(
|
||||
deadline: ProviderStartupDeadline,
|
||||
): Promise<Result<HopperServerInfo, HopperError>> {
|
||||
): Promise<Result<HopperServerInfo, AnalysisError>> {
|
||||
try {
|
||||
this.#runtimeRoot = await PrivateRuntimeRoot.create({
|
||||
this.#resources.runtimeRoot = await PrivateRuntimeRoot.create({
|
||||
parent: SESSION_ROOT,
|
||||
prefix: "rea-",
|
||||
});
|
||||
@@ -338,10 +340,9 @@ export class HopperClient {
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
if (deadline.signal.aborted) {
|
||||
await this.#cleanup();
|
||||
return err(startupInterruption(deadline));
|
||||
return this.#startupFailure(startupInterruption(deadline));
|
||||
}
|
||||
const socketPath = join(this.#runtimeRoot.path, "bridge.sock");
|
||||
const socketPath = join(this.#resources.runtimeRoot.path, "bridge.sock");
|
||||
this.#token = randomBytes(32).toString("hex");
|
||||
this.#lineage.reset();
|
||||
this.#launcherExitCode = undefined;
|
||||
@@ -353,7 +354,7 @@ export class HopperClient {
|
||||
> = await this.#options.launcher
|
||||
.launch(
|
||||
{
|
||||
directory: this.#runtimeRoot.path,
|
||||
directory: this.#resources.runtimeRoot.path,
|
||||
socketPath,
|
||||
token: this.#token,
|
||||
runId,
|
||||
@@ -362,22 +363,42 @@ export class HopperClient {
|
||||
)
|
||||
.catch((cause: unknown) => err(new HopperStartError({ cause })));
|
||||
if (!launched.ok) {
|
||||
await this.#cleanup();
|
||||
return deadline.signal.aborted
|
||||
? err(startupInterruption(deadline))
|
||||
: launched;
|
||||
return this.#startupFailure(
|
||||
deadline.signal.aborted
|
||||
? startupInterruption(deadline)
|
||||
: launched.error,
|
||||
);
|
||||
}
|
||||
this.#launch = launched.value;
|
||||
this.#resources.launch = launched.value;
|
||||
this.#attachLauncher(launched.value);
|
||||
const ownership = launched.value.ownership;
|
||||
if (ownership !== undefined) {
|
||||
try {
|
||||
await writeFileAtomic(
|
||||
join(this.#resources.runtimeRoot.path, "ownership.json"),
|
||||
`${JSON.stringify({
|
||||
run_id: runId,
|
||||
pid: ownership.leaderPid,
|
||||
process_group_id: ownership.processGroupId,
|
||||
parent_pid: process.pid,
|
||||
launcher: launched.value.launcherCommand ?? null,
|
||||
created_at: new Date().toISOString(),
|
||||
})}\n`,
|
||||
{ encoding: "utf8", mode: 0o600 },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return this.#startupFailure(new HopperStartError({ cause }));
|
||||
}
|
||||
}
|
||||
const connected = await this.#connect(socketPath, deadline);
|
||||
if (!connected.ok) {
|
||||
await this.#cleanup();
|
||||
return connected;
|
||||
return this.#startupFailure(connected.error);
|
||||
}
|
||||
const remainingMs = deadline.remainingMs();
|
||||
if (remainingMs <= 0) {
|
||||
await this.#cleanup();
|
||||
return err(new HopperTimeoutError(this.#options.startupTimeoutMs));
|
||||
return this.#startupFailure(
|
||||
new HopperTimeoutError(this.#options.startupTimeoutMs),
|
||||
);
|
||||
}
|
||||
const health = await this.#request(
|
||||
"health",
|
||||
@@ -388,17 +409,45 @@ export class HopperClient {
|
||||
},
|
||||
);
|
||||
if (!health.ok) {
|
||||
await this.#cleanup();
|
||||
return deadline.signal.aborted
|
||||
? err(startupInterruption(deadline))
|
||||
: health;
|
||||
return this.#startupFailure(
|
||||
deadline.signal.aborted ? startupInterruption(deadline) : health.error,
|
||||
);
|
||||
}
|
||||
const parsed = parseHopperServerInfo(health.value, runId);
|
||||
if (parsed.ok) await this.#lineage.observe(this.#launch);
|
||||
else await this.#cleanup();
|
||||
if (!parsed.ok) return this.#startupFailure(parsed.error);
|
||||
await this.#lineage.observe(this.#resources.launch);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async #startupFailure(
|
||||
primary: AnalysisError,
|
||||
): Promise<Result<never, AnalysisError>> {
|
||||
this.#rememberStartupFailure(primary);
|
||||
const closed = await this.#cleanup();
|
||||
return err(
|
||||
closed.ok
|
||||
? primary
|
||||
: analysisErrorWithCleanupFailure(primary, closed.error, "open_binary"),
|
||||
);
|
||||
}
|
||||
|
||||
#rememberStartupFailure(failure: AnalysisError): void {
|
||||
if (failure instanceof HopperProcessError)
|
||||
this.#rememberProcessFailure(failure, []);
|
||||
else if (
|
||||
this.#operationFailure === undefined &&
|
||||
(failure instanceof HopperTimeoutError ||
|
||||
failure instanceof HopperStartError)
|
||||
)
|
||||
this.#operationFailure = {
|
||||
state:
|
||||
failure instanceof HopperTimeoutError ? "not_started" : "unknown",
|
||||
exitCode: null,
|
||||
startupFailure: true,
|
||||
requests: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Invoke one declared operation, returning timeout and cancellation as values. */
|
||||
async callTool(
|
||||
name: string,
|
||||
@@ -426,13 +475,8 @@ export class HopperClient {
|
||||
: result;
|
||||
}
|
||||
|
||||
/** Stop the bridge, settle outstanding requests, and remove session artifacts. */
|
||||
close(): Promise<void> {
|
||||
return this.closeWithOutcome().then(() => undefined);
|
||||
}
|
||||
|
||||
/** Stop the bridge and report whether every owned resource was verified clean. */
|
||||
closeWithOutcome(
|
||||
close(
|
||||
options: HopperClientCloseOptions = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
const starting = this.#startPromise;
|
||||
@@ -445,7 +489,7 @@ export class HopperClient {
|
||||
}
|
||||
|
||||
async #close(
|
||||
starting: Promise<Result<HopperServerInfo, HopperError>> | undefined,
|
||||
starting: Promise<Result<HopperServerInfo, AnalysisError>> | undefined,
|
||||
controller: AbortController | undefined,
|
||||
options: HopperClientCloseOptions,
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
@@ -470,9 +514,7 @@ export class HopperClient {
|
||||
try {
|
||||
return await cleanupHopperSession({
|
||||
socket: this.#socket,
|
||||
launch: this.#launch,
|
||||
processSupervisor: this.#process,
|
||||
runtimeRoot: this.#runtimeRoot,
|
||||
resources: this.#resources,
|
||||
activeRequest: this.#requests.activity(),
|
||||
progress: options.progress,
|
||||
logger: this.#logger,
|
||||
@@ -487,14 +529,14 @@ export class HopperClient {
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
this.#socket = undefined;
|
||||
this.#process = undefined;
|
||||
this.#launch = undefined;
|
||||
this.#runtimeRoot = undefined;
|
||||
this.#token = undefined;
|
||||
this.#responses.reset();
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
if (this.#socket?.destroyed === true) this.#socket = undefined;
|
||||
|
||||
if (this.#socket === undefined) this.#token = undefined;
|
||||
if (this.#socket === undefined) this.#responses.reset();
|
||||
if (this.#resources.processSupervisor === undefined) {
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
}
|
||||
this.#closing = false;
|
||||
}
|
||||
}
|
||||
@@ -509,12 +551,12 @@ export class HopperClient {
|
||||
if (this.#closing) return err(new HopperProcessError(null));
|
||||
if (
|
||||
this.#launcherExitCode !== undefined &&
|
||||
this.#launch !== undefined &&
|
||||
(this.#launch.providerLifetime === "launcher-process" ||
|
||||
this.#resources.launch !== undefined &&
|
||||
(this.#resources.launch.providerLifetime === "launcher-process" ||
|
||||
this.#launcherExitCode !== 0)
|
||||
) {
|
||||
const failure = await this.#launcherStartupFailure(
|
||||
this.#launch.providerLifetime === "launcher-process",
|
||||
this.#resources.launch.providerLifetime === "launcher-process",
|
||||
this.#launcherExitCode,
|
||||
deadline,
|
||||
);
|
||||
@@ -558,13 +600,14 @@ export class HopperClient {
|
||||
"not_started",
|
||||
"launch",
|
||||
this.#launcherOutcome(
|
||||
(await this.#process?.waitForOutputClose(0)) ?? false,
|
||||
(await this.#resources.processSupervisor?.waitForOutputClose(0)) ??
|
||||
false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#launcherOutcome(outputClosed: boolean): HopperLauncherOutcome | undefined {
|
||||
const snapshot = this.#process?.snapshot();
|
||||
const snapshot = this.#resources.processSupervisor?.snapshot();
|
||||
const token = this.#token;
|
||||
if (snapshot === undefined) return undefined;
|
||||
const redact = (text: string): string =>
|
||||
@@ -586,7 +629,7 @@ export class HopperClient {
|
||||
exitCode: number | null,
|
||||
deadline: ProviderStartupDeadline,
|
||||
): Promise<HopperError> {
|
||||
const process = this.#process;
|
||||
const process = this.#resources.processSupervisor;
|
||||
// Descendants may inherit the helper's pipes. Bound drainage independently
|
||||
// from readiness, and report whether producer output actually closed.
|
||||
const outputClosed =
|
||||
@@ -700,7 +743,7 @@ export class HopperClient {
|
||||
}
|
||||
|
||||
#attachLauncher(launch: BridgeLaunch): void {
|
||||
this.#process = new ProviderProcessSupervisor(launch, {
|
||||
this.#resources.processSupervisor = new ProviderProcessSupervisor(launch, {
|
||||
onDiagnostic: (event) => this.#onLauncherDiagnostic(launch, event),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ describe("Hopper provider capabilities", () => {
|
||||
it("declines DOS MZ targets with a provider-specific support reason", () => {
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw new Error("expected valid configuration");
|
||||
const provider = new HopperProvider(config.value, silentLogger);
|
||||
const provider = new HopperProvider(config.value, silentLogger, {});
|
||||
expect(
|
||||
provider.inspectTargetSupport({
|
||||
path: "/tmp/legacy.exe",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { accessSync, constants } from "node:fs";
|
||||
|
||||
@@ -17,7 +18,7 @@ import type { AppConfig } from "../config.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { HopperApplicationLauncher } from "./BridgeLauncher.js";
|
||||
import {
|
||||
hopperLoaderArgsForTarget,
|
||||
@@ -42,6 +43,8 @@ const IDENTITY = HOPPER_PROVIDER_IDENTITY;
|
||||
|
||||
/** Concrete analysis provider backed by REA's private Hopper bridge. */
|
||||
export class HopperProvider implements AnalysisProviderCandidate {
|
||||
private readonly environment: Readonly<NodeJS.ProcessEnv>;
|
||||
|
||||
/**
|
||||
* Host platform, injected so availability and launch-mode decisions can be
|
||||
* exercised for any host rather than only the machine running the suite.
|
||||
@@ -51,8 +54,11 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
constructor(
|
||||
private readonly config: AppConfig,
|
||||
private readonly logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
private readonly platform: NodeJS.Platform = process.platform,
|
||||
) {}
|
||||
) {
|
||||
this.environment = snapshotEnvironment(environment, platform);
|
||||
}
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
return IDENTITY;
|
||||
@@ -159,7 +165,7 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
};
|
||||
const preparation = profile?.parameters.prepared_image;
|
||||
const parsedImage =
|
||||
@@ -178,7 +184,7 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
};
|
||||
const preparedImage = parsedImage?.data;
|
||||
const container =
|
||||
@@ -194,11 +200,12 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
if (!derivedLoaderArgs.ok)
|
||||
return {
|
||||
execute: () => Promise.resolve(err(derivedLoaderArgs.error)),
|
||||
close: () => Promise.resolve(),
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
};
|
||||
const executionProvider = profile?.provider ?? IDENTITY;
|
||||
const client = new HopperClient({
|
||||
launcher: new HopperApplicationLauncher({
|
||||
environment: this.environment,
|
||||
launcherPath: this.config.hopperLauncherPath,
|
||||
targetPath: target.path,
|
||||
targetKind: target.kind,
|
||||
@@ -300,13 +307,9 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
];
|
||||
},
|
||||
operationHealthSnapshot: () => client.operationHealth(),
|
||||
closeWithOutcome: async (options) => {
|
||||
close: async (options) => {
|
||||
await regexSearch.close();
|
||||
return client.closeWithOutcome(options);
|
||||
},
|
||||
close: async () => {
|
||||
await regexSearch.close();
|
||||
await client.close();
|
||||
return client.close(options);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ describe("Hopper provider discovery", () => {
|
||||
const provider = (launcherPath: string): HopperProvider => {
|
||||
const config = parseConfig({ HOPPER_LAUNCHER_PATH: launcherPath });
|
||||
if (!config.ok) throw config.error;
|
||||
return new HopperProvider(config.value, silentLogger);
|
||||
return new HopperProvider(config.value, silentLogger, {});
|
||||
};
|
||||
|
||||
const databaseTarget = (): BinaryTarget => ({
|
||||
|
||||
@@ -19,11 +19,6 @@ const MATCHING_DEADLINE_MS = 5_000;
|
||||
const inputSchema = z.strictObject({
|
||||
...analysisSearchInput,
|
||||
mode: z.literal("regex"),
|
||||
document: z.string().nullish(),
|
||||
case_sensitive: z
|
||||
.boolean()
|
||||
.nullish()
|
||||
.transform((value) => value ?? false),
|
||||
});
|
||||
const replySchema = z.discriminatedUnion("status", [
|
||||
z.strictObject({
|
||||
@@ -104,7 +99,9 @@ export class HopperRegexSearch {
|
||||
};
|
||||
const inventory = await this.client.callTool(
|
||||
operation === "search_strings" ? "list_strings" : "list_procedures",
|
||||
input.data.document == null ? {} : { document: input.data.document },
|
||||
input.data.document === undefined
|
||||
? {}
|
||||
: { document: input.data.document },
|
||||
inventoryOptions,
|
||||
);
|
||||
if (!inventory.ok) return inventory;
|
||||
|
||||
@@ -149,10 +149,10 @@ const tryAcquireLease = async (
|
||||
lease: {
|
||||
release: async () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
// Node removes a bound Unix socket on close. A second unlink here
|
||||
// could remove a new owner's socket bound after that close.
|
||||
await closeServer(server);
|
||||
released = true;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -40,6 +40,7 @@ export type LinuxPrivateDisplayProbeRunner = (
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy,
|
||||
options: {
|
||||
readonly helperPath: string;
|
||||
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly timeoutMs: number;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
@@ -61,6 +62,7 @@ export type LinuxPrivateDisplaySelection =
|
||||
/** Probe the exact Xvfb boundary and select the least-privileged viable strategy. */
|
||||
export const selectLinuxPrivateDisplayStrategy = async (options: {
|
||||
readonly helperPath: string;
|
||||
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly timeoutMs?: number;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly runProbe?: LinuxPrivateDisplayProbeRunner;
|
||||
@@ -113,6 +115,9 @@ export const runLinuxPrivateDisplayProbe: LinuxPrivateDisplayProbeRunner =
|
||||
arguments: command.arguments,
|
||||
runId: randomUUID(),
|
||||
expectedCommand: null,
|
||||
...(options.environment === undefined
|
||||
? {}
|
||||
: { hostEnvironment: options.environment }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
@@ -183,6 +188,7 @@ const evaluatedProbe = async (
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy,
|
||||
options: {
|
||||
readonly helperPath: string;
|
||||
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
timeoutMs: number,
|
||||
@@ -202,6 +208,9 @@ const evaluatedProbe = async (
|
||||
try {
|
||||
processResult = await runner(strategy, {
|
||||
helperPath: options.helperPath,
|
||||
...(options.environment === undefined
|
||||
? {}
|
||||
: { environment: options.environment }),
|
||||
timeoutMs,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user