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
@@ -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());
}
}