fix: harden structured configuration comparisons (#467)

* refactor(process): split ownership observation helpers

* fix: compare structured configuration canonically

* test(conformance): tolerate Markdown line wrapping

* refactor: name caught values explicitly
This commit is contained in:
morluto
2026-08-09 11:58:01 +08:00
committed by GitHub
parent 8f229ede70
commit 6901edc05d
15 changed files with 319 additions and 199 deletions
+2 -2
View File
@@ -260,11 +260,11 @@ export const importReferenceSource = async (
try {
return ok(createHistoricalSourceGraph(input));
} catch (error) {
} catch (cause: unknown) {
return err(
failure(
"parse",
error instanceof Error ? error.message : "Graph failed validation",
cause instanceof Error ? cause.message : "Graph failed validation",
),
);
}
+6 -2
View File
@@ -1,6 +1,7 @@
import { constants as fsConstants } from "node:fs";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import canonicalize from "canonicalize";
import { z } from "zod";
import writeFileAtomic from "write-file-atomic";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
@@ -257,8 +258,11 @@ const parseObject = (text: string): Record<string, unknown> =>
objectSchema.parse(JSON.parse(text));
const isMissing = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
const sameConfiguration = (left: unknown, right: unknown): boolean =>
JSON.stringify(left) === JSON.stringify(right);
const sameConfiguration = (left: unknown, right: unknown): boolean => {
const encodedLeft = canonicalize(left);
const encodedRight = canonicalize(right);
return encodedLeft !== undefined && encodedLeft === encodedRight;
};
const preserveConfigBackup = async (
source: string,
@@ -218,7 +218,7 @@ const executeStep = async (input: {
const remaining = scenario.limits.max_duration_ms - elapsed;
if (remaining <= 0) throw new Error("Scenario duration limit reached");
await session.perform(action, remaining, signal);
} catch (cause) {
} catch (cause: unknown) {
status = requestCancelled() ? "cancelled" : "failed";
error = session.redactError(cause);
}
@@ -376,7 +376,7 @@ export class PlaywrightBrowserScenarioProvider
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
try {
return ok(await runScenario(this.factory, scenario, options));
} catch (cause) {
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
return err(
new ProviderAdapterError(
+4 -4
View File
@@ -138,9 +138,9 @@ export const openPlaywrightScenarioBrowser = async (
);
await configureAttachedEnvironment(target.context, target.page, scenario);
return { ...target, browser, profilePath: undefined };
} catch (error) {
} catch (cause: unknown) {
await browser.close();
throw error;
throw cause;
}
}
@@ -174,9 +174,9 @@ export const openPlaywrightScenarioBrowser = async (
}
const page = context.pages()[0] ?? (await context.newPage());
return { context, page, browser, profilePath };
} catch (error) {
} catch (cause: unknown) {
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
throw error;
throw cause;
}
};
+4 -4
View File
@@ -297,11 +297,11 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
remaining(),
options.signal,
);
} catch (error) {
} catch (cause: unknown) {
void opening
.then((lateOpened) => closePlaywrightScenarioBrowser(lateOpened))
.catch(() => undefined);
throw error;
throw cause;
}
try {
await withPlaywrightExecutionBoundary(
@@ -336,9 +336,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
options.signal,
);
return session;
} catch (error) {
} catch (cause: unknown) {
await closePlaywrightScenarioBrowser(opened);
throw error;
throw cause;
}
}
+16 -6
View File
@@ -1,3 +1,4 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import type { ProcessCapture } from "./processCapture.js";
@@ -126,6 +127,11 @@ const filesystemObservations = (
},
];
const sameJsonValue = (left: unknown, right: unknown): boolean => {
const encodedLeft = canonicalize(left);
return encodedLeft !== undefined && encodedLeft === canonicalize(right);
};
/** Canonical observations for one process-comparison dimension. */
export const processDimensionObservations = (
capture: ProcessCapture,
@@ -153,7 +159,7 @@ const classifyCollection = (
left: readonly unknown[],
right: readonly unknown[],
): ComparisonStatus => {
if (JSON.stringify(left) === JSON.stringify(right)) return "unchanged";
if (sameJsonValue(left, right)) return "unchanged";
if (left.length === 0) return "added";
if (right.length === 0) return "removed";
return "changed";
@@ -194,7 +200,7 @@ const firstCollectionDivergence = (
for (let index = 0; index < length; index += 1) {
const leftValue = left[index] ?? null;
const rightValue = right[index] ?? null;
if (JSON.stringify(leftValue) === JSON.stringify(rightValue)) continue;
if (sameJsonValue(leftValue, rightValue)) continue;
return {
status: "found",
dimension,
@@ -366,8 +372,10 @@ const compareDimensions = (
exit:
hasUnknown(left, "exit") || hasUnknown(right, "exit")
? "unknown"
: JSON.stringify({ exit: left.exit, settlement: left.settlement }) ===
JSON.stringify({ exit: right.exit, settlement: right.settlement })
: sameJsonValue(
{ exit: left.exit, settlement: left.settlement },
{ exit: right.exit, settlement: right.settlement },
)
? "unchanged"
: "changed",
filesystem: classify(
@@ -410,8 +418,10 @@ export const compareProcessCaptures = (
trace: compareProcessTraces(left, right, options.traceSpecification),
};
}
const sameNormalization =
JSON.stringify(left.normalization) === JSON.stringify(right.normalization);
const sameNormalization = sameJsonValue(
left.normalization,
right.normalization,
);
const exactDimensions = compareDimensions(left, right, sameNormalization);
const trace =
options.traceSpecification === undefined
+2 -2
View File
@@ -305,11 +305,11 @@ const parseWithBabel = (
plugins,
});
return { ast, parseState: "parsed" };
} catch (error) {
} catch (cause: unknown) {
return {
ast: undefined,
parseState: "unknown",
reason: error instanceof Error ? error.message : "Parse failed",
reason: cause instanceof Error ? cause.message : "Parse failed",
};
}
};
+24 -173
View File
@@ -2,7 +2,12 @@ import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";
import { matchesOwnedProcessCommand } from "./ProcessCommandIdentity.js";
import {
observeOwnedProcessGroupWithHost,
observeOwnedProcessLineageWithHost,
} from "./ProcessOwnershipObservation.js";
import { launcherIdentityFailure } from "./ProcessOwnershipIdentity.js";
import { descendantsOf, liveProcesses } from "./ProcessOwnershipProcessTree.js";
const execFileAsync = promisify(execFile);
@@ -223,12 +228,9 @@ export const cleanupOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessCleanupResult> => {
let processes: readonly ProcessTableEntry[];
try {
processes = liveProcesses(await host.listProcesses());
} catch {
const processes = await readLiveProcessTable(host);
if (processes === undefined)
return { cleaned: false, reason: "process table could not be inspected" };
}
const plan = await createOwnedCleanupPlan(ownership, processes, host);
if ("cleaned" in plan) return plan;
let signaled = false;
@@ -258,12 +260,9 @@ export const verifyNoTokenOwnedProcesses = async (
runId: string,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessCleanupResult> => {
let processes: readonly ProcessTableEntry[];
try {
processes = liveProcesses(await host.listProcesses());
} catch {
const processes = await readLiveProcessTable(host);
if (processes === undefined)
return { cleaned: false, reason: "process table could not be inspected" };
}
const scan = await scanTokenOwnedProcesses(processes, runId, host);
if (scan.failures.length > 0) return cleanupValidationFailure(scan.failures);
return scan.owned.length === 0
@@ -271,6 +270,16 @@ export const verifyNoTokenOwnedProcesses = async (
: { cleaned: false, reason: "token-owned process remained after cleanup" };
};
const readLiveProcessTable = async (
host: ProcessOwnershipHost,
): Promise<readonly ProcessTableEntry[] | undefined> => {
try {
return liveProcesses(await host.listProcesses());
} catch {
return undefined;
}
};
interface OwnedCleanupPlan {
readonly signalOrder: readonly number[];
}
@@ -346,25 +355,6 @@ const createOwnedCleanupPlan = async (
};
};
const launcherIdentityFailure = (
launcher: ProcessTableEntry,
ownership: OwnedProcessGroup,
): string | null => {
if (launcher.processGroupId !== ownership.processGroupId)
return "owned launcher process-group identity did not match";
if (
ownership.expectedParentPid !== undefined &&
launcher.parentPid !== ownership.expectedParentPid
)
return "owned launcher parent identity did not match";
if (
ownership.expectedCommand !== undefined &&
!matchesOwnedProcessCommand(launcher.command, ownership.expectedCommand)
)
return `owned launcher command identity did not match (observed=${launcher.command}; expected=${ownership.expectedCommand})`;
return null;
};
const revalidateOwnedProcessGroup = async (
processGroupId: number,
ownership: OwnedProcessGroup,
@@ -472,39 +462,8 @@ const scanTokenOwnedProcesses = async (
export const observeOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessGroupObservation> => {
let members: readonly ProcessTableEntry[];
try {
members = (await host.listProcesses()).filter(
({ processGroupId }) => processGroupId === ownership.processGroupId,
);
} catch {
return {
state: "unverifiable",
reason: "process group could not be inspected",
};
}
const liveMembers = liveProcesses(members);
if (liveMembers.length === 0) return { state: "empty" };
for (const member of liveMembers) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return {
state: "unverifiable",
reason: "process ownership did not match",
};
} catch {
return {
state: "unverifiable",
reason: "process ownership could not be revalidated",
};
}
}
return { state: "alive" };
};
): Promise<ProcessGroupObservation> =>
observeOwnedProcessGroupWithHost(ownership, host);
/**
* Record the live launcher and descendant lineage after run-token validation.
@@ -516,113 +475,5 @@ export const observeOwnedProcessGroup = async (
export const observeOwnedProcessLineage = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessLineageObservation> => {
let processes: readonly ProcessTableEntry[];
try {
processes = liveProcesses(await host.listProcesses());
} catch {
return unavailableLineage(
ownership,
"process table could not be inspected",
);
}
const launcher = processes.find(({ pid }) => pid === ownership.leaderPid);
if (launcher === undefined)
return unavailableLineage(ownership, "owned launcher is not live");
if (launcher.processGroupId !== ownership.processGroupId)
return unavailableLineage(
ownership,
"owned launcher process-group identity did not match",
);
if (
ownership.expectedParentPid !== undefined &&
launcher.parentPid !== ownership.expectedParentPid
)
return unavailableLineage(
ownership,
"owned launcher parent identity did not match",
);
if (
ownership.expectedCommand !== undefined &&
!matchesOwnedProcessCommand(launcher.command, ownership.expectedCommand)
)
return unavailableLineage(
ownership,
`owned launcher command identity did not match (observed=${launcher.command}; expected=${ownership.expectedCommand})`,
);
const descendants = descendantsOf(launcher.pid, processes);
for (const member of [launcher, ...descendants]) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return unavailableLineage(
ownership,
"process lineage contains an unowned or PID-reused process",
);
} catch {
return unavailableLineage(
ownership,
"process ownership could not be revalidated",
);
}
}
return {
status: "verified",
observedAt: new Date().toISOString(),
lineage: {
schemaVersion: 1,
runId: ownership.runId,
launcherPid: launcher.pid,
launcherParentPid: launcher.parentPid,
processGroupId: launcher.processGroupId,
descendants: descendants
.sort((left, right) => left.pid - right.pid)
.map(({ pid, parentPid, processGroupId }) => ({
pid,
parentPid,
processGroupId,
})),
},
};
};
const descendantsOf = (
launcherPid: number,
processes: readonly ProcessTableEntry[],
): ProcessTableEntry[] => {
const childrenByParent = new Map<number, ProcessTableEntry[]>();
for (const process of processes) {
const siblings = childrenByParent.get(process.parentPid) ?? [];
siblings.push(process);
childrenByParent.set(process.parentPid, siblings);
}
const descendants: ProcessTableEntry[] = [];
const pending = [...(childrenByParent.get(launcherPid) ?? [])];
const visited = new Set<number>([launcherPid]);
for (const process of pending) {
if (visited.has(process.pid)) continue;
visited.add(process.pid);
descendants.push(process);
pending.push(...(childrenByParent.get(process.pid) ?? []));
}
return descendants;
};
const unavailableLineage = (
ownership: OwnedProcessGroup,
reason: string,
): Extract<ProcessLineageObservation, { readonly status: "unavailable" }> => ({
status: "unavailable",
observedAt: new Date().toISOString(),
runId: ownership.runId,
launcherPid: ownership.leaderPid,
processGroupId: ownership.processGroupId,
reason,
});
const liveProcesses = (
members: readonly ProcessTableEntry[],
): readonly ProcessTableEntry[] =>
members.filter(({ state }) => !state.startsWith("Z"));
): Promise<ProcessLineageObservation> =>
observeOwnedProcessLineageWithHost(ownership, host);
+25
View File
@@ -0,0 +1,25 @@
import { matchesOwnedProcessCommand } from "./ProcessCommandIdentity.js";
import type {
OwnedProcessGroup,
ProcessTableEntry,
} from "./ProcessOwnership.js";
/** Compare a live launcher against the identity committed at process launch. */
export const launcherIdentityFailure = (
launcher: ProcessTableEntry,
ownership: OwnedProcessGroup,
): string | null => {
if (launcher.processGroupId !== ownership.processGroupId)
return "owned launcher process-group identity did not match";
if (
ownership.expectedParentPid !== undefined &&
launcher.parentPid !== ownership.expectedParentPid
)
return "owned launcher parent identity did not match";
if (
ownership.expectedCommand !== undefined &&
!matchesOwnedProcessCommand(launcher.command, ownership.expectedCommand)
)
return `owned launcher command identity did not match (observed=${launcher.command}; expected=${ownership.expectedCommand})`;
return null;
};
+117
View File
@@ -0,0 +1,117 @@
import { launcherIdentityFailure } from "./ProcessOwnershipIdentity.js";
import { descendantsOf, liveProcesses } from "./ProcessOwnershipProcessTree.js";
import type {
OwnedProcessGroup,
ProcessGroupObservation,
ProcessLineageObservation,
ProcessOwnershipHost,
ProcessTableEntry,
} from "./ProcessOwnership.js";
/** Observe one group without signaling it, failing closed on identity doubt. */
export const observeOwnedProcessGroupWithHost = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost,
): Promise<ProcessGroupObservation> => {
let members: readonly ProcessTableEntry[];
try {
members = (await host.listProcesses()).filter(
({ processGroupId }) => processGroupId === ownership.processGroupId,
);
} catch {
return {
state: "unverifiable",
reason: "process group could not be inspected",
};
}
const liveMembers = liveProcesses(members);
if (liveMembers.length === 0) return { state: "empty" };
for (const member of liveMembers) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return {
state: "unverifiable",
reason: "process ownership did not match",
};
} catch {
return {
state: "unverifiable",
reason: "process ownership could not be revalidated",
};
}
}
return { state: "alive" };
};
/** Record the live launcher and descendant lineage after run-token validation. */
export const observeOwnedProcessLineageWithHost = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost,
): Promise<ProcessLineageObservation> => {
let processes: readonly ProcessTableEntry[];
try {
processes = liveProcesses(await host.listProcesses());
} catch {
return unavailableLineage(
ownership,
"process table could not be inspected",
);
}
const launcher = processes.find(({ pid }) => pid === ownership.leaderPid);
if (launcher === undefined)
return unavailableLineage(ownership, "owned launcher is not live");
const identityFailure = launcherIdentityFailure(launcher, ownership);
if (identityFailure !== null)
return unavailableLineage(ownership, identityFailure);
const descendants = descendantsOf(launcher.pid, processes);
for (const member of [launcher, ...descendants]) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return unavailableLineage(
ownership,
"process lineage contains an unowned or PID-reused process",
);
} catch {
return unavailableLineage(
ownership,
"process ownership could not be revalidated",
);
}
}
return {
status: "verified",
observedAt: new Date().toISOString(),
lineage: {
schemaVersion: 1,
runId: ownership.runId,
launcherPid: launcher.pid,
launcherParentPid: launcher.parentPid,
processGroupId: launcher.processGroupId,
descendants: descendants
.sort((left, right) => left.pid - right.pid)
.map(({ pid, parentPid, processGroupId }) => ({
pid,
parentPid,
processGroupId,
})),
},
};
};
const unavailableLineage = (
ownership: OwnedProcessGroup,
reason: string,
): Extract<ProcessLineageObservation, { readonly status: "unavailable" }> => ({
status: "unavailable",
observedAt: new Date().toISOString(),
runId: ownership.runId,
launcherPid: ownership.leaderPid,
processGroupId: ownership.processGroupId,
reason,
});
@@ -0,0 +1,30 @@
import type { ProcessTableEntry } from "./ProcessOwnership.js";
/** Exclude process-table entries that the operating system has already reaped. */
export const liveProcesses = (
members: readonly ProcessTableEntry[],
): readonly ProcessTableEntry[] =>
members.filter(({ state }) => !state.startsWith("Z"));
/** Return every live-table descendant of a launcher in breadth-first order. */
export const descendantsOf = (
launcherPid: number,
processes: readonly ProcessTableEntry[],
): ProcessTableEntry[] => {
const childrenByParent = new Map<number, ProcessTableEntry[]>();
for (const process of processes) {
const siblings = childrenByParent.get(process.parentPid) ?? [];
siblings.push(process);
childrenByParent.set(process.parentPid, siblings);
}
const descendants: ProcessTableEntry[] = [];
const pending = [...(childrenByParent.get(launcherPid) ?? [])];
const visited = new Set<number>([launcherPid]);
for (const process of pending) {
if (visited.has(process.pid)) continue;
visited.add(process.pid);
descendants.push(process);
pending.push(...(childrenByParent.get(process.pid) ?? []));
}
return descendants;
};
@@ -105,6 +105,32 @@ describe("agent lifecycle", () => {
).toEqual({ status: "unchanged" });
});
it("does not rewrite an equivalent Codex registration with reordered environment keys", async () => {
const home = await createTestTempDirectory("rea-toml-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
await mkdir(dirname(configPath), { recursive: true });
await writeFile(
configPath,
`[mcp_servers.rea]\ncommand = "rea"\nargs = ["mcp"]\nstartup_timeout_sec = 30\n\n[mcp_servers.rea.env]\nJAVA_HOME = "/opt/jdk-21"\nHOPPER_LAUNCHER_PATH = "/Hopper Path"\nGHIDRA_INSTALL_DIR = "/opt/ghidra"\n`,
);
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toEqual({ status: "unchanged" });
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it("updates a symlink target without replacing the TOML config symlink", async () => {
const home = await createTestTempDirectory("rea-toml-symlink-");
roots.push(home);
@@ -139,6 +139,26 @@ it("classifies missing observations as unknown and one-sided evidence as added",
expect(unknown.status).toBe("unknown");
});
it("treats equivalent normalization records as equal regardless of member order", () => {
const capture = emptyCapture();
expect(
compareProcessCaptures(capture, {
...capture,
normalization: {
patterns: [],
time_bucket_ms: 10,
ports: true,
pids: true,
paths: true,
},
}),
).toMatchObject({
status: "unchanged",
first_divergence: { status: "none" },
});
});
it("compares raw terminal chunks even when rendered states agree", () => {
const capture = {
schema_version: 4 as const,
@@ -114,6 +114,39 @@ describe("JSON client configuration transaction", () => {
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it("does not rewrite an equivalent configuration with reordered environment keys", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(
configPath,
`${JSON.stringify({
mcpServers: {
rea: {
env: {
JAVA_HOME: "/usr/lib/jvm/jdk-21",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
},
args: ["-y", pinnedPackage, "mcp"],
command: "npx",
},
},
})}\n`,
);
expect(
await configureJsonClient(
{ name: "cursor", configPath },
{
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
},
),
).toEqual({ status: "unchanged" });
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
});
describe("JSON client configuration migration and provider paths", () => {
+8 -4
View File
@@ -55,6 +55,9 @@ const toolCountsFromReadme = (content: string, path: string): number[] => {
throw new Error(`Missing tool-family inventory table in ${path}`);
};
const normalizedProse = (content: string): string =>
content.replace(/\s+/gu, " ").trim();
describe("localized README product facts", () => {
it.each(readmes)(
"keeps commands and requirements aligned in %s",
@@ -92,18 +95,19 @@ describe("localized README product facts", () => {
expect(content).toContain("--install-hopper");
expect(content).toContain("docs/installation.md");
expect(content).toContain("You do not need both");
expect(content).toContain(
expect(normalizedProse(content)).toContain(
"npx -y rea-agents@latest setup` once to repair registrations",
);
});
it("documents stale bootstrap recovery and explicit rollback", async () => {
const content = await readFile(resolve("docs/installation.md"), "utf8");
expect(content).toContain("before REA plans or writes configuration");
expect(content).toContain(
const prose = normalizedProse(content);
expect(prose).toContain("before REA plans or writes configuration");
expect(prose).toContain(
"npm exec --yes --package=rea-agents@2.4.0 -- rea setup",
);
expect(content).toContain(
expect(prose).toContain(
"pin persistent MCP registrations to the exact version",
);
});