feat(managed): add retained metadata overview and pages (#2413)

Add caller-selected managed metadata summaries and original collection pages while preserving complete CLI/MCP defaults and previous-runtime Evidence. Real SDK replies shrink substantially; actual Codex token/latency results remain mixed and are documented without a token-saving claim.

Validated focused SDK/domain tests, full static/docs checks, real two-assembly repeated workflows and portable old Evidence, real SQLite WASM, and all exact-head CI checks. Raw experimental artifacts remain private.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
Ysopwnable
2026-10-13 07:41:20 +08:00
committed by GitHub
co-authored by factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent f43fc02475
commit 82cfcee19f
17 changed files with 873 additions and 28 deletions
+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 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 and EVM 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. 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 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.',
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
+13 -2
View File
@@ -6,6 +6,7 @@ import { managedOutputSchemas } from "../toolOutputSchemaGroups.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
import { localPathStringSchema } from "../../domain/localPath.js";
import { analysisDetailSchema } from "../analysisDetail.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
export const managedTargetInputSchema = z.strictObject({
@@ -20,6 +21,11 @@ export const managedTargetInputSchema = z.strictObject({
.optional(),
});
/** Delivery selection belongs only to artifact inspection, not member/native queries. */
export const managedArtifactInputSchema = managedTargetInputSchema.extend({
detail: analysisDetailSchema.unwrap().optional(),
});
/** Member inspection may select declaring types before members are decoded. */
export const managedMembersInputSchema = managedTargetInputSchema.extend({
type_names: z
@@ -61,15 +67,20 @@ export const MANAGED_TOOL_CONTRACTS = [
name: "inspect_managed_artifact",
...toolContractMetadata("inspect_managed_artifact"),
description:
"Open and classify an explicit managed PE/CLI path, or inspect the active managed target, then inventory exact assembly/module identity, target framework evidence, references, resources, and custom attributes without loading or executing target code. Returns complete inline inventories when metadata is admitted and explicit partial or malformed coverage otherwise.",
'Inspect an explicit PE/CLI path, or the selected managed target, without loading or executing target code. Omitted or complete detail returns complete metadata inventories with original coverage. Select detail: "summary" on the first call for complete identity, PE/CLI, classification with its evidence, module/MVID, assembly, frameworks, returned-collection counts, coverage/issues and limitations. It retains complete Evidence and returns a distinct linked inspect_analysis_view summary. Page original references/resources/attributes with view kind managed and normalized_result.parent_evidence_id. Counts cover producer-returned rows; partial, unavailable or malformed metadata remains explicit and tokens remain build-local.',
kind: "managed-provider",
inputSchema: managedTargetInputSchema,
inputSchema: managedArtifactInputSchema,
outputSchema,
examples: [
{
title: "Example inspect managed artifact request",
input: { path: "/tmp/Example.dll" },
},
{
title:
"Inspect identity and coverage without unrelated metadata inventories",
input: { path: "/tmp/Example.dll", detail: "summary" },
},
],
},
{
+10 -2
View File
@@ -1,5 +1,8 @@
import { z } from "zod";
import { artifactInventorySummaryViewResultSchema } from "../domain/analysisView/analysisView.js";
import {
artifactInventorySummaryViewResultSchema,
managedArtifactSummaryViewResultSchema,
} from "../domain/analysisView/analysisView.js";
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
import { BINARY_ARCHITECTURES } from "../domain/binaryTargetTypes.js";
import {
@@ -402,7 +405,12 @@ export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
/** Exact Evidence schema for execution-free managed static analysis. */
export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_managed_artifact: evidenceResultOf(managedArtifactInspectionSchema),
inspect_managed_artifact: evidenceResultOf(
z.union([
managedArtifactInspectionSchema,
managedArtifactSummaryViewResultSchema,
]),
),
inspect_managed_members: evidenceResultOf(managedMemberInspectionSchema),
inspect_managed_native_boundaries: evidenceResultOf(
managedNativeBoundaryInspectionSchema,
@@ -733,6 +733,14 @@ it("does not match unavailable layout names using a display placeholder", () =>
});
it("rejects unsupported parent operations and incompatible collections", () => {
expect(
projectAnalysisView(layoutParent(), {
kind: "managed",
collection: "attributes",
offset: 0,
limit: 1,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const unsupported = projectAnalysisView(
{
evidenceId: `ev_${"d".repeat(64)}`,
+43 -15
View File
@@ -42,6 +42,13 @@ import {
evmSummarySchema,
} from "./evmInterfaceView.js";
import { projectArtifactInventoryView } from "./artifactInventoryView.js";
import {
projectManagedArtifactView,
managedViewRequestSchema,
managedViewItemSchema,
managedSummarySchema,
managedViewContextSchema,
} from "./managedArtifactView.js";
import {
projectWasmArtifactView,
wasmViewRequestSchema,
@@ -161,6 +168,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
inventoryViewSchema,
wasmViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
apiSurfaceViewSchema,
]);
@@ -274,6 +282,7 @@ const viewResultBase = {
"inventory_artifact",
"inspect_wasm_artifact",
"inspect_evm_interface",
"inspect_managed_artifact",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -324,6 +333,13 @@ export const evmInterfaceSummaryViewResultSchema = z.strictObject({
summary: evmSummarySchema,
});
/** Exact metadata overview for the managed artifact's selected delivery. */
export const managedArtifactSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_managed_artifact"),
summary: managedSummarySchema,
});
/** Projected facts for one selected view of retained analysis Evidence. */
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
z.strictObject({
@@ -345,6 +361,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
inventorySummarySchema,
wasmSummarySchema,
evmSummarySchema,
managedSummarySchema,
]),
}),
z.strictObject({
@@ -385,6 +402,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...viewResultBase,
parent_operation: z.literal("inspect_evm_interface"),
}),
z.strictObject({
kind: z.literal("managed"),
view: managedViewRequestSchema,
item: managedViewItemSchema,
...viewResultBase,
...managedViewContextSchema.shape,
parent_operation: z.literal("inspect_managed_artifact"),
}),
z.strictObject({
kind: z.literal("inventory"),
view: inventoryViewSchema,
@@ -451,7 +476,11 @@ export type UnsignedAnalysisView =
"view_digest"
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">;
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "managed" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
export const sealAnalysisView = (
@@ -496,7 +525,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, 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, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -520,6 +549,15 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
return parent.evidenceId;
};
/** Named source owners for views that need no extra decoder or accumulator. */
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
]);
/** Project one selected view from authenticated parent analysis Evidence. */
export const projectAnalysisView = (
parent: AnalysisViewParent,
@@ -591,19 +629,9 @@ export const projectAnalysisView = (
const projected = projectNativeFunctionView(parent, native.data, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_wasm_artifact") {
const projected = projectWasmArtifactView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_evm_interface") {
const projected = projectEvmInterfaceView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (
parent.operation === "inspect_artifact" ||
parent.operation === "inventory_artifact"
) {
const projected = projectArtifactInventoryView(parent, view);
const project = retainedViewProjectors.get(parent.operation);
if (project !== undefined) {
const projected = project(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
return err(unsupportedParent(parent));
@@ -218,6 +218,12 @@ export const projectBinaryLayoutView = (
...shared,
});
}
if (view.kind !== "page")
return err(
layoutIncompatible(
"Layout views require summary, facet, item or page selections.",
),
);
if (view.collection === "modules")
return err(
layoutIncompatible(
@@ -0,0 +1,140 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
} from "../managed/managedArtifact.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";
/** Original metadata rows; offsets count entries in the returned parent collection. */
export const managedViewRequestSchema = z.strictObject({
kind: z.literal("managed"),
collection: z.enum(["references", "resources", "attributes"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
export const managedViewItemSchema = z.union([
managedArtifactInspectionSchema.shape.references,
managedArtifactInspectionSchema.shape.resources,
managedArtifactInspectionSchema.shape.attributes,
]);
/** Keep complete classification and coverage; unrequested inventories remain retained. */
export const managedSummarySchema = managedArtifactInspectionSchema
.omit({ references: true, resources: true, attributes: true })
.extend({
reported_counts: z.strictObject({
references: z.number().int().nonnegative(),
resources: z.number().int().nonnegative(),
attributes: z.number().int().nonnegative(),
}),
identity_scope: managedMemberInspectionSchema.shape.identity_scope,
});
export const managedViewContextSchema = z.strictObject({
identity_scope: managedMemberInspectionSchema.shape.identity_scope,
source_metadata_status:
managedArtifactInspectionSchema.shape.metadata.shape.status,
source_coverage: managedArtifactInspectionSchema.shape.coverage,
});
/** Project authenticated metadata without reading a path or invoking a provider. */
export const projectManagedArtifactView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "managed")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Managed artifact inspection supports summary and managed views.",
},
]),
);
const parsed = managedArtifactInspectionSchema.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 identity_scope = {
token_identity: "build-local" as const,
requires_artifact_sha256: report.artifact.sha256,
requires_mvid: report.module?.mvid ?? null,
};
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_managed_artifact" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: uniqueSorted([...parent.limitations, ...report.limitations]),
unknowns: [
"Collection counts and pages cover producer-returned rows; metadata completeness remains the original metadata status and coverage, not an absence claim about unreturned rows.",
"Metadata tokens are build-local coordinates bound to the recorded artifact SHA-256 and module MVID; this view does not load or execute the assembly.",
...(parent.subject == null
? [
"The parent has no recorded subject; its normalized artifact identity cannot be cross-checked against a subject digest.",
]
: []),
...(identity_scope.requires_mvid === null
? [
"The module MVID is unknown; tokens cannot establish a cross-observation module match.",
]
: []),
],
};
if (view.kind === "summary") {
const { references, resources, attributes, ...summary } = report;
const reported_counts = {
references: references.length,
resources: resources.length,
attributes: attributes.length,
};
const total = references.length + resources.length + attributes.length;
return ok({
kind: "summary",
view,
...shared,
summary: { ...summary, reported_counts, identity_scope },
coverage: completeWithinViewCoverage(total, total),
});
}
const collection = report[view.collection];
const item = collection.slice(view.offset, view.offset + view.limit);
return ok({
kind: "managed",
view,
item,
...shared,
identity_scope,
source_metadata_status: report.metadata.status,
source_coverage: report.coverage,
coverage: pageViewCoverage(view.offset, item.length, collection.length),
});
};
+1 -1
View File
@@ -709,7 +709,7 @@ const registerBinaryAnalysisTools = ({
};
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, evidenceOptions);
registerArtifactTools(server, { ...evidenceOptions, evidenceById });
registerManagedTools(server, evidenceOptions);
registerManagedTools(server, { ...evidenceOptions, evidenceById });
if (session !== undefined)
registerManagedWorkflowTools(server, {
logger,
+29 -2
View File
@@ -1,11 +1,16 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import { MANAGED_TOOL_CONTRACTS } from "../contracts/managed/managedToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { err } from "../domain/result.js";
import { err, ok } from "../domain/result.js";
import type { Logger } from "pino";
import { registerEvidenceTools } from "./registerEvidenceTools.js";
import { runManagedProviderExecution } from "../composition/directAnalysis.js";
@@ -18,6 +23,7 @@ export const registerManagedTools = (
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly evidenceById?: EvidenceLookup | undefined;
readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis;
},
): void => {
@@ -28,6 +34,17 @@ export const registerManagedTools = (
execute: async (operation, parameters, executionOptions) => {
if (!isManagedToolName(operation))
return analysis.execute(operation, parameters, executionOptions);
const { detail: _detail, ...artifactParameters } = parameters;
if (
operation === "inspect_managed_artifact" &&
parameters.detail === "summary"
) {
const ready = requireAnalysisViewRetention(operation, {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
});
if (!ready.ok) return ready;
}
const requestedPath = parameters.path;
const activeTarget = options.activeTarget?.();
const path =
@@ -52,7 +69,9 @@ export const registerManagedTools = (
path,
operation,
executionOptions?.signal,
parameters,
operation === "inspect_managed_artifact"
? artifactParameters
: parameters,
);
if (execution.ok && typeof requestedPath === "string")
selectedManagedPath = requestedPath;
@@ -62,5 +81,13 @@ export const registerManagedTools = (
registerEvidenceTools(server, MANAGED_TOOL_CONTRACTS, {
...options,
analysisForAdmission,
projectEvidence: (operation, parameters, evidence) =>
operation === "inspect_managed_artifact" &&
parameters.detail === "summary"
? summarizeRetainedAnalysis(evidence, {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
})
: ok(evidence),
});
};