feat(dotnet): add managed member comparison

This commit is contained in:
N0zoM1z0
2026-07-16 18:27:08 +09:00
committed by N0zoM1z0
parent 98cad3788d
commit 55794d6083
121 changed files with 2789 additions and 195 deletions
@@ -32,6 +32,13 @@ export const MANAGED_STATIC_PROVIDER = {
version: "1",
} as const;
/** Provider identity for deterministic managed-code comparison workflows. */
export const MANAGED_WORKFLOW_PROVIDER = {
id: "rea-dotnet-workflows",
name: "REA managed-code workflows",
version: "1",
} as const;
/** Provider identity for deterministic static JavaScript application analysis. */
export const JAVASCRIPT_APPLICATION_PROVIDER = {
id: "rea-javascript-application",
@@ -0,0 +1,220 @@
import { readFile, stat } from "node:fs/promises";
import { z } from "zod";
import {
compareManagedMembers,
compareManagedMembersInputSchema,
managedMemberComparisonResultSchema,
parseManagedMemberEvidence,
type CompareManagedMembersInput,
} from "../domain/managedMemberComparison.js";
import {
AnalysisInputError,
AnalysisProtocolError,
type AnalysisError,
} from "../domain/errors.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { parseBinaryTarget } from "../domain/binaryTarget.js";
import { err, ok, type Result } from "../domain/result.js";
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
import { MANAGED_STATIC_PROVIDER } from "./InvestigationProviders.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
/** Authenticate two managed member Evidence records and compare token remaps. */
export const compareManagedMembersEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
const operation = "compare_managed_members";
const parsed = compareManagedMembersInputSchema.safeParse(rawInput);
if (!parsed.success) return err(new AnalysisInputError(operation));
try {
const left = parseManagedMemberEvidence(parsed.data.left);
const right = parseManagedMemberEvidence(parsed.data.right);
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
parsed.data.limits,
);
return ok(createManagedMemberComparisonEvidence(parsed.data, result));
} catch (cause: unknown) {
return workflowFailure(operation, cause);
}
};
/** Inspect two local PE artifacts and return one derived comparison Evidence. */
export const compareManagedMemberPaths = async (input: {
readonly leftPath: string;
readonly rightPath: string;
readonly memberLimits: ManagedMemberPathInspectionLimits;
readonly comparisonLimits: CompareManagedMembersInput["limits"];
}): Promise<Result<Evidence, AnalysisError>> => {
const operation = "compare_managed_members";
try {
const [leftTarget, rightTarget] = await Promise.all([
parseBinaryTarget(input.leftPath),
parseBinaryTarget(input.rightPath),
]);
if (!leftTarget.ok)
return err(
new AnalysisInputError(operation, { cause: leftTarget.error }),
);
if (!rightTarget.ok)
return err(
new AnalysisInputError(operation, { cause: rightTarget.error }),
);
const [leftStat, rightStat] = await Promise.all([
stat(leftTarget.value.path),
stat(rightTarget.value.path),
]);
if (
leftStat.size > input.memberLimits.maxFileBytes ||
rightStat.size > input.memberLimits.maxFileBytes
)
return err(
new AnalysisInputError(operation, {
cause: new RangeError(
`Managed comparison input exceeds max_file_bytes ${String(input.memberLimits.maxFileBytes)}`,
),
}),
);
const [leftBytes, rightBytes] = await Promise.all([
readFile(leftTarget.value.path),
readFile(rightTarget.value.path),
]);
const leftInspection = inspectManagedMembersBytes(
leftBytes,
leftTarget.value,
input.memberLimits,
);
const rightInspection = inspectManagedMembersBytes(
rightBytes,
rightTarget.value,
input.memberLimits,
);
const leftEvidence = createEvidence(
leftTarget.value,
MANAGED_STATIC_PROVIDER,
{
operation: "inspect_managed_members",
parameters: memberLimitParameters(input.memberLimits),
result: jsonValueSchema.parse(leftInspection),
rawResult: null,
limitations: leftInspection.limitations,
locations: [{ kind: "artifact-path", path: leftTarget.value.path }],
},
);
const rightEvidence = createEvidence(
rightTarget.value,
MANAGED_STATIC_PROVIDER,
{
operation: "inspect_managed_members",
parameters: memberLimitParameters(input.memberLimits),
result: jsonValueSchema.parse(rightInspection),
rawResult: null,
limitations: rightInspection.limitations,
locations: [{ kind: "artifact-path", path: rightTarget.value.path }],
},
);
const result = compareManagedMembers(
{
evidenceId: leftEvidence.evidence_id,
result: leftInspection,
},
{
evidenceId: rightEvidence.evidence_id,
result: rightInspection,
},
input.comparisonLimits,
);
return ok(
createManagedMemberComparisonEvidence(
{
left: leftEvidence,
right: rightEvidence,
limits: input.comparisonLimits,
},
result,
),
);
} catch (cause: unknown) {
return workflowFailure(operation, cause);
}
};
export interface ManagedMemberPathInspectionLimits {
readonly maxFileBytes: number;
readonly typeOffset: number;
readonly typeLimit: number;
readonly methodOffset: number;
readonly methodLimit: number;
readonly fieldOffset: number;
readonly fieldLimit: number;
readonly memberRefOffset: number;
readonly memberRefLimit: number;
readonly edgeOffset: number;
readonly edgeLimit: number;
readonly instructionAnchorLimit: number;
readonly maxMetadataBytes: number;
readonly maxTableRows: number;
readonly maxHeapItemBytes: number;
readonly maxMethodBodyBytes: number;
readonly maxMethodInstructions: number;
}
const createManagedMemberComparisonEvidence = (
parameters: Pick<CompareManagedMembersInput, "left" | "right" | "limits">,
result: z.infer<typeof managedMemberComparisonResultSchema>,
): Evidence =>
createEvidence(undefined, MANAGED_WORKFLOW_PROVIDER, {
predicateType: "rea.managed-member-comparison/v1",
operation: "compare_managed_members",
parameters: {
left_evidence_id: parameters.left.evidence_id,
right_evidence_id: parameters.right.evidence_id,
limits: jsonValueSchema.parse(parameters.limits),
},
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: result.limitations,
evidenceLinks: result.evidence_links,
});
const memberLimitParameters = (
limits: ManagedMemberPathInspectionLimits,
): Record<string, ReturnType<typeof jsonValueSchema.parse>> => ({
type_offset: limits.typeOffset,
type_limit: limits.typeLimit,
method_offset: limits.methodOffset,
method_limit: limits.methodLimit,
field_offset: limits.fieldOffset,
field_limit: limits.fieldLimit,
member_ref_offset: limits.memberRefOffset,
member_ref_limit: limits.memberRefLimit,
edge_offset: limits.edgeOffset,
edge_limit: limits.edgeLimit,
instruction_anchor_limit: limits.instructionAnchorLimit,
max_file_bytes: limits.maxFileBytes,
max_metadata_bytes: limits.maxMetadataBytes,
max_table_rows: limits.maxTableRows,
max_heap_item_bytes: limits.maxHeapItemBytes,
max_method_body_bytes: limits.maxMethodBodyBytes,
max_method_instructions: limits.maxMethodInstructions,
});
const workflowFailure = (
operation: string,
cause: unknown,
): Result<never, AnalysisError> =>
err(
cause instanceof z.ZodError || cause instanceof TypeError
? new AnalysisInputError(operation, { cause })
: new AnalysisProtocolError(
"Managed member comparison produced an invalid result",
{ cause },
),
);
+109
View File
@@ -8,6 +8,7 @@ import {
runProviderAnalysis,
runSessionStatus,
} from "./application/DirectAnalysis.js";
import { compareManagedMemberPaths } from "./application/ManagedMemberComparisonService.js";
import {
runSetup,
systemSetupHost,
@@ -716,6 +717,114 @@ const registerManagedCommands = (
),
),
});
cli.command(CLI_COMMANDS.compareManagedMembers, {
description:
"Compare two managed PE/CLI member inventories without name-based matching",
args: z.object({
leftPath: z
.string()
.describe("Baseline managed PE executable or assembly"),
rightPath: z
.string()
.describe("Candidate managed PE executable or assembly"),
}),
options: z.object({
maxMethodMatches: z.number().int().min(1).max(50_000).default(10_000),
maxFieldMatches: z.number().int().min(0).max(50_000).default(5_000),
maxCandidates: z.number().int().min(1).max(500).default(50),
typeLimit: z.number().int().min(1).max(500).default(500),
methodLimit: z.number().int().min(1).max(500).default(500),
fieldLimit: z.number().int().min(1).max(500).default(500),
memberRefLimit: z.number().int().min(1).max(500).default(500),
edgeLimit: z.number().int().min(1).max(1_000).default(1_000),
instructionAnchorLimit: z.number().int().min(0).max(500).default(500),
maxFileBytes: z
.number()
.int()
.min(4_096)
.max(1_073_741_824)
.default(268_435_456),
maxMetadataBytes: z
.number()
.int()
.min(256)
.max(268_435_456)
.default(67_108_864),
maxTableRows: z.number().int().min(1).max(1_000_000).default(100_000),
maxHeapItemBytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
maxMethodBodyBytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
maxMethodInstructions: z
.number()
.int()
.min(1)
.max(100_000)
.default(100_000),
}),
alias: {
maxMethodMatches: "max-method-matches",
maxFieldMatches: "max-field-matches",
maxCandidates: "max-candidates",
typeLimit: "type-limit",
methodLimit: "method-limit",
fieldLimit: "field-limit",
memberRefLimit: "member-ref-limit",
edgeLimit: "edge-limit",
instructionAnchorLimit: "instruction-anchor-limit",
maxFileBytes: "max-file-bytes",
maxMetadataBytes: "max-metadata-bytes",
maxTableRows: "max-table-rows",
maxHeapItemBytes: "max-heap-item-bytes",
maxMethodBodyBytes: "max-method-body-bytes",
maxMethodInstructions: "max-method-instructions",
},
run: ({ args, options }) =>
logCliCommand(logger, "compare-managed-members", async () => {
const result = await compareManagedMemberPaths({
leftPath: args.leftPath,
rightPath: args.rightPath,
comparisonLimits: {
max_method_matches: options.maxMethodMatches,
max_field_matches: options.maxFieldMatches,
max_candidates: options.maxCandidates,
},
memberLimits: {
maxFileBytes: options.maxFileBytes,
typeOffset: 0,
typeLimit: options.typeLimit,
methodOffset: 0,
methodLimit: options.methodLimit,
fieldOffset: 0,
fieldLimit: options.fieldLimit,
memberRefOffset: 0,
memberRefLimit: options.memberRefLimit,
edgeOffset: 0,
edgeLimit: options.edgeLimit,
instructionAnchorLimit: options.instructionAnchorLimit,
maxMetadataBytes: options.maxMetadataBytes,
maxTableRows: options.maxTableRows,
maxHeapItemBytes: options.maxHeapItemBytes,
maxMethodBodyBytes: options.maxMethodBodyBytes,
maxMethodInstructions: options.maxMethodInstructions,
},
});
return result.ok
? result.value
: {
error: "Managed member comparison failed",
...projectAnalysisError(result.error),
};
}),
});
};
const registerNativeCommands = (
+1
View File
@@ -18,6 +18,7 @@ export const CLI_COMMANDS = Object.freeze({
extractArtifact: "extract-artifact",
inspectManagedArtifact: "inspect-managed-artifact",
inspectManagedMembers: "inspect-managed-members",
compareManagedMembers: "compare-managed-members",
inspectMacho: "inspect-macho",
inspectSignature: "inspect-signature",
listArchitectures: "list-architectures",
+82
View File
@@ -0,0 +1,82 @@
import { createEvidence } from "../domain/evidence.js";
import type { ManagedMemberInspection } from "../domain/managedArtifact.js";
const MANAGED_STATIC_EXAMPLE_PROVIDER = {
id: "rea-dotnet-static",
name: "REA managed static analysis provider",
version: "1",
} as const;
const emptyManagedMembers = (
sha256: string,
mvid: string,
): ManagedMemberInspection => ({
schema_version: 1,
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: emptyPage(100),
fields: emptyPage(100),
methods: emptyPage(100),
member_refs: emptyPage(100),
call_edges: emptyPage(250),
field_accesses: emptyPage(250),
coverage: { state: "complete", issues: [] },
limitations: [],
});
const emptyPage = <Item>(limit: number) => ({
items: [] as Item[],
offset: 0,
limit,
total: 0,
returned: 0,
dropped: 0,
complete: true,
});
const evidence = (result: ManagedMemberInspection) =>
createEvidence(undefined, MANAGED_STATIC_EXAMPLE_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
});
/** 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-9988-7766-554433221100"),
),
limits: {
max_method_matches: 100,
max_field_matches: 50,
max_candidates: 25,
},
};
@@ -0,0 +1,35 @@
import { compareManagedMembersInputSchema } from "../domain/managedMemberComparison.js";
import type { ToolContract } from "./toolContracts.js";
import { managedWorkflowOutputSchemas } from "./toolOutputSchemas.js";
import { MANAGED_MEMBER_COMPARISON_EXAMPLE } from "./managedWorkflowExamples.js";
const comparisonOutputSchema =
managedWorkflowOutputSchemas.compare_managed_members;
if (comparisonOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for compare_managed_members",
);
/** Provider-neutral managed-code workflow contracts. */
export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
{
name: "compare_managed_members",
description:
"Compare two authenticated inspect_managed_members Evidence records using unique-only CIL/signature and structural method-shape tiers. Names are reported as observations but are not used as a matching basis; metadata tokens are remapped as build-local coordinates bound to each artifact SHA-256 and MVID.",
kind: "application",
inputSchema: compareManagedMembersInputSchema,
outputSchema: comparisonOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Compare two managed member observations",
input: MANAGED_MEMBER_COMPARISON_EXAMPLE,
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -27,6 +27,7 @@ import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
@@ -527,6 +528,7 @@ export const TOOL_CONTRACTS = [
...NATIVE_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
+8
View File
@@ -28,6 +28,7 @@ import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
} from "../domain/managedArtifact.js";
import { managedMemberComparisonResultSchema } from "../domain/managedMemberComparison.js";
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
import { functionComparisonResultSchema } from "../domain/functionComparison.js";
import { bundleComparisonResultSchema } from "../domain/bundleComparison.js";
@@ -539,6 +540,13 @@ export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_managed_members: resultOf(managedMemberInspectionSchema),
};
/** Exact Evidence v2 schema for provider-neutral managed workflows. */
export const managedWorkflowOutputSchemas: Readonly<
Record<string, z.ZodObject>
> = {
compare_managed_members: resultOf(managedMemberComparisonResultSchema),
};
/** Exact structured-content schemas for target lifecycle operations. */
export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
open_binary: lifecycleResultOf(
+769
View File
@@ -0,0 +1,769 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence } from "./evidence.js";
import {
managedMemberInspectionSchema,
type ManagedMemberInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const comparisonLimitsSchema = z.strictObject({
max_method_matches: z.number().int().min(1).max(50_000).default(10_000),
max_field_matches: z.number().int().min(0).max(50_000).default(5_000),
max_candidates: z.number().int().min(1).max(500).default(50),
});
/** Two authenticated managed member observations and deterministic bounds. */
export const compareManagedMembersInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
limits: comparisonLimitsSchema.default({
max_method_matches: 10_000,
max_field_matches: 5_000,
max_candidates: 50,
}),
unknown_registry_approved: z.literal(true).optional(),
})
.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",
});
});
const matchBasisSchema = z.enum([
"exact-il-signature",
"structural-method-shape",
"field-signature",
"none",
]);
const matchStatusSchema = z.enum(["matched", "unmatched", "ambiguous"]);
const itemStatusSchema = z.enum([
"unchanged",
"changed",
"added",
"removed",
"unknown",
]);
const memberIdentitySchema = z.strictObject({
token: tokenSchema,
declaring_type: z.string().nullable(),
name: z.string(),
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
});
const methodComparisonItemSchema = z.strictObject({
item_id: z.string().regex(/^mmc_method_[a-f0-9]{64}$/u),
status: itemStatusSchema,
left: memberIdentitySchema.nullable(),
right: memberIdentitySchema.nullable(),
match: z.strictObject({
status: matchStatusSchema,
basis: matchBasisSchema,
confidence: z.enum(["exact", "high", "unknown"]),
candidate_left_tokens: z.array(tokenSchema).max(500),
candidate_right_tokens: z.array(tokenSchema).max(500),
}),
dimensions: z
.array(
z.enum([
"signature",
"cil",
"opcode-shape",
"call-shape",
"field-shape",
"exception-shape",
"availability",
]),
)
.max(7),
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(boundedTextSchema).max(100),
});
const fieldComparisonItemSchema = z.strictObject({
item_id: z.string().regex(/^mmc_field_[a-f0-9]{64}$/u),
status: itemStatusSchema,
left: memberIdentitySchema.omit({ normalized_il_sha256: true }).nullable(),
right: memberIdentitySchema.omit({ normalized_il_sha256: true }).nullable(),
match: z.strictObject({
status: matchStatusSchema,
basis: matchBasisSchema,
confidence: z.enum(["exact", "high", "unknown"]),
candidate_left_tokens: z.array(tokenSchema).max(500),
candidate_right_tokens: z.array(tokenSchema).max(500),
}),
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(boundedTextSchema).max(100),
});
/** Obfuscation-resistant, execution-free managed member comparison. */
export const managedMemberComparisonResultSchema = z.strictObject({
schema_version: z.literal(1),
comparison_id: z.string().regex(/^mmc_[a-f0-9]{64}$/u),
algorithm: z.strictObject({
name: z.literal("rea-managed-member-comparison"),
version: z.literal(1),
token_identity: z.literal("build-local"),
name_matching: z.literal("not-used"),
}),
left: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
mvid: z.string().uuid().nullable(),
module_name: z.string().nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
methods_total: z.number().int().min(0),
fields_total: z.number().int().min(0),
}),
right: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
mvid: z.string().uuid().nullable(),
module_name: z.string().nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
methods_total: z.number().int().min(0),
fields_total: z.number().int().min(0),
}),
summary: z.strictObject({
unchanged: z.number().int().min(0),
changed: z.number().int().min(0),
added: z.number().int().min(0),
removed: z.number().int().min(0),
unknown: z.number().int().min(0),
}),
matching: z.strictObject({
exact_il_signature: z.number().int().min(0),
structural_method_shape: z.number().int().min(0),
field_signature: z.number().int().min(0),
ambiguous: z.number().int().min(0),
unmatched: z.number().int().min(0),
}),
methods: z.array(methodComparisonItemSchema).max(50_000),
fields: z.array(fieldComparisonItemSchema).max(50_000),
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
left_status: z.enum(["complete", "partial", "unavailable"]),
right_status: z.enum(["complete", "partial", "unavailable"]),
omitted_methods: z.number().int().min(0),
omitted_fields: z.number().int().min(0),
omitted_candidates: z.number().int().min(0),
}),
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(boundedTextSchema).max(1_000),
});
export type CompareManagedMembersInput = z.infer<
typeof compareManagedMembersInputSchema
>;
export type ManagedMemberComparisonResult = z.infer<
typeof managedMemberComparisonResultSchema
>;
type Method = ManagedMemberInspection["methods"]["items"][number];
type Field = ManagedMemberInspection["fields"]["items"][number];
type MethodItem = ManagedMemberComparisonResult["methods"][number];
type FieldItem = ManagedMemberComparisonResult["fields"][number];
type MatchBasis = z.infer<typeof matchBasisSchema>;
/** One authenticated side of a managed member comparison. */
export interface ManagedMemberComparisonSide {
readonly evidenceId: string;
readonly result: ManagedMemberInspection;
}
interface Keyed<Item> {
readonly item: Item;
readonly exactKey: string | null;
readonly structuralKey: string;
}
interface MatchedPair<Item> {
readonly left: Keyed<Item>;
readonly right: Keyed<Item>;
readonly basis: MatchBasis;
readonly confidence: "exact" | "high";
}
interface Ambiguous<Item> {
readonly left: readonly Keyed<Item>[];
readonly right: readonly Keyed<Item>[];
readonly basis: MatchBasis;
}
const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed comparison canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
/** Compare two parsed managed member observations without name-based matching. */
export const compareManagedMembers = (
left: ManagedMemberComparisonSide,
right: ManagedMemberComparisonSide,
limits: CompareManagedMembersInput["limits"],
): ManagedMemberComparisonResult => {
const methodMatches = matchMethods(
left.result.methods.items.map(keyMethod),
right.result.methods.items.map(keyMethod),
limits.max_candidates,
);
const fieldMatches = matchFields(
left.result.fields.items.map(keyField),
right.result.fields.items.map(keyField),
limits.max_candidates,
);
const methodItems = buildMethodItems(
methodMatches,
left.evidenceId,
right.evidenceId,
limits,
);
const fieldItems = buildFieldItems(
fieldMatches,
left.evidenceId,
right.evidenceId,
limits,
);
const allItems = [...methodItems.items, ...fieldItems.items];
const summary = {
unchanged: allItems.filter(({ status }) => status === "unchanged").length,
changed: allItems.filter(({ status }) => status === "changed").length,
added: allItems.filter(({ status }) => status === "added").length,
removed: allItems.filter(({ status }) => status === "removed").length,
unknown: allItems.filter(({ status }) => status === "unknown").length,
};
const matching = {
exact_il_signature: methodItems.items.filter(
({ match }) => match.basis === "exact-il-signature",
).length,
structural_method_shape: methodItems.items.filter(
({ match }) => match.basis === "structural-method-shape",
).length,
field_signature: fieldItems.items.filter(
({ match }) => match.basis === "field-signature",
).length,
ambiguous:
methodItems.items.filter(({ match }) => match.status === "ambiguous")
.length +
fieldItems.items.filter(({ match }) => match.status === "ambiguous")
.length,
unmatched: allItems.filter(({ match }) => match.status === "unmatched")
.length,
};
const limitations = comparisonLimitations(
left.result,
right.result,
methodItems.omitted + fieldItems.omitted,
methodMatches.omittedCandidates + fieldMatches.omittedCandidates,
);
const result = {
schema_version: 1,
comparison_id: `mmc_${sha256({
left: left.evidenceId,
right: right.evidenceId,
methods: [...methodItems.items],
fields: [...fieldItems.items],
limits,
})}`,
algorithm: {
name: "rea-managed-member-comparison",
version: 1,
token_identity: "build-local",
name_matching: "not-used",
},
left: sideManifest(left),
right: sideManifest(right),
summary,
matching,
methods: methodItems.items,
fields: fieldItems.items,
coverage: {
status:
methodItems.omitted + fieldItems.omitted > 0 ||
!left.result.methods.complete ||
!right.result.methods.complete ||
!left.result.fields.complete ||
!right.result.fields.complete
? "truncated"
: left.result.coverage.state === "complete" &&
right.result.coverage.state === "complete"
? "complete-within-inputs"
: "partial",
left_status: left.result.coverage.state,
right_status: right.result.coverage.state,
omitted_methods: methodItems.omitted,
omitted_fields: fieldItems.omitted,
omitted_candidates:
methodMatches.omittedCandidates + fieldMatches.omittedCandidates,
},
evidence_links: [left.evidenceId, right.evidenceId],
limitations,
} satisfies ManagedMemberComparisonResult;
return managedMemberComparisonResultSchema.parse(result);
};
const sideManifest = (
side: ManagedMemberComparisonSide,
): ManagedMemberComparisonResult["left"] => ({
evidence_id: side.evidenceId,
artifact_sha256: side.result.artifact.sha256,
mvid: side.result.module?.mvid ?? null,
module_name: side.result.module?.name ?? null,
metadata_status: side.result.metadata.status,
methods_total: side.result.methods.total,
fields_total: side.result.fields.total,
});
const keyMethod = (item: Method): Keyed<Method> => ({
item,
exactKey:
item.signature.parse_status === "decoded" &&
item.body.normalized_il_sha256 !== null
? stableKey([
"method-exact",
item.signature.raw_sha256,
item.body.normalized_il_sha256,
])
: null,
structuralKey: stableKey([
"method-structural",
item.signature.kind,
item.signature.calling_convention,
item.signature.generic_parameter_count,
item.signature.parameter_count,
item.signature.return_type,
item.signature.parameter_types,
item.body.status,
item.body.header_format,
item.body.il_size,
item.body.max_stack,
item.body.init_locals,
item.body.opcode_counts,
item.body.anchors.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
item.body.exception_regions.map((region) => [
region.flags,
region.try_length,
region.handler_length,
region.class_token === null ? null : "type-token",
region.filter_offset === null ? null : "filter",
]),
]),
});
const keyField = (item: Field): Keyed<Field> => ({
item,
exactKey:
item.signature.parse_status === "decoded"
? stableKey(["field-exact", item.signature.raw_sha256])
: null,
structuralKey: stableKey([
"field-structural",
item.signature.kind,
item.signature.field_type,
item.flags,
]),
});
const stableKey = (value: JsonValue): string => sha256(value);
const matchMethods = (
left: readonly Keyed<Method>[],
right: readonly Keyed<Method>[],
maxCandidates: number,
) =>
matchByKeys(left, right, maxCandidates, "exact-il-signature", [
"structural-method-shape",
]);
const matchFields = (
left: readonly Keyed<Field>[],
right: readonly Keyed<Field>[],
maxCandidates: number,
) => matchByKeys(left, right, maxCandidates, "field-signature", []);
const matchByKeys = <Item>(
left: readonly Keyed<Item>[],
right: readonly Keyed<Item>[],
maxCandidates: number,
exactBasis: MatchBasis,
fallbackBases: readonly MatchBasis[],
): {
readonly pairs: readonly MatchedPair<Item>[];
readonly ambiguous: readonly Ambiguous<Item>[];
readonly leftOnly: readonly Keyed<Item>[];
readonly rightOnly: readonly Keyed<Item>[];
readonly omittedCandidates: number;
} => {
const usedLeft = new Set<Keyed<Item>>();
const usedRight = new Set<Keyed<Item>>();
const pairs: MatchedPair<Item>[] = [];
const ambiguous: Ambiguous<Item>[] = [];
let omittedCandidates = 0;
const rounds: readonly {
readonly basis: MatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
}[] = [
{ basis: exactBasis, key: ({ exactKey }) => exactKey },
...fallbackBases.map((basis) => ({
basis,
key: ({ structuralKey }: Keyed<Item>) => structuralKey,
})),
];
for (const round of rounds) {
const leftGroups = groupBy(
left.filter((item) => !usedLeft.has(item)),
round.key,
);
const rightGroups = groupBy(
right.filter((item) => !usedRight.has(item)),
round.key,
);
for (const [key, leftItems] of leftGroups) {
const rightItems = rightGroups.get(key);
if (rightItems === undefined) continue;
if (leftItems.length === 1 && rightItems.length === 1) {
const [leftItem] = leftItems;
const [rightItem] = rightItems;
if (leftItem === undefined || rightItem === undefined) continue;
usedLeft.add(leftItem);
usedRight.add(rightItem);
pairs.push({
left: leftItem,
right: rightItem,
basis: round.basis,
confidence:
round.basis === "exact-il-signature" ||
round.basis === "field-signature"
? "exact"
: "high",
});
} else {
for (const item of leftItems) usedLeft.add(item);
for (const item of rightItems) usedRight.add(item);
omittedCandidates += Math.max(
0,
leftItems.length + rightItems.length - maxCandidates * 2,
);
ambiguous.push({
left: leftItems.slice(0, maxCandidates),
right: rightItems.slice(0, maxCandidates),
basis: round.basis,
});
}
}
}
return {
pairs,
ambiguous,
leftOnly: left.filter((item) => !usedLeft.has(item)),
rightOnly: right.filter((item) => !usedRight.has(item)),
omittedCandidates,
};
};
const groupBy = <Item>(
items: readonly Item[],
keyOf: (item: Item) => string | null,
): Map<string, readonly Item[]> => {
const grouped = new Map<string, Item[]>();
for (const item of items) {
const key = keyOf(item);
if (key === null) continue;
const bucket = grouped.get(key) ?? [];
bucket.push(item);
grouped.set(key, bucket);
}
return grouped;
};
const buildMethodItems = (
matches: ReturnType<typeof matchMethods>,
leftEvidenceId: string,
rightEvidenceId: string,
limits: CompareManagedMembersInput["limits"],
): { readonly items: MethodItem[]; readonly omitted: number } => {
const items: MethodItem[] = [];
for (const pair of matches.pairs) {
const dimensions = changedMethodDimensions(pair.left.item, pair.right.item);
items.push({
item_id: `mmc_method_${sha256({
left: pair.left.item.token,
right: pair.right.item.token,
basis: pair.basis,
})}`,
status: dimensions.length === 0 ? "unchanged" : "changed",
left: methodIdentity(pair.left.item),
right: methodIdentity(pair.right.item),
match: {
status: "matched",
basis: pair.basis,
confidence: pair.confidence,
candidate_left_tokens: [],
candidate_right_tokens: [],
},
dimensions,
evidence_links: [leftEvidenceId, rightEvidenceId],
limitations: [],
});
}
for (const ambiguous of matches.ambiguous) {
items.push({
item_id: `mmc_method_${sha256({
left: ambiguous.left.map(({ item }) => item.token),
right: ambiguous.right.map(({ item }) => item.token),
basis: ambiguous.basis,
})}`,
status: "unknown",
left: null,
right: null,
match: {
status: "ambiguous",
basis: ambiguous.basis,
confidence: "unknown",
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
},
dimensions: ["availability"],
evidence_links: [leftEvidenceId, rightEvidenceId],
limitations: [
"Multiple managed methods share the same non-name identity key; REA did not guess a token remap.",
],
});
}
for (const item of matches.leftOnly)
items.push(
methodOnlyItem(item.item, leftEvidenceId, rightEvidenceId, true),
);
for (const item of matches.rightOnly)
items.push(
methodOnlyItem(item.item, leftEvidenceId, rightEvidenceId, false),
);
return limitItems(items, limits.max_method_matches);
};
const buildFieldItems = (
matches: ReturnType<typeof matchFields>,
leftEvidenceId: string,
rightEvidenceId: string,
limits: CompareManagedMembersInput["limits"],
): { readonly items: FieldItem[]; readonly omitted: number } => {
const items: FieldItem[] = [];
for (const pair of matches.pairs) {
const changed =
pair.left.item.signature.raw_sha256 !==
pair.right.item.signature.raw_sha256 ||
pair.left.item.flags !== pair.right.item.flags;
items.push({
item_id: `mmc_field_${sha256({
left: pair.left.item.token,
right: pair.right.item.token,
})}`,
status: changed ? "changed" : "unchanged",
left: fieldIdentity(pair.left.item),
right: fieldIdentity(pair.right.item),
match: {
status: "matched",
basis: pair.basis,
confidence: pair.confidence,
candidate_left_tokens: [],
candidate_right_tokens: [],
},
evidence_links: [leftEvidenceId, rightEvidenceId],
limitations: [],
});
}
for (const ambiguous of matches.ambiguous)
items.push({
item_id: `mmc_field_${sha256({
left: ambiguous.left.map(({ item }) => item.token),
right: ambiguous.right.map(({ item }) => item.token),
})}`,
status: "unknown",
left: null,
right: null,
match: {
status: "ambiguous",
basis: ambiguous.basis,
confidence: "unknown",
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
},
evidence_links: [leftEvidenceId, rightEvidenceId],
limitations: [
"Multiple managed fields share the same signature; REA did not guess a token remap from names.",
],
});
for (const item of matches.leftOnly)
items.push(fieldOnlyItem(item.item, leftEvidenceId, rightEvidenceId, true));
for (const item of matches.rightOnly)
items.push(
fieldOnlyItem(item.item, leftEvidenceId, rightEvidenceId, false),
);
return limitItems(items, limits.max_field_matches);
};
const limitItems = <Item>(
items: readonly Item[],
limit: number,
): { readonly items: Item[]; readonly omitted: number } => ({
items: items.slice(0, limit),
omitted: Math.max(0, items.length - limit),
});
const methodOnlyItem = (
item: Method,
leftEvidenceId: string,
rightEvidenceId: string,
left: boolean,
): MethodItem => ({
item_id: `mmc_method_${sha256({ token: item.token, side: left ? "left" : "right" })}`,
status: left ? "removed" : "added",
left: left ? methodIdentity(item) : null,
right: left ? null : methodIdentity(item),
match: {
status: "unmatched",
basis: "none",
confidence: "unknown",
candidate_left_tokens: [],
candidate_right_tokens: [],
},
dimensions: ["availability"],
evidence_links: [leftEvidenceId, rightEvidenceId],
limitations: [],
});
const fieldOnlyItem = (
item: Field,
leftEvidenceId: string,
rightEvidenceId: string,
left: boolean,
): FieldItem => ({
item_id: `mmc_field_${sha256({ token: item.token, side: left ? "left" : "right" })}`,
status: left ? "removed" : "added",
left: left ? fieldIdentity(item) : null,
right: left ? null : fieldIdentity(item),
match: {
status: "unmatched",
basis: "none",
confidence: "unknown",
candidate_left_tokens: [],
candidate_right_tokens: [],
},
evidence_links: [leftEvidenceId, rightEvidenceId],
limitations: [],
});
const methodIdentity = (item: Method): NonNullable<MethodItem["left"]> => ({
token: item.token,
declaring_type: item.declaring_type,
name: item.name,
signature_sha256: item.signature.raw_sha256,
normalized_il_sha256: item.body.normalized_il_sha256,
});
const fieldIdentity = (item: Field): NonNullable<FieldItem["left"]> => ({
token: item.token,
declaring_type: item.declaring_type,
name: item.name,
signature_sha256: item.signature.raw_sha256,
});
const changedMethodDimensions = (
left: Method,
right: Method,
): MethodItem["dimensions"] => {
const dimensions: MethodItem["dimensions"] = [];
if (left.signature.raw_sha256 !== right.signature.raw_sha256)
dimensions.push("signature");
if (left.body.normalized_il_sha256 !== right.body.normalized_il_sha256)
dimensions.push("cil");
if (
canonicalize(left.body.opcode_counts) !==
canonicalize(right.body.opcode_counts)
)
dimensions.push("opcode-shape");
if (callShape(left.body.anchors) !== callShape(right.body.anchors))
dimensions.push("call-shape");
if (fieldShape(left.body.anchors) !== fieldShape(right.body.anchors))
dimensions.push("field-shape");
if (
canonicalize(left.body.exception_regions) !==
canonicalize(right.body.exception_regions)
)
dimensions.push("exception-shape");
if (left.body.status !== right.body.status) dimensions.push("availability");
return dimensions;
};
const callShape = (anchors: Method["body"]["anchors"]): string =>
JSON.stringify(
anchors
.filter(({ operand_kind }) => operand_kind === "method")
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
);
const fieldShape = (anchors: Method["body"]["anchors"]): string =>
JSON.stringify(
anchors
.filter(({ operand_kind }) => operand_kind === "field")
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
);
const comparisonLimitations = (
left: ManagedMemberInspection,
right: ManagedMemberInspection,
omittedItems: number,
omittedCandidates: number,
): string[] => {
const limitations: string[] = [
"Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.",
"Names are reported as observations but are not used as a matching basis.",
];
if (!left.methods.complete || !right.methods.complete)
limitations.push("At least one method page is incomplete.");
if (!left.fields.complete || !right.fields.complete)
limitations.push("At least one field page is incomplete.");
if (left.coverage.state !== "complete" || right.coverage.state !== "complete")
limitations.push("At least one managed member observation is partial.");
if (omittedItems > 0)
limitations.push(
`${String(omittedItems)} comparison items were omitted by output limits.`,
);
if (omittedCandidates > 0)
limitations.push(
`${String(omittedCandidates)} ambiguous candidates were omitted by candidate limits.`,
);
return limitations;
};
/** Extract and authenticate a managed member inspection Evidence record. */
export const parseManagedMemberEvidence = (
evidence: unknown,
): {
readonly evidenceId: string;
readonly result: ManagedMemberInspection;
} => {
const parsed = parseEvidence(evidence);
if (parsed.operation !== "inspect_managed_members")
throw new TypeError("Evidence operation is not inspect_managed_members");
return {
evidenceId: parsed.evidence_id,
result: managedMemberInspectionSchema.parse(parsed.normalized_result),
};
};
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.0.0-beta.4",
clientSdkVersion: "2.0.0-beta.4",
coreSdkVersion: "2.0.0-beta.4",
skillVersion: "18",
skillVersion: "19",
} as const;
+6
View File
@@ -9,6 +9,7 @@ import { registerSessionTools } from "./registerSessionTools.js";
import { registerNativeTools } from "./registerNativeTools.js";
import { registerArtifactTools } from "./registerArtifactTools.js";
import { registerManagedTools } from "./registerManagedTools.js";
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js";
import { silentLogger, type Logger } from "../logger.js";
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
@@ -175,6 +176,11 @@ export const createServer = (
activeTarget,
recordEvidence,
});
registerManagedWorkflowTools(server, {
logger: toolLogger,
recordEvidence,
recordEvidenceWithUnknown,
});
registerBrowserTools(server, {
logger: toolLogger,
browser: options.browserObservation,
@@ -0,0 +1,91 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { compareManagedMembersEvidence } from "../application/ManagedMemberComparisonService.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../contracts/managedWorkflowToolContracts.js";
import {
compareManagedMembersInputSchema,
managedMemberComparisonResultSchema,
} from "../domain/managedMemberComparison.js";
import type { Evidence } from "../domain/evidence.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toCallToolResult } from "./toolResult.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
interface ManagedWorkflowToolRegistration {
readonly logger: Logger;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidenceWithUnknown:
| BinarySessionPort["recordEvidenceWithUnknown"]
| undefined;
}
/** Register provider-neutral managed-code workflows. */
export const registerManagedWorkflowTools = (
server: McpServer,
options: ManagedWorkflowToolRegistration,
): void => {
const [contract] = MANAGED_WORKFLOW_TOOL_CONTRACTS;
if (contract === undefined)
throw new Error("Missing managed workflow contract");
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input) => {
const parsed = compareManagedMembersInputSchema.parse(input);
const result = await logToolExecution(options.logger, contract.name, () =>
Promise.resolve(compareManagedMembersEvidence(parsed)),
);
if (!result.ok) return toCallToolResult(result, contract);
const recorded = recordSources(options.recordEvidence, [
parsed.left,
parsed.right,
]);
if (!recorded.ok) return toCallToolResult(recorded, contract);
const comparison = managedMemberComparisonResultSchema.parse(
result.value.normalized_result,
);
const unknown = comparison.summary.unknown > 0;
const output =
parsed.unknown_registry_approved === true && unknown
? options.recordEvidenceWithUnknown?.(result.value, {
approved: true,
question:
"Which managed members remain unmatched or ambiguous across these versions?",
severity: "medium",
domain: "managed-member-comparison",
supporting_evidence_ids: [result.value.evidence_id],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "inspect_managed_members",
rationale:
"Repeat static member inspection with complete pages and method bodies.",
},
],
relationships: [],
})
: options.recordEvidence?.(result.value);
if (output !== undefined && !output.ok)
return toCallToolResult(output, contract);
return toCallToolResult({ ok: true, value: result.value }, contract, {
evidenceResourcesAvailable: output !== undefined,
});
},
);
};
const recordSources = (
recordEvidence: ManagedWorkflowToolRegistration["recordEvidence"],
sources: readonly Evidence[],
) => {
for (const source of sources) {
const recorded = recordEvidence?.(source);
if (recorded !== undefined && !recorded.ok) return recorded;
}
return { ok: true as const, value: null };
};