fix(publication)!: retain cleanup owners across export workflows

Require an ArtifactResourceScope for web script exports and share its lifetime with CLI or MCP shutdown. Retain setup-failed output trees in firmware and Wakaru providers. Preserve completed publications when descriptor cleanup fails, returning the full result after a successful retry or as a partial observation while cleanup remains unresolved.
This commit is contained in:
morluto
2026-10-11 05:17:10 +08:00
parent 3f8c51e9b5
commit be75ed5e4b
15 changed files with 801 additions and 166 deletions
+8 -7
View File
@@ -4,6 +4,7 @@ import { isAbsolute } from "node:path";
import { z } from "zod";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { publishWebScripts } from "../browser/assets/PublishWebScripts.js";
import { selectScriptCapture } from "../browser/assets/ScriptCaptureAdapters.js";
import {
@@ -37,11 +38,12 @@ const OPERATION = "export_web_scripts";
/** Export one local capture through the shared CLI/MCP application workflow. */
export const exportWebScripts = async (
rawInput: unknown,
resources: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const input = exportWebScriptsInputSchema.safeParse(rawInput);
return input.success
? exportWebScriptsValidated(input.data, options)
? exportWebScriptsValidated(input.data, resources, options)
: err(
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput),
);
@@ -50,6 +52,7 @@ export const exportWebScripts = async (
/** Publish input already parsed by a named adapter contract. */
export const exportWebScriptsValidated = async (
input: ExportWebScriptsInput,
resources: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
if (!isAbsolute(input.capture_path) || !isAbsolute(input.output_directory))
@@ -72,12 +75,10 @@ export const exportWebScriptsValidated = async (
if (!loaded.ok) return loaded;
options.signal?.throwIfAborted();
const sha256 = createHash("sha256").update(bytes).digest("hex");
const result = await publishWebScripts(
input,
loaded.value,
sha256,
options.signal,
);
const result = await publishWebScripts(input, loaded.value, sha256, {
resources,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
return ok(
createEvidence(
{ path: input.capture_path, sha256, format: "file" },
+93 -64
View File
@@ -3,8 +3,10 @@ import { join } from "node:path";
import { Readable } from "node:stream";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { DESTINATION_CASE_COLLISION_PREFIX } from "../../artifacts/ArtifactPaths.js";
import { SafeOutputTree } from "../../artifacts/SafeOutputTree.js";
import { SafeOutputTreeCreationFailure } from "../../artifacts/SafeOutputTreeCreationFailure.js";
import {
webScriptExportManifestSchema,
webScriptExportResultSchema,
@@ -27,78 +29,105 @@ const LIMITATIONS = [
"Captured response bytes are browser-decoded bytes; Debugger sources are the exposed text encoded as UTF-8. Redacted bytes are exported exactly as retained, and may no longer parse as JavaScript.",
];
interface PublishWebScriptsOptions {
readonly resources: ArtifactResourceScope;
readonly signal?: AbortSignal;
}
/** Exclusively publish verified bytes and a manifest, rolling back partial work. */
export const publishWebScripts = async (
input: ExportWebScriptsInput,
capture: SelectedScriptCapture & { readonly sourceEvidenceId: string | null },
captureSha256: string,
signal?: AbortSignal,
): Promise<WebScriptExportResult> => {
const planned = planWebScriptExport(capture.scripts);
const tree = await SafeOutputTree.create(input.output_directory);
try {
signal?.throwIfAborted();
const records: ExportedWebScript[] = [];
for (const [index, item] of planned.entries()) {
signal?.throwIfAborted();
records.push(await publishPlannedScript(tree, item, index, signal));
}
const manifest = webScriptExportManifestSchema.parse({
capture_path: input.capture_path,
capture_sha256: captureSha256,
capture_kind: capture.kind,
source_evidence_id: capture.sourceEvidenceId,
capture_completeness: capture.completeness,
output_directory: tree.outputRoot,
analysis_input: records.some(
({ content }) => content.state === "exported",
)
? { input_path: join(tree.outputRoot, "files"), format: "directory" }
: null,
scripts: records,
limitations: [
...capture.limitations,
...LIMITATIONS,
...(records.some(({ content }) => content.state === "exported")
? []
: [
"No script bytes were exportable. Include script sources in inspect_web_page or select response_body in capture_browser_scenario, then capture again.",
]),
],
});
const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
const digest = createHash("sha256").update(bytes).digest("hex");
const result = webScriptExportResultSchema.parse({
...manifest,
manifest: {
path: join(tree.outputRoot, "manifest.json"),
sha256: digest,
bytes: bytes.length,
},
});
await tree.write(
"manifest.json",
Readable.from([bytes]),
{ sha256: digest, bytes: bytes.byteLength },
signal,
);
signal?.throwIfAborted();
await tree.commit();
return result;
} catch (cause: unknown) {
options: PublishWebScriptsOptions,
): Promise<WebScriptExportResult> =>
options.resources.run(async () => {
const planned = planWebScriptExport(capture.scripts);
let tree: SafeOutputTree | undefined;
let result: WebScriptExportResult | undefined;
try {
await tree.rollback();
} catch (cleanupCause: unknown) {
throw new WebScriptExportError(
"io",
tree.outputRoot,
`Publication failed (${message(cause)}); rollback failed (${message(cleanupCause)}). Remove the residual output directory before retrying.`,
[tree.outputRoot],
tree = await SafeOutputTree.create(input.output_directory);
options.signal?.throwIfAborted();
const records: ExportedWebScript[] = [];
for (const [index, item] of planned.entries()) {
options.signal?.throwIfAborted();
records.push(
await publishPlannedScript(tree, item, index, options.signal),
);
}
const manifest = webScriptExportManifestSchema.parse({
capture_path: input.capture_path,
capture_sha256: captureSha256,
capture_kind: capture.kind,
source_evidence_id: capture.sourceEvidenceId,
capture_completeness: capture.completeness,
output_directory: tree.outputRoot,
analysis_input: records.some(
({ content }) => content.state === "exported",
)
? { input_path: join(tree.outputRoot, "files"), format: "directory" }
: null,
scripts: records,
limitations: [
...capture.limitations,
...LIMITATIONS,
...(records.some(({ content }) => content.state === "exported")
? []
: [
"No script bytes were exportable. Include script sources in inspect_web_page or select response_body in capture_browser_scenario, then capture again.",
]),
],
});
const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
const digest = createHash("sha256").update(bytes).digest("hex");
result = webScriptExportResultSchema.parse({
...manifest,
manifest: {
path: join(tree.outputRoot, "manifest.json"),
sha256: digest,
bytes: bytes.length,
},
});
await tree.write(
"manifest.json",
Readable.from([bytes]),
{ sha256: digest, bytes: bytes.byteLength },
options.signal,
);
options.signal?.throwIfAborted();
await tree.commit();
return result;
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
if (tree !== undefined) {
const cleanup = await options.resources.release({
kind: "output-tree",
resource: tree.outputRoot,
tree,
});
if (cleanup.kind === "failed") {
const cleanupCause = cleanup.cause;
const diagnostic = tree.published
? `Publication completed, but descriptor cleanup failed (${message(cleanupCause)}). The published output remains available.`
: `Publication failed (${message(cause)}); rollback failed (${message(cleanupCause)}). Remove the residual output directory before retrying.`;
const error = new WebScriptExportError(
cause instanceof ArtifactReaderFailure ? cause.reason : "io",
tree.outputRoot,
diagnostic,
[tree.outputRoot],
);
if (tree.published && result !== undefined)
error.retainPartialObservation({
kind: "web-script-export",
result,
});
throw error;
}
if (tree.published && result !== undefined) return result;
}
throw cause;
}
throw cause;
}
};
});
const publishPlannedScript = async (
tree: SafeOutputTree,
+37 -4
View File
@@ -1,9 +1,13 @@
import { Cli, z } from "incur";
import { exportWebScripts } from "../application/WebScriptExportService.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { Logger } from "pino";
/** Register the local captured-script export CLI workflow. */
@@ -26,10 +30,39 @@ export const registerWebScriptCommands = (
}),
run: ({ args }) =>
logCliCommand(logger, CLI_COMMANDS.exportWebScripts, async () => {
const result = await exportWebScripts({
capture_path: args.capturePath,
output_directory: args.outputDirectory,
});
const resources = new ArtifactResourceScope();
const result = await exportWebScripts(
{
capture_path: args.capturePath,
output_directory: args.outputDirectory,
},
resources,
);
try {
await resources.close();
} catch (cause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cause,
"Web script export resources",
);
const failure = new ProviderCleanupError(
"web-script-export",
cleanup.resources,
{ reason: cleanup.reason },
{ cause, operation: "export_web_scripts" },
);
const error = result.ok
? failure
: analysisErrorWithCleanupFailure(
result.error,
failure,
"export_web_scripts",
);
return {
error: "Script export failed",
...projectAnalysisError(error),
};
}
return result.ok
? result.value
: {
+29 -1
View File
@@ -25,6 +25,7 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import type { SafeOutputTree } from "../artifacts/SafeOutputTree.js";
import { publishFirmwareExtraction } from "./FirmwarePublication.js";
import {
FIRMWARE_LIMITS,
@@ -48,6 +49,7 @@ import {
type Outcome = Awaited<ReturnType<FirmwareAnalysisPort["execute"]>>;
interface PendingFirmwareCleanup {
supervisor?: ProviderProcessSupervisor;
tree?: SafeOutputTree;
readonly root: PrivateRuntimeRoot;
readonly engine: string;
readonly operation: string;
@@ -183,9 +185,24 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
);
continue;
}
try {
if (pending.tree !== undefined) {
await pending.tree.rollback();
delete pending.tree;
}
} catch (cause: unknown) {
failures.push(
new ProviderCleanupError(
pending.engine,
[path, pending.tree?.outputRoot ?? path],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{ operation: pending.operation, cause },
),
);
}
try {
await pending.root.close();
this.#pendingCleanup.delete(path);
if (pending.tree === undefined) this.#pendingCleanup.delete(path);
} catch (cause: unknown) {
// A verified stopped process cannot use this root. Keep ownership for
// later removal without blocking a new operation's disjoint workspace.
@@ -366,6 +383,17 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
selection: target.selection,
engine,
signal,
retainCleanup: (tree) => {
const pending: PendingFirmwareCleanup = this.#pendingCleanup.get(
ownedRoot.path,
) ?? {
root: ownedRoot,
engine: engineName,
operation: request.operation,
};
pending.tree = tree;
this.#pendingCleanup.set(ownedRoot.path, pending);
},
});
raw = { report, execution: processRun, version_execution: versionRun };
}
+24 -2
View File
@@ -2,8 +2,10 @@ import { createReadStream } from "node:fs";
import { join } from "node:path";
import type { z } from "zod";
import { SafeOutputTree } from "../artifacts/SafeOutputTree.js";
import { SafeOutputTreeCreationFailure } from "../artifacts/SafeOutputTreeCreationFailure.js";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { firmwareResultSchemas } from "../domain/firmware/firmwareAnalysis.js";
import { hashFirmwareFile, type FirmwareEntry } from "./FirmwareFiles.js";
import type { normalizeUnblobReport } from "./FirmwareReports.js";
@@ -16,8 +18,12 @@ export const publishFirmwareExtraction = async (context: {
selection: { offset: number; length: number; sha256: string };
engine: z.infer<typeof firmwareResultSchemas.extract_firmware>["engine"];
signal: AbortSignal;
retainCleanup: (tree: SafeOutputTree) => void;
}) => {
let tree: SafeOutputTree | undefined;
let result:
| z.infer<typeof firmwareResultSchemas.extract_firmware>
| undefined;
try {
const materialized = new Set(
context.entries
@@ -75,7 +81,7 @@ export const publishFirmwareExtraction = async (context: {
original_file_range: null,
});
}
const result = firmwareResultSchemas.extract_firmware.parse({
result = firmwareResultSchemas.extract_firmware.parse({
engine: context.engine,
selection: context.selection,
output_directory: tree.outputRoot,
@@ -93,9 +99,18 @@ export const publishFirmwareExtraction = async (context: {
await tree.commit();
return result;
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
try {
await tree?.rollback();
} catch (cleanupCause: unknown) {
if (tree !== undefined) context.retainCleanup(tree);
const publishedResult =
tree?.published === true && result !== undefined
? {
kind: "firmware" as const,
result: jsonValueSchema.parse(result),
}
: undefined;
throw new ProviderCleanupError(
"unblob",
[context.outputDirectory],
@@ -107,9 +122,16 @@ export const publishFirmwareExtraction = async (context: {
previous_error:
cause instanceof Error ? cause.message : String(cause),
},
{ cause: cleanupCause },
{
cause: cleanupCause,
operation: "extract_firmware",
...(publishedResult === undefined
? {}
: { partialObservation: publishedResult }),
},
);
}
if (tree?.published === true && result !== undefined) return result;
throw cause;
}
};
+60 -18
View File
@@ -7,9 +7,13 @@ import {
type ExecutionOptions,
} from "../../application/AnalysisProvider.js";
import { SafeOutputTree } from "../../artifacts/SafeOutputTree.js";
import { SafeOutputTreeCreationFailure } from "../../artifacts/SafeOutputTreeCreationFailure.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { JavaScriptRecoveryInput } from "../../domain/javascript/javascriptRecovery.js";
import {
javascriptRecoveryResultSchema,
type JavaScriptRecoveryInput,
} from "../../domain/javascript/javascriptRecovery.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err, ok, type Result } from "../../domain/result.js";
@@ -94,7 +98,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
if (pending !== undefined) return err(pending);
let root: string | undefined;
let tree: SafeOutputTree | undefined;
let failure: unknown;
let failed: { readonly cause: unknown } | undefined;
let execution: AnalysisExecution | undefined;
const deadline = Date.now() + RECOVERY_LIMITS.timeoutMs;
try {
@@ -110,15 +114,16 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
join(inputs, "bundle.js"),
options?.signal,
);
tree = await SafeOutputTree.create(input.output_directory).catch(
(cause: unknown) => {
throw recoveryInputFailure(
"output_directory",
`Cannot create new recovery directory ${input.output_directory}: ${recoveryFailureMessage(cause)}`,
cause,
);
},
);
try {
tree = await SafeOutputTree.create(input.output_directory);
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
throw recoveryInputFailure(
"output_directory",
`Cannot create new recovery directory ${input.output_directory}: ${recoveryFailureMessage(cause)}`,
cause,
);
}
execution = await prepareWakaruExecution({
root,
tree,
@@ -136,10 +141,12 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
checkRecoveryDeadline(deadline, options?.signal);
await tree.commit();
} catch (cause: unknown) {
failure = cause;
failed = { cause };
}
if (failure !== undefined) {
if (failed !== undefined) {
const failure = failed.cause;
const residuals: string[] = [];
const cleanupFailures: { resource: string; reason: string }[] = [];
const cleanupOwner =
failure instanceof WakaruCleanupFailure
? failure.cleanupOwner
@@ -147,10 +154,14 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
let failedTree: SafeOutputTree | undefined;
try {
await tree?.rollback();
} catch {
} catch (cause: unknown) {
if (tree !== undefined) {
failedTree = tree;
residuals.push(tree.outputRoot);
cleanupFailures.push({
resource: tree.outputRoot,
reason: recoveryFailureMessage(cause),
});
}
}
if (cleanupOwner !== undefined)
@@ -160,8 +171,12 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
try {
await rm(failedRoot, { recursive: true, force: true });
root = undefined;
} catch {
} catch (cause: unknown) {
residuals.push(failedRoot);
cleanupFailures.push({
resource: failedRoot,
reason: recoveryFailureMessage(cause),
});
}
}
if (
@@ -179,10 +194,37 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
}
if (residuals.length > 0)
return err(
new ProviderCleanupError("wakaru", residuals, {
previous_error: recoveryFailureMessage(failure),
}),
new ProviderCleanupError(
"wakaru",
residuals,
{
...(failure instanceof WakaruCleanupFailure
? failure.diagnostics
: {}),
previous_error:
failure instanceof WakaruCleanupFailure
? (failure.diagnostics?.previous_error ?? null)
: recoveryFailureMessage(failure),
cleanup_failures: cleanupFailures,
},
{
operation: OPERATION,
cause: failure,
...(tree?.published && execution !== undefined
? {
partialObservation: {
kind: "javascript-recovery" as const,
result: javascriptRecoveryResultSchema.parse(
execution.result,
),
},
}
: {}),
},
),
);
if (tree?.published === true && execution !== undefined)
return ok(execution);
return err(
failure instanceof AnalysisError
? failure
+7 -7
View File
@@ -211,7 +211,7 @@ export const createServer = (
options.webSourceLocation ?? createWebSourceLocationService(environment);
const javascriptRecovery =
options.javascriptRecovery ?? createJavaScriptRecoveryProvider(environment);
const javascriptApplicationResources = new ArtifactResourceScope();
const artifactResources = new ArtifactResourceScope();
const firmwareAnalysis = new FirmwareAnalysisService(
options.firmwareAnalysis ?? createFirmwareAnalysisProvider(environment),
);
@@ -248,7 +248,7 @@ export const createServer = (
evmInterface.close(),
webSourceLocation.close(),
javascriptRecovery.close?.() ?? Promise.resolve(),
javascriptApplicationResources.close(),
artifactResources.close(),
firmwareAnalysis.close(),
options.browserScenarioCapture?.close?.() ?? Promise.resolve(),
])
@@ -289,7 +289,7 @@ export const createServer = (
recordEvidence,
recordEvidenceWithUnknown,
withAdmittedAnalysis: analysisAdmission,
javascriptApplicationResources,
artifactResources,
};
registerBinaryAnalysisTools(toolContext);
const previousOnclose = server.server.onclose;
@@ -501,7 +501,7 @@ const createSessionRecorders = (
});
interface ServerToolContext extends ReturnType<typeof createSessionRecorders> {
readonly javascriptApplicationResources: ArtifactResourceScope;
readonly artifactResources: ArtifactResourceScope;
readonly server: EvidenceMcpServer;
readonly session: BinarySessionPort | undefined;
readonly options: CreateServerOptions;
@@ -572,10 +572,10 @@ const registerObservationTools = ({
recordEvidence,
recordEvidenceWithUnknown,
withAdmittedAnalysis,
javascriptApplicationResources,
artifactResources,
}: ServerToolContext): void => {
const common = { logger, recordEvidence, withAdmittedAnalysis };
registerWebScriptTool(server, common);
registerWebScriptTool(server, { ...common, artifactResources });
registerBrowserTools(server, {
...common,
browser: options.browserObservation,
@@ -588,7 +588,7 @@ const registerObservationTools = ({
});
registerElectronTools(server, {
...common,
javascriptApplicationResources,
artifactResources,
evidenceById,
electron: options.electronObservation,
electronActive: options.electronActiveObservation,
+2 -2
View File
@@ -35,7 +35,7 @@ import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
interface ElectronToolRegistration {
readonly javascriptApplicationResources: ArtifactResourceScope;
readonly artifactResources: ArtifactResourceScope;
readonly logger: Logger;
readonly observationLoadFailure?: OptionalProviderLoadFailure | undefined;
readonly activeLoadFailure?: OptionalProviderLoadFailure | undefined;
@@ -106,7 +106,7 @@ export const registerElectronTools = (
async ({ detail, ...request }, { signal, progress }) => {
const analyzed = await analyzeJavaScriptApplicationValidated(
request,
options.javascriptApplicationResources,
options.artifactResources,
{ signal, progress },
);
return detail === "summary" && analyzed.ok
+3 -1
View File
@@ -8,6 +8,7 @@ import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
/** Register local script export without requiring a live browser provider. */
export const registerWebScriptTool = (
@@ -15,6 +16,7 @@ export const registerWebScriptTool = (
options: {
readonly logger: Logger;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly artifactResources: ArtifactResourceScope;
readonly withAdmittedAnalysis?: WithAdmittedAnalysis;
},
): void => {
@@ -33,7 +35,7 @@ export const registerWebScriptTool = (
options.logger,
contract.name,
() =>
exportWebScriptsValidated(input, {
exportWebScriptsValidated(input, options.artifactResources, {
signal: context.mcpReq.signal,
}),
);