chore: preserve current main archive typing and runtime fixes

This commit is contained in:
64579525
2026-10-13 12:12:03 +08:00
65 changed files with 4164 additions and 151 deletions
@@ -0,0 +1,40 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { FlutterBuildAnalysisService } from "./FlutterBuildAnalysisService.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
type AnalysisViewRetention,
} from "../analysisView/AnalysisViewService.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { dartAotInspectionInputSchema } from "../../domain/flutter/flutterBuildAnalysis.js";
import type { Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, type Result } from "../../domain/result.js";
/** Keep the caller's ABI choice and complete analysis; select only its delivery. */
export const inspectDartAot = async (
service: FlutterBuildAnalysisService,
rawInput: unknown,
retention: AnalysisViewRetention,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> => {
const operation = "inspect_dart_aot";
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const parsed = dartAotInspectionInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(operation, parsed.error.issues, rawInput, {
cause: parsed.error,
}),
);
if (parsed.data.detail === "summary") {
const ready = requireAnalysisViewRetention(operation, retention);
if (!ready.ok) return ready;
}
const { detail, ...providerInput } = parsed.data;
const executed = await service.execute(operation, providerInput, options);
if (!executed.ok || detail !== "summary") return executed;
return summarizeRetainedAnalysis(executed.value, retention);
};
+1 -1
View File
@@ -16,7 +16,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_analysis_view"),
kind: "application",
description:
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_evm_interface, inspect_managed_artifact, inspect_android_package or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. For layout, JavaScript, native, inventory, WASM, EVM, managed artifact and Android package sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions; occurrence logical_paths matches exact recorded strings (omitted means all available, [] means none). source_complete distinguishes complete inventories from partial source records; page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Android package summaries retain all declarations, engine identity and counts without decoded manifest text. Android manifest pages use kind android, facet manifest, offset and limit in UTF-16 code units; source_status preserves partial decoded coverage even when the retained text page is exhausted. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.',
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_evm_interface, inspect_managed_artifact, inspect_android_package, inspect_dart_aot or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. For layout, JavaScript, inventory, WASM, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions; occurrence logical_paths matches exact recorded strings (omitted means all available, [] means none). source_complete distinguishes complete inventories from partial source records; page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Android package summaries retain all declarations, engine identity and counts without decoded manifest text. Android manifest pages use kind android, facet manifest, offset and limit in UTF-16 code units; source_status preserves partial decoded coverage even when the retained text page is exhausted. Dart AOT summary preserves target/ABI/library identity, snapshot headers and pool lower bounds. String pages use kind dart-aot, collection package_uris/dart_uris/class_like_tokens; source coverage remains partial when the producer says partial. Native function Evidence requires kind native: view: {kind: "native", facet: "procedure"}. Facets select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.',
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
+15 -3
View File
@@ -1,7 +1,10 @@
import { z } from "zod";
import {
flutterInputSchemas,
dartAotInspectionInputSchema,
flutterResultSchemas,
} from "../../domain/flutter/flutterBuildAnalysis.js";
import { dartAotSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
import type { ToolContract } from "../toolContractTypes.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
import { toolContractMetadata } from "../toolEffects.js";
@@ -27,10 +30,15 @@ export const FLUTTER_TOOL_CONTRACTS = [
name: "inspect_dart_aot",
...toolContractMetadata("inspect_dart_aot"),
description:
"Inspect one ABI's Dart AOT snapshot inside an APK: the four snapshot symbols located through the ELF dynamic symbol table with their offsets, sizes, and section headers (magic, kind, length), the snapshot hash, and a bounded string-pool projection from the isolate data section (package: source URIs, dart: SDK URIs, identifier-like tokens) exposing the app's dependency structure. String-pool entries are byte-pattern observations, not deserialized cluster semantics; typed class and function recovery needs an SDK-specific parser. No engine, no execution.",
"Inspect one ABI's Dart AOT snapshot inside an APK: the four snapshot symbols located through the ELF dynamic symbol table with their offsets, sizes, and section headers (magic, kind, length), the snapshot hash, and a bounded string-pool projection from the isolate data section (package: source URIs, dart: SDK URIs, identifier-like tokens) exposing the app's dependency structure. String-pool entries are byte-pattern observations, not deserialized cluster semantics; typed class and function recovery needs an SDK-specific parser. Omitted or complete detail returns the full observation. Select detail: \"summary\" for target/ABI/library identity, all snapshot headers, coverage and original lower-bound counts without string lists. The complete source stays retained; read returned strings via inspect_analysis_view with parent_evidence_id and kind dart-aot, collection package_uris/dart_uris/class_like_tokens, offset and limit. Exhausting pages does not imply complete pool coverage. No engine, no execution.",
kind: "flutter-provider",
inputSchema: flutterInputSchemas.inspect_dart_aot,
outputSchema: evidenceResultOf(flutterResultSchemas.inspect_dart_aot),
inputSchema: dartAotInspectionInputSchema,
outputSchema: evidenceResultOf(
z.union([
flutterResultSchemas.inspect_dart_aot,
dartAotSummaryViewResultSchema,
]),
),
examples: [
{
title: "Inspect the preferred ABI's AOT snapshot",
@@ -40,6 +48,10 @@ export const FLUTTER_TOOL_CONTRACTS = [
title: "Inspect one ABI explicitly",
input: { path: "/targets/Example.apk", abi: "arm64-v8a" },
},
{
title: "Inspect snapshot identity with retained string lists",
input: { path: "/targets/Example.apk", detail: "summary" },
},
],
},
] as const satisfies readonly ToolContract[];
+7 -1
View File
@@ -100,18 +100,24 @@ export class AnalysisOutputError extends AnalysisError {
export class AnalysisCapabilityUnavailableError extends AnalysisError {
readonly _tag = "AnalysisCapabilityUnavailableError";
override readonly userMessage: string | undefined;
/** Incomplete cleanup must settle before the operation can be retried. */
readonly retryable: boolean;
constructor(
readonly providerId: string,
readonly operation: string,
readonly reason: string,
options?: AnalysisErrorOptions & { readonly userMessage?: string },
options?: AnalysisErrorOptions & {
readonly userMessage?: string;
readonly retryable?: boolean;
},
) {
super(
`Provider ${providerId} cannot execute ${operation}: ${reason}`,
options,
);
this.userMessage = options?.userMessage;
this.retryable = options?.retryable === true && !this.cleanupIncomplete;
}
}
+7
View File
@@ -1,6 +1,7 @@
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisUnsupportedTargetError,
AnalysisResourceConstraintError,
@@ -33,6 +34,8 @@ import type { AnalysisErrorProjection } from "./analysisErrorProjection.js";
export const analysisErrorRemediationAction = (
error: AnalysisError,
): string => {
if (error instanceof AnalysisCapabilityUnavailableError && error.retryable)
return "Review details.reason, then retry the same analysis after the condition clears.";
if (error instanceof EvidenceFileError && error.published !== undefined)
return "Use the published file at details.published_path and resolve the reported staging cleanup failure.";
if (error instanceof AnalysisSnapshotMismatchError)
@@ -112,6 +115,8 @@ export const analysisErrorRemediationAction = (
export const analysisErrorCategory = (
error: AnalysisError,
): AnalysisErrorProjection["category"] => {
if (error instanceof AnalysisCapabilityUnavailableError && error.retryable)
return "unavailable";
if (
error instanceof BinaryTargetError &&
error.constraint === "load_selection_rejected"
@@ -220,6 +225,8 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
const hopperMessage = hopperErrorUserMessage(error);
if (hopperMessage !== undefined) return hopperMessage;
if (error.userMessage !== undefined) return error.userMessage;
if (error instanceof AnalysisCapabilityUnavailableError && error.retryable)
return "Required runtime controls are unavailable for this attempt.";
const standardMessage = standardErrorMessage(error._tag);
if (standardMessage !== undefined) return standardMessage;
if (error instanceof ArtifactOperationError) return artifactMessage(error);
@@ -25,6 +25,91 @@ import { ProviderSelectionError } from "./providerSelectionError.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import { nativeCallPartialObservationSchema } from "./native/nativeCallPartialObservation.js";
describe("capability failure retry disposition", () => {
it.each([
{ options: {}, retryable: false, category: "unsupported_provider" },
{
options: { retryable: false },
retryable: false,
category: "unsupported_provider",
},
{ options: { retryable: true }, retryable: true, category: "unavailable" },
] as const)(
"preserves the producer's $retryable disposition",
({ options, retryable, category }) => {
const reason = "Native self-test failed with a sharing violation";
const projected = projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture-provider",
"inspect",
reason,
options,
),
);
expect(projected).toMatchObject({
code: "capability_unavailable",
category,
retryable,
details: { reason },
});
if (retryable) {
expect(projected.message).toBe(
"Required runtime controls are unavailable for this attempt.",
);
expect(projected.remediation.action).toContain(
"retry the same analysis",
);
}
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it("preserves a caller-selected message for a retryable failure", () => {
expect(
projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture-provider",
"inspect",
"temporary failure",
{
retryable: true,
userMessage: "Selected runtime diagnostic",
},
),
).message,
).toBe("Selected runtime diagnostic");
});
it("retains cleanup ownership before allowing a transient operation to retry", () => {
expect(
projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture-provider",
"inspect",
"temporary failure",
{
retryable: true,
cleanup: {
reason: "owned handle is still live",
resources: ["native-owner"],
},
},
),
),
).toMatchObject({
code: "cleanup_incomplete",
retryable: false,
details: {
cleanup: "incomplete",
resources: ["native-owner"],
execution_failure: "capability_unavailable",
},
});
});
});
it("projects a published file receipt alongside retained cleanup failure", () => {
const projected = projectAnalysisError(
new EvidenceFileError("write", "io", {
+2
View File
@@ -83,6 +83,8 @@ export const projectAnalysisError = (
message: analysisErrorUserMessage(error),
retryable:
RETRYABLE_CODES.has(code) ||
(error instanceof AnalysisCapabilityUnavailableError &&
error.retryable) ||
(code === "resource_constraint" &&
error instanceof AnalysisResourceConstraintError &&
error.resource === "capacity"),
+30 -1
View File
@@ -73,6 +73,12 @@ import {
androidViewRequestSchema,
androidManifestViewItemSchema,
} from "./androidPackageView.js";
import {
projectDartAotView,
dartAotSummarySchema,
dartAotViewRequestSchema,
dartAotViewContextSchema,
} from "./dartAotView.js";
/** Public name of the selected-view workflow. */
export const INSPECT_ANALYSIS_VIEW_OPERATION = "inspect_analysis_view" as const;
@@ -190,6 +196,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
apiSurfaceViewSchema,
captureViewRequestSchema,
qlogViewRequestSchema,
dartAotViewRequestSchema,
]);
// The application owns admission and authenticated Evidence parsing. SDK and
@@ -305,6 +312,7 @@ const viewResultBase = {
"inspect_managed_artifact",
"inspect_web_network_capture",
"inspect_android_package",
"inspect_dart_aot",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -376,6 +384,13 @@ export const androidPackageSummaryViewResultSchema = z.strictObject({
summary: androidPackageSummarySchema,
});
/** Exact snapshot and pool-coverage carrier for selected AOT delivery. */
export const dartAotSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_dart_aot"),
summary: dartAotSummarySchema,
});
/** Projected facts for one selected view of retained analysis Evidence. */
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
z.strictObject({
@@ -400,6 +415,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
managedSummarySchema,
captureSummarySchema,
androidPackageSummarySchema,
dartAotSummarySchema,
]),
}),
z.strictObject({
@@ -470,6 +486,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...viewResultBase,
parent_operation: z.literal("inspect_android_package"),
}),
z.strictObject({
kind: z.literal("dart-aot"),
view: dartAotViewRequestSchema,
items: z.array(z.string()),
...viewResultBase,
...dartAotViewContextSchema.shape,
parent_operation: z.literal("inspect_dart_aot"),
}),
z.strictObject({
kind: z.literal("inventory"),
view: inventoryViewSchema,
@@ -549,6 +573,10 @@ export type UnsignedAnalysisView =
| Omit<
Extract<AnalysisViewResult, { readonly kind: "android" }>,
"view_digest"
>
| Omit<
Extract<AnalysisViewResult, { readonly kind: "dart-aot" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
@@ -594,7 +622,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -624,6 +652,7 @@ const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_android_package", projectAndroidPackageView],
["inspect_dart_aot", projectDartAotView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
]);
+123
View File
@@ -0,0 +1,123 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { flutterResultSchemas } from "../flutter/flutterBuildAnalysis.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const aotSchema = flutterResultSchemas.inspect_dart_aot;
/** Snapshot identity and original coverage, without unrelated string inventories. */
export const dartAotSummarySchema = aotSchema.extend({
string_pool: aotSchema.shape.string_pool
.omit({ package_uris: true, dart_uris: true, class_like_tokens: true })
.extend({
returned_counts: z.strictObject({
package_uris: z.number().int().nonnegative(),
dart_uris: z.number().int().nonnegative(),
class_like_tokens: z.number().int().nonnegative(),
}),
}),
});
/** Pages of the producer-returned strings, preserving original order and scope. */
export const dartAotViewRequestSchema = z.strictObject({
kind: z.literal("dart-aot"),
collection: z.enum(["package_uris", "dart_uris", "class_like_tokens"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
export const dartAotViewContextSchema = z.strictObject({
abi: aotSchema.shape.abi,
libapp: aotSchema.shape.libapp,
source_coverage: aotSchema.shape.coverage,
string_pool: dartAotSummarySchema.shape.string_pool,
});
/** Reuse authenticated AOT Evidence without opening the APK or rescanning its ELF. */
export const projectDartAotView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "dart-aot")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message: "Dart AOT Evidence supports summary and string-pool pages.",
},
]),
);
const parsed = aotSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
const report = parsed.data;
const { package_uris, dart_uris, class_like_tokens, ...pool } =
report.string_pool;
const string_pool = {
...pool,
returned_counts: {
package_uris: package_uris.length,
dart_uris: dart_uris.length,
class_like_tokens: class_like_tokens.length,
},
};
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_dart_aot" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.target.path, sha256: report.target.sha256 },
limitations: [...parent.limitations],
unknowns: [
"String-pool entries are byte-pattern observations, not recovered typed classes or functions.",
"Counts ending in _at_least remain lower bounds; exhausting returned strings does not establish a complete snapshot inventory.",
...(parent.subject == null
? [
"The parent has no recorded subject; its normalized target identity cannot be cross-checked against a subject digest.",
]
: []),
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: { ...report, string_pool },
coverage: completeWithinViewCoverage(1, 1),
});
const collection = report.string_pool[view.collection];
const items = collection.slice(view.offset, view.offset + view.limit);
return ok({
kind: "dart-aot",
view,
...shared,
items,
abi: report.abi,
libapp: report.libapp,
source_coverage: report.coverage,
string_pool,
coverage: pageViewCoverage(view.offset, items.length, collection.length),
});
};
+3 -13
View File
@@ -1,3 +1,5 @@
import type { ZipPackageFormat } from "./zipPackageFormat.js";
/** Provider-neutral CPU families detected from supported executable headers. */
export const BINARY_ARCHITECTURES = [
"x86",
@@ -167,19 +169,7 @@ export type BinaryTarget =
| (BinaryTargetIdentity &
NonExecutableMetadata & {
readonly kind: "archive";
readonly format:
| "zip"
| "ipa"
| "apk"
| "msix"
| "appx"
| "hap"
| "hsp"
| "app-pack"
| "asar"
| "ines"
| "dmg"
| "pkg";
readonly format: ZipPackageFormat | "asar" | "ines" | "dmg" | "pkg";
})
| (BinaryTargetIdentity &
NonExecutableMetadata & {
@@ -30,6 +30,12 @@ export const flutterInputSchemas = {
}),
} as const;
/** Retained delivery is selected independently of the provider's ABI request. */
export const dartAotInspectionInputSchema =
flutterInputSchemas.inspect_dart_aot.extend({
detail: z.enum(["complete", "summary"]).optional(),
});
/** Supported Flutter-backed operations. */
export type FlutterOperation = keyof typeof flutterInputSchemas;
/** Validated Flutter requests carry their selected operation. */
@@ -27,10 +27,8 @@ import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { ok, err, type Result } from "../../domain/result.js";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import {
PrivateRuntimeRoot,
PrivateRuntimeRootUnavailableError,
} from "../../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRootUnavailableError } from "../../process/PrivateRuntimeRootUnavailableError.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
import {
ProviderProcessSupervisor,
@@ -735,7 +733,7 @@ export class JavaScriptAnalysisWorker {
PROVIDER,
OPERATION,
cause.message,
{ cause },
{ cause, retryable: cause.retryable },
)
: new ProviderAdapterError(PROVIDER, OPERATION, {
cause,
@@ -16,10 +16,8 @@ import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import { WEB_SOURCE_MAP_LIMITS } from "../../domain/webSourceLocation.js";
import {
PrivateRuntimeRoot,
PrivateRuntimeRootUnavailableError,
} from "../../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRootUnavailableError } from "../../process/PrivateRuntimeRootUnavailableError.js";
import { ProviderStartupDeadline } from "../../process/ProviderDeadline.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
import { cleanupOwnedProcessGroup } from "../../process/ProcessOwnership.js";
@@ -261,7 +259,7 @@ class OwnedCodec implements SourceMapCleanupOwner {
PROVIDER,
OPERATION,
cause.message,
{ cause },
{ cause, retryable: cause.retryable },
)
: new ProviderAdapterError(PROVIDER, OPERATION, {
cause,
+4 -11
View File
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { WindowsPrivateRuntime } from "../windows/WindowsPrivateRuntime.js";
import { PrivateRuntimeRootUnavailableError } from "./PrivateRuntimeRootUnavailableError.js";
import {
windowsNativeCapabilities,
@@ -34,16 +35,6 @@ export const privateRuntimeRootCapability = (
? windowsNativeCapabilities(platform).private_runtime_dacl
: { available: true, reason: null, proof: "posix-mkdtemp-owner-only" };
/** Expected failure when a runtime root's privacy boundary is unavailable. */
export class PrivateRuntimeRootUnavailableError extends Error {
readonly code = "private-runtime-root-authority-unavailable";
constructor(message: string) {
super(message);
this.name = "PrivateRuntimeRootUnavailableError";
}
}
/**
* Owns a private temporary runtime root and removes it idempotently.
*
@@ -66,7 +57,9 @@ export class PrivateRuntimeRoot {
const platform = options.platform ?? process.platform;
const capability = privateRuntimeRootCapability(platform);
if (!capability.available)
throw new PrivateRuntimeRootUnavailableError(capability.reason);
throw new PrivateRuntimeRootUnavailableError(capability.reason, {
retryable: capability.retryable === true,
});
if (platform === "win32") {
const runtime = WindowsPrivateRuntime.create(
options.parent ?? tmpdir(),
@@ -0,0 +1,14 @@
/** Expected failure when a runtime root's privacy boundary is unavailable. */
export class PrivateRuntimeRootUnavailableError extends Error {
readonly code = "private-runtime-root-authority-unavailable";
readonly retryable: boolean;
constructor(
message: string,
options?: ErrorOptions & { readonly retryable?: boolean },
) {
super(message, options);
this.name = "PrivateRuntimeRootUnavailableError";
this.retryable = options?.retryable ?? false;
}
}
+2
View File
@@ -11,6 +11,7 @@ export type WindowsNativeCapability =
readonly available: false;
readonly reason: string;
readonly proof: "not-proven" | "not-applicable";
readonly retryable?: true;
};
/** Security controls required before REA may claim Windows isolation. */
@@ -52,6 +53,7 @@ export const windowsNativeCapabilities = (
available: false,
reason: loaded.reason,
proof: "not-proven",
...(loaded.retryable === true ? { retryable: true as const } : {}),
} as const);
return {
job_object_process_ownership: capability,
+1
View File
@@ -444,6 +444,7 @@ export const createServer = (
toolLogger,
recordEvidence,
analysisAdmission,
evidenceById,
);
registerApktoolTools(
server,
+26 -11
View File
@@ -1,10 +1,15 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { FlutterBuildAnalysisService } from "../application/flutter/FlutterBuildAnalysisService.js";
import { inspectDartAot } from "../application/flutter/DartAotInspection.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import type { Logger } from "pino";
import { createContractToolHandler } from "./contractToolHandler.js";
import {
createContractToolHandler,
type ContractToolService,
} from "./contractToolHandler.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Bind Flutter handlers to their exact named contracts through admission. */
@@ -14,6 +19,7 @@ export const registerFlutterTools = (
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
evidenceById?: EvidenceLookup,
): void => {
const handler = createContractToolHandler(
server,
@@ -22,14 +28,23 @@ export const registerFlutterTools = (
recordEvidence,
withAdmittedAnalysis,
);
for (const contract of [
toolContract("identify_flutter_build"),
toolContract("inspect_dart_aot"),
] as const) {
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
handler(contract),
);
}
const identify = toolContract("identify_flutter_build");
server.registerTool(
identify.name,
toolRegistrationOptions(identify),
handler(identify),
);
const aotService: ContractToolService<"inspect_dart_aot"> = {
execute: (_operation, input, options) =>
inspectDartAot(service, input, { recordEvidence, evidenceById }, options),
};
const aotHandler = createContractToolHandler(
server,
aotService,
logger,
recordEvidence,
withAdmittedAnalysis,
);
const aot = toolContract("inspect_dart_aot");
server.registerTool(aot.name, toolRegistrationOptions(aot), aotHandler(aot));
};
+44 -34
View File
@@ -3,12 +3,11 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { WabtArtifactProvider } from "./WabtArtifactProvider.js";
import {
PrivateRuntimeRoot,
PrivateRuntimeRootUnavailableError,
} from "../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRootUnavailableError } from "../process/PrivateRuntimeRootUnavailableError.js";
import { spawnOwnedProviderProcess } from "../process/ProviderProcess.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
const failureTags: Readonly<Record<string, string>> = {
invalid: "AnalysisInputError",
@@ -40,40 +39,51 @@ it("returns actionable unavailable without creating a workspace when tools are a
});
});
it("reports an unavailable private runtime root without a misleading WABT remediation", async () => {
const toolRoot = await createTestTempDirectory("rea-wabt-tool-root-");
for (const tool of ["wasm-validate", "wasm-objdump", "wasm2wat"])
await writeFile(
join(toolRoot, tool + (process.platform === "win32" ? ".exe" : "")),
"source-owned executable seam",
{ mode: 0o700 },
);
const provider = new WabtArtifactProvider(
{ REA_WABT_BIN_DIRECTORY: toolRoot },
undefined,
() => {
throw new PrivateRuntimeRootUnavailableError(
"REA Windows native controls are unavailable: probe failure",
it.each([false, true])(
"reports an unavailable private runtime root with retryable=%s without a misleading WABT remediation",
async (retryable) => {
const toolRoot = await createTestTempDirectory("rea-wabt-tool-root-");
for (const tool of ["wasm-validate", "wasm-objdump", "wasm2wat"])
await writeFile(
join(toolRoot, tool + (process.platform === "win32" ? ".exe" : "")),
"source-owned executable seam",
{ mode: 0o700 },
);
},
);
expect(
await provider.inspect({
const provider = new WabtArtifactProvider(
{ REA_WABT_BIN_DIRECTORY: toolRoot },
undefined,
() => {
throw new PrivateRuntimeRootUnavailableError(
"REA Windows native controls are unavailable: probe failure",
{ retryable },
);
},
);
const result = await provider.inspect({
path: "/module.wasm",
glue_paths: [],
candidate_paths: [],
}),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
userMessage: undefined,
message: expect.stringContaining(
"REA Windows native controls are unavailable",
),
},
});
});
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
retryable,
userMessage: undefined,
message: expect.stringContaining(
"REA Windows native controls are unavailable",
),
},
});
if (result.ok)
throw new Error("Unavailable runtime must refuse inspection");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
retryable,
category: retryable ? "unavailable" : "unsupported_provider",
});
},
);
it.each([
"success",
"invalid",
+2 -2
View File
@@ -11,7 +11,7 @@ import {
} from "../domain/analysisErrorCore.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import { PrivateRuntimeRootUnavailableError } from "../process/PrivateRuntimeRoot.js";
import { PrivateRuntimeRootUnavailableError } from "../process/PrivateRuntimeRootUnavailableError.js";
import { WABT_LIMITS, WABT_PROVIDER_IDENTITY } from "./WabtRelease.js";
/** Preserve lifecycle failures and diagnostic bytes instead of returning partial success. */
export const wabtFailure = (
@@ -76,7 +76,7 @@ export const wabtFailure = (
WABT_PROVIDER_IDENTITY.id,
"inspect_wasm_artifact",
reason,
{ cause },
{ cause, retryable: cause.retryable },
);
if (phase === "configuration")
return new AnalysisCapabilityUnavailableError(
+23 -3
View File
@@ -1,6 +1,7 @@
import { win32 } from "node:path";
import { z } from "zod";
import { PrivateRuntimeRootUnavailableError } from "../process/PrivateRuntimeRootUnavailableError.js";
import {
requireWindowsNativeAuthority,
@@ -23,6 +24,13 @@ const fileSchema = windowsFileIdentitySchema.extend({
handle: windowsHandleSchema,
});
const runtimes = new Map<string, WindowsPrivateRuntime>();
// Retry only a proven pre-allocation sharing/lock conflict, never opaque text
// or an operation that may already own an unpublished runtime directory.
const transientRuntimeAdmissionSchema = z.object({
code: z.literal("ERR_REA_WINDOWS_NATIVE"),
win32Code: z.union([z.literal(32), z.literal(33)]),
runtimeAllocation: z.literal("not-started"),
});
/** Retain private DACL and path handles until native recursive cleanup settles. */
export class WindowsPrivateRuntime {
@@ -40,9 +48,21 @@ export class WindowsPrivateRuntime {
/** Create a new directory with its private DACL installed at creation. */
static create(parent: string, prefix: string): WindowsPrivateRuntime {
const authority = requireWindowsNativeAuthority();
const observation = runtimeSchema.parse(
authority.call("runtime_create", [parent, prefix]),
);
let observed: unknown;
try {
observed = authority.call("runtime_create", [parent, prefix]);
} catch (cause: unknown) {
if (
cause instanceof Error &&
transientRuntimeAdmissionSchema.safeParse(cause).success
)
throw new PrivateRuntimeRootUnavailableError(cause.message, {
cause,
retryable: true,
});
throw cause;
}
const observation = runtimeSchema.parse(observed);
const runtime = new WindowsPrivateRuntime(observation, authority);
runtimes.set(windowsRuntimeIdentityKey(observation), runtime);
return runtime;