Merge remote-tracking branch 'origin/main' into fix/mcp-error-schema-delivery

This commit is contained in:
N0zoM1z0
2026-10-09 13:06:26 +00:00
52 changed files with 1279 additions and 613 deletions
+3 -1
View File
@@ -57,7 +57,9 @@ without this lane reports Windows native controls as unavailable.
deduplicated using Windows ordinal comparison, preserving their native Unicode
semantics and caller-selected values.
- Cleanup walks locked directory objects, removes files by handle, and unlinks
reparse entries without traversing their targets. Normal close, cancellation,
reparse entries without traversing their targets. Failed removal retains the
root and ancestor leases for retry; a partially removed runtime accepts only
cleanup, and its registry entry remains until removal succeeds. Normal close, cancellation,
startup failure, and timeout release provider resources. Abrupt owner death
kills the owned job; it can leave private runtime files for later operator
cleanup and does not claim transactional deletion after a crash.
+1
View File
@@ -86,6 +86,7 @@ struct Runtime : Resource {
std::vector<Handle> parents;
Handle directory;
std::vector<Handle> immutableFiles;
bool closing = false;
// Main-thread admission is single-flight; only the accepted copy owns the
// atomic cancellation flag consumed by its async worker. ERROR_BUSY rejects
// another copy before it can reset that flag or replace pending ownership.
+6 -4
View File
@@ -328,14 +328,11 @@ static void disposeSnapshot(Runtime& root, Handle& file, const std::wstring& pat
void closeRuntime(Runtime& root) {
if (root.closed) return;
root.closing = true;
// Windows keeps the bearer descriptor and snapshot leases until this owner
// cleanup. POSIX removes its consumed descriptor earlier. Abrupt owner death
// closes process jobs but cannot run this walk, so private files can remain.
root.immutableFiles.clear();
struct ReleaseRuntime {
Runtime& root;
~ReleaseRuntime() { root.directory.reset(); root.parents.clear(); root.closed = true; }
} release{root};
// Each traversed directory stays locked against replacement. Reparse entries
// are unlinked as objects; their targets are never enumerated or deleted.
struct Frame {
@@ -380,6 +377,10 @@ void closeRuntime(Runtime& root) {
frames.push_back(std::make_unique<Frame>(std::move(child), path));
else dispose(child.get(), path);
}
// Failed walks retain the root's identity leases for a later cleanup retry.
root.directory.reset();
root.parents.clear();
root.closed = true;
}
struct SnapshotWork {
@@ -528,6 +529,7 @@ napi_value filesystemCall(napi_env env, const std::wstring& operation, const std
return result;
}
auto& root = static_cast<Runtime&>(resource(env, args[0], Kind::Runtime));
require(!root.closing || operation == L"runtime_close", "Runtime cleanup is pending", root.path, ERROR_BUSY);
if (operation == L"runtime_snapshot_cancel") { root.snapshotCancelled.store(true); return null(env); }
require(!root.snapshotPending, "Runtime snapshot is still pending", root.path, ERROR_BUSY);
// Reject overlapping operations before snapshot() resets cancellation. The
+60 -1
View File
@@ -3,6 +3,7 @@
import assert from "node:assert/strict";
import { execFileSync, spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { once } from "node:events";
import {
access,
mkdir,
@@ -28,7 +29,7 @@ const { requireWindowsNativeAuthority } = await import(
pathToFileURL(join(packageRoot, "dist/windows/WindowsNativeLoader.js"))
);
const native = requireWindowsNativeAuthority();
const { WindowsPrivateRuntime } = await import(
const { WindowsPrivateRuntime, windowsPrivateRuntime } = await import(
pathToFileURL(join(packageRoot, "dist/windows/WindowsPrivateRuntime.js"))
);
const workspace = await mkdtemp(join(tmpdir(), "rea-native-conformance-"));
@@ -338,6 +339,64 @@ try {
} finally {
await readbackRuntime.close();
}
const retryRuntime = WindowsPrivateRuntime.create(
workspace,
"cleanup-retry-",
);
const heldPath = join(retryRuntime.observation.path, "snapshot.bin");
await retryRuntime.snapshot(source, "snapshot.bin");
const holder = spawn(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
"$ErrorActionPreference = 'Stop'; " +
"$stream = [IO.File]::Open($env:REA_CLEANUP_HELD_PATH, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite); " +
"try { [Console]::WriteLine('ready'); [Console]::In.ReadLine() | Out-Null } " +
"finally { $stream.Dispose() }",
],
{
env: { ...process.env, REA_CLEANUP_HELD_PATH: heldPath },
stdio: ["pipe", "pipe", "pipe"],
},
);
const holderClosed = once(holder, "close");
void holderClosed.catch(() => undefined);
try {
const [ready] = await once(holder.stdout, "data", {
signal: AbortSignal.timeout(15_000),
});
assert.equal(String(ready).trim(), "ready");
await assert.rejects(
retryRuntime.close(),
/owned cleanup object|Delete owned object/u,
);
assert.equal(
windowsPrivateRuntime(retryRuntime.observation.path),
retryRuntime,
);
assert.equal(await exists(heldPath), true);
assert.throws(
() => retryRuntime.writeFile("after-close.txt", "forbidden"),
/cleanup is pending/u,
);
holder.stdin.end("\n");
const [exitCode] = await holderClosed;
assert.equal(exitCode, 0);
await retryRuntime.close();
await retryRuntime.close();
assert.equal(await exists(retryRuntime.observation.path), false);
assert.throws(
() => windowsPrivateRuntime(retryRuntime.observation.path),
/No native private runtime/u,
);
report.controls.cleanupFailureRetainsOwnershipForRetry = true;
} finally {
holder.kill();
await holderClosed.catch(() => undefined);
await retryRuntime.close();
}
report.controls = {
...report.controls,
protectedDaclReadback: true,
@@ -59,7 +59,7 @@ const failedEntry = (
return {
path: entry.path,
kind: "symlink",
target: "<unreadable>",
target: null,
target_state: "unreadable",
classifications,
limitations: [limitation],
+9 -2
View File
@@ -221,7 +221,7 @@ class ArtifactClient implements AnalysisClient {
}),
);
} catch (cause: unknown) {
return err(translateFailure(operation, cause));
return err(translateArtifactFailure(operation, cause));
}
}
@@ -378,7 +378,8 @@ const isArtifactOperation = (
operation as (typeof ARTIFACT_ANALYSIS_OPERATIONS)[number],
);
const translateFailure = (
/** Translate one artifact boundary failure while retaining cleanup evidence. */
export const translateArtifactFailure = (
operation: ArtifactAnalysisOperation,
cause: unknown,
): AnalysisError => {
@@ -388,6 +389,12 @@ const translateFailure = (
cause.reason,
cause.details,
cause.message,
{
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
...(cause.partialObservation === undefined
? {}
: { partialObservation: cause.partialObservation }),
},
);
// Caller-selection and unsupported-target failures are already typed; keep
// their correction details instead of reducing them to an I/O failure.
+64 -1
View File
@@ -1,6 +1,15 @@
import type { Readable } from "node:stream";
import type { ArtifactCommand } from "../domain/artifactGraph.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import type {
AnalysisCleanupObservation,
AnalysisPartialObservation,
} from "../domain/analysisErrorBase.js";
export interface ArtifactReaderFailureOptions extends ErrorOptions {
readonly cleanup?: AnalysisCleanupObservation;
readonly partialObservation?: AnalysisPartialObservation;
}
/** Archive-neutral entry metadata. Reader adapters never choose output paths. */
export interface ArtifactEntry {
@@ -33,6 +42,9 @@ export interface ArtifactReader {
/** Typed adapter failure translated at provider boundary. */
export class ArtifactReaderFailure extends Error {
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly partialObservation: AnalysisPartialObservation | undefined;
constructor(
readonly reason:
| "cancelled"
@@ -43,7 +55,7 @@ export class ArtifactReaderFailure extends Error {
| "path"
| "unavailable",
message: string,
options?: ErrorOptions,
options?: ArtifactReaderFailureOptions,
readonly details?: Readonly<{
logicalPath: string;
declaredSha256: string | null;
@@ -53,5 +65,56 @@ export class ArtifactReaderFailure extends Error {
) {
super(message, options);
this.name = "ArtifactReaderFailure";
this.cleanup = options?.cleanup;
this.partialObservation = options?.partialObservation;
}
/** Preserve the primary failure while attaching cleanup and any complete observation. */
static withCleanup(
cause: unknown,
cleanup: AnalysisCleanupObservation,
partialObservation?: AnalysisPartialObservation,
): ArtifactReaderFailure {
const primary =
cause instanceof ArtifactReaderFailure
? cause
: new ArtifactReaderFailure("io", errorMessage(cause), { cause });
const mergedObservation = partialObservation ?? primary.partialObservation;
return new ArtifactReaderFailure(
primary.reason,
primary.message,
{
cause: primary,
cleanup: combineCleanup(primary.cleanup, cleanup),
...(mergedObservation === undefined
? {}
: { partialObservation: mergedObservation }),
},
primary.details,
);
}
/** Give otherwise opaque cleanup failures a concrete owned resource. */
static cleanupObservation(
cause: unknown,
resource: string,
): AnalysisCleanupObservation {
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return cause.cleanup;
return { reason: errorMessage(cause), resources: [resource] };
}
}
const combineCleanup = (
primary: AnalysisCleanupObservation | undefined,
cleanup: AnalysisCleanupObservation,
): AnalysisCleanupObservation =>
primary === undefined || primary === cleanup
? cleanup
: {
reason: `${primary.reason}; ${cleanup.reason}`,
resources: [...new Set([...primary.resources, ...cleanup.resources])],
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
+18 -5
View File
@@ -188,7 +188,18 @@ export class NativeDmgArtifactReader implements ArtifactReader {
throw new ArtifactReaderFailure(
"unavailable",
`DMG detach or mount-root cleanup failed for ${JSON.stringify(this.path)}: ${failureMessage(detachFailure)}`,
{ cause: detachFailure },
{
cause: detachFailure,
cleanup: {
reason: failureMessage(detachFailure),
resources: [
...this.#devices.map((device) => `DMG device ${device}`),
...(this.#mountRoot === undefined
? []
: [`DMG mount root ${this.#mountRoot}`]),
],
},
},
);
}
@@ -298,10 +309,12 @@ export class NativeDmgArtifactReader implements ArtifactReader {
cleanupFailure = cleanupCause;
}
if (cleanupFailure !== undefined)
throw new ArtifactReaderFailure(
"unavailable",
`DMG attach failed and cleanup could not detach every device: ${failureMessage(cause)}; cleanup: ${failureMessage(cleanupFailure)}`,
{ cause: new AggregateError([cause, cleanupFailure]) },
throw ArtifactReaderFailure.withCleanup(
cause,
ArtifactReaderFailure.cleanupObservation(
cleanupFailure,
`DMG mount root ${this.#mountRoot ?? this.path}`,
),
);
throw cause;
}
+17 -2
View File
@@ -208,7 +208,12 @@ export class SafeOutputTree {
/** Remove only this operation's unsealed tree and verify absence. */
async rollback(): Promise<SafeOutputCleanup> {
if (this.#published) return structuredClone(this.#cleanup);
await rm(this.#outputRoot, { recursive: true, force: true });
let removalFailure: unknown;
try {
await rm(this.#outputRoot, { recursive: true, force: true });
} catch (cause: unknown) {
removalFailure = cause;
}
const absent = await isAbsent(this.#outputRoot);
this.#cleanup = absent
? { status: "complete", residualPaths: [] }
@@ -219,7 +224,17 @@ export class SafeOutputTree {
if (!absent)
throw new ArtifactReaderFailure(
"integrity",
"Extraction output cleanup could not be verified",
`Extraction output cleanup could not be verified${removalFailure === undefined ? "" : `: ${removalFailure instanceof Error ? removalFailure.message : String(removalFailure)}`}`,
{
cause: removalFailure,
cleanup: {
reason:
removalFailure instanceof Error
? removalFailure.message
: "Extraction output root remains after rollback",
resources: [this.#outputRoot],
},
},
);
return structuredClone(this.#cleanup);
}
+48 -8
View File
@@ -1,5 +1,6 @@
import { lstat, realpath } from "node:fs/promises";
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
import { AsarArtifactReader } from "../AsarArtifactReader.js";
import {
@@ -136,10 +137,12 @@ const materializeSelection = async ({
selected.map((item) => [item.occurrence.logical_path, item]),
);
const reader = await createReader(sourcePath, input);
const output = await SafeOutputTree.create(input.outputRoot);
let output: SafeOutputTree | undefined;
let readerCloseAttempted = false;
let readerClosed = false;
const extracted: ExtractedOccurrence[] = [];
try {
output = await SafeOutputTree.create(input.outputRoot);
const materialized: SelectedOccurrence[] = [];
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
@@ -171,10 +174,11 @@ const materializeSelection = async ({
});
materialized.push(selectedItem);
}
readerCloseAttempted = true;
await reader.close();
readerClosed = true;
extracted.sort((left, right) =>
left.relative_path.localeCompare(right.relative_path, "en"),
compareCodePoints(left.relative_path, right.relative_path),
);
const result = createExtractionResult(
input,
@@ -185,12 +189,48 @@ const materializeSelection = async ({
await output.commit();
return result;
} catch (cause: unknown) {
if (!readerClosed)
await reader.close().catch((cause: unknown) => {
// best-effort cleanup: reader close must not mask the extraction failure.
void cause;
const cleanupFailures: {
readonly cause: unknown;
readonly resource: string;
}[] = [];
if (readerCloseAttempted && !readerClosed)
cleanupFailures.push({
cause,
resource: `artifact reader for ${sourcePath}`,
});
await output.rollback();
if (!readerCloseAttempted) {
try {
readerCloseAttempted = true;
await reader.close();
} catch (cleanupCause: unknown) {
cleanupFailures.push({
cause: cleanupCause,
resource: `artifact reader for ${sourcePath}`,
});
}
}
if (output !== undefined) {
try {
await output.rollback();
} catch (cleanupCause: unknown) {
cleanupFailures.push({
cause: cleanupCause,
resource: input.outputRoot,
});
}
}
if (cleanupFailures.length > 0) {
const observations = cleanupFailures.map(
({ cause: cleanupCause, resource }) =>
ArtifactReaderFailure.cleanupObservation(cleanupCause, resource),
);
throw ArtifactReaderFailure.withCleanup(cause, {
reason: observations.map(({ reason }) => reason).join("; "),
resources: [
...new Set(observations.flatMap(({ resources }) => resources)),
],
});
}
throw cause;
}
};
@@ -205,7 +245,7 @@ const createExtractionResult = (
source_manifest_id: inventory.manifest.manifest_id,
selected_occurrence_ids: selected
.map(({ occurrence }) => occurrence.occurrence_id)
.sort((left, right) => left.localeCompare(right)),
.sort(compareCodePoints),
files_sha256: canonicalDigest(extracted, "Artifact"),
output_root_alias: "$OUTPUT_ROOT" as const,
};
+42 -15
View File
@@ -45,6 +45,7 @@ import {
export const scanCanonicalArtifactInventory = async (
path: string,
options: ArtifactInventoryOptions = {},
readerFactory: typeof createReader = createReader,
): Promise<ArtifactInventorySnapshot> => {
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
const metadata = await lstat(path);
@@ -52,33 +53,59 @@ export const scanCanonicalArtifactInventory = async (
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(createReadStream(path), options.signal);
const reader = await createReader(
const reader = await readerFactory(
path,
rootFormat,
options.environment ?? {},
options.signal,
);
let outcome:
| {
readonly kind: "completed";
readonly snapshot: ArtifactInventorySnapshot;
}
| { readonly kind: "failed"; readonly cause: unknown };
try {
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
options.signal,
integrity,
);
return await buildInventorySnapshot({
path,
metadata,
rootFormat,
rootDigest,
reader,
signal: options.signal,
nodes,
occurrences,
pendingContradictions,
});
} finally {
await reader?.close();
outcome = {
kind: "completed",
snapshot: await buildInventorySnapshot({
path,
metadata,
rootFormat,
rootDigest,
reader,
signal: options.signal,
nodes,
occurrences,
pendingContradictions,
}),
};
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
try {
await reader?.close();
} catch (cleanupCause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupCause,
`artifact reader for ${path}`,
);
const primary = outcome.kind === "failed" ? outcome.cause : cleanupCause;
throw ArtifactReaderFailure.withCleanup(
primary,
cleanup,
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.snapshot;
};
interface SnapshotBuildInput {
@@ -1,10 +1,11 @@
// Fake-backed composition coverage; real browser verification lives in
// `npm run verify:browser`.
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";
import { PlaywrightBrowserScenarioProvider } from "./PlaywrightBrowserScenarioProvider.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import { PlaywrightScenarioBrowserCleanupOwner } from "./PlaywrightScenarioBrowser.js";
import {
browserScenarioSchema,
type BrowserScenario,
@@ -318,3 +319,56 @@ describe("PlaywrightBrowserScenarioProvider", () => {
expect(session.closeCalls).toBe(1);
});
});
it("shares concurrent close and retries browser cleanup after failure", async () => {
const browserClose = vi
.fn<() => Promise<void>>()
.mockRejectedValueOnce(new Error("browser close failed"))
.mockResolvedValue(undefined);
const removeProfile = vi
.fn<() => Promise<void>>()
.mockResolvedValue(undefined);
const finishEvents = vi
.fn<() => Promise<void>>()
.mockResolvedValue(undefined);
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: browserClose,
removeProfile,
});
const first = cleanup.close(finishEvents);
const concurrent = cleanup.close(finishEvents);
await expect(first).rejects.toMatchObject({ reason: "cleanup_failed" });
await expect(concurrent).rejects.toMatchObject({ reason: "cleanup_failed" });
expect(browserClose).toHaveBeenCalledTimes(1);
expect(removeProfile).not.toHaveBeenCalled();
expect(finishEvents).toHaveBeenCalledTimes(1);
await expect(cleanup.close(finishEvents)).resolves.toBeUndefined();
await expect(cleanup.close(finishEvents)).resolves.toBeUndefined();
expect(browserClose).toHaveBeenCalledTimes(2);
expect(removeProfile).toHaveBeenCalledTimes(1);
expect(finishEvents).toHaveBeenCalledTimes(1);
});
it("keeps failed event finalization failed across cleanup retries", async () => {
const finishEvents = vi
.fn<() => Promise<void>>()
.mockRejectedValue(new Error("event finalization failed"));
const closeBrowser = vi
.fn<() => Promise<void>>()
.mockResolvedValue(undefined);
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser,
removeProfile: undefined,
});
await expect(cleanup.close(finishEvents)).rejects.toMatchObject({
reason: "cleanup_failed",
});
await expect(cleanup.close(finishEvents)).rejects.toMatchObject({
reason: "cleanup_failed",
});
expect(finishEvents).toHaveBeenCalledTimes(1);
expect(closeBrowser).toHaveBeenCalledTimes(1);
});
+13 -15
View File
@@ -2,8 +2,8 @@ import { afterEach, expect, it, vi } from "vitest";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import {
closePlaywrightScenarioBrowser,
openPlaywrightScenarioBrowser,
PlaywrightScenarioBrowserCleanupOwner,
} from "./PlaywrightScenarioBrowser.js";
afterEach(() => vi.unstubAllEnvs());
@@ -42,23 +42,21 @@ it("passes the selected environment to the actual browser launch boundary", asyn
it("returns cancellation instead of success when an attached browser hangs on close", async () => {
const controller = new AbortController();
let closeStarted = false;
const closing = closePlaywrightScenarioBrowser(
{
browser: {
close: () => {
closeStarted = true;
return new Promise<void>(() => undefined);
},
},
context: { close: async () => undefined },
profilePath: undefined,
let resolveCloseStarted: () => void = () => undefined;
const closeStarted = new Promise<void>((resolve) => {
resolveCloseStarted = resolve;
});
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => {
resolveCloseStarted();
return new Promise<void>(() => undefined);
},
controller.signal,
);
removeProfile: undefined,
});
const closing = cleanup.close(undefined, controller.signal);
await closeStarted;
controller.abort();
expect(closeStarted).toBe(true);
await expect(closing).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "cleanup_failed",
+162 -43
View File
@@ -10,6 +10,7 @@ import {
} from "playwright-core";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
@@ -20,12 +21,98 @@ export interface OpenedScenarioBrowser {
readonly page: Page;
readonly browser: Browser;
readonly profilePath: string | undefined;
readonly cleanup: PlaywrightScenarioBrowserCleanupOwner;
}
interface CloseableScenarioBrowser {
readonly context: Pick<BrowserContext, "close">;
readonly browser: Pick<Browser, "close">;
readonly profilePath: string | undefined;
/** Provider actions retained until the owned browser and profile are released. */
export interface PlaywrightScenarioCleanupResources {
readonly closeBrowser: () => Promise<void>;
readonly removeProfile: (() => Promise<void>) | undefined;
}
/** Owns one browser connection and optional private profile through cleanup retries. */
export class PlaywrightScenarioBrowserCleanupOwner {
#browserClosed = false;
#profileRemoved: boolean;
#closePromise: Promise<void> | undefined;
#eventFinalizationPromise: Promise<void> | undefined;
/** Keep the narrow provider actions needed to release one opened browser. */
constructor(private readonly resources: PlaywrightScenarioCleanupResources) {
this.#profileRemoved = resources.removeProfile === undefined;
}
close(
finishEvents?: () => Promise<void>,
signal?: AbortSignal,
): Promise<void> {
const cleanup = this.#closePromise ?? this.#closeResources(finishEvents);
if (this.#closePromise === undefined) {
this.#closePromise = cleanup;
void cleanup.catch(() => {
if (this.#closePromise === cleanup) this.#closePromise = undefined;
});
}
return this.#awaitCleanup(cleanup, signal);
}
async #awaitCleanup(
cleanup: Promise<void>,
signal?: AbortSignal,
): Promise<void> {
try {
await withPlaywrightExecutionBoundary(() => cleanup, 1_000, signal);
} catch (cause: unknown) {
throw new BrowserObservationError(OPERATION, "cleanup_failed", {
cause,
cleanup: {
reason: cause instanceof Error ? cause.message : String(cause),
resources: [
"browser_transport",
...(this.resources.removeProfile === undefined
? []
: ["browser_profile"]),
],
},
});
}
}
async #closeResources(finishEvents?: () => Promise<void>): Promise<void> {
const failures: unknown[] = [];
const eventFinalization = (this.#eventFinalizationPromise ??=
Promise.resolve().then(async () => {
await finishEvents?.();
}));
try {
await eventFinalization;
} catch (cause: unknown) {
failures.push(cause);
}
if (!this.#browserClosed) {
try {
await this.resources.closeBrowser();
this.#browserClosed = true;
} catch (cause: unknown) {
failures.push(cause);
}
}
if (
this.#browserClosed &&
!this.#profileRemoved &&
this.resources.removeProfile !== undefined
) {
try {
await this.resources.removeProfile();
this.#profileRemoved = true;
} catch (cause: unknown) {
failures.push(cause);
}
}
if (failures.length === 1) throw failures[0];
if (failures.length > 1)
throw new AggregateError(failures, "Browser session cleanup failed");
}
}
const allowedBrowserEnvironment = (
@@ -54,7 +141,6 @@ const allowedBrowserEnvironment = (
),
);
};
const findConnectedPage = async (
browser: Browser,
targetId: string,
@@ -105,6 +191,41 @@ const configureAttachedEnvironment = async (
}
};
/** Preserve an operation failure while reporting any incomplete cleanup. */
export const failBrowserScenarioOperation = async (
cleanup: () => Promise<void>,
primaryFailure: unknown,
fallbackCleanupResources: readonly string[] = ["browser_transport"],
): Promise<never> => {
try {
await cleanup();
} catch (cleanupFailure: unknown) {
const cleanupDetails =
cleanupFailure instanceof AnalysisError &&
cleanupFailure.cleanup !== undefined
? cleanupFailure.cleanup
: {
reason:
cleanupFailure instanceof Error
? cleanupFailure.message
: String(cleanupFailure),
resources:
cleanupFailure instanceof AnalysisError
? cleanupFailure.cleanupResources
: fallbackCleanupResources,
};
throw new BrowserObservationError(OPERATION, "cleanup_failed", {
cause: new AggregateError(
[primaryFailure, cleanupFailure],
"Browser scenario operation and cleanup both failed",
{ cause: primaryFailure },
),
cleanup: cleanupDetails,
});
}
throw primaryFailure;
};
/** Launch or attach using the caller-selected environment and browser engine. */
export const openPlaywrightScenarioBrowser = async (
scenario: BrowserScenario,
@@ -119,23 +240,32 @@ export const openPlaywrightScenarioBrowser = async (
scenario.browser.cdp_endpoint,
{ timeout: 0 },
);
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => browser.close(),
removeProfile: undefined,
});
try {
const target = await findConnectedPage(
browser,
scenario.browser.target_id,
);
await configureAttachedEnvironment(target.context, target.page, scenario);
return { ...target, browser, profilePath: undefined };
return {
...target,
browser,
profilePath: undefined,
cleanup,
};
} catch (cause: unknown) {
await browser.close();
throw cause;
return failBrowserScenarioOperation(() => cleanup.close(), cause);
}
}
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
await chmod(profilePath, 0o700);
let context: BrowserContext;
try {
const context = await launcher.launchPersistentContext(profilePath, {
await chmod(profilePath, 0o700);
context = await launcher.launchPersistentContext(profilePath, {
executablePath: resolve(scenario.browser.executable_path),
headless: scenario.browser.headless,
acceptDownloads: false,
@@ -155,42 +285,31 @@ export const openPlaywrightScenarioBrowser = async (
handleSIGTERM: false,
timeout: 0,
});
const browser = context.browser();
if (browser === null) {
await context.close();
throw new BrowserObservationError(OPERATION, "protocol_error");
}
const page = context.pages()[0] ?? (await context.newPage());
return { context, page, browser, profilePath };
} catch (cause: unknown) {
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
throw cause;
return failBrowserScenarioOperation(
() => rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
cause,
["browser_profile"],
);
}
};
export const closePlaywrightScenarioBrowser = async (
{ context, browser, profilePath }: CloseableScenarioBrowser,
signal?: AbortSignal,
): Promise<void> => {
const cleanup = (async () => {
try {
// In connect mode Playwright's Browser.close disconnects its CDP client;
// it does not close the externally owned browser process.
if (profilePath === undefined) await browser.close();
else await context.close();
} finally {
if (profilePath !== undefined)
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
}
})();
// best-effort cleanup: the bounded execution boundary below observes the
// same cleanup promise; this early attachment only prevents unhandled rejection.
void cleanup.catch(() => undefined);
// The shared execution boundary rejects cancellation/timeouts instead of
// returning a successful capture whose browser or profile may still exist.
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => context.close(),
removeProfile: () =>
rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
});
try {
await withPlaywrightExecutionBoundary(() => cleanup, 1_000, signal);
const browser = context.browser();
if (browser === null)
throw new BrowserObservationError(OPERATION, "protocol_error");
const page = context.pages()[0] ?? (await context.newPage());
return {
context,
page,
browser,
profilePath,
cleanup,
};
} catch (cause: unknown) {
throw new BrowserObservationError(OPERATION, "cleanup_failed", { cause });
return failBrowserScenarioOperation(() => cleanup.close(), cause);
}
};
+15 -20
View File
@@ -11,7 +11,7 @@ import type {
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import {
closePlaywrightScenarioBrowser,
failBrowserScenarioOperation,
openPlaywrightScenarioBrowser,
type OpenedScenarioBrowser,
} from "./PlaywrightScenarioBrowser.js";
@@ -103,10 +103,8 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly product = "Chromium";
readonly version: string;
readonly initialUrl: string;
private closed = false;
private readonly secrets: BrowserScenarioSecrets;
private readonly eventCapture: PlaywrightScenarioEvents;
private readonly signal: AbortSignal | undefined;
private constructor(
private readonly opened: OpenedScenarioBrowser,
@@ -114,7 +112,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly mode: BrowserScenario["browser"]["mode"];
readonly secrets: BrowserScenarioSecrets;
readonly eventCapture: PlaywrightScenarioEvents;
readonly signal?: AbortSignal;
},
) {
this.mode = options.mode;
@@ -122,7 +119,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
options.mode === "launch" ? "provider-owned" : "external";
this.secrets = options.secrets;
this.eventCapture = options.eventCapture;
this.signal = options.signal;
this.version = opened.browser.version();
this.initialUrl = opened.page.url();
}
@@ -141,6 +137,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
throw new BrowserObservationError(OPERATION, "secret_unavailable");
const opening = openPlaywrightScenarioBrowser(scenario, environment);
let opened: OpenedScenarioBrowser;
let events: PlaywrightScenarioEvents | undefined;
try {
opened = await withPlaywrightExecutionBoundary(
() => opening,
@@ -150,7 +147,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
} catch (cause: unknown) {
void opening
.then((lateOpened) =>
closePlaywrightScenarioBrowser(lateOpened, options.signal),
lateOpened.cleanup.close(undefined, options.signal),
)
.catch((cause: unknown) => {
// best-effort cleanup: late-open cleanup must not mask the boundary failure.
@@ -164,7 +161,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
undefined,
options.signal,
);
const events = new PlaywrightScenarioEvents({
events = new PlaywrightScenarioEvents({
page: opened.page,
context: opened.context,
ownsContext: scenario.browser.mode === "launch",
@@ -177,7 +174,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
mode: scenario.browser.mode,
secrets,
eventCapture: events,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
await withPlaywrightExecutionBoundary(
() =>
@@ -190,8 +186,16 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
);
return session;
} catch (cause: unknown) {
await closePlaywrightScenarioBrowser(opened, options.signal);
throw cause;
return failBrowserScenarioOperation(
() =>
opened.cleanup.close(
events === undefined
? undefined
: () => events?.finish() ?? Promise.resolve(),
options.signal,
),
cause,
);
}
}
@@ -260,16 +264,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
}
async close() {
if (this.closed)
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
this.closed = true;
try {
await this.eventCapture.finish();
} finally {
await closePlaywrightScenarioBrowser(this.opened, this.signal);
}
await this.opened.cleanup.close(() => this.eventCapture.finish());
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
@@ -103,16 +103,3 @@ export const SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE = {
};
export { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "./javascriptExportShapeComparisonExample.js";
/** Full-Evidence compatibility fixture used by pure domain and adapter tests. */
export const JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE = {
application: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
seed: TRACE_SEED,
direction: "both" as const,
};
/** Full-Evidence compatibility comparison fixture. */
export const JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE = {
left: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
right: reconciliationEvidence,
};
+2 -2
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { traceJavaScriptSemanticsRequestSchema } from "./javascript/applicationWorkflowInputContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE } from "./javascript/javascriptApplicationWorkflowExamples.js";
import { JAVASCRIPT_FEATURE_TRACE_EXAMPLE } from "./javascript/javascriptApplicationWorkflowExamples.js";
import {
MANAGED_APPLICATION_GRAPH_EXAMPLE,
MANAGED_MEMBER_COMPARISON_EXAMPLE,
@@ -24,7 +24,7 @@ describe("workflow input contracts", () => {
traceJavaScriptSemanticsRequestSchema.safeParse({ query }).success,
).toBe(false);
const evidence = JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application;
const evidence = JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application;
expect(
traceJavaScriptSemanticsRequestSchema.safeParse({
application: evidence,
+5 -1
View File
@@ -87,10 +87,14 @@ import type {
import type { FileOffsetPartialObservation } from "./native/fileOffsetPartialObservation.js";
import type { NativeCallPartialObservation } from "./native/nativeCallPartialObservation.js";
import type { ElectronActivePartialObservation } from "./javascript/electronActiveObservation.js";
import type { JavaScriptRuntimeObservation } from "./javascript/javascriptRuntimeObservation.js";
import type { ArtifactInventoryPartialObservation } from "./artifactPartialObservation.js";
/** Provider-neutral evidence collected before a typed analysis failure. */
export type AnalysisPartialObservation =
| PartialProcessCaptureObservation
| NativeCallPartialObservation
| FileOffsetPartialObservation
| ElectronActivePartialObservation;
| ElectronActivePartialObservation
| JavaScriptRuntimeObservation
| ArtifactInventoryPartialObservation;
+6 -1
View File
@@ -1,4 +1,7 @@
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** Artifact inventory or extraction failed a typed safety boundary. */
export class ArtifactOperationError extends AnalysisError {
@@ -33,11 +36,13 @@ export class ArtifactOperationError extends AnalysisError {
}>,
/** The specific constraint that failed, such as the colliding path. */
readonly detail?: string,
options?: AnalysisErrorOptions,
) {
super(
artifactDetails === undefined
? `Artifact ${operation} failed: ${reason}`
: `Artifact ${operation} failed: ${reason} at ${artifactDetails.logicalPath} (declared_sha256=${artifactDetails.declaredSha256 ?? "unavailable"}, calculated_sha256=${artifactDetails.calculatedSha256 ?? "unavailable"}, unpacked=${String(artifactDetails.unpacked)})`,
options,
);
}
}
+7
View File
@@ -0,0 +1,7 @@
import type { ArtifactInventorySnapshot } from "./artifactInventorySnapshot.js";
/** A complete inventory retained when releasing its provider resources fails. */
export interface ArtifactInventoryPartialObservation {
readonly kind: "artifact-inventory";
readonly inventory: ArtifactInventorySnapshot;
}
@@ -109,9 +109,17 @@ const sameSymbolName = (expected: string, native: NativeSymbol): boolean =>
const normalizeModule = (value: string): string =>
basename(value)
.toLowerCase()
.replace(/^lib/u, "")
.replace(/\.(dll|dylib|so|node|exe)$/u, "");
const nativeModuleIdentities = (value: string): ReadonlySet<string> => {
const filename = basename(value).toLowerCase();
const stem = normalizeModule(filename);
const identities = new Set([stem]);
if (/\.(dylib|so)$/u.test(filename) && stem.startsWith("lib"))
identities.add(stem.slice("lib".length));
return identities;
};
const moduleCompatible = (
scope: string | null,
symbol: NativeSymbol,
@@ -120,8 +128,7 @@ const moduleCompatible = (
const expected = normalizeModule(scope);
return [symbol.module_name, symbol.module_path]
.filter((value): value is string => value !== null)
.map(normalizeModule)
.some((value) => value === expected);
.some((value) => nativeModuleIdentities(value).has(expected));
};
const candidateNames = (
@@ -215,7 +215,9 @@ describe("process trace constraints and evidence sufficiency", () => {
compareProcessTraces(workerFirst, workerFirst, specification),
).toMatchObject({ verdict: "equivalent" });
});
});
describe("unknown process trace evidence", () => {
it("never proves equivalence from truncated, unknown, or journal-free evidence", () => {
const complete = capture(values(["terminal", "process"]));
const truncated = capture(values(["terminal", "process"]), {
@@ -230,6 +232,17 @@ describe("process trace constraints and evidence sufficiency", () => {
expect(
compareProcessTraces(complete, unknown, partialSpecification()).verdict,
).toBe("unknown");
expect(
compareProcessTraces(complete, unknown, partialSpecification()),
).toMatchObject({
verdict: "unknown",
right: {
status: "unknown",
matched_variant: null,
satisfied_constraints: [],
raw_trace: [{ event_id: "ready" }, { event_id: "worker" }],
},
});
const noJournal = parseProcessCapture({ ...complete, event_journal: [] });
expect(
compareProcessTraces(complete, noJournal, partialSpecification()),
+13 -6
View File
@@ -90,11 +90,13 @@ const scopesFor = (
}),
);
const unknownSide = (): z.infer<typeof sideResultSchema> => ({
const unknownSide = (
rawTrace: z.infer<typeof matchedEventSchema>[] = [],
): z.infer<typeof sideResultSchema> => ({
status: "unknown",
matched_variant: null,
satisfied_constraints: [],
raw_trace: [],
raw_trace: rawTrace,
});
export type EvaluatedSide = {
@@ -411,11 +413,9 @@ export const evaluateProcessTraceSide = (
): EvaluatedSide => {
const sources = new Set(specification.events.map(({ source }) => source));
const relevantScopes = scopesFor(sources);
if (
const incomplete =
capture.truncated ||
capture.residual_unknowns.some(({ scope }) => relevantScopes.has(scope))
)
return { result: unknownSide(), diagnostic: null };
capture.residual_unknowns.some(({ scope }) => relevantScopes.has(scope));
if (capture.event_journal.length === 0)
return {
result: unknownSide(),
@@ -427,6 +427,13 @@ export const evaluateProcessTraceSide = (
},
};
const matched = matchRecords(collectRecords(capture, sources), specification);
if (incomplete)
return {
result: unknownSide(
"rawTrace" in matched ? matched.rawTrace : matched.result.raw_trace,
),
diagnostic: null,
};
return "rawTrace" in matched
? evaluateMatchedTrace(matched, specification)
: matched;
+49 -1
View File
@@ -58,7 +58,11 @@ const unavailableFileEntry = (
...overrides,
});
const symlinkEntry = (overrides: Partial<SymlinkEntry> = {}): SymlinkEntry => ({
type KnownTargetSymlinkEntry = Extract<SymlinkEntry, { target: string }>;
const symlinkEntry = (
overrides: Partial<KnownTargetSymlinkEntry> = {},
): KnownTargetSymlinkEntry => ({
path: "src/package.json",
kind: "symlink",
target: "main.ts",
@@ -237,6 +241,50 @@ describe("historical source graph", () => {
});
describe("partial historical source graphs", () => {
it("keeps an unreadable symlink target unknown and out of root identity", () => {
const base = graphInput();
base.inventory_state = "partial";
base.entries[2] = {
path: "src/package.json",
kind: "symlink",
target: null,
target_state: "unreadable",
classifications: ["manifest"],
limitations: ["Target could not be read."],
};
const graph = createHistoricalSourceGraph(base);
expect(graph.entries[2]).toMatchObject({
kind: "symlink",
target: null,
target_state: "unreadable",
});
const changedMessage = structuredClone(base);
changedMessage.entries[2] = {
path: "src/package.json",
kind: "symlink",
target: null,
target_state: "unreadable",
classifications: ["manifest"],
limitations: ["A different diagnostic."],
};
const revised = createHistoricalSourceGraph(changedMessage);
expect(revised.root_sha256).toBe(graph.root_sha256);
expect(computeHistoricalSourceGraphSha256(revised)).not.toBe(
computeHistoricalSourceGraphSha256(graph),
);
expect(() =>
createHistoricalSourceGraph({
...base,
entries: base.entries.map((entry) =>
entry.kind === "symlink"
? { ...entry, target: "<unreadable>" }
: entry,
),
}),
).toThrow();
});
it("preserves partial observations but rejects every partial complete graph", () => {
const partial = graphInput();
partial.inventory_state = "partial";
+15 -12
View File
@@ -92,18 +92,20 @@ const isPortableAbsoluteSymlinkTarget = (target: string): boolean =>
/^[A-Za-z]:[\\/]/u.test(target) ||
/^\\\\[^\\/]+[\\/][^\\/]+/u.test(target);
const sourceSymlinkSchema = z.strictObject({
...entryBaseShape,
kind: z.literal("symlink"),
target: symlinkTargetSchema,
target_state: z.enum([
"internal",
"external",
"missing",
"unreadable",
"unknown",
]),
});
const sourceSymlinkSchema = z.union([
z.strictObject({
...entryBaseShape,
kind: z.literal("symlink"),
target: symlinkTargetSchema,
target_state: z.enum(["internal", "external", "missing"]),
}),
z.strictObject({
...entryBaseShape,
kind: z.literal("symlink"),
target: z.null(),
target_state: z.enum(["unreadable", "unknown"]),
}),
]);
const sourceEntrySchema = z.union([
sourceFileSchema,
@@ -314,6 +316,7 @@ const checkSymlinks = (
): void => {
for (const [index, entry] of graph.entries.entries()) {
if (entry.kind !== "symlink") continue;
if (entry.target === null) continue;
const absolute = isPortableAbsoluteSymlinkTarget(entry.target);
if (
(entry.target_state === "external" && !absolute) ||
@@ -4,6 +4,9 @@ import {
closeInspectorConnection,
inspectorCleanupError,
} from "./V8InspectorProvider.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import { javascriptRuntimeObservationSchema } from "../domain/javascript/javascriptRuntimeObservation.js";
it("returns promptly on cancellation while a V8 socket close is hung", async () => {
const controller = new AbortController();
@@ -32,6 +35,59 @@ it("maps a rejected close to incomplete cleanup and preserves the primary failur
expect(error.cleanupIncomplete).toBe(true);
expect(error.cleanupResources).toEqual(["browser_transport"]);
expect(error.cause).toBeInstanceOf(AggregateError);
if (!(error.cause instanceof AggregateError)) return;
expect(error.cause.errors).toEqual([primary, cleanup]);
expect(error.cause).toMatchObject({ errors: [primary, cleanup] });
});
it("projects a completed runtime observation with the cleanup failure", () => {
const observation = javascriptRuntimeObservationSchema.parse({
runtime: {
product: "Node.js",
protocol_version: "1.3",
v8_version: "12.0",
},
target: {
target_id: "target-1",
protocol_type: "node",
attached: false,
location: { kind: "file", file_path: "/fixture.js" },
runtime_kind: "node",
runtime_kind_authority: "caller-declared-unverified",
},
capture: {
observation_ms: 0,
events_observed: 0,
events_retained: 0,
events_dropped: 0,
metadata_bytes_retained: 0,
truncated: false,
truncation_reasons: [],
},
scripts: {
items: [],
observed_total: 0,
excluded: { unsupported_location: 0, invalid_protocol_value: 0 },
},
execution_contexts: [],
directly_observed: ["Inspector target attached and queried."],
unavailable_without_instrumentation: [],
unknowns: [],
limitations: [],
});
const primary = new Error("observation failed");
const cleanup = new Error("socket close failed");
const error = inspectorCleanupError(primary, cleanup, true, observation);
const cause = error.cause;
expect(cause).toBeInstanceOf(AggregateError);
expect(cause).toMatchObject({ errors: [primary, cleanup] });
const projected = projectAnalysisError(error);
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup_reason: "socket close failed",
resources: ["browser_transport"],
partial_observation: observation,
},
});
});
+26 -2
View File
@@ -13,6 +13,7 @@ import {
} from "../domain/javascript/javascriptRuntimeObservation.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type { AnalysisPartialObservation } from "../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { type BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -190,7 +191,18 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
}
}
if (cleanupFailed) {
return err(inspectorCleanupError(primaryFailure, cleanupFailure, failed));
return err(
inspectorCleanupError(
primaryFailure,
cleanupFailure,
failed,
outcome?.ok === true
? outcome.value
: outcome?.ok === false
? outcome.error.partialObservation
: undefined,
),
);
}
return (
outcome ??
@@ -232,6 +244,7 @@ export const inspectorCleanupError = (
primaryFailure: unknown,
cleanupFailure: unknown,
hasPrimaryFailure: boolean,
partialObservation?: AnalysisPartialObservation,
): BrowserObservationError => {
const cause = hasPrimaryFailure
? new AggregateError(
@@ -239,10 +252,21 @@ export const inspectorCleanupError = (
"Inspector observation and cleanup both failed",
)
: cleanupFailure;
const cleanupReason =
cleanupFailure instanceof Error
? cleanupFailure.message
: String(cleanupFailure);
return new BrowserObservationError(
"observe_javascript_runtime",
"cleanup_failed",
{ cause },
{
cause,
cleanup: {
reason: cleanupReason,
resources: ["browser_transport"],
},
...(partialObservation === undefined ? {} : { partialObservation }),
},
);
};
+7 -7
View File
@@ -128,7 +128,10 @@ export class WindowsPrivateRuntime {
/** Remove owned objects by handle, unlinking reparse entries without traversal. */
close(): Promise<void> {
this.#closePromise ??= this.#remove();
this.#closePromise ??= this.#remove().catch((cause: unknown) => {
this.#closePromise = undefined;
throw cause;
});
return this.#closePromise;
}
@@ -137,12 +140,9 @@ export class WindowsPrivateRuntime {
if (this.#pending !== undefined)
this.authority.call("runtime_snapshot_cancel", [this.observation.handle]);
await this.#pending?.catch(() => undefined);
try {
this.authority.call("runtime_close", [this.observation.handle]);
} finally {
this.#closed = true;
runtimes.delete(this.observation.path.toLowerCase());
}
this.authority.call("runtime_close", [this.observation.handle]);
this.#closed = true;
runtimes.delete(this.observation.path.toLowerCase());
}
}
@@ -10,8 +10,8 @@ import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
@@ -226,7 +226,7 @@ describe("application workflow CLI parity", () => {
it("accepts inline trace JSON and file-backed comparison JSON", async () => {
const traced = await runCli([
"trace-application-feature",
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE),
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_EXAMPLE),
"--json",
]);
expect(traced).toMatchObject({
@@ -258,7 +258,7 @@ describe("application workflow CLI parity", () => {
const comparisonPath = join(root, "comparison.json");
await writeFile(
comparisonPath,
JSON.stringify(JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE),
JSON.stringify(JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE),
);
const compared = await runCli([
"compare-application-versions",
@@ -289,7 +289,7 @@ describe("application workflow CLI parity", () => {
"compare-source-to-bundle",
JSON.stringify({
reference: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
application: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
application: JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application,
}),
"--json",
]);
@@ -445,10 +445,10 @@ describe("application workflow CLI input", () => {
const result = await runCli([
"compare-application-versions",
JSON.stringify({
left: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
left: JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE.left
.evidence_id,
right:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE.right.evidence_id,
}),
"--json",
]);
@@ -5,7 +5,15 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { translateArtifactFailure } from "../../../src/artifacts/ArtifactProvider.js";
import {
ArtifactReaderFailure,
type ArtifactReader,
} from "../../../src/artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../../../src/artifacts/DirectoryArtifactReader.js";
import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
describe("artifact inventory snapshot", () => {
it("retains the complete scan after the source directory changes", async () => {
@@ -22,4 +30,54 @@ describe("artifact inventory snapshot", () => {
]);
expect(snapshot.manifest.occurrence_count).toBe(3);
});
it("projects the complete inventory when reader cleanup fails after scanning", async () => {
const root = await createTestTempDirectory("rea-inventory-cleanup-");
await writeFile(join(root, "observed.txt"), "observed");
const directory = new DirectoryArtifactReader(root);
const reader: ArtifactReader = {
format: directory.format,
entries: (signal) => directory.entries(signal),
open: (entry, signal) => directory.open(entry, signal),
provenance: () => directory.provenance(),
async close() {
await directory.close();
throw new ArtifactReaderFailure("unavailable", "mount still attached", {
cleanup: {
reason: "DMG detach failed",
resources: ["/dev/disk-test", "/tmp/rea-mount-test"],
},
});
},
};
const failure = await scanCanonicalArtifactInventory(
root,
{},
async () => reader,
).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
if (!(failure instanceof ArtifactReaderFailure))
throw failure instanceof Error
? failure
: new Error("Expected the reader cleanup failure", { cause: failure });
const projection = projectAnalysisError(
translateArtifactFailure("inventory_artifact", failure),
);
expect(projection).toMatchObject({
code: "cleanup_incomplete",
details: {
execution_failure: "artifact_operation_failed",
resources: ["/dev/disk-test", "/tmp/rea-mount-test"],
partial_observation: {
kind: "artifact-inventory",
inventory: {
manifest: { occurrence_count: 2 },
occurrences: expect.arrayContaining([
expect.objectContaining({ logical_path: "observed.txt" }),
]),
},
},
},
});
});
});
@@ -11,7 +11,11 @@ import {
importReferenceSource,
normalizeHistoricalSourceParseFailures,
} from "../../../src/application/ReferenceSourceImport.js";
import { projectReferenceSourceEntryFailure } from "../../../src/application/ReferenceSourceImportEntries.js";
import {
parseReferenceSourceEntries,
projectReferenceSourceEntryFailure,
} from "../../../src/application/ReferenceSourceImportEntries.js";
import type { ReferenceSourceRead } from "../../../src/reference/ReferenceSourceReader.js";
import {
projectReferenceSourceImportError,
type ReferenceSourceImportError,
@@ -114,6 +118,33 @@ describe("reference source import error projection", () => {
});
describe("reference source symlink import", () => {
it("preserves an unreadable target as unknown instead of a synthetic path", () => {
const read: ReferenceSourceRead = {
root: "/reference",
entries: [
{
status: "failed",
kind: "symlink",
path: "src/link.ts",
code: "io",
message: "Symbolic link target could not be read",
},
],
bytesRead: 0,
limitations: [],
};
const parsed = parseReferenceSourceEntries(read, new Set());
expect(parsed.entries).toContainEqual(
expect.objectContaining({
kind: "symlink",
path: "src/link.ts",
target: null,
target_state: "unreadable",
}),
);
});
it("retains external symlink targets as local graph diagnostics", async () => {
const root = await createTestTempDirectory("rea-reference-links-");
const outside = await createTestTempDirectory("rea-reference-outside-");
@@ -289,8 +320,6 @@ describe("reference source import behavior", () => {
importTree(leftRoot),
importTree(rightRoot),
]);
expect(left.ok).toBe(true);
expect(right.ok).toBe(true);
if (!left.ok || !right.ok) throw new Error("expected imports to pass");
expect(createHistoricalSourceManifest(left.value)).toEqual(
createHistoricalSourceManifest(right.value),
@@ -1,5 +1,12 @@
import { createHash } from "node:crypto";
import { access, readFile, readdir, readlink, rm } from "node:fs/promises";
import {
access,
chmod,
readFile,
readdir,
readlink,
rm,
} from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
@@ -8,6 +15,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SafeOutputTree } from "../../../src/artifacts/SafeOutputTree.js";
import { ArtifactReaderFailure } from "../../../src/artifacts/ArtifactReader.js";
describe("safe artifact output tree", () => {
it.skipIf(process.platform !== "linux")(
@@ -49,6 +57,32 @@ describe("safe artifact output tree", () => {
expect(await readdir(parent)).toEqual([]);
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"reports the owned residual root when rollback lacks directory permissions",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-rollback-");
const output = join(parent, "published");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("retained until rollback can retry");
await tree.write(
"nested/file.txt",
Readable.from(bytes),
createHash("sha256").update(bytes).digest("hex"),
);
try {
await chmod(output, 0o500);
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(failure).toMatchObject({
cleanup: { resources: [output] },
});
} finally {
await chmod(output, 0o700).catch(() => undefined);
await tree.rollback();
}
},
);
it("publishes files while building and preserves them after sealing", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
@@ -113,143 +113,141 @@ describe("Inspector execution-context lifecycle metadata", () => {
});
});
describe("passive V8 Inspector provider", () => {
test("rejects unknown runtime observation fields", () => {
expect(
observeJavaScriptRuntimeInputSchema.safeParse({
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "target-1",
unknown_field: true,
}).success,
).toBe(false);
});
test("rejects unknown runtime observation fields", () => {
expect(
observeJavaScriptRuntimeInputSchema.safeParse({
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "target-1",
unknown_field: true,
}).success,
).toBe(false);
});
test("returns every target exposed by the selected Inspector endpoint inline", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetCount: 205,
test("returns every target exposed by the selected Inspector endpoint inline", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetCount: 205,
});
try {
const listed = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
try {
const listed = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toHaveLength(206);
expect(listed.value.targets[0]?.target_id).toBe(fake.targetId);
} finally {
await fake.close();
}
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toHaveLength(206);
expect(listed.value.targets[0]?.target_id).toBe(fake.targetId);
} finally {
await fake.close();
}
});
test("includes targets outside the old caller root filter", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("outside.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetUrl: pathToFileURL(outside).href,
test("includes targets outside the old caller root filter", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("outside.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetUrl: pathToFileURL(outside).href,
});
try {
const result = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
try {
const result = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
if (!result.ok) throw result.error;
expect(result.value.targets).toHaveLength(2);
expect(
result.value.targets.map(({ location }) => location),
).toContainEqual(expect.objectContaining({ file_path: outside }));
} finally {
await fake.close();
}
});
if (!result.ok) throw result.error;
expect(result.value.targets).toHaveLength(2);
expect(result.value.targets.map(({ location }) => location)).toContainEqual(
expect.objectContaining({ file_path: outside }),
);
} finally {
await fake.close();
}
});
test("captures complete metadata with two enable commands", async () => {
test("captures complete metadata with two enable commands", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("secret.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptUrls: [
pathToFileURL(fixture.entry).href,
"node:fs",
pathToFileURL(outside).href,
],
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(3);
expect(result.value.scripts.excluded.unsupported_location).toBe(0);
expect(result.value.execution_contexts).toEqual([
{
context_key: "1",
state: "created",
name: "node[fixture]",
origin: "",
},
]);
expect(new Set(fake.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
expect(JSON.stringify(result.value)).toContain(outside);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
);
} finally {
await fake.close();
}
});
test("excludes an Electron main target that reports only bare file://", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: "file://",
scriptUrls: [pathToFileURL(fixture.entry).href],
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toEqual([]);
const observed = await provider.observe(
observeInput(fake.endpoint, fake.targetId, "electron-main"),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/target/u);
} finally {
await fake.close();
}
});
test.each([
["node", "node"],
["electron-main", "node"],
["electron-preload", "page"],
["electron-renderer", "page"],
] as const)(
"admits declared %s only on its protocol target family",
async (runtimeKind, targetType) => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("secret.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptUrls: [
pathToFileURL(fixture.entry).href,
"node:fs",
pathToFileURL(outside).href,
],
targetType,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(3);
expect(result.value.scripts.excluded.unsupported_location).toBe(0);
expect(result.value.execution_contexts).toEqual([
{
context_key: "1",
state: "created",
name: "node[fixture]",
origin: "",
},
]);
expect(new Set(fake.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
expect(JSON.stringify(result.value)).toContain(outside);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
observeInput(fake.endpoint, fake.targetId, runtimeKind),
);
expect(result.ok).toBe(true);
} finally {
await fake.close();
}
});
test("excludes an Electron main target that reports only bare file://", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: "file://",
scriptUrls: [pathToFileURL(fixture.entry).href],
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toEqual([]);
const observed = await provider.observe(
observeInput(fake.endpoint, fake.targetId, "electron-main"),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/target/u);
} finally {
await fake.close();
}
});
test.each([
["node", "node"],
["electron-main", "node"],
["electron-preload", "page"],
["electron-renderer", "page"],
] as const)(
"admits declared %s only on its protocol target family",
async (runtimeKind, targetType) => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
targetType,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, runtimeKind),
);
expect(result.ok).toBe(true);
} finally {
await fake.close();
}
},
);
});
},
);
describe("complete Inspector script hashes", () => {
test("keeps more than one hundred long script hashes distinct", async () => {
@@ -105,9 +105,6 @@ it("advertises exact schemas and projects one layout section from retained Evide
parent_evidence_id: parent.evidence_id,
item: { name: { display: ".data" } },
});
expect(parsed.normalized_result).toEqual(
parseEvidence(parsed).normalized_result,
);
expect(session.evidenceById(parsed.evidence_id)).toEqual(
parseEvidence(parsed),
);
@@ -4,9 +4,8 @@ import { describe, expect, it } from "vitest";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import {
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
@@ -15,64 +14,6 @@ import {
type ApplicationMcpHarness,
} from "../../fixtures/applicationMcpHarness.js";
async function runInlineEvidenceScenarios(
client: Client,
session: BinarySession,
): Promise<void> {
const traced = await client.callTool({
name: "trace_application_feature",
arguments: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
});
expect(traced.isError).not.toBe(true);
expect(traced.structuredContent).toMatchObject({
normalized_result: {
seed: { kind: "module", value: "renderer.js", match: "exact" },
summary: { matched_seeds: 1, traced_nodes: 1, unknown_facts: 0 },
coverage: {
status: "complete-within-source",
source_graph_status: "complete",
total_seed_matches: 1,
},
},
});
const compared = await client.callTool({
name: "compare_application_versions",
arguments: {
...JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
},
});
expect(compared.isError).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
normalized_result: {
summary: { unchanged: 0, added: 2, removed: 0, changed: 1, unknown: 0 },
coverage: {
left_graph_status: "complete",
right_graph_status: "complete",
status: "complete-within-inputs",
},
},
});
const sourceCompared = await client.callTool({
name: "compare_source_to_bundle",
arguments: {
reference: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
application: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
},
});
expect(sourceCompared.isError).not.toBe(true);
expect(sourceCompared.structuredContent).toMatchObject({
normalized_result: {
reference: {
root_sha256: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
},
scoring: { algorithm: "rea-source-to-bundle-signals" },
},
});
expect(session.exportEvidenceBundle().records.length).toBeGreaterThan(2);
}
async function runInlineWorkflowScenarios(
harness: ApplicationMcpHarness,
): Promise<void> {
@@ -98,15 +39,15 @@ async function runInlineWorkflowScenarios(
const comparedInline = await harness.client.callTool({
name: "compare_application_versions",
arguments: {
...JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
...JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
},
});
expect(comparedInline).toMatchObject({
structuredContent: {
normalized_result: {
evidence_links: expect.arrayContaining([
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE.left.evidence_id,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE.right.evidence_id,
]),
},
},
@@ -116,21 +57,21 @@ async function runInlineWorkflowScenarios(
name: "compare_application_versions",
arguments: {
left_evidence_id:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE.left.evidence_id,
right_evidence_id:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE.right.evidence_id,
},
});
expect(idsRejected.isError).toBe(true);
const sourceComparedById = await harness.client.callTool({
const sourceCompared = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: {
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
},
});
expect(sourceComparedById.isError).not.toBe(true);
expect(sourceComparedById.structuredContent).toMatchObject({
expect(sourceCompared.isError).not.toBe(true);
expect(sourceCompared.structuredContent).toMatchObject({
normalized_result: {
reference: {
root_sha256: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
@@ -148,6 +89,9 @@ async function runInlineWorkflowScenarios(
],
},
});
expect(harness.session.exportEvidenceBundle().records.length).toBeGreaterThan(
2,
);
}
async function assertRejectedEvidenceReferences(
@@ -195,10 +139,10 @@ async function assertRejectedInlineEvidence(client: Client): Promise<void> {
const duplicateNative = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
native_observations: [
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application,
],
},
});
@@ -207,9 +151,9 @@ async function assertRejectedInlineEvidence(client: Client): Promise<void> {
const spoofed = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application: {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application,
provider: { id: "spoofed", name: "spoofed", version: "1" },
},
},
@@ -221,7 +165,6 @@ describe("application workflow MCP parity", () => {
it("traces and compares authenticated graph Evidence in the session", async () => {
const harness = await createApplicationMcpHarness();
try {
await runInlineEvidenceScenarios(harness.client, harness.session);
await runInlineWorkflowScenarios(harness);
await assertRejectedEvidenceReferences(harness.client, harness.session);
await assertRejectedInlineEvidence(harness.client);
@@ -65,7 +65,6 @@ it("advertises exact valid schemas and records inline layout without a binary ta
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const viewed = await client.callTool({
name: "inspect_analysis_view",
@@ -67,7 +67,6 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
expect(evidence.confidence).toBe("inferred");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
-2
View File
@@ -46,8 +46,6 @@ it("executes named firmware contracts with inline Evidence and no native binary
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const result = contract.outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(result);
expect(result.normalized_result).toEqual(evidence.normalized_result);
expect(result.evidence_id).toBe(evidence.evidence_id);
expect(evidence.operation).toBe(contract.name);
expect(evidence.raw_result).not.toBeNull();
}
@@ -66,8 +66,6 @@ it.skipIf(process.platform !== "linux" || process.arch !== "x64")(
rewrite_level: "standard",
},
});
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(parsed.evidence_id).toBe(evidence.evidence_id);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
await assertRecoveryCleanup(fixture.launches);
},
@@ -65,7 +65,6 @@ it("advertises exact valid schemas and records inline recorded-core evidence wit
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
@@ -71,7 +71,6 @@ it("publishes valid SDK schemas and records the named module trace without a bin
},
],
});
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const invalid = await client.callTool({
name: "trace_web_module_imports",
@@ -73,7 +73,6 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the
response.structuredContent,
);
const evidence = parseEvidence(parsed);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
const capture = webNetworkCaptureSchema.parse(parsed.normalized_result);
expect(capture.container.reported).toEqual({
creator: "fixture",
-1
View File
@@ -62,7 +62,6 @@ it("advertises actual SDK schemas, instrumentation effects and session-owned inl
response.structuredContent,
);
const evidence = parseEvidence(parsed);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
}
expect(toolContract("observe_web_execution").effects).toMatchObject({
@@ -73,7 +73,6 @@ it("publishes valid SDK schemas and records the named module trace without a bin
},
raw_result: { source_map_text: data.sourceMap.text },
});
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const invalid = await client.callTool({
name: "trace_web_source_location",
@@ -136,8 +136,6 @@ it("publishes and executes all APK contracts with inline Evidence and no active
expect(validateOutput(response.structuredContent)).toBe(true);
const result = contract.outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(result);
expect(result.normalized_result).toEqual(evidence.normalized_result);
expect(result.evidence_id).toBe(evidence.evidence_id);
expect(evidence.operation).toBe(contract.name);
expect(evidence.raw_result).not.toBeNull();
}
@@ -214,7 +214,8 @@ describe("Ghidra headless launcher", () => {
const token = "secret-token-that-must-not-leak";
const javaHome = "C:\\Java\\jdk-21";
const launcher = new GhidraHeadlessLauncher({
environment: {},
// Select the fixture's Node PATH and injected JVM options explicitly.
environment: process.env,
analyzeHeadlessPath: fixturePath,
// POSIX follows the real inspected-JVM route; Windows uses the official
// batch script because its launcher contract differs.
@@ -115,14 +115,7 @@ describe("Hopper process cleanup", () => {
[cleanupTimeoutFixturePath, helperPath],
{ encoding: "utf8", timeout: 5_000 },
);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout) as {
readonly returncode: number;
readonly elapsed_ms: number;
};
expect(parsed.returncode).toBe(-9);
expect(parsed.elapsed_ms).toBeGreaterThanOrEqual(1_800);
expect(parsed.elapsed_ms).toBeLessThan(4_000);
expect(result.status, result.stderr).toBe(0);
},
);
});
@@ -1,11 +1,4 @@
import {
access,
mkdir,
readFile,
readdir,
symlink,
writeFile,
} from "node:fs/promises";
import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -14,7 +7,6 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { TOOL_EFFECTS } from "../../../../src/contracts/toolEffects.js";
import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
@@ -22,33 +14,6 @@ import {
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
describe("artifact extraction", () => {
it("declares possible native mounts and fresh extraction directories", () => {
for (const platform of ["linux", "darwin"] as const) {
const provider = new ArtifactProvider(process.env, platform);
for (const operation of [
"inventory_artifact",
"inspect_artifact",
"extract_artifact",
] as const) {
expect(
provider
.capabilities()
.find((capability) => capability.operation === operation)?.effects,
).toMatchObject({ launchesProcess: true, mayWriteFilesystem: true });
}
}
expect(TOOL_EFFECTS.inspect_artifact).toMatchObject({
launchesProcess: true,
writesFilesystem: true,
mutatesTarget: false,
});
expect(TOOL_EFFECTS.extract_artifact).toMatchObject({
launchesProcess: true,
writesFilesystem: true,
idempotent: false,
mutatesTarget: false,
});
});
it("extracts all regular occurrences through an exclusively owned output tree", async () => {
const root = await createTestTempDirectory("rea-extract-");
const source = join(root, "source");
@@ -140,39 +105,6 @@ describe("artifact extraction", () => {
"source",
]);
});
it("refuses a format without an extraction reader before inventory or output", async () => {
const root = await createTestTempDirectory("rea-extract-dmg-");
const image = join(root, "Image.dmg");
await writeFile(image, "not mounted");
// A caller-specific alias must be the path the refusal reports.
const alias = join(root, "Alias.dmg");
await symlink(image, alias);
const output = join(root, "output");
const extract = (signal?: AbortSignal) =>
new ArtifactProvider(process.env)
.createClient(target(alias, "dmg"))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
signal === undefined ? undefined : { signal },
);
expect(await extract()).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
operation: "extract_artifact",
path: alias,
reason: "Artifact format has no extraction reader: dmg",
},
});
const controller = new AbortController();
controller.abort();
expect(await extract(controller.signal)).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
await expect(access(output)).rejects.toThrow();
});
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider(process.env)
@@ -0,0 +1,56 @@
import { access, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
describe("artifact extraction format support", () => {
it("refuses unsupported formats before inventory or output", async () => {
const root = await createTestTempDirectory("rea-extract-format-");
const image = join(root, "Image.dmg");
await writeFile(image, "not mounted");
const alias = join(root, "Alias.dmg");
await symlink(image, alias);
const output = join(root, "output");
const extract = (signal?: AbortSignal) =>
new ArtifactProvider(process.env)
.createClient(archiveTarget(alias, "dmg"))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
signal === undefined ? undefined : { signal },
);
expect(await extract()).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
operation: "extract_artifact",
path: alias,
reason: "Artifact format has no extraction reader: dmg",
},
});
const controller = new AbortController();
controller.abort();
expect(await extract(controller.signal)).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
await expect(access(output)).rejects.toThrow();
});
});
const archiveTarget = (
path: string,
format: Extract<BinaryTarget, { kind: "archive" }>["format"],
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "archive",
format,
});
@@ -0,0 +1,45 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
describe("artifact extraction identity", () => {
it("uses code-point order for path-independent extraction identities", async () => {
const root = await createTestTempDirectory("rea-extract-order-");
const source = join(root, "source");
await mkdir(source);
for (const name of ["ä.js", "a.js", "Z.js"])
await writeFile(join(source, name), `${name}\n`);
const result = await new ArtifactProvider(process.env)
.createClient(directoryTarget(source))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({
output_root: join(root, "output"),
}),
);
if (!result.ok) throw result.error;
const extracted = artifactExtractionResultSchema.parse(result.value.result);
expect(
extracted.artifacts.map(({ relative_path }) => relative_path),
).toEqual(["Z.js", "a.js", "ä.js"]);
expect(extracted.extraction_manifest.selected_occurrence_ids).toEqual(
[...extracted.extraction_manifest.selected_occurrence_ids].sort(),
);
});
});
const directoryTarget = (path: string): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "archive",
format: "asar",
});
@@ -121,7 +121,14 @@ describe("native DMG artifact reader", () => {
undefined,
host,
),
).rejects.toThrow("cleanup could not detach every device");
).rejects.toMatchObject({
cleanup: {
resources: expect.arrayContaining([
"DMG device /dev/disk-fixture",
expect.stringMatching(/^DMG mount root /u),
]),
},
});
});
});
@@ -570,6 +577,12 @@ describe("APFS disk image detach", () => {
await expect(reader.close()).rejects.toMatchObject({
reason: "unavailable",
message: expect.stringContaining("No such file or directory"),
cleanup: {
resources: expect.arrayContaining([
"DMG device /dev/disk4",
expect.stringMatching(/^DMG mount root /u),
]),
},
});
});
@@ -16,7 +16,7 @@ const exampleInput = () =>
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
);
const nativeEvidenceWithExports = (names: readonly string[]) => {
const nativeEvidenceWithExports = (names: readonly string[], path?: string) => {
const input = exampleInput();
const native = input.native_observations[0];
if (native === undefined || native.subject === null)
@@ -24,7 +24,7 @@ const nativeEvidenceWithExports = (names: readonly string[]) => {
const macho = inspectMachoSchema.parse(native.normalized_result);
return createEvidence(
{
path: native.subject.local_path,
path: path ?? native.subject.local_path,
sha256: native.subject.digest.sha256,
format: native.subject.format,
...(native.subject.architecture === null
@@ -60,6 +60,29 @@ const nativeEvidenceWithExports = (names: readonly string[]) => {
);
};
const inputWithImportScope = (scope: string) => {
const input = exampleInput();
const managed = input.managed_boundaries;
const normalized = managedNativeBoundaryInspectionSchema.parse(
managed.normalized_result,
);
return {
...input,
managed_boundaries: createEvidence(undefined, managed.provider, {
operation: managed.operation,
parameters: managed.parameters,
result: {
...normalized,
pinvoke_imports: normalized.pinvoke_imports.map((item) => ({
...item,
import_scope_name: scope,
})),
},
rawResult: null,
}),
};
};
describe("managed/native boundary Evidence identity", () => {
it("rejects managed boundary Evidence whose subject digest differs from its artifact", () => {
const input = exampleInput();
@@ -108,165 +131,166 @@ describe("managed/native boundary Evidence identity", () => {
});
});
describe("managed/native boundary verification", () => {
it("verifies a P/Invoke declaration against native export Evidence", () => {
const result = verifyManagedNativeBoundaries(exampleInput());
it("verifies a P/Invoke declaration against native export Evidence", () => {
const result = verifyManagedNativeBoundaries(exampleInput());
expect(result).toMatchObject({
algorithm: {
name: "rea-managed-native-verification",
token_to_address_mapping: "not-inferred",
},
managed_boundary: {
artifact_sha256: "6".repeat(64),
mvid: "00112233-4455-4677-8899-aabbccddeeff",
pinvoke_imports_total: 1,
},
native_observations: {
total: 1,
accepted: 1,
unsupported: 0,
symbols: 1,
},
summary: {
verified: 1,
inferred: 0,
unresolved: 0,
contradicted: 0,
},
pinvoke_imports: [
{
managed: {
import_name: "open_native",
import_scope_name: "nativehelper.dll",
declaration_verification: "managed-declaration-only",
},
status: "verified",
basis: "exact-export-name",
confidence: "observed",
matched_native: {
name: "open_native",
source: "macho-export",
},
expect(result).toMatchObject({
managed_boundary: {
artifact_sha256: "6".repeat(64),
mvid: "00112233-4455-4677-8899-aabbccddeeff",
pinvoke_imports_total: 1,
},
summary: { verified: 1 },
pinvoke_imports: [
{
managed: {
import_name: "open_native",
import_scope_name: "nativehelper.dll",
},
],
});
expect(result.verification_id).toMatch(/^mnv_[a-f0-9]{64}$/u);
expect(result.limitations.join(" ")).toContain(
"does not prove CLR binding",
);
});
it("reports module mismatch as a contradiction within supplied Evidence", () => {
const input = exampleInput();
const native = input.native_observations[0];
if (native === undefined || native.subject === null)
throw new Error("missing native example");
const mismatched = createEvidence(
{
path: "/examples/other.dll",
sha256: native.subject.digest.sha256,
format: "pe",
...(native.subject.architecture === null
? {}
: { architecture: native.subject.architecture }),
status: "verified",
basis: "exact-export-name",
confidence: "observed",
matched_native: { name: "open_native" },
},
native.provider,
{
operation: native.operation,
parameters: native.parameters,
result: native.normalized_result,
rawResult: native.raw_result,
confidence: native.confidence,
authority: native.authority,
environment: native.environment,
limitations: native.limitations,
locations: native.locations,
evidenceLinks: native.evidence_links,
},
);
],
});
});
const result = verifyManagedNativeBoundaries({
...input,
native_observations: [mismatched],
});
it("reports module mismatch as a contradiction within supplied Evidence", () => {
const input = exampleInput();
const native = input.native_observations[0];
if (native === undefined || native.subject === null)
throw new Error("missing native example");
const mismatched = createEvidence(
{
path: "/examples/other.dll",
sha256: native.subject.digest.sha256,
format: "pe",
...(native.subject.architecture === null
? {}
: { architecture: native.subject.architecture }),
},
native.provider,
{
operation: native.operation,
parameters: native.parameters,
result: native.normalized_result,
rawResult: native.raw_result,
confidence: native.confidence,
authority: native.authority,
environment: native.environment,
limitations: native.limitations,
locations: native.locations,
evidenceLinks: native.evidence_links,
},
);
expect(result.summary).toMatchObject({
verified: 0,
contradicted: 1,
});
expect(result.pinvoke_imports[0]).toMatchObject({
status: "contradicted",
basis: "module-mismatch",
});
const result = verifyManagedNativeBoundaries({
...input,
native_observations: [mismatched],
});
it("treats supported native Evidence with no symbols as unresolved", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [nativeEvidenceWithExports([])],
});
expect(result.summary).toMatchObject({
verified: 0,
contradicted: 1,
});
expect(result.pinvoke_imports[0]).toMatchObject({
status: "contradicted",
basis: "module-mismatch",
});
});
expect(result.native_observations).toMatchObject({
accepted: 1,
unsupported: 0,
symbols: 0,
});
expect(result.summary).toMatchObject({
verified: 0,
unresolved: 1,
});
expect(result.pinvoke_imports[0]).toMatchObject({
status: "unresolved",
basis: "no-native-candidate",
});
it("keeps literal module names distinct and accepts the shared-library lib alias", () => {
const literalName = verifyManagedNativeBoundaries({
...inputWithImportScope("library"),
native_observations: [
nativeEvidenceWithExports(["open_native"], "/examples/rary.dylib"),
],
});
expect(literalName.pinvoke_imports[0]).toMatchObject({
status: "contradicted",
basis: "module-mismatch",
matched_native: { module_path: "/examples/rary.dylib" },
});
it("does not verify a symbol whose spelling differs only by case", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [nativeEvidenceWithExports(["OPEN_NATIVE"])],
});
const sharedLibraryAlias = verifyManagedNativeBoundaries({
...inputWithImportScope("foo"),
native_observations: [
nativeEvidenceWithExports(["open_native"], "/examples/libfoo.dylib"),
],
});
expect(sharedLibraryAlias.pinvoke_imports[0]).toMatchObject({
status: "verified",
basis: "exact-export-name",
matched_native: { module_path: "/examples/libfoo.dylib" },
});
});
expect(result.summary).toMatchObject({ verified: 0, unresolved: 1 });
expect(result.pinvoke_imports[0]).toMatchObject({
status: "unresolved",
matched_native: null,
candidates: [],
});
it("treats supported native Evidence with no symbols as unresolved", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [nativeEvidenceWithExports([])],
});
it("retains every observed native candidate", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [
nativeEvidenceWithExports(["open_native", "_open_native"]),
],
});
expect(result.native_observations).toMatchObject({
accepted: 1,
unsupported: 0,
symbols: 0,
});
expect(result.summary).toMatchObject({
verified: 0,
unresolved: 1,
});
expect(result.pinvoke_imports[0]).toMatchObject({
status: "unresolved",
basis: "no-native-candidate",
});
});
expect(result.coverage).toMatchObject({
status: "complete-within-inputs",
});
expect(result.pinvoke_imports[0]?.candidates).toHaveLength(2);
it("does not verify a symbol whose spelling differs only by case", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [nativeEvidenceWithExports(["OPEN_NATIVE"])],
});
it("wraps verification in derived workflow Evidence", () => {
const evidence = verifyManagedNativeBoundariesEvidence(exampleInput());
if (!evidence.ok) throw evidence.error;
expect(evidence.value).toMatchObject({
operation: "verify_managed_native_boundaries",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
authority: "analyst-inference",
normalized_result: {
summary: { verified: 1 },
},
});
expect(evidence.value.evidence_links).toHaveLength(2);
expect(result.summary).toMatchObject({ verified: 0, unresolved: 1 });
expect(result.pinvoke_imports[0]).toMatchObject({
status: "unresolved",
matched_native: null,
candidates: [],
});
});
it("retains every observed native candidate", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [
nativeEvidenceWithExports(["open_native", "_open_native"]),
],
});
expect(result.coverage).toMatchObject({
status: "complete-within-inputs",
});
expect(result.pinvoke_imports[0]?.candidates).toHaveLength(2);
});
it("wraps verification in derived workflow Evidence", () => {
const evidence = verifyManagedNativeBoundariesEvidence(exampleInput());
if (!evidence.ok) throw evidence.error;
expect(evidence.value).toMatchObject({
operation: "verify_managed_native_boundaries",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
authority: "analyst-inference",
normalized_result: {
summary: { verified: 1 },
},
});
expect(evidence.value.evidence_links).toHaveLength(2);
});
describe("managed/native verification result algebra", () => {
it("rejects states without their required native match", () => {
const result = verifyManagedNativeBoundaries(exampleInput());