feat(analysis): add opt-in retained inventory and WASM views (#2122)
Add opt-in retained inventory and WASM Evidence views with exact nested output contracts and a small static WASM descriptor. Preserve old complete CLI/MCP workflows, producer choices, original authenticated Evidence and cleanup ownership. Validated with real public applications, genuine old Evidence migration, 123 focused assertions, 11 synchronized description checks and 42 installed-package WABT cases. Detailed generated experiment JSON stays outside the final tree; concise findings and reproduction inputs remain. Main-existing completion/package CI failures are separately attributed and left unchanged. Refs #2016 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent
3159732597
commit
58fb372071
@@ -69,6 +69,7 @@ export const inspectAnalysisViewValidated = (
|
||||
evidenceId: parent.evidence_id,
|
||||
operation: parent.operation,
|
||||
normalizedResult: parent.normalized_result,
|
||||
subject: parent.subject,
|
||||
limitations: parent.limitations,
|
||||
parameters: parent.parameters,
|
||||
artifact:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { WasmArtifactPort } from "./WasmArtifactPort.js";
|
||||
@@ -12,6 +11,7 @@ import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
inspectWasmArtifactInputSchema,
|
||||
wasmArtifactSchema,
|
||||
wasmArtifactMatchesSubject,
|
||||
} from "../../domain/wasm/wasmArtifact.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
@@ -66,10 +66,7 @@ export class WasmArtifactService {
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.data.path ||
|
||||
execution.subject?.path !== input.data.path ||
|
||||
execution.subject.sha256 !== report.data.artifact.sha256 ||
|
||||
createHash("sha256").update(report.data.wat.text).digest("hex") !==
|
||||
report.data.wat.sha256 ||
|
||||
!wasmArtifactMatchesSubject(report.data.artifact, execution.subject) ||
|
||||
JSON.stringify(report.data.glue.map((item) => item.artifact.path)) !==
|
||||
JSON.stringify(input.data.glue_paths) ||
|
||||
JSON.stringify(report.data.candidates.map((item) => item.path)) !==
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { createWasmArtifactService } from "../composition/wasm.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
@@ -14,8 +13,8 @@ export const registerWasmCommands = (
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createWasmArtifactService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectWasmArtifact, {
|
||||
const service = wasmArtifactModule.create(environment);
|
||||
cli.command(wasmArtifactModule.cliCommand, {
|
||||
description: "Inspect an explicit local WASM artifact with WABT",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local WASM artifact"),
|
||||
@@ -35,7 +34,7 @@ export const registerWasmCommands = (
|
||||
try {
|
||||
return await logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.inspectWasmArtifact,
|
||||
wasmArtifactModule.cliCommand,
|
||||
async () => {
|
||||
const result = await service.inspect(
|
||||
{
|
||||
|
||||
@@ -1,7 +1,29 @@
|
||||
import { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
|
||||
import { WabtArtifactProvider } from "../wasm/WabtArtifactProvider.js";
|
||||
import { INSPECT_WASM_ARTIFACT_CONTRACT } from "../contracts/wasm/wasmToolContracts.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
/** Compose the caller-supplied offline toolchain without acquisition or import-time I/O. */
|
||||
export const createWasmArtifactService = (
|
||||
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
): WasmArtifactService =>
|
||||
new WasmArtifactService(new WabtArtifactProvider(environment));
|
||||
|
||||
/**
|
||||
* Internal static descriptor for one named domain operation and its lifetime.
|
||||
* CLI/MCP share this binding; the service keeps failed resource ownership so
|
||||
* close can be retried. Construction performs no acquisition or target I/O.
|
||||
*/
|
||||
export const wasmArtifactModule = {
|
||||
contract: INSPECT_WASM_ARTIFACT_CONTRACT,
|
||||
cliCommand: CLI_COMMANDS.inspectWasmArtifact,
|
||||
create(
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
injected?: WasmArtifactService,
|
||||
): Pick<WasmArtifactService, "inspect" | "close"> {
|
||||
const service = injected ?? createWasmArtifactService(environment);
|
||||
return {
|
||||
inspect: service.inspect.bind(service),
|
||||
close: service.close.bind(service),
|
||||
};
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -9,23 +9,39 @@ import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
|
||||
|
||||
const RETAINED_EXAMPLE_ID = `ev_${"a".repeat(64)}`;
|
||||
|
||||
/** Selected views of already completed layout, JavaScript and native function Evidence. */
|
||||
/** Selected views of completed layout, JavaScript, native, inventory, WASM and web network Evidence. */
|
||||
export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_analysis_view",
|
||||
...toolContractMetadata("inspect_analysis_view"),
|
||||
kind: "application",
|
||||
description:
|
||||
"Inspect selected views of completed binary-layout, JavaScript application or native analyze_function 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. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, 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. 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 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 and WASM 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. 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: [
|
||||
{
|
||||
title: "Read exact inventory paths from retained inspection Evidence",
|
||||
input: {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: RETAINED_EXAMPLE_ID,
|
||||
},
|
||||
view: {
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: ["package.json", "main.js"],
|
||||
offset: 0,
|
||||
limit: 32,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Group requests from retained HAR Evidence",
|
||||
input: API_SURFACE_EXAMPLE.input,
|
||||
},
|
||||
{
|
||||
title: "Summarize retained JavaScript application Evidence",
|
||||
title: "Summarize retained analysis Evidence, including WASM",
|
||||
input: {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
|
||||
@@ -9,11 +9,23 @@ import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
|
||||
import { appleAssetCatalogInputSchema } from "../domain/apple/appleAssetCatalog.js";
|
||||
import { dylibResolutionInputSchema } from "../domain/apple/dylibResolution.js";
|
||||
import { keyedArchiveInputSchema } from "../domain/apple/keyedArchive.js";
|
||||
import { analysisDetailSchema } from "./analysisDetail.js";
|
||||
/** Exact caller boundary for deterministic artifact inventory. */
|
||||
export const artifactInventoryInputSchema = z.strictObject({
|
||||
integrity_policy: artifactIntegrityPolicySchema,
|
||||
});
|
||||
|
||||
/** Delivery selection belongs to the adapter, not the inventory producer. */
|
||||
export const artifactInspectionInputSchema =
|
||||
artifactInventoryInputSchema.extend({
|
||||
detail: analysisDetailSchema
|
||||
.unwrap()
|
||||
.optional()
|
||||
.describe(
|
||||
"Omitted or complete returns the complete inspection Evidence. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; use normalized_result.parent_evidence_id for inventory views.",
|
||||
),
|
||||
});
|
||||
|
||||
/** Extraction needs no selector: it materializes every regular child file. */
|
||||
export const artifactExtractionInputSchema = z.strictObject({
|
||||
integrity_policy: artifactIntegrityPolicySchema,
|
||||
@@ -67,8 +79,8 @@ const artifact = <
|
||||
export const ARTIFACT_TOOL_CONTRACTS = [
|
||||
artifact(
|
||||
"inspect_artifact",
|
||||
"Inspect an active archive or application package in one call. Returns the complete content-addressed artifact graph once, as the nested inventory Evidence, with root and integrity observations, integrity contradictions, hypotheses, unexplored branches, limitations, and next probes inline. Read-only DMG mounting is used automatically on supported macOS hosts. Integrity mismatches fail by default; record-and-continue keeps mismatches explicitly untrusted. It does not extract files; use extract_artifact to materialize its regular contents.",
|
||||
artifactInventoryInputSchema,
|
||||
"Inspect an active archive or application package in one call. By default returns the complete content-addressed artifact graph once, as the typed nested inventory Evidence, with root and integrity observations, integrity contradictions, hypotheses, unexplored branches, limitations, and next probes inline. Optional detail summary retains the complete inspection and returns its derived summary view; read exact paths or inventory pages with inspect_analysis_view using parent_evidence_id. This changes delivery, not inventory coverage. Read-only DMG mounting is used automatically on supported macOS hosts. Integrity mismatches fail by default; record-and-continue keeps mismatches explicitly untrusted. It does not extract files; use extract_artifact to materialize its regular contents.",
|
||||
artifactInspectionInputSchema,
|
||||
),
|
||||
artifact(
|
||||
"extract_artifact",
|
||||
|
||||
@@ -25,6 +25,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
|
||||
"decodes bytecode in REA's bundled worker without executing it",
|
||||
inspect_wasm_artifact:
|
||||
"WABT validates and decompiles the module without executing it",
|
||||
inspect_analysis_view:
|
||||
"reports retained WASM execution/network states without performing execution",
|
||||
inspect_managed_artifact: "reads metadata without executing target code",
|
||||
inspect_managed_members: "reads metadata without executing target code",
|
||||
inspect_managed_native_boundaries:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { artifactInventorySummaryViewResultSchema } from "../domain/analysisView/analysisView.js";
|
||||
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
|
||||
import { BINARY_ARCHITECTURES } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
@@ -37,7 +38,7 @@ import {
|
||||
listArchitecturesSchema,
|
||||
} from "../domain/native/nativeInspection.js";
|
||||
import { artifactExtractionResultSchema } from "../domain/artifactGraph.js";
|
||||
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
|
||||
import { artifactInspectionOutputSchema } from "../domain/artifactInspection.js";
|
||||
import { interfaceBuilderAnalysisSchema } from "../domain/apple/interfaceBuilderGraph.js";
|
||||
import { dylibResolutionResultSchema } from "../domain/apple/dylibResolution.js";
|
||||
import { keyedArchiveResultSchema } from "../domain/apple/keyedArchive.js";
|
||||
@@ -385,7 +386,12 @@ export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
|
||||
/** Exact Evidence schemas for provider-neutral artifact graph operations. */
|
||||
export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
inspect_artifact: evidenceResultOf(artifactInspectionResultSchema),
|
||||
inspect_artifact: evidenceResultOf(
|
||||
z.union([
|
||||
artifactInspectionOutputSchema,
|
||||
artifactInventorySummaryViewResultSchema,
|
||||
]),
|
||||
),
|
||||
extract_artifact: evidenceResultOf(artifactExtractionResultSchema),
|
||||
decode_interface_builder: evidenceResultOf(interfaceBuilderAnalysisSchema),
|
||||
inspect_keyed_archive: evidenceResultOf(keyedArchiveResultSchema),
|
||||
|
||||
@@ -6,24 +6,25 @@ import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
/** Optional caller-supplied WABT capability with target-free CLI/MCP parity. */
|
||||
export const WASM_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_wasm_artifact",
|
||||
...toolContractMetadata("inspect_wasm_artifact"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Validate an explicit local WASM artifact with caller-supplied WABT 1.0.42, retain exact byte SHA-256, sections, upstream import/export WAT forms and decoded WAT inline as Evidence. Optionally associate selected JavaScript glue literals with explicit local candidates while preserving ambiguous URL/basename matches. Configure absolute REA_WABT_BIN_DIRECTORY. No installation, implicit fetch, WASM execution or original-source claim.",
|
||||
inputSchema: inspectWasmArtifactInputSchema,
|
||||
outputSchema: evidenceResultOf(wasmArtifactSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect a selected local WASM module",
|
||||
input: {
|
||||
path: "/artifacts/module.wasm",
|
||||
glue_paths: [],
|
||||
candidate_paths: [],
|
||||
},
|
||||
export const INSPECT_WASM_ARTIFACT_CONTRACT = {
|
||||
name: "inspect_wasm_artifact",
|
||||
...toolContractMetadata("inspect_wasm_artifact"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Validate an explicit local WASM artifact with caller-supplied WABT 1.0.42, retain exact byte SHA-256, sections, upstream import/export WAT forms and decoded WAT inline as Evidence. Optionally associate selected JavaScript glue literals with explicit local candidates while preserving ambiguous URL/basename matches. Configure absolute REA_WABT_BIN_DIRECTORY. No installation, implicit fetch, WASM execution or original-source claim.",
|
||||
inputSchema: inspectWasmArtifactInputSchema,
|
||||
outputSchema: evidenceResultOf(wasmArtifactSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect a selected local WASM module",
|
||||
input: {
|
||||
path: "/artifacts/module.wasm",
|
||||
glue_paths: [],
|
||||
candidate_paths: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
},
|
||||
],
|
||||
} as const satisfies ToolContract;
|
||||
|
||||
/** Keep the public catalog in its existing order, using its named contract. */
|
||||
export const WASM_TOOL_CONTRACTS = [INSPECT_WASM_ARTIFACT_CONTRACT] as const;
|
||||
|
||||
@@ -8,12 +8,20 @@ import {
|
||||
} from "../analysisErrorCore.js";
|
||||
import { digestCanonicalValue } from "../canonicalDigest.js";
|
||||
import { digestSchema, prefixedDigestSchema } from "../digests.js";
|
||||
import { evidenceSchema } from "../evidence.js";
|
||||
import { evidenceSchema, type Evidence } from "../evidence.js";
|
||||
import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import { binaryLayoutSchema } from "../native/binaryLayout.js";
|
||||
import { functionDossierSchema } from "../hopperValues.js";
|
||||
import {
|
||||
artifactGraphManifestSchema,
|
||||
artifactNodeSchema,
|
||||
artifactOccurrenceSchema,
|
||||
artifactEdgeSchema,
|
||||
integrityContradictionSchema,
|
||||
} from "../artifactGraph.js";
|
||||
import { artifactInspectionResultSchema } from "../artifactInspection.js";
|
||||
import {
|
||||
parseOwnedJavaScriptApplicationAnalysisSteps,
|
||||
type JavaScriptApplicationAnalysisResult,
|
||||
@@ -27,6 +35,13 @@ import {
|
||||
apiSurfaceViewSchema,
|
||||
} from "./webNetworkApiSurfaceView.js";
|
||||
import { projectNativeFunctionView } from "./nativeFunctionView.js";
|
||||
import { projectArtifactInventoryView } from "./artifactInventoryView.js";
|
||||
import {
|
||||
projectWasmArtifactView,
|
||||
wasmViewRequestSchema,
|
||||
wasmViewItemSchema,
|
||||
wasmSummarySchema,
|
||||
} from "./wasmArtifactView.js";
|
||||
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
|
||||
|
||||
/** Public name of the selected-view workflow. */
|
||||
@@ -108,6 +123,28 @@ const nativeViewSchema = z.strictObject({
|
||||
limit: z.number().int().positive().default(64),
|
||||
});
|
||||
|
||||
/** Original inventory records in stable order, optionally matching exact paths. */
|
||||
const inventoryViewSchema = z.discriminatedUnion("collection", [
|
||||
z.strictObject({
|
||||
kind: z.literal("inventory"),
|
||||
collection: z.literal("occurrences"),
|
||||
logical_paths: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe(
|
||||
"Exact recorded logical paths. Omitted selects all available occurrences; an empty array selects none. This does not resolve filesystem paths.",
|
||||
),
|
||||
offset: z.number().int().nonnegative().default(0),
|
||||
limit: z.number().int().positive().default(64),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("inventory"),
|
||||
collection: z.enum(["nodes", "edges", "integrity_contradictions"]),
|
||||
offset: z.number().int().nonnegative().default(0),
|
||||
limit: z.number().int().positive().default(64),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Caller-selected projection of already completed analysis Evidence. */
|
||||
export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
|
||||
summaryViewSchema,
|
||||
@@ -115,6 +152,8 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
|
||||
itemViewSchema,
|
||||
pageViewSchema,
|
||||
nativeViewSchema,
|
||||
inventoryViewSchema,
|
||||
wasmViewRequestSchema,
|
||||
apiSurfaceViewSchema,
|
||||
]);
|
||||
|
||||
@@ -192,30 +231,30 @@ const javascriptSummarySchema = z.strictObject({
|
||||
limitation_count: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
const summaryViewResultFields = {
|
||||
kind: z.literal("summary"),
|
||||
view: summaryViewSchema,
|
||||
parent_evidence_id: prefixedDigestSchema("ev"),
|
||||
parent_digest: digestSchema,
|
||||
view_digest: digestSchema,
|
||||
artifact: artifactSchema,
|
||||
coverage: coverageSchema,
|
||||
limitations: z.array(z.string()),
|
||||
unknowns: z.array(z.string()),
|
||||
} as const;
|
||||
|
||||
/** Summary `inspect_binary_layout` detail returns; no other view kind. */
|
||||
export const binaryLayoutSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultFields,
|
||||
summary: layoutSummarySchema,
|
||||
parent_operation: z.literal("inspect_binary_layout"),
|
||||
});
|
||||
|
||||
/** Summary `analyze_javascript_application` detail returns; no other view kind. */
|
||||
export const javascriptApplicationSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultFields,
|
||||
summary: javascriptSummarySchema,
|
||||
parent_operation: z.literal("analyze_javascript_application"),
|
||||
const inventorySummarySchema = z.strictObject({
|
||||
manifest: artifactGraphManifestSchema,
|
||||
available_counts: z.strictObject({
|
||||
nodes: z.number().int().nonnegative(),
|
||||
occurrences: z.number().int().nonnegative(),
|
||||
edges: z.number().int().nonnegative(),
|
||||
integrity_contradictions: z.number().int().nonnegative(),
|
||||
}),
|
||||
observed_entry_kind_counts: z.strictObject({
|
||||
file: z.number().int().nonnegative(),
|
||||
directory: z.number().int().nonnegative(),
|
||||
symlink: z.number().int().nonnegative(),
|
||||
slice: z.number().int().nonnegative(),
|
||||
}),
|
||||
source_complete: z.boolean(),
|
||||
inventory_evidence_ids: z.array(prefixedDigestSchema("ev")).min(1),
|
||||
inspection: z
|
||||
.strictObject({
|
||||
coverage: artifactInspectionResultSchema.shape.coverage,
|
||||
unexplored_branches:
|
||||
artifactInspectionResultSchema.shape.unexplored_branches,
|
||||
})
|
||||
.nullable(),
|
||||
limitation_count: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
const viewResultBase = {
|
||||
@@ -224,6 +263,9 @@ const viewResultBase = {
|
||||
"inspect_binary_layout",
|
||||
"analyze_javascript_application",
|
||||
"analyze_function",
|
||||
"inspect_artifact",
|
||||
"inventory_artifact",
|
||||
"inspect_wasm_artifact",
|
||||
]),
|
||||
parent_digest: digestSchema,
|
||||
view_digest: digestSchema,
|
||||
@@ -233,6 +275,33 @@ const viewResultBase = {
|
||||
unknowns: z.array(z.string()),
|
||||
} as const;
|
||||
|
||||
const summaryViewResultBase = {
|
||||
kind: z.literal("summary"),
|
||||
view: summaryViewSchema,
|
||||
...viewResultBase,
|
||||
} as const;
|
||||
|
||||
/** Summary `inspect_binary_layout` detail returns; no other view kind. */
|
||||
export const binaryLayoutSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
summary: layoutSummarySchema,
|
||||
parent_operation: z.literal("inspect_binary_layout"),
|
||||
});
|
||||
|
||||
/** Summary `analyze_javascript_application` detail returns; no other view kind. */
|
||||
export const javascriptApplicationSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
summary: javascriptSummarySchema,
|
||||
parent_operation: z.literal("analyze_javascript_application"),
|
||||
});
|
||||
|
||||
/** Exact summary carrier for artifact inspection's optional delivery contract. */
|
||||
export const artifactInventorySummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
parent_operation: z.enum(["inspect_artifact", "inventory_artifact"]),
|
||||
summary: inventorySummarySchema,
|
||||
});
|
||||
|
||||
/** Projected facts for one selected view of retained analysis Evidence. */
|
||||
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
z.strictObject({
|
||||
@@ -247,10 +316,13 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
}),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("summary"),
|
||||
view: summaryViewSchema,
|
||||
summary: z.union([layoutSummarySchema, javascriptSummarySchema]),
|
||||
...viewResultBase,
|
||||
...summaryViewResultBase,
|
||||
summary: z.union([
|
||||
layoutSummarySchema,
|
||||
javascriptSummarySchema,
|
||||
inventorySummarySchema,
|
||||
wasmSummarySchema,
|
||||
]),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("facet"),
|
||||
@@ -277,6 +349,28 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
item: jsonValueSchema,
|
||||
...viewResultBase,
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("wasm"),
|
||||
view: wasmViewRequestSchema,
|
||||
item: wasmViewItemSchema,
|
||||
...viewResultBase,
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("inventory"),
|
||||
view: inventoryViewSchema,
|
||||
manifest: artifactGraphManifestSchema,
|
||||
inventory_evidence_ids: z.array(prefixedDigestSchema("ev")).min(1),
|
||||
source_complete: z.boolean(),
|
||||
items: z.array(
|
||||
z.union([
|
||||
artifactNodeSchema,
|
||||
artifactOccurrenceSchema,
|
||||
artifactEdgeSchema,
|
||||
integrityContradictionSchema,
|
||||
]),
|
||||
),
|
||||
...viewResultBase,
|
||||
}),
|
||||
]);
|
||||
|
||||
export type AnalysisViewRequest = z.output<typeof analysisViewRequestSchema>;
|
||||
@@ -291,6 +385,8 @@ export interface AnalysisViewParent {
|
||||
readonly evidenceId: string;
|
||||
readonly operation: string;
|
||||
readonly normalizedResult: unknown;
|
||||
/** Preserve the authenticated source identity, including explicit absence. */
|
||||
readonly subject?: Evidence["subject"];
|
||||
readonly limitations: readonly string[];
|
||||
readonly artifact?: { readonly path: string; readonly sha256: string } | null;
|
||||
/** Parent Evidence parameters, when the parent operation records them. */
|
||||
@@ -319,7 +415,12 @@ export type UnsignedAnalysisView =
|
||||
| Omit<
|
||||
Extract<AnalysisViewResult, { readonly kind: "native" }>,
|
||||
"view_digest"
|
||||
>;
|
||||
>
|
||||
| Omit<
|
||||
Extract<AnalysisViewResult, { readonly kind: "inventory" }>,
|
||||
"view_digest"
|
||||
>
|
||||
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">;
|
||||
|
||||
/** Attach the content digest that must change when projected bytes change. */
|
||||
export const sealAnalysisView = (
|
||||
@@ -364,7 +465,7 @@ const unsupportedParent = (
|
||||
new AnalysisUnsupportedTargetError(
|
||||
INSPECT_ANALYSIS_VIEW_OPERATION,
|
||||
parentArtifactPath(parent),
|
||||
`Parent Evidence operation ${JSON.stringify(parent.operation)} is not inspect_binary_layout, analyze_javascript_application or analyze_function.`,
|
||||
`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.`,
|
||||
);
|
||||
|
||||
const parentArtifactPath = (parent: AnalysisViewParent): string => {
|
||||
@@ -459,5 +560,16 @@ 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_artifact" ||
|
||||
parent.operation === "inventory_artifact"
|
||||
) {
|
||||
const projected = projectArtifactInventoryView(parent, view);
|
||||
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
|
||||
}
|
||||
return err(unsupportedParent(parent));
|
||||
};
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import {
|
||||
analysisViewInputError,
|
||||
type AnalysisViewCoverage,
|
||||
} from "./analysisView.js";
|
||||
import { pageViewCoverage } from "./analysisViewCoverage.js";
|
||||
|
||||
const viewError = (message: string): AnalysisError =>
|
||||
analysisViewInputError([
|
||||
{ path: ["view"], reason: "invalid_value", message },
|
||||
]);
|
||||
|
||||
/** Slice text by UTF-16 code units without losing a partial Unicode character. */
|
||||
export const analysisTextPage = (
|
||||
body: string,
|
||||
offset: number,
|
||||
limit: number,
|
||||
label = "Pseudocode",
|
||||
): Result<
|
||||
{
|
||||
readonly item: { readonly text: string; readonly unit: "utf16-code-units" };
|
||||
readonly coverage: AnalysisViewCoverage;
|
||||
},
|
||||
AnalysisError
|
||||
> => {
|
||||
const start = Math.min(offset, body.length);
|
||||
const high = (n: number) => n >= 0xd800 && n <= 0xdbff;
|
||||
const low = (n: number) => n >= 0xdc00 && n <= 0xdfff;
|
||||
if (
|
||||
start > 0 &&
|
||||
start < body.length &&
|
||||
high(body.charCodeAt(start - 1)) &&
|
||||
low(body.charCodeAt(start))
|
||||
)
|
||||
return err(viewError(`${label} offset splits a UTF-16 surrogate pair.`));
|
||||
let end = Math.min(start + limit, body.length);
|
||||
if (
|
||||
end > start &&
|
||||
end < body.length &&
|
||||
high(body.charCodeAt(end - 1)) &&
|
||||
low(body.charCodeAt(end))
|
||||
)
|
||||
end--;
|
||||
if (end === start && start < body.length)
|
||||
return err(
|
||||
viewError(
|
||||
`Increase ${label.toLowerCase()} limit to include the next complete Unicode character.`,
|
||||
),
|
||||
);
|
||||
return ok({
|
||||
item: { text: body.slice(start, end), unit: "utf16-code-units" },
|
||||
coverage: pageViewCoverage(start, end - start, body.length),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,203 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import {
|
||||
parseArtifactInventoryEvidence,
|
||||
parseArtifactInventoryResult,
|
||||
validateArtifactInventorySubject,
|
||||
type InventorySet,
|
||||
} from "../artifactInventoryEvidence.js";
|
||||
import {
|
||||
artifactInspectionResultSchema,
|
||||
type ArtifactInspectionResult,
|
||||
} from "../artifactInspection.js";
|
||||
import type {
|
||||
AnalysisViewParent,
|
||||
AnalysisViewRequest,
|
||||
UnsignedAnalysisView,
|
||||
} from "./analysisView.js";
|
||||
import {
|
||||
completeWithinViewCoverage,
|
||||
pageViewCoverage,
|
||||
} from "./analysisViewCoverage.js";
|
||||
|
||||
const inputError = (message: string): AnalysisInputError =>
|
||||
new AnalysisInputError("inspect_analysis_view", undefined, [
|
||||
{
|
||||
path: ["source"],
|
||||
reason: "invalid_value",
|
||||
message,
|
||||
},
|
||||
]);
|
||||
|
||||
interface InventorySource {
|
||||
readonly inventory: InventorySet;
|
||||
readonly evidenceIds: readonly string[];
|
||||
readonly inspection: ArtifactInspectionResult | null;
|
||||
}
|
||||
|
||||
/** Reuse the owning inventory integrity/completeness parser for both carriers. */
|
||||
const parseSource = (
|
||||
parent: AnalysisViewParent,
|
||||
): Result<InventorySource, AnalysisError> => {
|
||||
try {
|
||||
if (parent.operation === "inventory_artifact")
|
||||
return ok({
|
||||
inventory: parseArtifactInventoryResult(
|
||||
parent.normalizedResult,
|
||||
parent.subject ?? null,
|
||||
),
|
||||
evidenceIds: [parent.evidenceId],
|
||||
inspection: null,
|
||||
});
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
parent.normalizedResult,
|
||||
);
|
||||
for (const step of inspection.substeps) {
|
||||
if (
|
||||
step.evidence_id !== step.evidence.evidence_id ||
|
||||
step.evidence.operation !== step.operation
|
||||
)
|
||||
throw new TypeError(
|
||||
"Inspection substep identity differs from its source Evidence",
|
||||
);
|
||||
}
|
||||
const parsed = parseArtifactInventoryEvidence(
|
||||
inspection.substeps.map(({ evidence }) => evidence),
|
||||
);
|
||||
const manifest = parsed.inventory.manifest;
|
||||
validateArtifactInventorySubject(parent.subject ?? null, manifest);
|
||||
if (
|
||||
inspection.subject.manifest_id !== manifest.manifest_id ||
|
||||
inspection.subject.root_artifact_id !== manifest.root_artifact_id ||
|
||||
inspection.subject.root_sha256 !== manifest.root_sha256 ||
|
||||
inspection.subject.root_format !== manifest.root_format
|
||||
)
|
||||
throw new TypeError(
|
||||
"Inspection subject differs from its inventory manifest",
|
||||
);
|
||||
return ok({
|
||||
inventory: parsed.inventory,
|
||||
evidenceIds: parsed.evidence.map(({ evidence_id }) => evidence_id),
|
||||
inspection,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof TypeError) && !(cause instanceof z.ZodError))
|
||||
throw cause;
|
||||
return err(inputError(cause.message));
|
||||
}
|
||||
};
|
||||
|
||||
/** Project exact source records; exhausted pages cover available records, not runtime behavior. */
|
||||
export const projectArtifactInventoryView = (
|
||||
parent: AnalysisViewParent,
|
||||
view: AnalysisViewRequest,
|
||||
): Result<UnsignedAnalysisView, AnalysisError> => {
|
||||
const operation = parent.operation;
|
||||
if (operation !== "inventory_artifact" && operation !== "inspect_artifact")
|
||||
return err(
|
||||
inputError(
|
||||
"Inventory views require inventory_artifact or inspect_artifact Evidence.",
|
||||
),
|
||||
);
|
||||
if (view.kind !== "summary" && view.kind !== "inventory")
|
||||
return err(
|
||||
inputError("Artifact Evidence supports summary and inventory views."),
|
||||
);
|
||||
const parsed = parseSource(parent);
|
||||
if (!parsed.ok) return parsed;
|
||||
const { inventory, evidenceIds, inspection } = parsed.value;
|
||||
const limitations = uniqueSorted([
|
||||
...parent.limitations,
|
||||
...inventory.limitations,
|
||||
...(inspection?.limitations ?? []),
|
||||
]);
|
||||
const shared = {
|
||||
parent_evidence_id: parent.evidenceId,
|
||||
parent_operation: operation,
|
||||
parent_digest: parent.evidenceId.slice(3),
|
||||
artifact: {
|
||||
path: parent.artifact?.path ?? "",
|
||||
sha256: inventory.manifest.root_sha256,
|
||||
},
|
||||
limitations,
|
||||
unknowns: [
|
||||
"Inventory does not establish application runtime behavior or complete format-specific analysis.",
|
||||
...(inventory.complete
|
||||
? []
|
||||
: [
|
||||
"Parent inventory is partial; counts and exhausted pages cover only available records. Missing matches do not establish absence.",
|
||||
]),
|
||||
],
|
||||
} satisfies Pick<
|
||||
UnsignedAnalysisView,
|
||||
| "parent_evidence_id"
|
||||
| "parent_operation"
|
||||
| "parent_digest"
|
||||
| "artifact"
|
||||
| "limitations"
|
||||
| "unknowns"
|
||||
>;
|
||||
if (view.kind === "summary") {
|
||||
const counts = { file: 0, directory: 0, symlink: 0, slice: 0 };
|
||||
for (const occurrence of inventory.occurrences)
|
||||
counts[occurrence.entry_kind]++;
|
||||
const examined =
|
||||
inventory.nodes.length +
|
||||
inventory.occurrences.length +
|
||||
inventory.edges.length;
|
||||
return ok({
|
||||
kind: "summary",
|
||||
view,
|
||||
summary: {
|
||||
manifest: inventory.manifest,
|
||||
available_counts: {
|
||||
nodes: inventory.nodes.length,
|
||||
occurrences: inventory.occurrences.length,
|
||||
edges: inventory.edges.length,
|
||||
integrity_contradictions: inventory.integrityContradictions.length,
|
||||
},
|
||||
observed_entry_kind_counts: counts,
|
||||
source_complete: inventory.complete,
|
||||
inventory_evidence_ids: [...evidenceIds],
|
||||
inspection:
|
||||
inspection === null
|
||||
? null
|
||||
: {
|
||||
coverage: inspection.coverage,
|
||||
unexplored_branches: inspection.unexplored_branches,
|
||||
},
|
||||
limitation_count: limitations.length,
|
||||
},
|
||||
coverage: completeWithinViewCoverage(examined, examined),
|
||||
...shared,
|
||||
});
|
||||
}
|
||||
const paths =
|
||||
view.collection === "occurrences" && view.logical_paths !== undefined
|
||||
? new Set(view.logical_paths)
|
||||
: undefined;
|
||||
const rows =
|
||||
view.collection === "occurrences" && paths !== undefined
|
||||
? inventory.occurrences.filter((row) => paths.has(row.logical_path))
|
||||
: view.collection === "occurrences"
|
||||
? inventory.occurrences
|
||||
: view.collection === "nodes"
|
||||
? inventory.nodes
|
||||
: view.collection === "edges"
|
||||
? inventory.edges
|
||||
: inventory.integrityContradictions;
|
||||
const items = rows.slice(view.offset, view.offset + view.limit);
|
||||
return ok({
|
||||
kind: "inventory",
|
||||
view,
|
||||
manifest: inventory.manifest,
|
||||
inventory_evidence_ids: [...evidenceIds],
|
||||
source_complete: inventory.complete,
|
||||
items,
|
||||
coverage: pageViewCoverage(view.offset, items.length, rows.length),
|
||||
...shared,
|
||||
});
|
||||
};
|
||||
@@ -156,6 +156,14 @@ export const projectBinaryLayoutView = (
|
||||
return err(
|
||||
layoutIncompatible("Native views require analyze_function Evidence."),
|
||||
);
|
||||
if (view.kind === "inventory")
|
||||
return err(
|
||||
layoutIncompatible("Inventory views require artifact Evidence."),
|
||||
);
|
||||
if (view.kind === "wasm")
|
||||
return err(
|
||||
layoutIncompatible("WASM views require inspect_wasm_artifact Evidence."),
|
||||
);
|
||||
if (view.kind === "summary")
|
||||
return ok({
|
||||
kind: "summary",
|
||||
|
||||
@@ -247,6 +247,12 @@ export const projectJavaScriptApplicationView = (
|
||||
return err(
|
||||
jsIncompatible("Native views require analyze_function Evidence."),
|
||||
);
|
||||
if (view.kind === "inventory")
|
||||
return err(jsIncompatible("Inventory views require artifact Evidence."));
|
||||
if (view.kind === "wasm")
|
||||
return err(
|
||||
jsIncompatible("WASM views require inspect_wasm_artifact Evidence."),
|
||||
);
|
||||
if (view.kind === "summary")
|
||||
return ok({
|
||||
kind: "summary",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { analysisTextPage } from "./analysisViewText.js";
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import type { FunctionDossier } from "../hopperValues.js";
|
||||
@@ -5,7 +6,6 @@ import { jsonValueSchema } from "../jsonValue.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import {
|
||||
analysisViewInputError,
|
||||
type AnalysisViewCoverage,
|
||||
type AnalysisViewParent,
|
||||
type AnalysisViewRequest,
|
||||
type UnsignedAnalysisView,
|
||||
@@ -59,47 +59,6 @@ const parentFields = (
|
||||
};
|
||||
};
|
||||
|
||||
const pseudocodePage = (
|
||||
body: string,
|
||||
offset: number,
|
||||
limit: number,
|
||||
): Result<
|
||||
{
|
||||
readonly item: { readonly text: string; readonly unit: "utf16-code-units" };
|
||||
readonly coverage: AnalysisViewCoverage;
|
||||
},
|
||||
AnalysisError
|
||||
> => {
|
||||
const start = Math.min(offset, body.length);
|
||||
const high = (n: number) => n >= 0xd800 && n <= 0xdbff;
|
||||
const low = (n: number) => n >= 0xdc00 && n <= 0xdfff;
|
||||
if (
|
||||
start > 0 &&
|
||||
start < body.length &&
|
||||
high(body.charCodeAt(start - 1)) &&
|
||||
low(body.charCodeAt(start))
|
||||
)
|
||||
return err(viewError("Pseudocode offset splits a UTF-16 surrogate pair."));
|
||||
let end = Math.min(start + limit, body.length);
|
||||
if (
|
||||
end > start &&
|
||||
end < body.length &&
|
||||
high(body.charCodeAt(end - 1)) &&
|
||||
low(body.charCodeAt(end))
|
||||
)
|
||||
end--;
|
||||
if (end === start && start < body.length)
|
||||
return err(
|
||||
viewError(
|
||||
"Increase pseudocode limit to include the next complete Unicode character.",
|
||||
),
|
||||
);
|
||||
return ok({
|
||||
item: { text: body.slice(start, end), unit: "utf16-code-units" },
|
||||
coverage: pageViewCoverage(start, end - start, body.length),
|
||||
});
|
||||
};
|
||||
|
||||
const nativeRows = (
|
||||
dossier: FunctionDossier,
|
||||
facet: Exclude<
|
||||
@@ -193,7 +152,7 @@ export const projectNativeFunctionView = (
|
||||
return ok(singleton(status));
|
||||
}
|
||||
if (view.facet === "pseudocode") {
|
||||
const page = pseudocodePage(dossier.pseudocode, view.offset, view.limit);
|
||||
const page = analysisTextPage(dossier.pseudocode, view.offset, view.limit);
|
||||
return page.ok
|
||||
? ok({ kind: "native", view, ...page.value, ...common })
|
||||
: page;
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { z } from "zod";
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import {
|
||||
wasmArtifactSchema,
|
||||
wasmArtifactMatchesSubject,
|
||||
} from "../wasm/wasmArtifact.js";
|
||||
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
|
||||
import {
|
||||
analysisViewInputError,
|
||||
type AnalysisViewParent,
|
||||
type AnalysisViewRequest,
|
||||
type UnsignedAnalysisView,
|
||||
} from "./analysisView.js";
|
||||
import {
|
||||
completeWithinViewCoverage,
|
||||
pageViewCoverage,
|
||||
} from "./analysisViewCoverage.js";
|
||||
import { analysisTextPage } from "./analysisViewText.js";
|
||||
|
||||
/** Source forms and text from completed WASM Evidence; this never executes a VM. */
|
||||
export const wasmViewRequestSchema = z.strictObject({
|
||||
kind: z.literal("wasm"),
|
||||
facet: z.enum([
|
||||
"sections",
|
||||
"imports",
|
||||
"exports",
|
||||
"candidates",
|
||||
"glue",
|
||||
"wat",
|
||||
"headers",
|
||||
"details",
|
||||
"tool_profile",
|
||||
]),
|
||||
offset: z.number().int().nonnegative().default(0),
|
||||
limit: z.number().int().positive().default(64),
|
||||
});
|
||||
|
||||
export const wasmViewItemSchema = z.union([
|
||||
wasmArtifactSchema.shape.sections,
|
||||
wasmArtifactSchema.shape.imports,
|
||||
wasmArtifactSchema.shape.candidates,
|
||||
wasmArtifactSchema.shape.glue,
|
||||
wasmArtifactSchema.shape.tool_profile,
|
||||
z.strictObject({ text: z.string(), unit: z.literal("utf16-code-units") }),
|
||||
]);
|
||||
|
||||
/** Counts are observations of the completed producer, independent of runtime semantics. */
|
||||
export const wasmSummarySchema = z.strictObject({
|
||||
bytes: wasmArtifactSchema.shape.artifact.shape.bytes,
|
||||
validation: wasmArtifactSchema.shape.validation,
|
||||
available_counts: z.strictObject({
|
||||
sections: z.number().int().nonnegative(),
|
||||
imports: z.number().int().nonnegative(),
|
||||
exports: z.number().int().nonnegative(),
|
||||
candidates: z.number().int().nonnegative(),
|
||||
glue: z.number().int().nonnegative(),
|
||||
}),
|
||||
wat: wasmArtifactSchema.shape.wat
|
||||
.omit({ text: true })
|
||||
.extend({ code_units: z.number().int().nonnegative() }),
|
||||
tool_profile: wasmArtifactSchema.shape.tool_profile,
|
||||
runtime_execution: wasmArtifactSchema.shape.runtime_execution,
|
||||
network_fetch: wasmArtifactSchema.shape.network_fetch,
|
||||
limitation_count: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
/** Read the exact retained WABT forms with source identity and explicit uncertainty. */
|
||||
export const projectWasmArtifactView = (
|
||||
parent: AnalysisViewParent,
|
||||
view: AnalysisViewRequest,
|
||||
): Result<UnsignedAnalysisView, AnalysisError> => {
|
||||
if (view.kind !== "summary" && view.kind !== "wasm")
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["view"],
|
||||
reason: "invalid_value",
|
||||
message: "WASM Evidence supports summary and wasm views.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const parsed = wasmArtifactSchema.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;
|
||||
if (
|
||||
!wasmArtifactMatchesSubject(
|
||||
report.artifact,
|
||||
parent.subject == null
|
||||
? null
|
||||
: {
|
||||
path: parent.subject.local_path,
|
||||
sha256: parent.subject.digest.sha256,
|
||||
},
|
||||
)
|
||||
)
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["source", "subject"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"WASM parent Evidence subject must identify the report's exact path and SHA-256.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const limitations = uniqueSorted([
|
||||
...parent.limitations,
|
||||
...report.limitations,
|
||||
]);
|
||||
const shared = {
|
||||
parent_evidence_id: parent.evidenceId,
|
||||
parent_operation: "inspect_wasm_artifact" as const,
|
||||
parent_digest: parent.evidenceId.slice(3),
|
||||
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
|
||||
limitations,
|
||||
unknowns: [
|
||||
"Decoded WAT is not original source. Runtime behavior and network acquisition were not performed.",
|
||||
...(report.glue.some((glue) => glue.parse_status !== "complete")
|
||||
? [
|
||||
"Selected glue parsing is incomplete; unmatched references do not establish absence.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
if (view.kind === "summary")
|
||||
return ok({
|
||||
kind: "summary",
|
||||
view,
|
||||
...shared,
|
||||
summary: {
|
||||
bytes: report.artifact.bytes,
|
||||
validation: report.validation,
|
||||
available_counts: {
|
||||
sections: report.sections.length,
|
||||
imports: report.imports.length,
|
||||
exports: report.exports.length,
|
||||
candidates: report.candidates.length,
|
||||
glue: report.glue.length,
|
||||
},
|
||||
wat: {
|
||||
sha256: report.wat.sha256,
|
||||
representation: report.wat.representation,
|
||||
code_units: report.wat.text.length,
|
||||
},
|
||||
tool_profile: report.tool_profile,
|
||||
runtime_execution: report.runtime_execution,
|
||||
network_fetch: report.network_fetch,
|
||||
limitation_count: limitations.length,
|
||||
},
|
||||
coverage: completeWithinViewCoverage(
|
||||
report.sections.length + report.imports.length + report.exports.length,
|
||||
report.sections.length + report.imports.length + report.exports.length,
|
||||
),
|
||||
});
|
||||
if (view.facet === "tool_profile") {
|
||||
if (view.offset !== 0)
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["view", "offset"],
|
||||
reason: "invalid_value",
|
||||
message: "Singleton tool_profile requires offset 0.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
return ok({
|
||||
kind: "wasm",
|
||||
view,
|
||||
item: report.tool_profile,
|
||||
coverage: completeWithinViewCoverage(1, 1),
|
||||
...shared,
|
||||
});
|
||||
}
|
||||
if (
|
||||
view.facet === "wat" ||
|
||||
view.facet === "headers" ||
|
||||
view.facet === "details"
|
||||
) {
|
||||
const text = view.facet === "wat" ? report.wat.text : report[view.facet];
|
||||
const page = analysisTextPage(text, view.offset, view.limit, view.facet);
|
||||
return page.ok
|
||||
? ok({ kind: "wasm", view, ...page.value, ...shared })
|
||||
: page;
|
||||
}
|
||||
const rows = report[view.facet];
|
||||
const item = rows.slice(view.offset, view.offset + view.limit);
|
||||
return ok({
|
||||
kind: "wasm",
|
||||
view,
|
||||
item,
|
||||
coverage: pageViewCoverage(view.offset, item.length, rows.length),
|
||||
...shared,
|
||||
});
|
||||
};
|
||||
@@ -101,7 +101,7 @@ const artifactCommandSchema = z.object({
|
||||
export type ArtifactCommand = z.infer<typeof artifactCommandSchema>;
|
||||
|
||||
/** One content-addressed application artifact in deterministic manifest order. */
|
||||
const artifactNodeSchema = z.object({
|
||||
export const artifactNodeSchema = z.object({
|
||||
artifact_id: artifactIdSchema,
|
||||
format: artifactContentFormatSchema,
|
||||
sha256: sha256Schema,
|
||||
@@ -113,7 +113,7 @@ const artifactNodeSchema = z.object({
|
||||
});
|
||||
|
||||
/** One path or virtual location where an artifact occurs in its parent. */
|
||||
const artifactOccurrenceSchema = z.object({
|
||||
export const artifactOccurrenceSchema = z.object({
|
||||
occurrence_id: occurrenceIdSchema,
|
||||
artifact_id: artifactIdSchema.nullable(),
|
||||
parent_occurrence_id: occurrenceIdSchema.nullable(),
|
||||
@@ -159,7 +159,7 @@ export const integrityContradictionSchema = z.object({
|
||||
* Parent-child derivation relation between two content-addressed artifacts.
|
||||
* The child artifact and its logical path are those of the edge's occurrence.
|
||||
*/
|
||||
const artifactEdgeSchema = z.object({
|
||||
export const artifactEdgeSchema = z.object({
|
||||
edge_id: edgeIdSchema,
|
||||
ordinal: z.number().int().min(0),
|
||||
parent_artifact_id: artifactIdSchema,
|
||||
@@ -177,7 +177,7 @@ const artifactEdgeSchema = z.object({
|
||||
});
|
||||
|
||||
/** Stable cryptographic commitment and counts for a complete artifact graph. */
|
||||
const artifactGraphManifestSchema = z.object({
|
||||
export const artifactGraphManifestSchema = z.object({
|
||||
manifest_id: manifestIdSchema,
|
||||
root_artifact_id: artifactIdSchema,
|
||||
root_sha256: sha256Schema,
|
||||
|
||||
@@ -103,6 +103,24 @@ export type ArtifactInspectionResult = z.infer<
|
||||
typeof artifactInspectionResultSchema
|
||||
>;
|
||||
|
||||
/**
|
||||
* The current producer guarantees a concrete inventory payload. Specialize
|
||||
* its output without narrowing the historical inspection/Evidence input
|
||||
* parser or applying inventory defaults inside an authenticated imported record.
|
||||
*/
|
||||
export const artifactInspectionOutputSchema =
|
||||
artifactInspectionResultSchema.safeExtend({
|
||||
substeps: z
|
||||
.array(
|
||||
artifactInspectionResultSchema.shape.substeps.element.safeExtend({
|
||||
evidence: evidenceSchema.safeExtend({
|
||||
normalized_result: artifactInventoryResultSchema,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.min(1),
|
||||
});
|
||||
|
||||
/** Project one successful inventory Evidence record into an inspection report. */
|
||||
export const createArtifactInspection = (
|
||||
inventoryInput: unknown,
|
||||
|
||||
@@ -37,37 +37,63 @@ export interface ParsedInventorySet {
|
||||
/** Parse, merge, and verify inventory Evidence pages. */
|
||||
export const parseArtifactInventoryEvidence = (
|
||||
input: unknown,
|
||||
): ParsedInventorySet =>
|
||||
assembleInventorySet(
|
||||
(Array.isArray(input) ? input : [input]).map((value) => {
|
||||
const evidence = parseEvidence(value);
|
||||
const inventoryEvidence =
|
||||
evidence.operation === "inventory_artifact"
|
||||
? evidence
|
||||
: evidence.operation === "inspect_artifact"
|
||||
? artifactInspectionResultSchema.parse(evidence.normalized_result)
|
||||
.substeps[0]?.evidence
|
||||
: undefined;
|
||||
if (inventoryEvidence === undefined)
|
||||
throw new TypeError(
|
||||
"Artifact comparison requires inspect_artifact Evidence",
|
||||
);
|
||||
const inventory = artifactInventoryResultSchema.parse(
|
||||
inventoryEvidence.normalized_result,
|
||||
): ParsedInventorySet => {
|
||||
const pages = (Array.isArray(input) ? input : [input]).map((value) => {
|
||||
const evidence = parseEvidence(value);
|
||||
const inventoryEvidence =
|
||||
evidence.operation === "inventory_artifact"
|
||||
? evidence
|
||||
: evidence.operation === "inspect_artifact"
|
||||
? artifactInspectionResultSchema.parse(evidence.normalized_result)
|
||||
.substeps[0]?.evidence
|
||||
: undefined;
|
||||
if (inventoryEvidence === undefined)
|
||||
throw new TypeError(
|
||||
"Artifact comparison requires inspect_artifact Evidence",
|
||||
);
|
||||
if (
|
||||
inventoryEvidence.subject === null ||
|
||||
inventoryEvidence.subject.digest.sha256 !==
|
||||
inventory.manifest.root_sha256 ||
|
||||
inventoryEvidence.subject.format !== inventory.manifest.root_format
|
||||
)
|
||||
throw new TypeError(
|
||||
"Artifact inventory Evidence subject does not match its root digest",
|
||||
);
|
||||
validateInventoryPage(inventory);
|
||||
return { evidence, inventory };
|
||||
}),
|
||||
);
|
||||
const inventory = artifactInventoryResultSchema.parse(
|
||||
inventoryEvidence.normalized_result,
|
||||
);
|
||||
validateArtifactInventorySubject(
|
||||
inventoryEvidence.subject,
|
||||
inventory.manifest,
|
||||
);
|
||||
validateInventoryPage(inventory);
|
||||
return { evidence, inventory };
|
||||
});
|
||||
return {
|
||||
evidence: pages.map(({ evidence }) => evidence),
|
||||
inventory: assembleInventoryResults(
|
||||
pages.map(({ inventory }) => inventory),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
/** Validate one already authenticated parent payload with the same graph proofs. */
|
||||
export const parseArtifactInventoryResult = (
|
||||
input: unknown,
|
||||
subject: Evidence["subject"],
|
||||
): InventorySet => {
|
||||
const inventory = artifactInventoryResultSchema.parse(input);
|
||||
validateArtifactInventorySubject(subject, inventory.manifest);
|
||||
validateInventoryPage(inventory);
|
||||
return assembleInventoryResults([inventory]);
|
||||
};
|
||||
|
||||
/** Both inventory carriers require the same authenticated root identity. */
|
||||
export const validateArtifactInventorySubject = (
|
||||
subject: Evidence["subject"],
|
||||
manifest: ArtifactInventoryResult["manifest"],
|
||||
): void => {
|
||||
if (
|
||||
subject === null ||
|
||||
subject.digest.sha256 !== manifest.root_sha256 ||
|
||||
subject.format !== manifest.root_format
|
||||
)
|
||||
throw new TypeError(
|
||||
"Artifact inventory Evidence subject does not match its root digest",
|
||||
);
|
||||
};
|
||||
|
||||
const validateInventoryPage = (inventory: ArtifactInventoryResult): void => {
|
||||
assertUnique(
|
||||
@@ -91,45 +117,30 @@ const validateInventoryPage = (inventory: ArtifactInventoryResult): void => {
|
||||
throw new TypeError("Artifact node ID is not content-addressed");
|
||||
};
|
||||
|
||||
const assembleInventorySet = (
|
||||
pages: readonly {
|
||||
readonly evidence: Evidence;
|
||||
readonly inventory: ArtifactInventoryResult;
|
||||
}[],
|
||||
): ParsedInventorySet => {
|
||||
const assembleInventoryResults = (
|
||||
pages: readonly ArtifactInventoryResult[],
|
||||
): InventorySet => {
|
||||
const first = pages[0];
|
||||
if (first === undefined)
|
||||
throw new TypeError("Artifact inventory requires Evidence pages");
|
||||
const manifestJson = canonicalJson(
|
||||
first.inventory.manifest,
|
||||
"Artifact inventory",
|
||||
);
|
||||
const manifestJson = canonicalJson(first.manifest, "Artifact inventory");
|
||||
const nodes = new Map<string, ArtifactNode>();
|
||||
const occurrences = new Map<string, ArtifactOccurrence>();
|
||||
const paths = new Map<string, ArtifactOccurrence>();
|
||||
const edges = new Map<string, ArtifactInventoryResult["edges"][number]>();
|
||||
for (const page of pages) {
|
||||
if (
|
||||
canonicalJson(page.inventory.manifest, "Artifact inventory") !==
|
||||
manifestJson
|
||||
)
|
||||
if (canonicalJson(page.manifest, "Artifact inventory") !== manifestJson)
|
||||
throw new TypeError("Artifact inventory pages do not share one manifest");
|
||||
if (
|
||||
canonicalJson(
|
||||
page.inventory.integrity_contradictions,
|
||||
"Artifact inventory",
|
||||
) !==
|
||||
canonicalJson(
|
||||
first.inventory.integrity_contradictions,
|
||||
"Artifact inventory",
|
||||
)
|
||||
canonicalJson(page.integrity_contradictions, "Artifact inventory") !==
|
||||
canonicalJson(first.integrity_contradictions, "Artifact inventory")
|
||||
)
|
||||
throw new TypeError(
|
||||
"Artifact inventory pages do not share integrity contradictions",
|
||||
);
|
||||
for (const node of page.inventory.nodes)
|
||||
for (const node of page.nodes)
|
||||
mergeExact(nodes, node.artifact_id, node, "node");
|
||||
for (const occurrence of page.inventory.occurrences) {
|
||||
for (const occurrence of page.occurrences) {
|
||||
mergeExact(
|
||||
occurrences,
|
||||
occurrence.occurrence_id,
|
||||
@@ -138,21 +149,21 @@ const assembleInventorySet = (
|
||||
);
|
||||
mergeExact(paths, occurrence.logical_path, occurrence, "logical path");
|
||||
}
|
||||
for (const edge of page.inventory.edges)
|
||||
for (const edge of page.edges)
|
||||
mergeExact(edges, edge.edge_id, edge, "edge");
|
||||
}
|
||||
const inventory = orderedInventory(first.inventory, pages, {
|
||||
const inventory = orderedInventory(first, pages, {
|
||||
nodes,
|
||||
occurrences,
|
||||
edges,
|
||||
});
|
||||
if (inventory.complete) validateCompleteInventory(inventory);
|
||||
return { evidence: pages.map(({ evidence }) => evidence), inventory };
|
||||
return inventory;
|
||||
};
|
||||
|
||||
const orderedInventory = (
|
||||
first: ArtifactInventoryResult,
|
||||
pages: readonly { readonly inventory: ArtifactInventoryResult }[],
|
||||
pages: readonly ArtifactInventoryResult[],
|
||||
values: {
|
||||
readonly nodes: ReadonlyMap<string, ArtifactNode>;
|
||||
readonly occurrences: ReadonlyMap<string, ArtifactOccurrence>;
|
||||
@@ -178,7 +189,7 @@ const orderedInventory = (
|
||||
edges,
|
||||
integrityContradictions: first.integrity_contradictions,
|
||||
limitations: [
|
||||
...new Set(pages.flatMap(({ inventory }) => inventory.limitations)),
|
||||
...new Set(pages.flatMap((inventory) => inventory.limitations)),
|
||||
].sort(compareUnicodeCodePoints),
|
||||
complete:
|
||||
nodes.length === first.manifest.node_count &&
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
|
||||
@@ -83,6 +84,15 @@ export const wasmArtifactSchema = z
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (
|
||||
createHash("sha256").update(value.wat.text, "utf8").digest("hex") !==
|
||||
value.wat.sha256
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["wat", "sha256"],
|
||||
message: "Decoded WAT digest does not match its UTF-8 text.",
|
||||
});
|
||||
const selected = value.candidates[0];
|
||||
if (
|
||||
selected?.path !== value.artifact.path ||
|
||||
@@ -125,3 +135,13 @@ export const wasmArtifactSchema = z
|
||||
export type InspectWasmArtifactInput = z.infer<
|
||||
typeof inspectWasmArtifactInputSchema
|
||||
>;
|
||||
export type WasmArtifact = z.infer<typeof wasmArtifactSchema>;
|
||||
|
||||
/** A WASM observation must identify the exact selected path and byte digest. */
|
||||
export const wasmArtifactMatchesSubject = (
|
||||
artifact: WasmArtifact["artifact"],
|
||||
subject: Pick<WasmArtifact["artifact"], "path" | "sha256"> | null | undefined,
|
||||
): subject is Pick<WasmArtifact["artifact"], "path" | "sha256"> =>
|
||||
subject != null &&
|
||||
subject.path === artifact.path &&
|
||||
subject.sha256 === artifact.sha256;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
|
||||
import { createWasmArtifactService } from "../composition/wasm.js";
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
import { registerWasmTools } from "./registerWasmTools.js";
|
||||
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
import { createPeResourcesService } from "../composition/binaryDiagnostics.js";
|
||||
@@ -246,8 +246,10 @@ export const createServer = (
|
||||
);
|
||||
const android =
|
||||
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
|
||||
const wasmArtifact =
|
||||
options.wasmArtifact ?? createWasmArtifactService(environment);
|
||||
const wasmArtifact = wasmArtifactModule.create(
|
||||
environment,
|
||||
options.wasmArtifact,
|
||||
);
|
||||
const apktool =
|
||||
options.apktoolAnalysis ??
|
||||
createApktoolResourceAnalysisProvider(environment);
|
||||
@@ -399,7 +401,7 @@ const registerConfiguredAnalysisTools = (
|
||||
withAdmittedAnalysis,
|
||||
}: ServerToolContext,
|
||||
android: AndroidAnalysisPort,
|
||||
wasmArtifact: WasmArtifactService,
|
||||
wasmArtifact: Pick<WasmArtifactService, "inspect" | "close">,
|
||||
jeb: JebAnalysisPort,
|
||||
firmwareAnalysis: FirmwareAnalysisService,
|
||||
): void => {
|
||||
@@ -557,6 +559,7 @@ const registerBinaryAnalysisTools = ({
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
evidenceById,
|
||||
withAdmittedAnalysis,
|
||||
}: ServerToolContext): void => {
|
||||
const recordUnknown =
|
||||
@@ -592,7 +595,7 @@ const registerBinaryAnalysisTools = ({
|
||||
withAdmittedAnalysis,
|
||||
};
|
||||
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, evidenceOptions);
|
||||
registerArtifactTools(server, evidenceOptions);
|
||||
registerArtifactTools(server, { ...evidenceOptions, evidenceById });
|
||||
registerManagedTools(server, evidenceOptions);
|
||||
if (session !== undefined)
|
||||
registerManagedWorkflowTools(server, {
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "../contracts/artifactToolContracts.js";
|
||||
import {
|
||||
ARTIFACT_TOOL_CONTRACTS,
|
||||
artifactInspectionInputSchema,
|
||||
} from "../contracts/artifactToolContracts.js";
|
||||
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
|
||||
import { summarizeRetainedAnalysis } from "../application/analysisView/AnalysisViewService.js";
|
||||
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import type { Logger } from "pino";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
@@ -14,11 +21,29 @@ export const registerArtifactTools = (
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly evidenceById?: EvidenceLookup | undefined;
|
||||
readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis;
|
||||
},
|
||||
): void => {
|
||||
registerEvidenceTools(server, ARTIFACT_TOOL_CONTRACTS, {
|
||||
...options,
|
||||
parametersForExecution: (operation, parameters) => {
|
||||
if (operation === "inspect_artifact") {
|
||||
const { detail: _detail, ...execution } =
|
||||
artifactInspectionInputSchema.parse(parameters);
|
||||
return execution;
|
||||
}
|
||||
return operation === "extract_artifact"
|
||||
? { ...parameters, output_root: createArtifactExtractionDestination() }
|
||||
: parameters;
|
||||
},
|
||||
projectEvidence: (operation, parameters, evidence) =>
|
||||
operation === "inspect_artifact" && parameters.detail === "summary"
|
||||
? summarizeRetainedAnalysis(evidence, {
|
||||
recordEvidence: options.recordEvidence,
|
||||
evidenceById: options.evidenceById,
|
||||
})
|
||||
: ok(evidence),
|
||||
sourceEvidence: (operation, result) =>
|
||||
operation === "inspect_artifact"
|
||||
? artifactInspectionResultSchema
|
||||
|
||||
@@ -8,12 +8,13 @@ import type {
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { ok, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "pino";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
|
||||
interface EvidenceToolRegistration {
|
||||
@@ -28,6 +29,15 @@ interface EvidenceToolRegistration {
|
||||
operation: Exclude<AnalysisOperation, "health">,
|
||||
result: import("../domain/jsonValue.js").JsonValue,
|
||||
) => readonly Evidence[];
|
||||
readonly parametersForExecution?: (
|
||||
operation: Exclude<AnalysisOperation, "health">,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
) => Readonly<Record<string, JsonValue>>;
|
||||
readonly projectEvidence?: (
|
||||
operation: Exclude<AnalysisOperation, "health">,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
evidence: Evidence,
|
||||
) => Result<Evidence, AnalysisError>;
|
||||
}
|
||||
|
||||
/** Register provider-backed contracts that return atomic Evidence observations. */
|
||||
@@ -57,12 +67,8 @@ export const registerEvidenceTools = (
|
||||
});
|
||||
const parameters = jsonObjectSchema.parse(input);
|
||||
const executionParameters =
|
||||
contract.name === "extract_artifact"
|
||||
? {
|
||||
...parameters,
|
||||
output_root: createArtifactExtractionDestination(),
|
||||
}
|
||||
: parameters;
|
||||
options.parametersForExecution?.(contract.name, parameters) ??
|
||||
parameters;
|
||||
const execution = await logToolExecution(
|
||||
options.logger,
|
||||
contract.name,
|
||||
@@ -108,9 +114,14 @@ export const registerEvidenceTools = (
|
||||
contract,
|
||||
);
|
||||
}
|
||||
const recorded = options.recordEvidence?.(evidence);
|
||||
const projected =
|
||||
options.projectEvidence?.(contract.name, parameters, evidence) ??
|
||||
ok(evidence);
|
||||
if (!projected.ok)
|
||||
return server.delivery.toCallToolResult(projected, contract);
|
||||
const recorded = options.recordEvidence?.(projected.value);
|
||||
return server.delivery.toEvidenceToolResult(
|
||||
evidence,
|
||||
projected.value,
|
||||
contract,
|
||||
recorded,
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
|
||||
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
import type { Logger } from "pino";
|
||||
import { createEvidenceToolHandler } from "./contractToolHandler.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
@@ -11,12 +11,12 @@ import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
/** Bind the named WASM contract to shared validation and session Evidence recording. */
|
||||
export const registerWasmTools = (
|
||||
server: EvidenceMcpServer,
|
||||
service: WasmArtifactService,
|
||||
service: Pick<WasmArtifactService, "inspect">,
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
): void => {
|
||||
const contract = toolContract("inspect_wasm_artifact");
|
||||
const contract = wasmArtifactModule.contract;
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.inspect(input, options),
|
||||
|
||||
Reference in New Issue
Block a user