feat(android): add opt-in package summaries and retained manifest views

Add explicit package summary delivery and exact retained manifest pages while preserving complete MCP defaults, one-shot CLI output, provider requests, source identity and session lifetime. Return distinct linked Evidence and preserve partial/null facts; reject unavailable retention before engine work.

Validation: 27 relevant SDK/domain/Android boundary checks, focused test-only correction rerun, full supported compiler/lint and docs checks, real NewPipe SDK pairs, authentic old Evidence continuation, four actual Codex trials with failures/regressions retained, and all 39 exact-head CI checks. Package replies shrink 119,527 to 8,659 bytes; no model-token or time gain is established.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
Ysopwnable
2026-10-13 10:21:53 +08:00
committed by GitHub
co-authored by factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent ca2d15b3ee
commit f254f5ac2b
14 changed files with 777 additions and 11 deletions
@@ -0,0 +1,43 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AndroidAnalysisService } from "./AndroidAnalysisService.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
type AnalysisViewRetention,
} from "../analysisView/AnalysisViewService.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { androidPackageInspectionInputSchema } from "../../domain/android/androidAnalysis.js";
import type { Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, type Result } from "../../domain/result.js";
/** Preserve the complete provider request; select retained delivery explicitly. */
export const inspectAndroidPackage = async (
service: AndroidAnalysisService,
rawInput: unknown,
retention: AnalysisViewRetention,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> => {
const operation = "inspect_android_package";
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const parsed = androidPackageInspectionInputSchema.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 executed = await service.execute(
operation,
{ path: parsed.data.path },
options,
);
if (!executed.ok || parsed.data.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 or inspect_web_network_capture Evidence without repeating analysis. 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 and managed artifact 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. 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 or inspect_web_network_capture Evidence without repeating analysis. 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.',
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
+13 -3
View File
@@ -1,7 +1,10 @@
import { z } from "zod";
import {
androidInputSchemas,
androidPackageInspectionInputSchema,
androidResultSchemas,
} from "../../domain/android/androidAnalysis.js";
import { androidPackageSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
import type { ToolContract } from "../toolContractTypes.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
import { toolContractMetadata } from "../toolEffects.js";
@@ -12,14 +15,21 @@ export const ANDROID_TOOL_CONTRACTS = [
name: "inspect_android_package",
...toolContractMetadata("inspect_android_package"),
description:
"Inspect a local APK's package, SDK and permission declarations, decoded manifest and class/resource counts. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and JDK; uses one worker in an isolated temporary workspace.",
'Inspect a local APK\'s package, SDK and permission declarations, decoded manifest and class/resource counts. Omitted or complete detail preserves the complete result. Select detail: "summary" for all declarations, engine identity and counts without decoded manifest text or duplicate raw calls; retains the complete source and returns a distinct linked inspect_analysis_view summary. Read the exact retained manifest with view kind android, facet manifest, offset and limit (UTF-16 code units), using normalized_result.parent_evidence_id. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and JDK; uses one worker in an isolated temporary workspace.',
kind: "android-provider",
inputSchema: androidInputSchemas.inspect_android_package,
inputSchema: androidPackageInspectionInputSchema,
outputSchema: evidenceResultOf(
androidResultSchemas.inspect_android_package,
z.union([
androidResultSchemas.inspect_android_package,
androidPackageSummaryViewResultSchema,
]),
),
examples: [
{ title: "Inspect an APK", input: { path: "/tmp/Example.apk" } },
{
title: "Inspect APK declarations with retained manifest",
input: { path: "/tmp/Example.apk", detail: "summary" },
},
],
},
{
+29 -1
View File
@@ -56,6 +56,12 @@ import {
wasmSummarySchema,
} from "./wasmArtifactView.js";
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
import {
projectAndroidPackageView,
androidPackageSummarySchema,
androidViewRequestSchema,
androidManifestViewItemSchema,
} from "./androidPackageView.js";
/** Public name of the selected-view workflow. */
export const INSPECT_ANALYSIS_VIEW_OPERATION = "inspect_analysis_view" as const;
@@ -169,6 +175,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
wasmViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
androidViewRequestSchema,
apiSurfaceViewSchema,
]);
@@ -283,6 +290,7 @@ const viewResultBase = {
"inspect_wasm_artifact",
"inspect_evm_interface",
"inspect_managed_artifact",
"inspect_android_package",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -340,6 +348,13 @@ export const managedArtifactSummaryViewResultSchema = z.strictObject({
summary: managedSummarySchema,
});
/** Exact package declarations with retained decoded manifest text. */
export const androidPackageSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_android_package"),
summary: androidPackageSummarySchema,
});
/** Projected facts for one selected view of retained analysis Evidence. */
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
z.strictObject({
@@ -362,6 +377,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
wasmSummarySchema,
evmSummarySchema,
managedSummarySchema,
androidPackageSummarySchema,
]),
}),
z.strictObject({
@@ -410,6 +426,13 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...managedViewContextSchema.shape,
parent_operation: z.literal("inspect_managed_artifact"),
}),
z.strictObject({
kind: z.literal("android"),
view: androidViewRequestSchema,
item: androidManifestViewItemSchema,
...viewResultBase,
parent_operation: z.literal("inspect_android_package"),
}),
z.strictObject({
kind: z.literal("inventory"),
view: inventoryViewSchema,
@@ -480,6 +503,10 @@ export type UnsignedAnalysisView =
| Omit<
Extract<AnalysisViewResult, { readonly kind: "managed" }>,
"view_digest"
>
| Omit<
Extract<AnalysisViewResult, { readonly kind: "android" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
@@ -525,7 +552,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, 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, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -554,6 +581,7 @@ const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_android_package", projectAndroidPackageView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
]);
@@ -0,0 +1,136 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { androidResultSchemas } from "../android/androidAnalysis.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 } from "./analysisViewCoverage.js";
import { analysisTextPage } from "./analysisViewText.js";
const packageSchema = androidResultSchemas.inspect_android_package;
/** All package declarations remain inline; decoded manifest text stays retained. */
export const androidPackageSummarySchema = packageSchema.extend({
manifest: packageSchema.shape.manifest.omit({ text: true }).extend({
text_code_units: z.number().int().nonnegative(),
text_included: z.literal(false),
}),
});
/** Exact decoded text; offsets and limits count UTF-16 code units. */
export const androidViewRequestSchema = z.strictObject({
kind: z.literal("android"),
facet: z.literal("manifest"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive(),
});
export const androidManifestViewItemSchema = z.strictObject({
text: z.string(),
unit: z.literal("utf16-code-units"),
source_status: packageSchema.shape.manifest.shape.status,
reported_total_bytes: packageSchema.shape.manifest.shape.reported_total_bytes,
});
/** Project an authenticated package record without reopening the APK or engine. */
export const projectAndroidPackageView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "android")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Android package Evidence supports summary and manifest views.",
},
]),
);
const parsed = packageSchema.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 },
),
);
// Engine artifact_sha256 identifies the JAR, never the APK. A missing
// authenticated APK subject cannot be repaired using the engine identity.
if (parent.subject == null)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Android package views require the recorded APK subject identity.",
},
]),
);
const report = parsed.data;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_android_package" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
},
limitations: [...parent.limitations],
unknowns: [
"APK signatures were not verified; package declarations do not establish authenticity or runtime behavior.",
...(report.manifest.status === "partial"
? [
"The decoded manifest is partial; exhausting retained text does not establish complete manifest coverage.",
]
: []),
],
};
if (view.kind === "summary") {
const { text, ...manifest } = report.manifest;
return ok({
kind: "summary",
view,
...shared,
summary: {
...report,
manifest: {
...manifest,
text_code_units: text.length,
text_included: false,
},
},
coverage: completeWithinViewCoverage(1, 1),
});
}
const page = analysisTextPage(
report.manifest.text,
view.offset,
view.limit,
"Manifest",
);
if (!page.ok) return page;
return ok({
kind: "android",
view,
...shared,
item: {
...page.value.item,
source_status: report.manifest.status,
reported_total_bytes: report.manifest.reported_total_bytes,
},
coverage: page.value.coverage,
});
};
@@ -314,7 +314,7 @@ export const projectJavaScriptApplicationView = (
...shared,
});
}
if (view.collection !== "modules")
if (view.kind !== "page" || view.collection !== "modules")
return err(
jsIncompatible(
"Section and symbol collections apply to inspect_binary_layout Evidence.",
+6
View File
@@ -45,6 +45,12 @@ export const androidInputSchemas = {
}),
} as const;
/** Optional retained delivery is separate from the engine's APK request. */
export const androidPackageInspectionInputSchema =
androidInputSchemas.inspect_android_package.extend({
detail: z.enum(["complete", "summary"]).optional(),
});
/** Supported static Android operations. */
export type AndroidOperation = keyof typeof androidInputSchemas;
/** Validated Android requests carry their selected operation. */
+1
View File
@@ -515,6 +515,7 @@ const registerConfiguredAnalysisTools = (
toolLogger,
recordEvidence,
withAdmittedAnalysis,
evidenceById,
);
registerJebTools(
server,
+20 -1
View File
@@ -1,6 +1,8 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { AndroidAnalysisService } from "../application/android/AndroidAnalysisService.js";
import { inspectAndroidPackage } from "../application/android/AndroidPackageInspection.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import { summarizeRetainedAndroidSearch } from "../application/android/AndroidSearchEvidenceSummary.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
@@ -18,6 +20,7 @@ export const registerAndroidTools = (
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
evidenceById?: EvidenceLookup,
): void => {
const handler = createContractToolHandler(
server,
@@ -44,10 +47,26 @@ export const registerAndroidTools = (
withAdmittedAnalysis,
);
const packageContract = toolContract("inspect_android_package");
const packageService: ContractToolService<"inspect_android_package"> = {
execute: (_operation, input, options) =>
inspectAndroidPackage(
service,
input,
{ recordEvidence, evidenceById },
options,
),
};
const packageHandler = createContractToolHandler(
server,
packageService,
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
packageContract.name,
toolRegistrationOptions(packageContract),
handler(packageContract),
packageHandler(packageContract),
);
const searchContract = toolContract("search_android_classes");
server.registerTool(