Files
reverse-engineering-anything/scripts/verify-real-hopper-deadlines.mjs
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

170 lines
5.7 KiB
JavaScript

import assert from "node:assert/strict";
import { copyFile, mkdtemp, realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { firstProcedureAddress } from "./lib/real-hopper-assertions.mjs";
import { HopperDeadlineCleanup } from "./lib/hopper-deadline-cleanup.mjs";
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
import { ArtifactResourceScope } from "../dist/artifacts/ArtifactResourceScope.js";
import { AnalysisCleanupLease } from "../dist/artifacts/AnalysisCleanupLease.js";
import { resolveHopperAnalysisProfile } from "../dist/hopper/HopperAnalysisProfile.js";
import { HopperApplicationLauncher } from "../dist/hopper/BridgeLauncher.js";
import { HopperClient } from "../dist/hopper/HopperClient.js";
import { HOPPER_PROVIDER_IDENTITY } from "../dist/hopper/HopperProviderMetadata.js";
import { loadRealHopperFixtureTargets } from "./lib/real-hopper-fixture.mjs";
// These options belong to the native client, below the CLI/MCP tool surface.
assert.equal(
process.platform,
"darwin",
"This lane requires native macOS Hopper",
);
const fixtures = await loadRealHopperFixtureTargets(
process.env.REA_HOPPER_CONFORMANCE_MANIFEST_PATH ??
"build/conformance/manifest.json",
);
const root = await realpath(
await mkdtemp(join(tmpdir(), "rea-hopper-deadlines-")),
);
const target = join(root, "deadline-fixture");
const profileResources = new ArtifactResourceScope();
const cleanupOwner = new HopperDeadlineCleanup(root, profileResources);
const profileResourceScope = {
retain: (owner, resource) =>
profileResources.retain({
kind: "lease",
resource,
lease: AnalysisCleanupLease.forCloseOwner(owner, resource),
}),
run: (operation) => profileResources.run(operation),
};
let client;
let primaryFailure;
let operationFailed = false;
try {
await copyFile(fixtures.primary.path, target);
const parsed = await parseBinaryTarget(target);
if (!parsed.ok) throw parsed.error;
const launcherPath =
process.env.HOPPER_LAUNCHER_PATH ??
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
const resolved = await resolveHopperAnalysisProfile(parsed.value, {
launcherPath,
loaderArgsOverride: [],
provider: HOPPER_PROVIDER_IDENTITY,
resourceScope: profileResourceScope,
});
if (!resolved.ok) throw resolved.error;
const profile = resolved.value.profile;
assert.notEqual(
profile,
null,
"This lane requires a resolved Hopper launcher profile",
);
const loaderArgs = profile.parameters.loader?.arguments;
assert.ok(
Array.isArray(loaderArgs) &&
loaderArgs.every((argument) => typeof argument === "string"),
"The Hopper profile must report its effective loader arguments",
);
const image = profile.parameters.prepared_image;
client = new HopperClient({
launcher: new HopperApplicationLauncher({
environment: process.env,
launcherPath,
targetPath: target,
targetKind: "executable",
launchMode: "native",
loaderArgs,
...(image === undefined
? {}
: {
preparedImage: { image, sourceSha256: parsed.value.sha256 },
}),
bridgeScriptPath: fileURLToPath(
new URL("../bridge/hopper_bridge.py", import.meta.url),
),
}),
});
const call = async (name, args = {}) => {
const result = await client.callTool(name, args);
if (!result.ok) throw result.error;
return result.value;
};
const procedures = await call("list_procedures");
const address = firstProcedureAddress(procedures);
const original = await call("comment", { address });
for (const timeoutMs of [0, 10]) {
const result = await client.callTool(
"set_comment",
{ address, comment: "expired mutation must never reach Hopper" },
{
timeoutMs,
...(timeoutMs === 0
? {}
: {
progress: {
report: () => {
const started = performance.now();
while (performance.now() - started < 30) {
// Delay the timer callback beyond the admitted deadline.
}
return Promise.resolve();
},
},
}),
},
);
assert.equal(result.ok, false);
assert.equal(result.error._tag, "HopperTimeoutError");
assert.equal(result.error.providerState, "not_started");
assert.equal(await call("comment", { address }), original);
assert.equal(client.requestActivity(), null);
}
const active = await client.callTool(
"analyze_function",
{ procedure: address },
{ timeoutMs: 1 },
);
if (!active.ok) assert.equal(active.error._tag, "HopperTimeoutError");
const activityAfterDeadline = client.requestActivity();
await call("health");
assert.equal(client.requestActivity(), null);
const closed = await client.close();
if (!closed.ok) throw closed.error;
console.log(
JSON.stringify(
{
expiredNativeMutations: "not_applied",
delayedProgress: "deadline_enforced",
activeAnalysis: active.ok
? "completed_within_deadline"
: "caller_timed_out",
nativeWorkRetained: activityAfterDeadline !== null,
lateReplyRecovery: "passed",
cleanShutdown: true,
},
null,
2,
),
);
} catch (cause) {
operationFailed = true;
primaryFailure = cause;
throw cause;
} finally {
try {
if (client !== undefined) cleanupOwner.setClient(client);
await cleanupOwner.close();
} catch (cleanupFailure) {
throw operationFailed
? new AggregateError(
[primaryFailure, cleanupFailure],
"Hopper verification and cleanup failed",
)
: cleanupFailure;
}
}