refactor(domain): remove provider-specific target and snapshot state
Move Hopper loader derivation and compatibility projection into the Hopper adapter so BinaryTarget carries only provider-neutral identity and format metadata. Introduce bounded canonical analysis-profile commitments, exact provider/profile snapshot v2 bindings, legacy snapshot rejection guidance, and backward-compatible profiled Evidence v2 records. Partition cache and replay behavior by target, concrete provider build, and profile while preserving custom Hopper loader overrides. Propagate profiles consistently through CLI, MCP, composed workflows, and session lifecycle; preserve the 78-tool contract and legacy loaderArgs response projection. Add migration documentation, generated API updates, property regressions, package verification, and real Hopper coverage.
This commit is contained in:
@@ -4,6 +4,7 @@ import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
|
||||
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
|
||||
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { EvidenceLocation } from "../domain/evidence.js";
|
||||
@@ -29,6 +30,7 @@ export interface AnalysisExecution {
|
||||
readonly result: JsonValue;
|
||||
readonly rawResult: JsonValue | null;
|
||||
readonly provider: ProviderIdentity;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations: readonly string[];
|
||||
readonly locations: readonly EvidenceLocation[];
|
||||
readonly subject: EvidenceSubjectTarget | null;
|
||||
@@ -40,6 +42,7 @@ export const createAnalysisExecution = (
|
||||
provider: ProviderIdentity,
|
||||
options: {
|
||||
readonly rawResult?: unknown;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly subject?: EvidenceSubjectTarget;
|
||||
@@ -51,6 +54,9 @@ export const createAnalysisExecution = (
|
||||
? jsonValueSchema.parse(result)
|
||||
: jsonValueSchema.parse(options.rawResult),
|
||||
provider,
|
||||
...(options.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: structuredClone(options.analysisProfile) }),
|
||||
limitations: [...(options.limitations ?? [])],
|
||||
locations: [...(options.locations ?? [])],
|
||||
subject: options.subject ?? null,
|
||||
@@ -70,7 +76,10 @@ export interface AnalysisClient extends AnalysisOperationPort {
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export type AnalysisClientFactory = (target: BinaryTarget) => AnalysisClient;
|
||||
export type AnalysisClientFactory = (
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
) => AnalysisClient;
|
||||
|
||||
export interface ProviderIdentity {
|
||||
readonly id: string;
|
||||
@@ -78,6 +87,12 @@ export interface ProviderIdentity {
|
||||
readonly version: string | null;
|
||||
}
|
||||
|
||||
/** Profile plus opaque compatibility output resolved before provider startup. */
|
||||
export interface AnalysisProfileResolution {
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
interface CapabilityEffects {
|
||||
readonly mutatesArtifact: boolean;
|
||||
readonly launchesProcess: boolean;
|
||||
@@ -114,5 +129,11 @@ export type CapabilityDescriptor = CapabilityAvailability & {
|
||||
export interface AnalysisProvider {
|
||||
identity(): ProviderIdentity;
|
||||
capabilities(): readonly CapabilityDescriptor[];
|
||||
createClient(target: BinaryTarget): AnalysisClient;
|
||||
resolveAnalysisProfile?(
|
||||
target: BinaryTarget,
|
||||
): Promise<Result<AnalysisProfileResolution, AnalysisError>>;
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
): AnalysisClient;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
@@ -11,17 +12,19 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
analysisQueryId,
|
||||
createAnalysisSnapshotEntry,
|
||||
snapshotBinding,
|
||||
snapshotMatchesProfile,
|
||||
snapshotMatchesTarget,
|
||||
snapshotTarget,
|
||||
type AnalysisSnapshot,
|
||||
type AnalysisSnapshotEntry,
|
||||
type AnalysisSnapshotBinding,
|
||||
type AnalysisSnapshotTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
|
||||
@@ -72,30 +75,44 @@ export const isSnapshotCacheable = (
|
||||
export class AnalysisSnapshotCache {
|
||||
readonly #entries = new Map<string, AnalysisSnapshotEntry>();
|
||||
#target: AnalysisSnapshotTarget | undefined;
|
||||
#binding: AnalysisSnapshotBinding | undefined;
|
||||
|
||||
/** Whether staged entries belong to the supplied binary. */
|
||||
matches(target: BinaryTarget): boolean {
|
||||
/** Whether staged entries belong to the supplied target and profile. */
|
||||
matches(
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
this.#target === undefined || snapshotMatchesTarget(this.#target, target)
|
||||
(this.#target === undefined && this.#binding === undefined) ||
|
||||
(this.#target !== undefined &&
|
||||
this.#binding !== undefined &&
|
||||
profile !== undefined &&
|
||||
snapshotMatchesTarget(this.#target, target) &&
|
||||
snapshotMatchesProfile(this.#binding, profile))
|
||||
);
|
||||
}
|
||||
|
||||
/** Replace cache state when the active binary identity changes. */
|
||||
select(target: BinaryTarget): void {
|
||||
if (!this.matches(target)) this.#entries.clear();
|
||||
/** Replace cache state when the target or selected profile changes. */
|
||||
select(target: BinaryTarget, profile: AnalysisProfileCommitment): void {
|
||||
if (!this.matches(target, profile)) this.#entries.clear();
|
||||
this.#target = snapshotTarget(target);
|
||||
this.#binding = snapshotBinding(profile);
|
||||
}
|
||||
|
||||
/** Merge already-validated entries and return the new-entry count. */
|
||||
stage(snapshot: AnalysisSnapshot): number {
|
||||
if (
|
||||
this.#target !== undefined &&
|
||||
(this.#target.sha256 !== snapshot.target.sha256 ||
|
||||
this.#target.format !== snapshot.target.format ||
|
||||
this.#target.architecture !== snapshot.target.architecture)
|
||||
(this.#target !== undefined &&
|
||||
JSON.stringify(this.#target) !== JSON.stringify(snapshot.target)) ||
|
||||
(this.#binding !== undefined &&
|
||||
!snapshotMatchesProfile(
|
||||
this.#binding,
|
||||
snapshot.binding.analysis_profile,
|
||||
))
|
||||
)
|
||||
this.#entries.clear();
|
||||
this.#target = structuredClone(snapshot.target);
|
||||
this.#binding = structuredClone(snapshot.binding);
|
||||
let imported = 0;
|
||||
for (const entry of snapshot.entries) {
|
||||
if (!this.#entries.has(entry.query_id)) imported += 1;
|
||||
@@ -107,12 +124,15 @@ export class AnalysisSnapshotCache {
|
||||
/** Build a complete snapshot for an active target. */
|
||||
export(
|
||||
target: BinaryTarget | undefined,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
evidenceBundle: EvidenceBundle,
|
||||
): Result<AnalysisSnapshot, NoBinaryOpenError> {
|
||||
if (target === undefined) return err(new NoBinaryOpenError());
|
||||
if (target === undefined || profile === undefined)
|
||||
return err(new NoBinaryOpenError());
|
||||
return ok({
|
||||
snapshot_version: 1,
|
||||
snapshot_version: 2,
|
||||
target: snapshotTarget(target),
|
||||
binding: snapshotBinding(profile),
|
||||
entries: this.entries(),
|
||||
evidence_bundle: structuredClone(evidenceBundle),
|
||||
});
|
||||
@@ -121,15 +141,24 @@ export class AnalysisSnapshotCache {
|
||||
/** Validate target identity, merge evidence atomically, then stage entries. */
|
||||
import(
|
||||
snapshot: AnalysisSnapshot,
|
||||
active: BinaryTarget | undefined,
|
||||
active:
|
||||
| {
|
||||
readonly target: BinaryTarget;
|
||||
readonly profile: AnalysisProfileCommitment;
|
||||
}
|
||||
| undefined,
|
||||
mergeEvidence: (
|
||||
bundle: EvidenceBundle,
|
||||
) => Result<number, EvidenceIntegrityError | EvidenceLimitError>,
|
||||
): Result<number, AnalysisError> {
|
||||
if (active !== undefined && !snapshotMatchesTarget(snapshot.target, active))
|
||||
if (
|
||||
active !== undefined &&
|
||||
(!snapshotMatchesTarget(snapshot.target, active.target) ||
|
||||
!snapshotMatchesProfile(snapshot.binding, active.profile))
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the active binary",
|
||||
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the active binary",
|
||||
),
|
||||
);
|
||||
const importedEvidence = mergeEvidence(snapshot.evidence_bundle);
|
||||
@@ -146,15 +175,15 @@ export class AnalysisSnapshotCache {
|
||||
/** Replay an exact provider-specific query, marking its cached provenance. */
|
||||
lookup(
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
provider: ProviderIdentity,
|
||||
): AnalysisExecution | undefined {
|
||||
const queryId = analysisQueryId(
|
||||
snapshotTarget(target),
|
||||
snapshotBinding(profile),
|
||||
operation,
|
||||
parameters,
|
||||
provider,
|
||||
);
|
||||
const cached = this.#entries.get(queryId);
|
||||
if (cached === undefined) return undefined;
|
||||
@@ -163,6 +192,7 @@ export class AnalysisSnapshotCache {
|
||||
result: cached.execution.result,
|
||||
rawResult: cached.execution.raw_result,
|
||||
provider: cached.execution.provider,
|
||||
analysisProfile: structuredClone(profile),
|
||||
limitations: [
|
||||
...cached.execution.limitations,
|
||||
"Loaded from a local REA analysis snapshot; this call did not re-run the provider.",
|
||||
@@ -187,20 +217,23 @@ export class AnalysisSnapshotCache {
|
||||
}
|
||||
|
||||
/** Record one successful immutable call unless the cache is full. */
|
||||
record(
|
||||
target: BinaryTarget,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
): void {
|
||||
record(input: {
|
||||
readonly target: BinaryTarget;
|
||||
readonly profile: AnalysisProfileCommitment;
|
||||
readonly operation: AnalysisOperation;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly execution: AnalysisExecution;
|
||||
}): void {
|
||||
const { target, profile, operation, parameters, execution } = input;
|
||||
if (this.#entries.size >= 10_000) return;
|
||||
this.select(target);
|
||||
const entry = createAnalysisSnapshotEntry(
|
||||
snapshotTarget(target),
|
||||
this.select(target, profile);
|
||||
const entry = createAnalysisSnapshotEntry({
|
||||
target: snapshotTarget(target),
|
||||
binding: snapshotBinding(profile),
|
||||
operation,
|
||||
parameters,
|
||||
execution,
|
||||
);
|
||||
});
|
||||
this.#entries.set(entry.query_id, entry);
|
||||
}
|
||||
|
||||
@@ -208,5 +241,6 @@ export class AnalysisSnapshotCache {
|
||||
clear(): void {
|
||||
this.#entries.clear();
|
||||
this.#target = undefined;
|
||||
this.#binding = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,9 +21,7 @@ export const readAnalysisSnapshot = async (
|
||||
return ok(parseAnalysisSnapshot(loaded.value));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Analysis snapshot validation failed", {
|
||||
cause,
|
||||
}),
|
||||
new EvidenceIntegrityError(snapshotValidationMessage(cause), { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -42,10 +40,13 @@ export const writeAnalysisSnapshot = async (
|
||||
encoded = serializeAnalysisSnapshot(snapshot);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Analysis snapshot validation failed", {
|
||||
cause,
|
||||
}),
|
||||
new EvidenceIntegrityError(snapshotValidationMessage(cause), { cause }),
|
||||
);
|
||||
}
|
||||
return writeBoundedText(encoded, path, overwrite, policy);
|
||||
};
|
||||
|
||||
const snapshotValidationMessage = (cause: unknown): string =>
|
||||
cause instanceof TypeError
|
||||
? cause.message
|
||||
: "Analysis snapshot validation failed";
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
analysisProfilesEqual,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "../domain/analysisProfile.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
AnalysisCancelledError,
|
||||
NoBinaryOpenError,
|
||||
ProviderAdapterError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
@@ -18,6 +24,7 @@ import type {
|
||||
AnalysisClient,
|
||||
AnalysisExecution,
|
||||
AnalysisClientFactory,
|
||||
AnalysisProfileResolution,
|
||||
AnalysisOperationPort,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
@@ -36,6 +43,7 @@ import { enhancedToolNameSchema } from "../contracts/enhancedInputs.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import {
|
||||
snapshotMatchesBinding,
|
||||
snapshotMatchesTarget,
|
||||
snapshotTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
@@ -67,11 +75,19 @@ const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
*/
|
||||
export class BinarySession implements BinarySessionPort {
|
||||
#active:
|
||||
| { readonly target: BinaryTarget; readonly client: AnalysisClient }
|
||||
| {
|
||||
readonly target: BinaryTarget;
|
||||
readonly client: AnalysisClient;
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
| undefined;
|
||||
#transition: Promise<void> = Promise.resolve();
|
||||
readonly #calls = new Set<Promise<unknown>>();
|
||||
readonly #createClient: AnalysisClientFactory;
|
||||
readonly #resolveAnalysisProfile: (
|
||||
target: BinaryTarget,
|
||||
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
|
||||
readonly #providerIdentity: ProviderIdentity;
|
||||
readonly #capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
|
||||
readonly #evidence = new EvidenceLedger({
|
||||
@@ -85,18 +101,28 @@ export class BinarySession implements BinarySessionPort {
|
||||
{ readonly available: boolean; readonly reason: string | null }
|
||||
>();
|
||||
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
|
||||
readonly #snapshotsEnabled: boolean;
|
||||
#snapshotInvalidated = false;
|
||||
|
||||
constructor(
|
||||
readonly provider: AnalysisProvider | AnalysisClientFactory,
|
||||
options: { readonly snapshotsEnabled?: boolean } = {},
|
||||
options: {
|
||||
readonly resolveAnalysisProfile?: (
|
||||
target: BinaryTarget,
|
||||
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
|
||||
} = {},
|
||||
) {
|
||||
this.#snapshotsEnabled = options.snapshotsEnabled ?? true;
|
||||
this.#createClient =
|
||||
typeof provider === "function"
|
||||
? provider
|
||||
: (target) => provider.createClient(target);
|
||||
: (target, profile) => provider.createClient(target, profile);
|
||||
this.#resolveAnalysisProfile =
|
||||
options.resolveAnalysisProfile ??
|
||||
(typeof provider === "function" ||
|
||||
provider.resolveAnalysisProfile === undefined
|
||||
? () => Promise.resolve(ok({ profile: null, compatibility: {} }))
|
||||
: (target) =>
|
||||
provider.resolveAnalysisProfile?.(target) ??
|
||||
Promise.resolve(ok({ profile: null, compatibility: {} })));
|
||||
this.#providerIdentity =
|
||||
typeof provider === "function"
|
||||
? { id: "unidentified", name: "Unidentified provider", version: null }
|
||||
@@ -113,10 +139,11 @@ export class BinarySession implements BinarySessionPort {
|
||||
|
||||
/** Identify the provider producing evidence for this session. */
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
|
||||
let selected = this.#providerIdentity;
|
||||
if (operation !== undefined) {
|
||||
const exact = this.#capabilities?.get(operation)?.provider;
|
||||
if (exact !== undefined) return structuredClone(exact);
|
||||
if (enhancedToolNameSchema.safeParse(operation).success) {
|
||||
if (exact !== undefined) selected = exact;
|
||||
else if (enhancedToolNameSchema.safeParse(operation).success) {
|
||||
const providers = new Map<string, ProviderIdentity>();
|
||||
for (const descriptor of this.#capabilities?.values() ?? [])
|
||||
if (
|
||||
@@ -126,11 +153,37 @@ export class BinarySession implements BinarySessionPort {
|
||||
providers.set(descriptor.provider.id, descriptor.provider);
|
||||
if (providers.size === 1) {
|
||||
const provider = providers.values().next().value;
|
||||
if (provider !== undefined) return structuredClone(provider);
|
||||
if (provider !== undefined) selected = provider;
|
||||
}
|
||||
}
|
||||
}
|
||||
return structuredClone(this.#providerIdentity);
|
||||
const profile = this.#active?.profile;
|
||||
return structuredClone(
|
||||
profile !== null &&
|
||||
profile !== undefined &&
|
||||
profile.provider.id === selected.id
|
||||
? profile.provider
|
||||
: selected,
|
||||
);
|
||||
}
|
||||
|
||||
/** Return the selected immutable profile, optionally scoped to an operation. */
|
||||
analysisProfile(
|
||||
operation?: AnalysisOperation,
|
||||
): AnalysisProfileCommitment | undefined {
|
||||
const profile = this.#active?.profile;
|
||||
if (profile === null || profile === undefined) return undefined;
|
||||
if (
|
||||
operation !== undefined &&
|
||||
this.providerIdentity(operation).id !== profile.provider.id
|
||||
)
|
||||
return undefined;
|
||||
return structuredClone(profile);
|
||||
}
|
||||
|
||||
/** Return opaque adapter metadata retained for legacy open_binary output. */
|
||||
openCompatibility(): Readonly<Record<string, JsonValue>> {
|
||||
return structuredClone(this.#active?.compatibility ?? {});
|
||||
}
|
||||
|
||||
/** Observe runtime provider-health changes that affect discovery metadata. */
|
||||
@@ -173,12 +226,6 @@ export class BinarySession implements BinarySessionPort {
|
||||
|
||||
/** Export immutable cached calls and session evidence for the active target. */
|
||||
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError> {
|
||||
if (!this.#snapshotsEnabled)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable with custom Hopper loader arguments",
|
||||
),
|
||||
);
|
||||
if (this.#snapshotInvalidated)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
@@ -186,8 +233,16 @@ export class BinarySession implements BinarySessionPort {
|
||||
),
|
||||
);
|
||||
const target = this.#active?.target;
|
||||
const profile = this.#active?.profile ?? undefined;
|
||||
if (target !== undefined && profile === undefined)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshots require a concrete provider analysis profile",
|
||||
),
|
||||
);
|
||||
return this.#snapshot.export(
|
||||
target,
|
||||
profile,
|
||||
target === undefined
|
||||
? this.#evidence.export()
|
||||
: evidenceBundleForTarget(this.#evidence.export(), target.sha256),
|
||||
@@ -198,14 +253,19 @@ export class BinarySession implements BinarySessionPort {
|
||||
importAnalysisSnapshot(
|
||||
snapshot: AnalysisSnapshot,
|
||||
): Result<number, AnalysisError> {
|
||||
if (!this.#snapshotsEnabled)
|
||||
const active = this.#active;
|
||||
if (active?.profile === null)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable with custom Hopper loader arguments",
|
||||
"Analysis snapshot profile_mismatch: the active target has no concrete analysis profile",
|
||||
),
|
||||
);
|
||||
return this.#snapshot.import(snapshot, this.#active?.target, (bundle) =>
|
||||
this.#evidence.import(bundle),
|
||||
return this.#snapshot.import(
|
||||
snapshot,
|
||||
active === undefined
|
||||
? undefined
|
||||
: { target: active.target, profile: active.profile },
|
||||
(bundle) => this.#evidence.import(bundle),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -333,26 +393,47 @@ export class BinarySession implements BinarySessionPort {
|
||||
options.targetKind,
|
||||
);
|
||||
if (!parsed.ok) return parsed;
|
||||
const resolvedProfile = await this.#resolveAnalysisProfile(parsed.value);
|
||||
if (!resolvedProfile.ok) return resolvedProfile;
|
||||
const normalizedProfile = normalizeProfileResolution(
|
||||
resolvedProfile.value,
|
||||
this.#providerIdentity.id,
|
||||
);
|
||||
if (!normalizedProfile.ok) return normalizedProfile;
|
||||
const { profile, compatibility } = normalizedProfile.value;
|
||||
if (
|
||||
options.snapshot !== undefined &&
|
||||
!snapshotMatchesTarget(options.snapshot.target, parsed.value)
|
||||
(profile === null ||
|
||||
!snapshotMatchesBinding(options.snapshot, parsed.value, profile))
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the requested binary",
|
||||
),
|
||||
);
|
||||
if (this.#active === undefined && !this.#snapshot.matches(parsed.value))
|
||||
if (
|
||||
this.#active === undefined &&
|
||||
!this.#snapshot.matches(parsed.value, profile ?? undefined)
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
"Analysis snapshot profile_mismatch: staged target, provider, or analysis profile does not match",
|
||||
),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const activeProfile = this.#active?.profile;
|
||||
const sameProfile =
|
||||
activeProfile === null || activeProfile === undefined
|
||||
? profile === null
|
||||
: profile !== null && analysisProfilesEqual(activeProfile, profile);
|
||||
if (
|
||||
this.#active?.target.path === parsed.value.path &&
|
||||
snapshotMatchesTarget(snapshotTarget(this.#active.target), parsed.value)
|
||||
snapshotMatchesTarget(
|
||||
snapshotTarget(this.#active.target),
|
||||
parsed.value,
|
||||
) &&
|
||||
sameProfile
|
||||
) {
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
@@ -364,7 +445,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
await previous?.client.close();
|
||||
const client = this.#createClient(parsed.value);
|
||||
const client = this.#createClient(parsed.value, profile ?? undefined);
|
||||
const started = await client.execute("health", {}, options);
|
||||
if (!started.ok) {
|
||||
await client.close();
|
||||
@@ -376,9 +457,15 @@ export class BinarySession implements BinarySessionPort {
|
||||
await this.#restore(previous);
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
}
|
||||
this.#active = { target: parsed.value, client };
|
||||
this.#active = {
|
||||
target: parsed.value,
|
||||
client,
|
||||
profile,
|
||||
compatibility: structuredClone(compatibility),
|
||||
};
|
||||
this.#clearRuntimeAvailability();
|
||||
this.#snapshot.select(parsed.value);
|
||||
if (profile === null) this.#snapshot.clear();
|
||||
else this.#snapshot.select(parsed.value, profile);
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) {
|
||||
@@ -504,28 +591,38 @@ export class BinarySession implements BinarySessionPort {
|
||||
);
|
||||
const active = this.#active;
|
||||
if (active === undefined) return err(new NoBinaryOpenError());
|
||||
const cacheable = isSnapshotCacheable(name, capability, arguments_);
|
||||
const profile =
|
||||
active.profile !== null &&
|
||||
(capability === undefined ||
|
||||
capability.provider.id === active.profile.provider.id)
|
||||
? active.profile
|
||||
: undefined;
|
||||
const cacheable =
|
||||
profile !== undefined &&
|
||||
isSnapshotCacheable(name, capability, arguments_);
|
||||
const cached = cacheable
|
||||
? this.#snapshot.lookup(
|
||||
active.target,
|
||||
name,
|
||||
arguments_,
|
||||
capability.provider,
|
||||
)
|
||||
? this.#snapshot.lookup(active.target, profile, name, arguments_)
|
||||
: undefined;
|
||||
if (cached !== undefined) return ok(cached);
|
||||
const call = active.client.execute(name, arguments_, options);
|
||||
this.#calls.add(call);
|
||||
try {
|
||||
const result = await call;
|
||||
this.#observeRuntimeAvailability(name, result);
|
||||
if (result.ok && cacheable)
|
||||
this.#snapshot.record(active.target, name, arguments_, result.value);
|
||||
else if (result.ok && capability?.effects.mutatesArtifact === true) {
|
||||
const profiled = commitExecutionProfile(name, result, profile);
|
||||
this.#observeRuntimeAvailability(name, profiled);
|
||||
if (profiled.ok && cacheable)
|
||||
this.#snapshot.record({
|
||||
target: active.target,
|
||||
profile,
|
||||
operation: name,
|
||||
parameters: arguments_,
|
||||
execution: profiled.value,
|
||||
});
|
||||
else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = true;
|
||||
}
|
||||
return result;
|
||||
return profiled;
|
||||
} finally {
|
||||
this.#calls.delete(call);
|
||||
}
|
||||
@@ -615,13 +712,27 @@ export class BinarySession implements BinarySessionPort {
|
||||
|
||||
async #restore(
|
||||
previous:
|
||||
| { readonly target: BinaryTarget; readonly client: AnalysisClient }
|
||||
| {
|
||||
readonly target: BinaryTarget;
|
||||
readonly client: AnalysisClient;
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
| undefined,
|
||||
): Promise<void> {
|
||||
if (previous === undefined) return;
|
||||
const client = this.#createClient(previous.target);
|
||||
const client = this.#createClient(
|
||||
previous.target,
|
||||
previous.profile ?? undefined,
|
||||
);
|
||||
const started = await client.execute("health", {});
|
||||
if (started.ok) this.#active = { target: previous.target, client };
|
||||
if (started.ok)
|
||||
this.#active = {
|
||||
target: previous.target,
|
||||
client,
|
||||
profile: previous.profile,
|
||||
compatibility: previous.compatibility,
|
||||
};
|
||||
else await client.close();
|
||||
}
|
||||
|
||||
@@ -664,3 +775,45 @@ export class BinarySession implements BinarySessionPort {
|
||||
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
const commitExecutionProfile = (
|
||||
operation: AnalysisOperation,
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
): Result<AnalysisExecution, AnalysisError> => {
|
||||
if (!result.ok || profile === undefined) return result;
|
||||
const provider = result.value.provider;
|
||||
if (
|
||||
provider.id !== profile.provider.id ||
|
||||
provider.name !== profile.provider.name ||
|
||||
provider.version !== profile.provider.version
|
||||
)
|
||||
return err(
|
||||
new ProviderAdapterError(profile.provider.id, `${operation}:profile`),
|
||||
);
|
||||
return ok({
|
||||
...result.value,
|
||||
analysisProfile: structuredClone(profile),
|
||||
});
|
||||
};
|
||||
|
||||
const normalizeProfileResolution = (
|
||||
resolution: AnalysisProfileResolution,
|
||||
providerId: string,
|
||||
): Result<AnalysisProfileResolution, ProviderAdapterError> => {
|
||||
try {
|
||||
return ok({
|
||||
profile:
|
||||
resolution.profile === null
|
||||
? null
|
||||
: analysisProfileSchema.parse(resolution.profile),
|
||||
compatibility: jsonObjectSchema.parse(resolution.compatibility),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProviderAdapterError(providerId, "resolve_analysis_profile", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type {
|
||||
AnalysisError,
|
||||
EvidenceIntegrityError,
|
||||
@@ -81,5 +82,9 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
UnknownRegistryError
|
||||
>;
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
|
||||
analysisProfile(
|
||||
operation?: AnalysisOperation,
|
||||
): AnalysisProfileCommitment | undefined;
|
||||
openCompatibility(): Readonly<Record<string, JsonValue>>;
|
||||
onAvailabilityChanged?(listener: () => void | Promise<void>): () => void;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ProviderSelectionError } from "../domain/errors.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
@@ -24,10 +25,19 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
readonly #identity: ProviderIdentity;
|
||||
readonly #capabilities: readonly CapabilityDescriptor[];
|
||||
readonly #providerByOperation: ReadonlyMap<string, AnalysisProvider>;
|
||||
readonly #profileProvider: AnalysisProvider | undefined;
|
||||
|
||||
constructor(readonly providers: readonly AnalysisProvider[]) {
|
||||
if (providers.length === 0)
|
||||
throw new RangeError("CompositeProvider requires at least one provider");
|
||||
const profileProviders = providers.filter(
|
||||
({ resolveAnalysisProfile }) => resolveAnalysisProfile !== undefined,
|
||||
);
|
||||
if (profileProviders.length > 1)
|
||||
throw new TypeError(
|
||||
"CompositeProvider supports at most one target-bound analysis profile",
|
||||
);
|
||||
this.#profileProvider = profileProviders[0];
|
||||
this.#identity = Object.freeze(compositeIdentity(providers));
|
||||
const routes = new Map<string, AnalysisProvider>();
|
||||
const capabilities: CapabilityDescriptor[] = [];
|
||||
@@ -59,12 +69,25 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
return this.#capabilities;
|
||||
}
|
||||
|
||||
createClient(target: BinaryTarget): AnalysisClient {
|
||||
resolveAnalysisProfile(target: BinaryTarget) {
|
||||
const resolve = this.#profileProvider?.resolveAnalysisProfile;
|
||||
return resolve === undefined
|
||||
? Promise.resolve(ok({ profile: null, compatibility: {} }))
|
||||
: resolve.call(this.#profileProvider, target);
|
||||
}
|
||||
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
): AnalysisClient {
|
||||
const clients = new Map<AnalysisProvider, AnalysisClient>();
|
||||
const clientFor = (provider: AnalysisProvider): AnalysisClient => {
|
||||
const existing = clients.get(provider);
|
||||
if (existing !== undefined) return existing;
|
||||
const created = provider.createClient(target);
|
||||
const created = provider.createClient(
|
||||
target,
|
||||
profile?.provider.id === provider.identity().id ? profile : undefined,
|
||||
);
|
||||
clients.set(provider, created);
|
||||
return created;
|
||||
};
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotMatchesTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
|
||||
@@ -34,12 +35,10 @@ import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
type DeferredFileWriteAuthorization,
|
||||
} from "./DeferredFileAuthorization.js";
|
||||
|
||||
const WORKFLOW_PROVIDER = {
|
||||
id: "rea-workflow",
|
||||
name: "REA composed investigation workflow",
|
||||
version: "1",
|
||||
} as const;
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
} from "./InvestigationProviders.js";
|
||||
|
||||
type DirectAnalysisTool =
|
||||
| "binary_overview"
|
||||
@@ -51,9 +50,9 @@ type DirectAnalysisTool =
|
||||
| "trace_feature";
|
||||
|
||||
/**
|
||||
* Open one binary, execute one tool, and always release the bridge session.
|
||||
* Open one binary, execute one tool, and always release provider resources.
|
||||
* Unlike MCP mode, every CLI invocation is intentionally isolated and does not
|
||||
* retain a target or bridge resources for a subsequent command.
|
||||
* retain a target or provider client for a subsequent command.
|
||||
*/
|
||||
export const runDirectAnalysis = async (
|
||||
path: string,
|
||||
@@ -93,7 +92,7 @@ export const runProviderAnalysis = async (
|
||||
}),
|
||||
);
|
||||
|
||||
/** Describe configured providers without opening a target or launching Hopper. */
|
||||
/** Describe configured providers without opening a target or starting one. */
|
||||
export const runSessionStatus = async (
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => {
|
||||
@@ -252,31 +251,39 @@ const runAnalysis = async (
|
||||
snapshotPath,
|
||||
});
|
||||
if (!authorization.ok) return cliError(authorization.error);
|
||||
const unavailable = snapshotUnavailable(
|
||||
snapshotPath,
|
||||
config.value.hopperLoaderArgs,
|
||||
);
|
||||
if (unavailable !== undefined) return cliError(unavailable);
|
||||
const session = createBinarySession(config.value, logger);
|
||||
try {
|
||||
const prepared = await prepareSnapshot({
|
||||
path,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
snapshotPath,
|
||||
policy: config.value.analysisSnapshotFilePolicy,
|
||||
provider: replayProviderFor(session, tool),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
if (prepared.value.evidence !== undefined) return prepared.value.evidence;
|
||||
const writable = await authorizeDeferredWrite(authorization.value);
|
||||
if (!writable.ok) return cliError(writable.error);
|
||||
const { snapshot } = prepared.value;
|
||||
const opened = await session.open(
|
||||
path,
|
||||
snapshot === undefined ? { signal } : { signal, snapshot },
|
||||
);
|
||||
if (!opened.ok) return cliError(opened.error);
|
||||
const evidenceProfile = analysisProfileForEvidence(session, tool);
|
||||
const bindingProfile = session.analysisProfile();
|
||||
if (
|
||||
snapshot !== undefined &&
|
||||
evidenceProfile !== undefined &&
|
||||
bindingProfile !== undefined
|
||||
) {
|
||||
const cached = snapshotEvidenceForQuery(snapshot, {
|
||||
target: opened.value,
|
||||
bindingProfile,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider: replayProviderFor(session, tool),
|
||||
evidenceProfile,
|
||||
});
|
||||
if (cached !== undefined) return cached;
|
||||
}
|
||||
const writable = await authorizeDeferredWrite(authorization.value);
|
||||
if (!writable.ok) return cliError(writable.error);
|
||||
let output: JsonValue;
|
||||
let evidence: Evidence | undefined;
|
||||
if (
|
||||
@@ -295,11 +302,14 @@ const runAnalysis = async (
|
||||
opened.value,
|
||||
tool === "analyze_function"
|
||||
? session.providerIdentity(tool)
|
||||
: WORKFLOW_PROVIDER,
|
||||
: REA_WORKFLOW_PROVIDER,
|
||||
{
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
...(evidenceProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: evidenceProfile }),
|
||||
confidence: "derived",
|
||||
limitations: ["Derived by an REA composed workflow."],
|
||||
},
|
||||
@@ -317,6 +327,9 @@ const runAnalysis = async (
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value.result,
|
||||
...(result.value.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: result.value.analysisProfile }),
|
||||
rawResult: result.value.rawResult,
|
||||
limitations: result.value.limitations,
|
||||
locations: result.value.locations,
|
||||
@@ -360,25 +373,12 @@ const withProcessCancellation = async <Value>(
|
||||
|
||||
const prepareSnapshot = async (options: {
|
||||
readonly path: string;
|
||||
readonly tool: string;
|
||||
readonly arguments: Readonly<Record<string, JsonValue>>;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly policy: Parameters<typeof readAnalysisSnapshot>[1];
|
||||
readonly provider: Parameters<typeof snapshotEvidenceForQuery>[1]["provider"];
|
||||
}): Promise<
|
||||
Result<
|
||||
{ readonly snapshot?: AnalysisSnapshot; readonly evidence?: Evidence },
|
||||
AnalysisError
|
||||
>
|
||||
Result<{ readonly snapshot?: AnalysisSnapshot }, AnalysisError>
|
||||
> => {
|
||||
const {
|
||||
path,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
snapshotPath,
|
||||
policy,
|
||||
provider,
|
||||
} = options;
|
||||
const { path, snapshotPath, policy } = options;
|
||||
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
|
||||
return ok({});
|
||||
const loaded = await readAnalysisSnapshot(snapshotPath, policy);
|
||||
@@ -391,37 +391,27 @@ const prepareSnapshot = async (options: {
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
),
|
||||
);
|
||||
const evidence = snapshotEvidenceForQuery(loaded.value, {
|
||||
target: target.value,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider,
|
||||
});
|
||||
return ok(
|
||||
evidence === undefined
|
||||
? { snapshot: loaded.value }
|
||||
: { snapshot: loaded.value, evidence },
|
||||
);
|
||||
return ok({ snapshot: loaded.value });
|
||||
};
|
||||
|
||||
const snapshotUnavailable = (
|
||||
snapshotPath: string | undefined,
|
||||
loaderArgs: readonly string[],
|
||||
): EvidenceIntegrityError | undefined =>
|
||||
snapshotPath !== undefined && loaderArgs.length > 0
|
||||
? new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable with custom Hopper loader arguments",
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const replayProviderFor = (
|
||||
session: ReturnType<typeof createBinarySession>,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
) =>
|
||||
tool === "binary_overview" || tool === "trace_feature"
|
||||
? WORKFLOW_PROVIDER
|
||||
? REA_WORKFLOW_PROVIDER
|
||||
: session.providerIdentity(tool);
|
||||
|
||||
const analysisProfileForEvidence = (
|
||||
session: ReturnType<typeof createBinarySession>,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
): AnalysisProfileCommitment | undefined => {
|
||||
if (tool !== "binary_overview" && tool !== "trace_feature")
|
||||
return session.analysisProfile(tool);
|
||||
const upstream = session.analysisProfile();
|
||||
return upstream === undefined ? undefined : workflowAnalysisProfile(upstream);
|
||||
};
|
||||
|
||||
const fileExists = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
await access(path);
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
import {
|
||||
createAnalysisProfile,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "../domain/analysisProfile.js";
|
||||
|
||||
/** Provider identity for deterministic composed analysis workflows. */
|
||||
export const REA_WORKFLOW_PROVIDER = {
|
||||
id: "rea-workflow",
|
||||
name: "REA composed investigation workflow",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Commit a workflow result to the exact upstream deep-analysis profile. */
|
||||
export const workflowAnalysisProfile = (
|
||||
upstream: AnalysisProfileCommitment,
|
||||
): AnalysisProfileCommitment =>
|
||||
createAnalysisProfile(REA_WORKFLOW_PROVIDER, 1, {
|
||||
upstream_analysis_profile: upstream,
|
||||
});
|
||||
|
||||
/** Provider identity for deterministic artifact inventories. */
|
||||
export const ARTIFACT_GRAPH_PROVIDER = {
|
||||
id: "rea-artifact-graph",
|
||||
|
||||
@@ -8,8 +8,8 @@ import { silentLogger, type Logger } from "../logger.js";
|
||||
|
||||
/**
|
||||
* Compose the target-switching runtime shared directly by CLI and MCP adapters.
|
||||
* This is the sole production wiring point for Hopper so neither adapter shells
|
||||
* out to the other and both retain identical loader and bridge semantics.
|
||||
* This is the sole production wiring point, so both adapters share identical
|
||||
* provider selection, profile, lifecycle, and Evidence semantics.
|
||||
*/
|
||||
export const createBinarySession = (
|
||||
config: AppConfig,
|
||||
@@ -24,6 +24,5 @@ export const createBinarySession = (
|
||||
new NativeMacOSProvider(),
|
||||
new HopperProvider(config, logger),
|
||||
]),
|
||||
{ snapshotsEnabled: config.hopperLoaderArgs.length === 0 },
|
||||
);
|
||||
};
|
||||
|
||||
+2
-2
@@ -99,7 +99,7 @@ const registerCoreCommands = (
|
||||
cli.command(CLI_COMMANDS.analyze, {
|
||||
description: "Get an overview of an app",
|
||||
args: z.object({
|
||||
path: z.string().describe("App, program, or Hopper database path"),
|
||||
path: z.string().describe("App, program, or analysis database path"),
|
||||
}),
|
||||
options: overviewOptions,
|
||||
run: ({ args, options }) =>
|
||||
@@ -115,7 +115,7 @@ const registerCoreCommands = (
|
||||
cli.command(CLI_COMMANDS.inspect, {
|
||||
description: "Inspect an app overview with evidence",
|
||||
args: z.object({
|
||||
path: z.string().describe("App, program, or Hopper database path"),
|
||||
path: z.string().describe("App, program, or analysis database path"),
|
||||
}),
|
||||
options: overviewOptions,
|
||||
run: ({ args, options }) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { z } from "zod";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
browserTargetListSchema,
|
||||
inspectWebPageInputSchema,
|
||||
@@ -31,17 +31,17 @@ import {
|
||||
} from "../domain/webScreenshot.js";
|
||||
|
||||
const evidenceResult = <Schema extends z.ZodType>(schema: Schema) =>
|
||||
evidenceSchema
|
||||
evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: schema });
|
||||
const listOutputSchema = evidenceResult(browserTargetListSchema);
|
||||
const inspectionOutputSchema = evidenceSchema
|
||||
const inspectionOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: webPageInspectionSchema });
|
||||
const bundleOutputSchema = evidenceSchema
|
||||
const bundleOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: webBundleAnalysisSchema });
|
||||
const observationSessionOutputSchema = evidenceSchema
|
||||
const observationSessionOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: webObservationSessionSchema });
|
||||
const webMcpOutputSchema = evidenceResult(webMcpDiscoverySchema);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
electronPageInspectionSchema,
|
||||
electronTargetListSchema,
|
||||
@@ -7,10 +7,10 @@ import {
|
||||
listElectronTargetsInputSchema,
|
||||
} from "../domain/electronObservation.js";
|
||||
|
||||
const listOutputSchema = evidenceSchema
|
||||
const listOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: electronTargetListSchema });
|
||||
const inspectionOutputSchema = evidenceSchema
|
||||
const inspectionOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: electronPageInspectionSchema });
|
||||
|
||||
|
||||
@@ -405,7 +405,7 @@ export const binarySessionInputSchema = z.object({
|
||||
export const SESSION_TOOL_CONTRACTS = [
|
||||
session(
|
||||
"open_binary",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or Hopper database after validation. An optional provider-neutral snapshot is imported atomically and must match the binary digest, format, and architecture exactly; provider resources may still start before an MCP cache replay.",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. An optional snapshot v2 is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly; provider resources may still start before an MCP cache replay.",
|
||||
openBinaryInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
processCaptureComparisonSchema,
|
||||
processCaptureSchema,
|
||||
@@ -28,7 +28,7 @@ import { reconstructionVerificationResultSchema } from "../domain/reconstruction
|
||||
import { analysisErrorProjectionSchema } from "./errorSchemas.js";
|
||||
|
||||
const resultOf = (schema: z.ZodType) =>
|
||||
evidenceSchema
|
||||
evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: schema });
|
||||
const lifecycleResultOf = (schema: z.ZodType) => z.object({ result: schema });
|
||||
@@ -45,6 +45,7 @@ export const requireOutputSchema = (
|
||||
};
|
||||
const targetFormatSchema = z.enum([
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
@@ -473,47 +474,47 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
}),
|
||||
),
|
||||
capture_process_scenario: lifecycleResultOf(
|
||||
evidenceSchema
|
||||
evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: processCaptureSchema }),
|
||||
),
|
||||
compare_process_captures: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: processCaptureComparisonSchema,
|
||||
}),
|
||||
),
|
||||
compare_artifacts: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: artifactComparisonResultSchema,
|
||||
}),
|
||||
),
|
||||
compare_functions: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: functionComparisonResultSchema,
|
||||
}),
|
||||
),
|
||||
compare_bundles: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: bundleComparisonResultSchema,
|
||||
}),
|
||||
),
|
||||
find_changed_behavior: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: changedBehaviorResultSchema,
|
||||
}),
|
||||
),
|
||||
build_call_path: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: callPathResultSchema,
|
||||
}),
|
||||
),
|
||||
correlate_static_and_runtime: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: staticRuntimeCorrelationResultSchema,
|
||||
}),
|
||||
),
|
||||
verify_reconstruction: lifecycleResultOf(
|
||||
evidenceSchema.omit({ normalized_result: true }).extend({
|
||||
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
|
||||
normalized_result: reconstructionVerificationResultSchema,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { isJsonWithinLimits } from "./jsonLimits.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "./jsonValue.js";
|
||||
|
||||
const PROFILE_MAX_BYTES = 64 * 1024;
|
||||
const PROFILE_JSON_LIMITS = Object.freeze({
|
||||
maxDepth: 16,
|
||||
maxStringLength: 16 * 1024,
|
||||
maxNodes: 4_096,
|
||||
});
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
|
||||
/** Concrete provider identity committed by an analysis profile. */
|
||||
export const committedProviderSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
version: z.string().min(1),
|
||||
});
|
||||
|
||||
const boundedParametersSchema = jsonObjectSchema.superRefine(
|
||||
(parameters, context) => {
|
||||
if (!isJsonWithinLimits(parameters, PROFILE_JSON_LIMITS)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Analysis profile parameters exceed structural limits",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
Buffer.byteLength(canonicalJson(parameters), "utf8") > PROFILE_MAX_BYTES
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Analysis profile parameters exceed the byte limit",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const unsignedAnalysisProfileSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
provider: committedProviderSchema,
|
||||
provider_profile_schema_version: z.number().int().min(1),
|
||||
parameters: boundedParametersSchema,
|
||||
});
|
||||
|
||||
/** Canonical, provider-neutral commitment to analysis-affecting semantics. */
|
||||
export const analysisProfileSchema = unsignedAnalysisProfileSchema
|
||||
.extend({ digest: digestSchema })
|
||||
.superRefine((profile, context) => {
|
||||
const { digest: _digest, ...unsigned } = profile;
|
||||
if (profileDigest(unsigned) !== profile.digest)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["digest"],
|
||||
message: "Analysis profile digest does not match its parameters",
|
||||
});
|
||||
});
|
||||
|
||||
export type CommittedProviderIdentity = z.infer<typeof committedProviderSchema>;
|
||||
export type AnalysisProfileCommitment = z.infer<typeof analysisProfileSchema>;
|
||||
|
||||
/** Create a validated RFC 8785 profile commitment at a provider boundary. */
|
||||
export const createAnalysisProfile = (
|
||||
provider: CommittedProviderIdentity,
|
||||
providerProfileSchemaVersion: number,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
): AnalysisProfileCommitment => {
|
||||
const unsigned = unsignedAnalysisProfileSchema.parse({
|
||||
schema_version: 1,
|
||||
provider,
|
||||
provider_profile_schema_version: providerProfileSchemaVersion,
|
||||
parameters,
|
||||
});
|
||||
return analysisProfileSchema.parse({
|
||||
...unsigned,
|
||||
digest: profileDigest(unsigned),
|
||||
});
|
||||
};
|
||||
|
||||
/** Compare two already-validated commitments without interpreting parameters. */
|
||||
export const analysisProfilesEqual = (
|
||||
left: AnalysisProfileCommitment,
|
||||
right: AnalysisProfileCommitment,
|
||||
): boolean =>
|
||||
left.digest === right.digest &&
|
||||
left.provider.id === right.provider.id &&
|
||||
left.provider.name === right.provider.name &&
|
||||
left.provider.version === right.provider.version &&
|
||||
left.schema_version === right.schema_version &&
|
||||
left.provider_profile_schema_version ===
|
||||
right.provider_profile_schema_version;
|
||||
|
||||
const profileDigest = (
|
||||
profile: z.infer<typeof unsignedAnalysisProfileSchema>,
|
||||
): string => createHash("sha256").update(canonicalJson(profile)).digest("hex");
|
||||
|
||||
const canonicalJson = (value: JsonValue): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("RFC 8785 canonicalization rejected analysis profile");
|
||||
return encoded;
|
||||
};
|
||||
+158
-58
@@ -3,10 +3,12 @@ import { createHash } from "node:crypto";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
analysisProfilesEqual,
|
||||
committedProviderSchema,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import {
|
||||
evidenceBundleForTarget,
|
||||
@@ -15,8 +17,9 @@ import {
|
||||
} from "./evidenceBundle.js";
|
||||
import {
|
||||
evidenceLocationSchema,
|
||||
providerSchema,
|
||||
type Evidence,
|
||||
type EvidenceLocation,
|
||||
type EvidenceSubjectTarget,
|
||||
} from "./evidence.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
@@ -27,7 +30,7 @@ import {
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const architectureSchema = z.enum(["x86", "x86_64", "arm", "arm64"]);
|
||||
const formatSchema = z.enum([
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
@@ -41,11 +44,13 @@ const formatSchema = z.enum([
|
||||
"javascript",
|
||||
"source-map",
|
||||
]);
|
||||
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
|
||||
const subjectSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
format: z.enum([
|
||||
...formatSchema.options,
|
||||
"hopper",
|
||||
"directory",
|
||||
"file",
|
||||
"unknown",
|
||||
@@ -57,10 +62,27 @@ const subjectSchema = z.object({
|
||||
});
|
||||
const targetSchema = z.object({
|
||||
sha256: digestSchema,
|
||||
kind: kindSchema,
|
||||
format: formatSchema,
|
||||
architecture: architectureSchema.nullable(),
|
||||
loader_args: z.array(z.string()),
|
||||
});
|
||||
const bindingSchema = z
|
||||
.object({
|
||||
provider: committedProviderSchema,
|
||||
analysis_profile: analysisProfileSchema,
|
||||
})
|
||||
.superRefine((binding, context) => {
|
||||
if (
|
||||
binding.provider.id !== binding.analysis_profile.provider.id ||
|
||||
binding.provider.name !== binding.analysis_profile.provider.name ||
|
||||
binding.provider.version !== binding.analysis_profile.provider.version
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["provider"],
|
||||
message: "Snapshot binding provider does not match analysis profile",
|
||||
});
|
||||
});
|
||||
const entrySchema = z.object({
|
||||
query_id: z.string().regex(/^query_[a-f0-9]{64}$/u),
|
||||
operation: z.string().min(1),
|
||||
@@ -68,17 +90,18 @@ const entrySchema = z.object({
|
||||
execution: z.object({
|
||||
result: jsonValueSchema,
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
provider: committedProviderSchema,
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
subject: subjectSchema.nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
/** Provider-neutral, deterministic cache of successful immutable analysis calls. */
|
||||
/** Provider- and profile-exact cache of successful immutable analysis calls. */
|
||||
export const analysisSnapshotSchema = z.object({
|
||||
snapshot_version: z.literal(1),
|
||||
snapshot_version: z.literal(2),
|
||||
target: targetSchema,
|
||||
binding: bindingSchema,
|
||||
entries: z.array(entrySchema).max(10_000),
|
||||
evidence_bundle: evidenceBundleSchema,
|
||||
});
|
||||
@@ -86,6 +109,21 @@ export const analysisSnapshotSchema = z.object({
|
||||
export type AnalysisSnapshot = z.infer<typeof analysisSnapshotSchema>;
|
||||
export type AnalysisSnapshotEntry = z.infer<typeof entrySchema>;
|
||||
export type AnalysisSnapshotTarget = z.infer<typeof targetSchema>;
|
||||
export type AnalysisSnapshotBinding = z.infer<typeof bindingSchema>;
|
||||
|
||||
interface SnapshotExecution {
|
||||
readonly result: JsonValue;
|
||||
readonly rawResult: JsonValue | null;
|
||||
readonly provider: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly version: string | null;
|
||||
};
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations: readonly string[];
|
||||
readonly locations: readonly EvidenceLocation[];
|
||||
readonly subject: EvidenceSubjectTarget | null;
|
||||
}
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const json = jsonValueSchema.parse(value);
|
||||
@@ -100,33 +138,71 @@ export const snapshotTarget = (
|
||||
target: BinaryTarget,
|
||||
): AnalysisSnapshotTarget => ({
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
loader_args: [...target.loaderArgs],
|
||||
});
|
||||
|
||||
/** Compare an open binary with the immutable identity in a snapshot. */
|
||||
/** Build the immutable provider/profile binding used by snapshot v2. */
|
||||
export const snapshotBinding = (
|
||||
profile: AnalysisProfileCommitment,
|
||||
): AnalysisSnapshotBinding =>
|
||||
bindingSchema.parse({
|
||||
provider: profile.provider,
|
||||
analysis_profile: profile,
|
||||
});
|
||||
|
||||
/** Compare an open binary with the immutable target identity in a snapshot. */
|
||||
export const snapshotMatchesTarget = (
|
||||
snapshot: AnalysisSnapshotTarget,
|
||||
target: BinaryTarget,
|
||||
): boolean =>
|
||||
snapshot.sha256 === target.sha256 &&
|
||||
snapshot.kind === target.kind &&
|
||||
snapshot.format === target.format &&
|
||||
snapshot.architecture === (target.architecture ?? null) &&
|
||||
JSON.stringify(snapshot.loader_args) === JSON.stringify(target.loaderArgs);
|
||||
snapshot.architecture === (target.architecture ?? null);
|
||||
|
||||
/** Find exact persisted CLI evidence without starting an analysis provider. */
|
||||
/** Compare a snapshot binding with the selected concrete analysis profile. */
|
||||
export const snapshotMatchesProfile = (
|
||||
binding: AnalysisSnapshotBinding,
|
||||
profile: AnalysisProfileCommitment,
|
||||
): boolean =>
|
||||
binding.provider.id === profile.provider.id &&
|
||||
binding.provider.name === profile.provider.name &&
|
||||
binding.provider.version === profile.provider.version &&
|
||||
analysisProfilesEqual(binding.analysis_profile, profile);
|
||||
|
||||
/** Require an exact target and selected provider/profile cache partition. */
|
||||
export const snapshotMatchesBinding = (
|
||||
snapshot: Pick<AnalysisSnapshot, "target" | "binding">,
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment,
|
||||
): boolean =>
|
||||
snapshotMatchesTarget(snapshot.target, target) &&
|
||||
snapshotMatchesProfile(snapshot.binding, profile);
|
||||
|
||||
/** Find exact persisted CLI Evidence without starting an analysis provider. */
|
||||
export const snapshotEvidenceForQuery = (
|
||||
snapshot: AnalysisSnapshot,
|
||||
query: {
|
||||
readonly target: BinaryTarget;
|
||||
readonly bindingProfile: AnalysisProfileCommitment;
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly provider: AnalysisExecution["provider"];
|
||||
readonly provider: SnapshotExecution["provider"];
|
||||
readonly evidenceProfile: AnalysisProfileCommitment;
|
||||
},
|
||||
): Evidence | undefined => {
|
||||
const { target, operation, parameters, provider } = query;
|
||||
if (!snapshotMatchesTarget(snapshot.target, target)) return undefined;
|
||||
const {
|
||||
target,
|
||||
bindingProfile,
|
||||
operation,
|
||||
parameters,
|
||||
provider,
|
||||
evidenceProfile,
|
||||
} = query;
|
||||
if (!snapshotMatchesBinding(snapshot, target, bindingProfile))
|
||||
return undefined;
|
||||
const encodedParameters = canonicalJson(parameters);
|
||||
return snapshot.evidence_bundle.records.find(
|
||||
(record) =>
|
||||
@@ -135,60 +211,66 @@ export const snapshotEvidenceForQuery = (
|
||||
record.provider.id === provider.id &&
|
||||
record.provider.name === provider.name &&
|
||||
record.provider.version === provider.version &&
|
||||
"analysis_profile" in record &&
|
||||
analysisProfilesEqual(record.analysis_profile, evidenceProfile) &&
|
||||
canonicalJson(record.parameters) === encodedParameters,
|
||||
);
|
||||
};
|
||||
|
||||
/** Compute the stable lookup key for one provider-specific analysis query. */
|
||||
/** Compute the stable lookup key for one provider/profile-specific query. */
|
||||
export const analysisQueryId = (
|
||||
target: AnalysisSnapshotTarget,
|
||||
binding: AnalysisSnapshotBinding,
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
provider: AnalysisExecution["provider"],
|
||||
): string =>
|
||||
`query_${createHash("sha256")
|
||||
.update(
|
||||
canonicalJson({
|
||||
target,
|
||||
operation,
|
||||
parameters,
|
||||
provider: {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
version: provider.version,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.update(canonicalJson({ target, binding, operation, parameters }))
|
||||
.digest("hex")}`;
|
||||
|
||||
/** Create one serializable snapshot entry from a successful provider call. */
|
||||
export const createAnalysisSnapshotEntry = (
|
||||
target: AnalysisSnapshotTarget,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
): AnalysisSnapshotEntry => ({
|
||||
query_id: analysisQueryId(target, operation, parameters, execution.provider),
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(parameters),
|
||||
execution: {
|
||||
result: execution.result,
|
||||
raw_result: execution.rawResult,
|
||||
provider: execution.provider,
|
||||
limitations: [...execution.limitations],
|
||||
locations: [...execution.locations],
|
||||
subject:
|
||||
execution.subject === null
|
||||
? null
|
||||
: {
|
||||
...execution.subject,
|
||||
architecture: execution.subject.architecture ?? null,
|
||||
},
|
||||
},
|
||||
});
|
||||
export const createAnalysisSnapshotEntry = (input: {
|
||||
readonly target: AnalysisSnapshotTarget;
|
||||
readonly binding: AnalysisSnapshotBinding;
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly execution: SnapshotExecution;
|
||||
}): AnalysisSnapshotEntry => {
|
||||
const { target, binding, operation, parameters, execution } = input;
|
||||
if (
|
||||
execution.analysisProfile === undefined ||
|
||||
!snapshotMatchesProfile(binding, execution.analysisProfile) ||
|
||||
execution.provider.id !== binding.provider.id ||
|
||||
execution.provider.name !== binding.provider.name ||
|
||||
execution.provider.version !== binding.provider.version
|
||||
)
|
||||
throw new TypeError(
|
||||
"Snapshot execution does not match its provider/profile binding",
|
||||
);
|
||||
return {
|
||||
query_id: analysisQueryId(target, binding, operation, parameters),
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(parameters),
|
||||
execution: {
|
||||
result: execution.result,
|
||||
raw_result: execution.rawResult,
|
||||
provider: binding.provider,
|
||||
limitations: [...execution.limitations],
|
||||
locations: [...execution.locations],
|
||||
subject:
|
||||
execution.subject === null
|
||||
? null
|
||||
: {
|
||||
...execution.subject,
|
||||
architecture: execution.subject.architecture ?? null,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Parse a snapshot and reject altered query IDs or non-canonical entry order. */
|
||||
/** Parse v2 and reject legacy snapshots, altered query IDs, or non-canonical order. */
|
||||
export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
rejectLegacySnapshot(input);
|
||||
const parsed = analysisSnapshotSchema.parse(input);
|
||||
parseEvidenceBundle(parsed.evidence_bundle);
|
||||
if (
|
||||
@@ -201,11 +283,17 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
);
|
||||
const ids = new Set<string>();
|
||||
for (const entry of parsed.entries) {
|
||||
if (
|
||||
entry.execution.provider.id !== parsed.binding.provider.id ||
|
||||
entry.execution.provider.name !== parsed.binding.provider.name ||
|
||||
entry.execution.provider.version !== parsed.binding.provider.version
|
||||
)
|
||||
throw new TypeError("Analysis snapshot entry provider does not match");
|
||||
const expected = analysisQueryId(
|
||||
parsed.target,
|
||||
parsed.binding,
|
||||
entry.operation,
|
||||
entry.parameters,
|
||||
entry.execution.provider,
|
||||
);
|
||||
if (entry.query_id !== expected)
|
||||
throw new TypeError("Analysis snapshot query identifier does not match");
|
||||
@@ -224,3 +312,15 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
/** Serialize a validated snapshot with byte-stable canonical entry ordering. */
|
||||
export const serializeAnalysisSnapshot = (snapshot: AnalysisSnapshot): string =>
|
||||
`${canonicalJson(parseAnalysisSnapshot(snapshot))}\n`;
|
||||
|
||||
const rejectLegacySnapshot = (input: unknown): void => {
|
||||
if (
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"snapshot_version" in input &&
|
||||
input.snapshot_version === 1
|
||||
)
|
||||
throw new TypeError(
|
||||
"Analysis snapshot v1 is incompatible with profile-exact replay; recapture it as snapshot v2. Its Evidence bundle may be imported separately.",
|
||||
);
|
||||
};
|
||||
|
||||
@@ -49,6 +49,7 @@ const artifactFormatSchema = z.enum([
|
||||
"elf",
|
||||
"pe",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
"apk",
|
||||
"plist",
|
||||
|
||||
+14
-39
@@ -18,12 +18,11 @@ import { err, ok, type Result } from "./result.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** CPU families understood by the supported executable loaders. */
|
||||
type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
|
||||
/** Provider-neutral CPU families detected from supported executable headers. */
|
||||
export type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
|
||||
/**
|
||||
* A canonical local target plus deterministic Hopper loader arguments.
|
||||
* Explicit loader and architecture flags prevent Hopper from presenting modal
|
||||
* format or FAT-architecture selection dialogs during agent-driven analysis.
|
||||
* Canonical local target identity and provider-neutral file classification.
|
||||
* Provider adapters translate this metadata into their own open options.
|
||||
*/
|
||||
export interface BinaryTarget {
|
||||
readonly path: string;
|
||||
@@ -31,7 +30,7 @@ export interface BinaryTarget {
|
||||
readonly sha256: string;
|
||||
readonly kind: "executable" | "database" | "archive" | "artifact";
|
||||
readonly format:
|
||||
| "hopper"
|
||||
| "analysis-database"
|
||||
| "mach-o"
|
||||
| "elf"
|
||||
| "pe"
|
||||
@@ -46,11 +45,10 @@ export interface BinaryTarget {
|
||||
| "source-map";
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly availableArchitectures?: readonly BinaryArchitecture[];
|
||||
readonly loaderArgs: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and classify a readable local target before Hopper is launched.
|
||||
* Resolve and classify a readable local target before a provider is selected.
|
||||
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
|
||||
* non-interactive; unsupported or ambiguous inputs are returned as typed errors.
|
||||
*/
|
||||
@@ -78,8 +76,7 @@ export const parseBinaryTarget = async (
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256File(path),
|
||||
kind: "database",
|
||||
format: "hopper",
|
||||
loaderArgs: [],
|
||||
format: "analysis-database",
|
||||
});
|
||||
const handle = await open(path, "r");
|
||||
let detected: Result<ExecutableMetadata, string>;
|
||||
@@ -92,7 +89,6 @@ export const parseBinaryTarget = async (
|
||||
sha256: await sha256File(path),
|
||||
kind: isArchiveFormat(artifactFormat) ? "archive" : "artifact",
|
||||
format: artifactFormat,
|
||||
loaderArgs: [],
|
||||
});
|
||||
detected = await readExecutableMetadata(handle, hostArchitecture);
|
||||
} finally {
|
||||
@@ -117,7 +113,10 @@ const detectArtifactFormat = async (
|
||||
path: string,
|
||||
handle: FileHandle,
|
||||
): Promise<
|
||||
| Exclude<BinaryTarget["format"], "hopper" | "mach-o" | "elf" | "pe">
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
const lower = path.toLowerCase();
|
||||
@@ -263,7 +262,7 @@ const decodeXml = (value: string): string =>
|
||||
|
||||
type ExecutableMetadata = Pick<
|
||||
BinaryTarget,
|
||||
"format" | "architecture" | "availableArchitectures" | "loaderArgs"
|
||||
"format" | "architecture" | "availableArchitectures"
|
||||
>;
|
||||
|
||||
const readExecutableMetadata = async (
|
||||
@@ -303,9 +302,8 @@ const readExecutableMetadata = async (
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse supported executable headers without I/O and derive explicit Hopper
|
||||
* loader arguments. The caller must supply the host architecture used for FAT
|
||||
* Mach-O slice selection.
|
||||
* Parse supported executable headers without I/O. The caller supplies the host
|
||||
* architecture used for deterministic FAT Mach-O slice selection.
|
||||
*/
|
||||
export const parseExecutableHeader = (
|
||||
bytes: Buffer,
|
||||
@@ -341,7 +339,6 @@ const parseThinMachO = (
|
||||
format: "mach-o",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
loaderArgs: ["-l", "Mach-O", hopperArchitectureFlag(architecture)],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -381,13 +378,6 @@ const parseFatMachO = (
|
||||
format: "mach-o",
|
||||
architecture: preferred,
|
||||
availableArchitectures: architectures,
|
||||
loaderArgs: [
|
||||
"-l",
|
||||
"FAT",
|
||||
hopperArchitectureFlag(preferred),
|
||||
"-l",
|
||||
"Mach-O",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -403,7 +393,6 @@ const parseElf = (bytes: Buffer): Result<ExecutableMetadata, string> => {
|
||||
format: "elf",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
loaderArgs: ["-l", "ELF", hopperArchitectureFlag(architecture)],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -423,7 +412,6 @@ const parsePeRecord = (record: Buffer): Result<ExecutableMetadata, string> => {
|
||||
format: "pe",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
loaderArgs: ["-l", "WinPE", hopperArchitectureFlag(architecture)],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -468,16 +456,3 @@ const peArchitecture = (machine: number): BinaryArchitecture | undefined => {
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const hopperArchitectureFlag = (architecture: BinaryArchitecture): string => {
|
||||
switch (architecture) {
|
||||
case "x86":
|
||||
return "--intel-32";
|
||||
case "x86_64":
|
||||
return "--intel-64";
|
||||
case "arm":
|
||||
return "--armv7";
|
||||
case "arm64":
|
||||
return "--aarch64";
|
||||
}
|
||||
};
|
||||
|
||||
+83
-25
@@ -3,6 +3,10 @@ import { createHash } from "node:crypto";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
||||
|
||||
@@ -18,6 +22,7 @@ const subjectSchema = z.object({
|
||||
digest: z.object({ sha256: digestSchema }),
|
||||
format: z.enum([
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
@@ -73,26 +78,65 @@ const executionEnvironmentSchema = z.object({
|
||||
isolation: z.enum(["none", "process", "container", "virtual-machine"]),
|
||||
});
|
||||
|
||||
/** Strict, provider-neutral record for one successful public observation. */
|
||||
export const evidenceSchema = z.object({
|
||||
schema_version: z.literal(2),
|
||||
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
subject: subjectSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
predicate_type: z.string().min(1),
|
||||
operation: z.string().min(1),
|
||||
parameters: z.record(z.string(), jsonValueSchema),
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
normalized_result: jsonValueSchema,
|
||||
confidence: z.enum(["observed", "derived", "inferred"]),
|
||||
authority: evidenceAuthoritySchema,
|
||||
environment: executionEnvironmentSchema.nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
evidence_links: z.array(z.string().regex(/^ev_[a-f0-9]{64}$/u)),
|
||||
const evidenceBaseSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(2),
|
||||
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
subject: subjectSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
predicate_type: z.string().min(1),
|
||||
operation: z.string().min(1),
|
||||
parameters: z.record(z.string(), jsonValueSchema),
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
normalized_result: jsonValueSchema,
|
||||
confidence: z.enum(["observed", "derived", "inferred"]),
|
||||
authority: evidenceAuthoritySchema,
|
||||
environment: executionEnvironmentSchema.nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
evidence_links: z.array(z.string().regex(/^ev_[a-f0-9]{64}$/u)),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Object envelope used to specialize caller-visible Evidence result schemas. */
|
||||
export const evidenceEnvelopeSchema = evidenceBaseSchema.extend({
|
||||
analysis_profile: analysisProfileSchema.optional(),
|
||||
});
|
||||
|
||||
export type Evidence = z.infer<typeof evidenceSchema>;
|
||||
const validateAnalysisProfileProvider = (
|
||||
evidence: z.infer<typeof evidenceEnvelopeSchema>,
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
const profile = evidence.analysis_profile;
|
||||
if (
|
||||
profile !== undefined &&
|
||||
(profile.provider.id !== evidence.provider.id ||
|
||||
profile.provider.name !== evidence.provider.name ||
|
||||
profile.provider.version !== evidence.provider.version)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["analysis_profile", "provider"],
|
||||
message: "Analysis profile provider does not match Evidence provider",
|
||||
});
|
||||
};
|
||||
|
||||
/** Strict, provider-neutral record for one successful public observation. */
|
||||
export const evidenceSchema = evidenceEnvelopeSchema.superRefine(
|
||||
validateAnalysisProfileProvider,
|
||||
);
|
||||
|
||||
const profiledEvidenceSchema = evidenceBaseSchema
|
||||
.extend({ analysis_profile: analysisProfileSchema })
|
||||
.superRefine(validateAnalysisProfileProvider);
|
||||
|
||||
/** JSON-exact union used where Evidence participates in larger schemas. */
|
||||
export const evidenceRecordSchema = z.union([
|
||||
profiledEvidenceSchema,
|
||||
evidenceBaseSchema,
|
||||
]);
|
||||
|
||||
export type Evidence = z.infer<typeof evidenceRecordSchema>;
|
||||
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
|
||||
|
||||
/** Minimal immutable local artifact identity accepted by Evidence v2. */
|
||||
@@ -116,6 +160,7 @@ export interface EvidenceObservation {
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly result: JsonValue;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly rawResult?: JsonValue;
|
||||
readonly confidence?: "observed" | "derived" | "inferred";
|
||||
readonly authority?: EvidenceAuthority;
|
||||
@@ -128,6 +173,11 @@ export interface EvidenceObservation {
|
||||
const sha256 = (value: string): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
type WithoutEvidenceId<Record_> = Record_ extends unknown
|
||||
? Omit<Record_, "evidence_id">
|
||||
: never;
|
||||
type EvidenceWithoutId = WithoutEvidenceId<Evidence>;
|
||||
|
||||
/** Serialize JSON according to RFC 8785 JSON Canonicalization Scheme. */
|
||||
const canonicalJson = (value: JsonValue): string => {
|
||||
const serialized = canonicalize(value);
|
||||
@@ -136,9 +186,7 @@ const canonicalJson = (value: JsonValue): string => {
|
||||
return serialized;
|
||||
};
|
||||
|
||||
const semanticProjection = (
|
||||
evidence: Omit<Evidence, "evidence_id">,
|
||||
): JsonValue => ({
|
||||
const semanticProjection = (evidence: EvidenceWithoutId): JsonValue => ({
|
||||
schema_version: evidence.schema_version,
|
||||
subject:
|
||||
evidence.subject === null
|
||||
@@ -149,6 +197,9 @@ const semanticProjection = (
|
||||
architecture: evidence.subject.architecture,
|
||||
},
|
||||
provider: evidence.provider,
|
||||
...(!("analysis_profile" in evidence)
|
||||
? {}
|
||||
: { analysis_profile: evidence.analysis_profile }),
|
||||
predicate_type: evidence.predicate_type,
|
||||
operation: evidence.operation,
|
||||
parameters: evidence.parameters,
|
||||
@@ -163,7 +214,7 @@ const semanticProjection = (
|
||||
});
|
||||
|
||||
/** Recompute the semantic identifier, excluding paths and raw payload bytes. */
|
||||
const computeEvidenceId = (evidence: Omit<Evidence, "evidence_id">): string =>
|
||||
const computeEvidenceId = (evidence: EvidenceWithoutId): string =>
|
||||
`ev_${sha256(canonicalJson(semanticProjection(evidence)))}`;
|
||||
|
||||
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
|
||||
@@ -177,7 +228,7 @@ export const parseEvidence = (input: unknown): Evidence => {
|
||||
throw new TypeError(
|
||||
`Unsupported evidence schema_version ${String(input.schema_version)}; Evidence v1 is not accepted. Produce Evidence v2.`,
|
||||
);
|
||||
const evidence = evidenceSchema.parse(input);
|
||||
const evidence = evidenceRecordSchema.parse(input);
|
||||
const { evidence_id: evidenceId, ...withoutId } = evidence;
|
||||
if (computeEvidenceId(withoutId) !== evidenceId)
|
||||
throw new TypeError(
|
||||
@@ -217,6 +268,9 @@ export const createEvidence = (
|
||||
name: provider.name,
|
||||
version: provider.version,
|
||||
},
|
||||
...(observation.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysis_profile: observation.analysisProfile }),
|
||||
predicate_type: observation.predicateType ?? "rea.analysis/v2",
|
||||
operation: observation.operation,
|
||||
parameters: observation.parameters,
|
||||
@@ -234,9 +288,13 @@ export const createEvidence = (
|
||||
locations: [...(observation.locations ?? [])],
|
||||
evidence_links: [...(observation.evidenceLinks ?? [])],
|
||||
} satisfies JsonValue;
|
||||
return evidenceSchema.parse({
|
||||
const normalized = evidenceRecordSchema.parse({
|
||||
...semantic,
|
||||
evidence_id: `ev_${sha256(canonicalJson(semantic))}`,
|
||||
evidence_id: `ev_${"0".repeat(64)}`,
|
||||
subject,
|
||||
});
|
||||
return parseEvidence({
|
||||
...normalized,
|
||||
evidence_id: computeEvidenceId(normalized),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
import { z } from "zod";
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js";
|
||||
import {
|
||||
evidenceEnvelopeSchema,
|
||||
evidenceRecordSchema,
|
||||
parseEvidence,
|
||||
providerSchema,
|
||||
type Evidence,
|
||||
} from "./evidence.js";
|
||||
import {
|
||||
residualUnknownSchema,
|
||||
type ResidualUnknown,
|
||||
} from "./residualUnknown.js";
|
||||
|
||||
const artifactManifestSchema = evidenceSchema.shape.subject.unwrap().pick({
|
||||
digest: true,
|
||||
format: true,
|
||||
architecture: true,
|
||||
});
|
||||
const providerManifestSchema = evidenceSchema.shape.provider;
|
||||
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
|
||||
const artifactManifestSchema = evidenceEnvelopeSchema.shape.subject
|
||||
.unwrap()
|
||||
.pick({
|
||||
digest: true,
|
||||
format: true,
|
||||
architecture: true,
|
||||
});
|
||||
const providerManifestSchema = providerSchema;
|
||||
const environmentManifestSchema =
|
||||
evidenceEnvelopeSchema.shape.environment.unwrap();
|
||||
const scenarioManifestSchema = z.object({
|
||||
evidence_id: evidenceSchema.shape.evidence_id,
|
||||
evidence_id: evidenceEnvelopeSchema.shape.evidence_id,
|
||||
operation: z.string().min(1),
|
||||
authority: z.literal("controlled-replay"),
|
||||
});
|
||||
const captureManifestSchema = z.object({
|
||||
evidence_id: evidenceSchema.shape.evidence_id,
|
||||
evidence_id: evidenceEnvelopeSchema.shape.evidence_id,
|
||||
predicate_type: z.string().min(1),
|
||||
});
|
||||
|
||||
@@ -32,7 +41,7 @@ export const evidenceBundleSchema = z.object({
|
||||
scenarios: z.array(scenarioManifestSchema),
|
||||
captures: z.array(captureManifestSchema),
|
||||
unknowns: z.array(residualUnknownSchema),
|
||||
records: z.array(evidenceSchema),
|
||||
records: z.array(evidenceRecordSchema),
|
||||
});
|
||||
|
||||
export type EvidenceBundle = z.infer<typeof evidenceBundleSchema>;
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
|
||||
import type {
|
||||
AnalysisProfileResolution,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { createAnalysisProfile } from "../domain/analysisProfile.js";
|
||||
import type {
|
||||
BinaryArchitecture,
|
||||
BinaryTarget,
|
||||
} from "../domain/binaryTarget.js";
|
||||
import { ProviderAdapterError, type AnalysisError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
interface HopperProfileOptions {
|
||||
readonly launcherPath: string;
|
||||
readonly loaderArgsOverride: readonly string[];
|
||||
readonly provider: ProviderIdentity;
|
||||
}
|
||||
|
||||
/** Resolve Hopper open semantics without placing its CLI flags in BinaryTarget. */
|
||||
export const resolveHopperAnalysisProfile = async (
|
||||
target: BinaryTarget,
|
||||
options: HopperProfileOptions,
|
||||
): Promise<Result<AnalysisProfileResolution, AnalysisError>> => {
|
||||
if (target.kind !== "executable" && target.kind !== "database")
|
||||
return ok({ profile: null, compatibility: {} });
|
||||
const derived = hopperLoaderArgsForTarget(target);
|
||||
if (!derived.ok) return derived;
|
||||
const loaderArgs =
|
||||
options.loaderArgsOverride.length === 0
|
||||
? derived.value
|
||||
: [...options.loaderArgsOverride];
|
||||
const compatibility = { loaderArgs: [...loaderArgs] };
|
||||
const launcherDigest = await sha256File(options.launcherPath);
|
||||
if (launcherDigest === undefined) return ok({ profile: null, compatibility });
|
||||
const provider = {
|
||||
id: options.provider.id,
|
||||
name: options.provider.name,
|
||||
version: `launcher-sha256:${launcherDigest}`,
|
||||
};
|
||||
return ok({
|
||||
profile: createAnalysisProfile(provider, 1, {
|
||||
target_kind: target.kind,
|
||||
target_format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
available_architectures: [
|
||||
...(target.availableArchitectures ?? []),
|
||||
].sort(),
|
||||
loader: {
|
||||
source:
|
||||
options.loaderArgsOverride.length === 0
|
||||
? "derived"
|
||||
: "configured_override",
|
||||
argument_count: loaderArgs.length,
|
||||
arguments_sha256: createHash("sha256")
|
||||
.update(JSON.stringify(loaderArgs))
|
||||
.digest("hex"),
|
||||
},
|
||||
}),
|
||||
compatibility,
|
||||
});
|
||||
};
|
||||
|
||||
/** Derive Hopper's complete non-interactive CLI loader selection. */
|
||||
export const hopperLoaderArgsForTarget = (
|
||||
target: BinaryTarget,
|
||||
): Result<readonly string[], ProviderAdapterError> => {
|
||||
if (target.kind === "database") return ok([]);
|
||||
const architecture = target.architecture;
|
||||
if (architecture === undefined)
|
||||
return err(new ProviderAdapterError("hopper", "resolve_analysis_profile"));
|
||||
const flag = hopperArchitectureFlag(architecture);
|
||||
switch (target.format) {
|
||||
case "mach-o":
|
||||
return ok(
|
||||
(target.availableArchitectures?.length ?? 0) > 1
|
||||
? ["-l", "FAT", flag, "-l", "Mach-O"]
|
||||
: ["-l", "Mach-O", flag],
|
||||
);
|
||||
case "elf":
|
||||
return ok(["-l", "ELF", flag]);
|
||||
case "pe":
|
||||
return ok(["-l", "WinPE", flag]);
|
||||
default:
|
||||
return err(
|
||||
new ProviderAdapterError("hopper", "resolve_analysis_profile"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const hopperArchitectureFlag = (architecture: BinaryArchitecture): string => {
|
||||
switch (architecture) {
|
||||
case "x86":
|
||||
return "--intel-32";
|
||||
case "x86_64":
|
||||
return "--intel-64";
|
||||
case "arm":
|
||||
return "--armv7";
|
||||
case "arm64":
|
||||
return "--aarch64";
|
||||
}
|
||||
};
|
||||
|
||||
const sha256File = async (path: string): Promise<string | undefined> => {
|
||||
try {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type { AppConfig } from "../config.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -17,6 +18,10 @@ import {
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { HopperApplicationLauncher } from "./BridgeLauncher.js";
|
||||
import {
|
||||
hopperLoaderArgsForTarget,
|
||||
resolveHopperAnalysisProfile,
|
||||
} from "./HopperAnalysisProfile.js";
|
||||
import { HopperClient } from "./HopperClient.js";
|
||||
|
||||
/** Public identity committed by every Hopper-backed observation. */
|
||||
@@ -90,7 +95,18 @@ export class HopperProvider implements AnalysisProvider {
|
||||
return CAPABILITIES;
|
||||
}
|
||||
|
||||
createClient(target: BinaryTarget): AnalysisClient {
|
||||
resolveAnalysisProfile(target: BinaryTarget) {
|
||||
return resolveHopperAnalysisProfile(target, {
|
||||
launcherPath: this.config.hopperLauncherPath,
|
||||
loaderArgsOverride: this.config.hopperLoaderArgs,
|
||||
provider: IDENTITY,
|
||||
});
|
||||
}
|
||||
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
): AnalysisClient {
|
||||
if (target.kind !== "executable" && target.kind !== "database")
|
||||
return {
|
||||
execute: (operation) =>
|
||||
@@ -105,6 +121,13 @@ export class HopperProvider implements AnalysisProvider {
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
const derivedLoaderArgs = hopperLoaderArgsForTarget(target);
|
||||
if (!derivedLoaderArgs.ok)
|
||||
return {
|
||||
execute: () => Promise.resolve(err(derivedLoaderArgs.error)),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
const executionProvider = profile?.provider ?? IDENTITY;
|
||||
const client = new HopperClient({
|
||||
launcher: new HopperApplicationLauncher({
|
||||
launcherPath: this.config.hopperLauncherPath,
|
||||
@@ -113,7 +136,7 @@ export class HopperProvider implements AnalysisProvider {
|
||||
loaderArgs:
|
||||
this.config.hopperLoaderArgs.length > 0
|
||||
? this.config.hopperLoaderArgs
|
||||
: target.loaderArgs,
|
||||
: derivedLoaderArgs.value,
|
||||
bridgeScriptPath: fileURLToPath(
|
||||
new URL("../../bridge/hopper_bridge.py", import.meta.url),
|
||||
),
|
||||
@@ -134,7 +157,8 @@ export class HopperProvider implements AnalysisProvider {
|
||||
return result.ok
|
||||
? {
|
||||
ok: true,
|
||||
value: createAnalysisExecution(result.value, IDENTITY, {
|
||||
value: createAnalysisExecution(result.value, executionProvider, {
|
||||
...(profile === undefined ? {} : { analysisProfile: profile }),
|
||||
limitations: [
|
||||
"Results depend on Hopper's completed static analysis.",
|
||||
],
|
||||
|
||||
@@ -125,6 +125,8 @@ export const createServer = (
|
||||
registerEnhancedTools(server, analysis, {
|
||||
logger: toolLogger,
|
||||
activeTarget,
|
||||
analysisProfile:
|
||||
session === undefined ? undefined : () => session.analysisProfile(),
|
||||
recordEvidence,
|
||||
recordUnknown:
|
||||
session === undefined
|
||||
|
||||
@@ -17,21 +17,23 @@ import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import { UnknownRegistryError } from "../domain/errors.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
} from "../application/InvestigationProviders.js";
|
||||
|
||||
/** Optional session services used by enhanced tool registration. */
|
||||
export interface EnhancedToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly analysisProfile:
|
||||
| (() => AnalysisProfileCommitment | undefined)
|
||||
| undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
|
||||
}
|
||||
|
||||
const WORKFLOW_PROVIDER = {
|
||||
id: "rea-workflow",
|
||||
name: "REA composed investigation workflow",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Register composed workflows against the same port as direct bridge tools. */
|
||||
export const registerEnhancedTools = (
|
||||
server: McpServer,
|
||||
@@ -43,6 +45,7 @@ export const registerEnhancedTools = (
|
||||
registerEnhancedTool(server, services, contract, {
|
||||
logger: options.logger,
|
||||
activeTarget: options.activeTarget,
|
||||
analysisProfile: options.analysisProfile,
|
||||
recordEvidence: options.recordEvidence,
|
||||
recordUnknown: options.recordUnknown,
|
||||
});
|
||||
@@ -56,6 +59,9 @@ const registerEnhancedTool = (
|
||||
registration: {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly analysisProfile:
|
||||
| (() => AnalysisProfileCommitment | undefined)
|
||||
| undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
|
||||
},
|
||||
@@ -92,13 +98,19 @@ const registerEnhancedTool = (
|
||||
terminal: true,
|
||||
});
|
||||
if (result.ok) {
|
||||
const upstreamProfile = registration.analysisProfile?.();
|
||||
const evidence = createEvidence(
|
||||
registration.activeTarget?.(),
|
||||
WORKFLOW_PROVIDER,
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
{
|
||||
operation: name,
|
||||
parameters,
|
||||
result: result.value,
|
||||
...(upstreamProfile === undefined
|
||||
? {}
|
||||
: {
|
||||
analysisProfile: workflowAnalysisProfile(upstreamProfile),
|
||||
}),
|
||||
confidence: "derived",
|
||||
limitations: [
|
||||
"Derived by an REA workflow from one or more provider observations.",
|
||||
|
||||
@@ -95,6 +95,9 @@ const registerOfficialTool = (
|
||||
operation: contract.name,
|
||||
parameters: arguments_,
|
||||
result: result.value.result,
|
||||
...(result.value.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: result.value.analysisProfile }),
|
||||
rawResult: result.value.rawResult,
|
||||
limitations: result.value.limitations,
|
||||
locations: result.value.locations,
|
||||
|
||||
@@ -507,7 +507,9 @@ const registerLifecycleTools = ({
|
||||
path: opened.value.path,
|
||||
format: opened.value.format,
|
||||
kind: opened.value.kind,
|
||||
loaderArgs: [...opened.value.loaderArgs],
|
||||
loaderArgs: z
|
||||
.array(z.string())
|
||||
.parse(session.openCompatibility().loaderArgs ?? []),
|
||||
sha256: opened.value.sha256,
|
||||
architecture: opened.value.architecture ?? null,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user