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 },
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user