refactor(managed): group capability workflows and verification (#926)

This commit is contained in:
ysopwnable
2026-10-07 19:22:04 +08:00
committed by GitHub
parent 2ccc86cd13
commit 28713f9b4d
75 changed files with 217 additions and 177 deletions
@@ -0,0 +1,94 @@
import { z } from "zod";
import type { ToolContract } from "../toolContracts.js";
import { managedOutputSchemas } from "../toolOutputSchemas.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
const managedTargetInputSchema = z.object({
path: z
.string()
.min(1)
.optional()
.describe(
"Explicit managed PE/CLI path; omit to reuse the previously selected managed target",
),
});
export const managedArtifactInputSchema = managedTargetInputSchema;
/** Exact caller boundary for execution-free metadata/signature/IL inspection. */
export const managedMemberInputSchema = managedTargetInputSchema;
/** Exact caller boundary for execution-free managed/native boundary inspection. */
export const managedNativeBoundaryInputSchema = managedTargetInputSchema;
const outputSchema = requireOutputSchema(
managedOutputSchemas,
"inspect_managed_artifact",
);
const memberOutputSchema = requireOutputSchema(
managedOutputSchemas,
"inspect_managed_members",
);
const nativeBoundaryOutputSchema = requireOutputSchema(
managedOutputSchemas,
"inspect_managed_native_boundaries",
);
/** Read-only managed artifact contracts. */
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.",
kind: "managed-provider",
inputSchema: managedArtifactInputSchema,
outputSchema,
examples: [
{
title: "Example inspect managed artifact request",
input: { path: "/tmp/Example.dll" },
},
],
},
{
name: "inspect_managed_members",
...toolContractMetadata("inspect_managed_members"),
description:
"Inspect PE/CLI metadata members, signatures, raw CIL hashes, decoded-instruction-tuple hashes, separately reported exception regions, call edges, and field-access anchors without loading or executing target code. Metadata tokens are reported as build-local coordinates bound to the artifact SHA-256 and MVID; the tuple hash does not resolve them or fully commit control flow.",
kind: "managed-provider",
inputSchema: managedMemberInputSchema,
outputSchema: memberOutputSchema,
examples: [
{
title: "Example inspect managed members request",
input: {},
},
],
},
{
name: "inspect_managed_native_boundaries",
...toolContractMetadata("inspect_managed_native_boundaries"),
description:
"Inspect PE/CLI ModuleRef, ImplMap/PInvoke declarations, CLI native-header indicators, and non-IL method implementation flags without loading or executing target code. Results are managed declarations and degraded native-boundary observations, not verified native exports or addresses.",
kind: "managed-provider",
inputSchema: managedNativeBoundaryInputSchema,
outputSchema: nativeBoundaryOutputSchema,
examples: [
{
title: "Example inspect managed/native boundary request",
input: {},
},
],
},
] as const satisfies readonly ToolContract[];
/** Names of execution-free managed static operations. */
export type ManagedToolName = (typeof MANAGED_TOOL_CONTRACTS)[number]["name"];
/** Parse whether an analysis operation belongs to the managed static tools. */
export const isManagedToolName = (name: string): name is ManagedToolName =>
MANAGED_TOOL_CONTRACTS.some((contract) => contract.name === name);
@@ -0,0 +1,309 @@
import { createEvidence } from "../../domain/evidence.js";
import type {
ManagedMemberInspection,
ManagedNativeBoundaryInspection,
} from "../../domain/managed/managedArtifact.js";
import type { InspectMacho } from "../../domain/nativeInspection.js";
const MANAGED_STATIC_EXAMPLE_PROVIDER = {
id: "rea-dotnet-static",
name: "REA managed static analysis provider",
version: "1",
} as const;
const NATIVE_EXAMPLE_PROVIDER = {
id: "native-macos",
name: "REA native macOS provider",
version: "1",
} as const;
const emptyManagedMembers = (
sha256: string,
mvid: string,
): ManagedMemberInspection => ({
artifact: {
path: `/examples/${sha256.slice(0, 8)}.dll`,
sha256,
byte_length: 4096,
format: "pe",
},
module: {
name: "Example.dll",
generation: 0,
mvid,
enc_id: null,
enc_base_id: null,
token: "0x00000001",
row_offset: 0,
},
metadata: {
status: "complete",
version: "v4.0.30319",
table_row_counts: {},
},
identity_scope: {
token_identity: "build-local",
requires_artifact_sha256: sha256,
requires_mvid: mvid,
},
types: [],
fields: [],
methods: [],
member_refs: [],
call_edges: [],
field_accesses: [],
coverage: { state: "complete", issues: [] },
limitations: [],
});
const evidence = (result: ManagedMemberInspection) =>
createEvidence(undefined, MANAGED_STATIC_EXAMPLE_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
});
const runtimeMembers = (): ManagedMemberInspection => {
const result = emptyManagedMembers(
"2".repeat(64),
"11112222-3333-4444-9555-666677778888",
);
return {
...result,
methods: [
{
token: "0x06000001",
row_offset: 128,
declaring_type_token: "0x02000001",
declaring_type: "Example.Program",
name: "Main",
rva: 8192,
impl_flags: 0,
flags: 22,
signature: {
raw_length: 3,
raw_sha256: "3".repeat(64),
kind: "method",
parse_status: "decoded",
calling_convention: "default",
generic_parameter_count: 0,
parameter_count: 0,
return_type: "void",
parameter_types: [],
field_type: null,
issue: null,
},
body: {
status: "present",
header_format: "tiny",
rva: 8192,
file_offset: 512,
max_stack: 8,
init_locals: false,
local_var_sig_token: null,
il_size: 1,
il_sha256: "4".repeat(64),
normalized_il_sha256: "5".repeat(64),
instruction_count: 1,
decoded_instruction_count: 1,
truncated_instructions: 0,
opcode_counts: { ret: 1 },
anchors: [],
exception_regions: [],
issue: null,
},
},
],
};
};
/** Minimal valid managed member comparison request for public contracts. */
export const MANAGED_MEMBER_COMPARISON_EXAMPLE = {
left: evidence(
emptyManagedMembers("0".repeat(64), "00112233-4455-6677-8899-aabbccddeeff"),
),
right: evidence(
emptyManagedMembers("1".repeat(64), "ffeeddcc-bbaa-4988-9766-554433221100"),
),
};
const runtimeExampleEvidence = evidence(runtimeMembers());
/** Minimal valid managed application graph projection request. */
export const MANAGED_APPLICATION_GRAPH_EXAMPLE = {
managed_members: runtimeExampleEvidence,
};
const boundaryEvidence = () => {
const result: ManagedNativeBoundaryInspection = {
artifact: {
path: "/examples/ManagedInterop.exe",
sha256: "6".repeat(64),
byte_length: 8192,
format: "pe",
},
module: {
name: "ManagedInterop.exe",
generation: 0,
mvid: "00112233-4455-4677-8899-aabbccddeeff",
enc_id: null,
enc_base_id: null,
token: "0x00000001",
row_offset: 0,
},
metadata: {
status: "complete",
version: "v4.0.30319",
table_row_counts: {},
},
identity_scope: {
token_identity: "build-local",
requires_artifact_sha256: "6".repeat(64),
requires_mvid: "00112233-4455-4677-8899-aabbccddeeff",
},
cli_native: {
il_only: true,
requires_32bit: false,
strong_name_signed: false,
native_entry_point: false,
ready_to_run_signature: false,
managed_native_header_rva: 0,
managed_native_header_size: 0,
},
module_refs: [
{
token: "0x1a000001",
row_offset: 256,
name: "nativehelper.dll",
},
],
pinvoke_imports: [
{
token: "0x1c000001",
row_offset: 288,
mapping_flags: 0,
mapping_flags_hex: "0x0000",
member_token: "0x06000001",
member_kind: "method",
member_name: "OpenNative",
import_name: "open_native",
import_scope_token: "0x1a000001",
import_scope_name: "nativehelper.dll",
no_mangle: true,
char_set: "not-specified",
call_convention: "cdecl",
supports_last_error: false,
best_fit: "assembly-default",
throw_on_unmappable_char: "assembly-default",
verification: "managed-declaration-only",
},
],
native_implementations: [],
summary: {
module_ref_count: 1,
pinvoke_import_count: 1,
native_implementation_count: 0,
ready_to_run: false,
mixed_mode_or_native_header: false,
},
coverage: { state: "complete", issues: [] },
limitations: [],
};
return createEvidence(undefined, MANAGED_STATIC_EXAMPLE_PROVIDER, {
operation: "inspect_managed_native_boundaries",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
});
};
const nativeExportEvidence = () => {
const result: InspectMacho = {
format: "mach-o",
endian: "little",
word_size: 64,
file_type: "dylib",
flags: [],
uuid: null,
entrypoints: coverage([]),
architectures: coverage([]),
build_metadata: coverage([]),
load_commands: coverage([]),
dependencies: coverage([]),
imports: coverage([]),
exports: coverage([
{
name: "open_native",
address: "0x1000",
weak: false,
reexport: false,
source: "nm",
},
]),
segments: coverage([]),
provenance: [],
limitations: [],
};
return createEvidence(
{
path: "/examples/nativehelper.dll",
sha256: "7".repeat(64),
format: "mach-o",
architecture: "x86_64",
},
NATIVE_EXAMPLE_PROVIDER,
{
operation: "inspect_macho",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
},
);
};
const coverage = <Item>(items: readonly Item[]) => ({
items: [...items],
total: items.length,
exhaustive: true,
limitations: [],
});
/** Minimal valid managed decompiler reconstruction import request. */
export const MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE = {
static_members: runtimeExampleEvidence,
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
family: "ilspy",
executable_sha256: null,
options: ["--disable-updatecheck", "--type", "Example.Program"],
},
methods: [
{
token: "0x06000001",
signature_sha256: "3".repeat(64),
normalized_il_sha256: "5".repeat(64),
reconstruction: {
kind: "decompiled-csharp",
language: "csharp",
text: "internal static void Main() { }",
source_path: "/examples/Example.Program.cs",
start_line: 1,
end_line: 1,
},
},
],
notes: [
"Synthetic example only; decompiler output is imported as inference.",
],
};
/** Minimal valid managed/native verification request. */
export const MANAGED_NATIVE_VERIFICATION_EXAMPLE = {
managed_boundaries: boundaryEvidence(),
native_observations: [nativeExportEvidence()],
};
@@ -0,0 +1,200 @@
import { z } from "zod";
import { evidenceSchema } from "../../domain/evidence.js";
import { managedReconstructionImportInputSchema } from "../../domain/managed/managedReconstruction.js";
import type { ToolContract } from "../toolContracts.js";
import { managedWorkflowOutputSchemas } from "../toolOutputSchemas.js";
import {
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
MANAGED_APPLICATION_GRAPH_EXAMPLE,
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
} from "./managedWorkflowExamples.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
/** Inputs for comparing two managed observations carried inline. */
export const compareManagedMembersReferenceInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
})
.superRefine((input, context) => {
if (input.left.evidence_id === input.right.evidence_id)
context.addIssue({
code: "custom",
path: ["right"],
message: "Managed member Evidence must be distinct",
});
});
/** Inline Evidence input for importing reconstruction. */
export const managedReconstructionReferenceInputSchema =
managedReconstructionImportInputSchema.extend({
static_members: evidenceSchema,
});
/** Inline Evidence inputs for managed/native verification. */
export const managedNativeVerificationReferenceInputSchema = z
.strictObject({
managed_boundaries: evidenceSchema,
native_observations: z
.array(evidenceSchema)
.min(1)
.describe("Native function or export Evidence records"),
})
.superRefine((input, context) => {
const ids = new Set<string>([input.managed_boundaries.evidence_id]);
for (const [index, evidence] of input.native_observations.entries()) {
if (evidence.evidence_id === input.managed_boundaries.evidence_id)
context.addIssue({
code: "custom",
path: ["native_observations", index],
message:
"Native observation Evidence must be distinct from managed boundary Evidence",
});
if (ids.has(evidence.evidence_id))
context.addIssue({
code: "custom",
path: ["native_observations", index],
message: "Native observation Evidence IDs must be unique",
});
ids.add(evidence.evidence_id);
}
});
const managedApplicationGraphReferenceFacts = {} as const;
const managedApplicationGraphReferenceShape = z.strictObject({
...managedApplicationGraphReferenceFacts,
managed_artifact: evidenceSchema.optional(),
managed_members: evidenceSchema.optional(),
managed_native_boundaries: evidenceSchema.optional(),
});
/** Inline Evidence sources for managed application graph projection. */
export const managedApplicationGraphReferenceInputSchema = z
.union([
managedApplicationGraphReferenceShape.extend({
managed_artifact: evidenceSchema,
}),
managedApplicationGraphReferenceShape.extend({
managed_members: evidenceSchema,
}),
managedApplicationGraphReferenceShape.extend({
managed_native_boundaries: evidenceSchema,
}),
])
.superRefine((input, context) => {
const ids = [
input.managed_artifact?.evidence_id,
input.managed_members?.evidence_id,
input.managed_native_boundaries?.evidence_id,
].filter((id): id is string => id !== undefined);
if (ids.length === 0)
context.addIssue({
code: "custom",
message: "Provide at least one managed Evidence source",
});
if (new Set(ids).size !== ids.length)
context.addIssue({
code: "custom",
message: "Managed application graph Evidence IDs must be unique",
});
});
const comparisonOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"compare_managed_members",
);
const reconstructionOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"import_managed_reconstruction",
);
const nativeVerificationOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"verify_managed_native_boundaries",
);
const managedApplicationGraphOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"project_managed_application_graph",
);
/** Provider-neutral managed-code workflow contracts. */
export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
{
name: "compare_managed_members",
...toolContractMetadata("compare_managed_members"),
description:
"Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact CIL/signature, exact declared type, name, and raw signature (decoded or not), and decoded structural method shape. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.",
kind: "application",
inputSchema: compareManagedMembersReferenceInputSchema,
outputSchema: comparisonOutputSchema,
examples: [
{
title: "Compare two managed member observations",
input: {
left: MANAGED_MEMBER_COMPARISON_EXAMPLE.left,
right: MANAGED_MEMBER_COMPARISON_EXAMPLE.right,
},
},
],
},
{
name: "verify_managed_native_boundaries",
...toolContractMetadata("verify_managed_native_boundaries"),
description:
"Verify managed P/Invoke/native-boundary declarations against authenticated native export or function Evidence without executing managed code or translating managed metadata tokens into native addresses. The workflow preserves declaration-only, verified, inferred, contradicted, and unresolved states.",
kind: "application",
inputSchema: managedNativeVerificationReferenceInputSchema,
outputSchema: nativeVerificationOutputSchema,
examples: [
{
title: "Verify a managed P/Invoke declaration against native Evidence",
input: {
managed_boundaries:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
native_observations:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations,
},
},
],
},
{
name: "import_managed_reconstruction",
...toolContractMetadata("import_managed_reconstruction"),
description:
"Import decompiler-produced managed reconstruction against authenticated inspect_managed_members Evidence. The workflow locks each method to artifact SHA-256, MVID, metadata token, signature hash, and the limited decoded-IL tuple hash, records the decompiler identity and options, and marks C# or pseudocode as analyst inference rather than canonical byte observation.",
kind: "application",
inputSchema: managedReconstructionReferenceInputSchema,
outputSchema: reconstructionOutputSchema,
examples: [
{
title: "Import a decompiler reconstruction for one managed method",
input: {
static_members: MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE.static_members,
decompiler: MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE.decompiler,
methods: MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE.methods,
notes: MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE.notes,
},
},
],
},
{
name: "project_managed_application_graph",
...toolContractMetadata("project_managed_application_graph"),
description:
"Project authenticated managed artifact, member, and native-boundary Evidence into the provider-neutral application graph without executing managed code, loading assemblies, or translating managed metadata tokens to native addresses. The graph preserves managed static observations as managed-specific nodes linked to source Evidence.",
kind: "application",
inputSchema: managedApplicationGraphReferenceInputSchema,
outputSchema: managedApplicationGraphOutputSchema,
examples: [
{
title: "Project static managed observations into an application graph",
input: {
managed_members: MANAGED_APPLICATION_GRAPH_EXAMPLE.managed_members,
},
},
],
},
] as const satisfies readonly ToolContract[];