mirror of
https://github.com/morluto/rea.git
synced 2026-12-03 17:44:27 +00:00
* fix(hopper): report the stalled export function and shell recovery decompile_all reports a progress update every five seconds while one function stays pending, naming the function and its position. MCP sends it as a progress notification and the CLI as a rea_progress line on stderr. A retained Hopper document now carries remediation that holds after a one-shot command has ended: Hopper is still running the named operation and must finish or be quit. The close_binary retry text is kept as guidance for a continuing caller. Refs #14840 * fix(hopper): qualify the advice to quit Hopper while it is still working The recovery text for an ended invocation told the user to quit Hopper to stop a running operation without the condition its sibling text carries. Hopper is the user's application and may hold other documents, so the advice now applies only when it has no other work. * fix(decompile-all): time only provider requests when reporting a function wait The wait reporter timed a whole function attempt, including journal appends and file commits, so a slow output volume was reported as the provider still decompiling. It now wraps each provider request (procedure_info and procedure_pseudo_code) and names the request it waits on. The progress test now uses phase gates and releases and joins the export on every path. * docs(decompile-all): say the wait report times provider requests only * fix(progress): rate-limit each progress phase separately The shared reporter dropped any intermediate update within 100 ms of the previous one, whatever its phase. Hopper's one-second request heartbeat could therefore suppress every decompile_all wait report that fired just after it. The interval now applies per phase, so a heartbeat cannot hide a rarer update from another phase. The decompile_all progress test also restores its commitFunctionFile spy.
1025 lines
36 KiB
TypeScript
1025 lines
36 KiB
TypeScript
import {
|
|
admitOneShotOperation,
|
|
type DirectAnalysisTool,
|
|
type DirectEnhancedToolName,
|
|
} from "./oneShotOperationInput.js";
|
|
import { completedOperationEvidence } from "./binary/SessionEvidenceReuse.js";
|
|
import {
|
|
runInRetainedArtifactScope,
|
|
selectedArtifactDirectory,
|
|
} from "./artifacts/ArtifactPathInspection.js";
|
|
import type { EspFlashSelection } from "../domain/firmware/espFlashLocation.js";
|
|
import { dispatchQueuedInterrupts } from "../process/queuedInterrupts.js";
|
|
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
|
import type { NativeLoadSelection } from "../domain/rawBinary.js";
|
|
import type { JsonValue } from "../domain/jsonValue.js";
|
|
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
|
|
import type { BinarySession } from "./binary/BinarySession.js";
|
|
import type { SessionProviderRoute } from "./binary/SessionProviderRouter.js";
|
|
import {
|
|
routeAllowsSnapshotReplay,
|
|
routeProviderIdentity,
|
|
} from "./binary/SessionProviderPolicy.js";
|
|
import type { ResolvedSessionOpen } from "./binary/BinarySessionOpen.js";
|
|
import { silentLogger } from "../logger.js";
|
|
import type { Logger } from "pino";
|
|
import { withEvidenceCallerInputPath } from "../domain/evidence.js";
|
|
import { createImmutableEvidenceBundle } from "../domain/evidenceBundle.js";
|
|
import { recognizeEvidence } from "../domain/evidenceValidation.js";
|
|
import {
|
|
retainAnalysisResultSources,
|
|
type AnalysisResultWithSources,
|
|
} from "./investigation/recordEvidenceSources.js";
|
|
import {
|
|
createInvestigationEvidenceClosureChecker,
|
|
collectInvestigationEvidenceClosure,
|
|
} from "./investigation/InvestigationEvidence.js";
|
|
import type { Evidence } from "../domain/evidence.js";
|
|
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
|
|
import {
|
|
ARTIFACT_ANALYSIS_OPERATIONS,
|
|
type ArtifactAnalysisOperation,
|
|
} from "../contracts/artifactToolContracts.js";
|
|
import {
|
|
isManagedToolName,
|
|
type ManagedToolName,
|
|
} from "../contracts/managed/managedToolContracts.js";
|
|
import {
|
|
EvidenceFileError,
|
|
AnalysisSnapshotMismatchError,
|
|
type PublishedEvidenceFile,
|
|
} from "../domain/evidenceErrors.js";
|
|
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
|
|
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
import { access, stat } from "node:fs/promises";
|
|
import { absoluteCallerPath } from "../filesystem/callerPath.js";
|
|
import {
|
|
requestsStandaloneDecompile,
|
|
requiresNativeSourceAdmissionBeforeReplay,
|
|
} from "./binary/AnalysisSnapshotCache.js";
|
|
import {
|
|
snapshotBindingMismatch,
|
|
snapshotEvidenceForQuery,
|
|
} from "../domain/analysisSnapshot.js";
|
|
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
|
import { profilelessNativeDispatchProfile } from "./binary/ProfilelessNativeWorkflowSnapshot.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
|
import type { AnalysisExecution } from "../ports/AnalysisProvider.js";
|
|
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
|
|
import { REA_WORKFLOW_PROVIDER } from "../domain/investigationProviders.js";
|
|
import { workflowAnalysisProfile } from "./WorkflowAnalysisProfile.js";
|
|
import {
|
|
composedLimitationBudget,
|
|
executeComposedWorkflow,
|
|
createWorkflowEvidence,
|
|
retainPartialWorkflowEvidence,
|
|
workflowSnapshotRecord,
|
|
recordWorkflowUnknowns,
|
|
} from "./WorkflowEvidence.js";
|
|
import type { AnalysisProviderSelector } from "../domain/providerSelection.js";
|
|
import { executeWithNativeSymbolSelection } from "./NativeSymbolSelection.js";
|
|
import { cancelledBy, CallerAbort } from "../domain/analysisErrorCore.js";
|
|
import type { BinaryTargetError } from "../domain/configurationErrors.js";
|
|
import {
|
|
directAnalysisCleanupFailure,
|
|
projectDirectAnalysisFailure,
|
|
projectInvocationFailure,
|
|
managedAnalysisCleanupFailure,
|
|
withSessionCleanup,
|
|
} from "./DirectAnalysisCleanup.js";
|
|
import { completeProviderEvidence } from "./ProviderOperationExecution.js";
|
|
import type { ProgressReporter } from "../ports/ProgressReporter.js";
|
|
import { BUNDLE_RESOURCE_OPERATIONS } from "../ports/BundleResourceOperations.js";
|
|
import { classifyBinaryTargetFilesystemFailure } from "../domain/binaryTargetFilesystemFailure.js";
|
|
|
|
// These one-shot CLI questions require native utilities, not a deep engine.
|
|
// Runtime observation retains the ordinary session and authority checks.
|
|
const NATIVE_INSPECTION_OPERATIONS: ReadonlySet<string> = new Set([
|
|
"inspect_macho",
|
|
"inspect_signature",
|
|
"list_architectures",
|
|
"inspect_plist",
|
|
"demangle_swift",
|
|
] satisfies readonly NativeToolName[]);
|
|
|
|
const ARTIFACT_ANALYSIS_OPERATION_SET: ReadonlySet<string> = new Set(
|
|
ARTIFACT_ANALYSIS_OPERATIONS,
|
|
);
|
|
/**
|
|
* 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, provider session or runtime setting for a subsequent
|
|
* command. Failures are projected for that invocation lifetime, so they never
|
|
* offer same-session reuse or runtime updates; a new invocation's launch
|
|
* environment or arguments carry any changed limit.
|
|
*/
|
|
export const runDirectAnalysis = async (
|
|
dependencies: DirectAnalysisDependencies,
|
|
path: string,
|
|
tool: DirectAnalysisTool,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
options: {
|
|
readonly logger?: Logger;
|
|
readonly snapshotPath?: string | undefined;
|
|
readonly signal?: AbortSignal;
|
|
readonly providerId?: AnalysisProviderSelector;
|
|
readonly loadSelection?: NativeLoadSelection;
|
|
readonly espFlash?: EspFlashSelection;
|
|
readonly includeEvidenceSources?: boolean;
|
|
/** Receives a long workflow's own waiting reports; provider reads stay silent. */
|
|
readonly progress?: ProgressReporter;
|
|
} = {},
|
|
): Promise<AnalysisResultWithSources<Evidence, JsonValue>> =>
|
|
withProcessCancellation(options.signal, (signal) => {
|
|
const admitted = admitOneShotOperation(tool, arguments_, signal);
|
|
if (!admitted.ok)
|
|
return Promise.resolve(err(cliError(admitted.error, path)));
|
|
return runAnalysis(
|
|
dependencies,
|
|
path,
|
|
admitted.value.name,
|
|
admitted.value.input,
|
|
{
|
|
evidenceParameters: arguments_,
|
|
logger: options.logger ?? silentLogger,
|
|
snapshotPath: options.snapshotPath,
|
|
signal,
|
|
...(options.includeEvidenceSources === true
|
|
? { includeEvidenceSources: true }
|
|
: {}),
|
|
...(options.progress === undefined
|
|
? {}
|
|
: { progress: options.progress }),
|
|
...targetSelection(options),
|
|
...(options.providerId === undefined
|
|
? {}
|
|
: { providerId: options.providerId }),
|
|
},
|
|
);
|
|
});
|
|
|
|
/** How the caller asks an artifact target to be read. */
|
|
export interface ArtifactTargetSelection {
|
|
readonly loadSelection?: NativeLoadSelection;
|
|
readonly espFlash?: EspFlashSelection;
|
|
}
|
|
|
|
/** The caller's target interpretation, forwarded unchanged to every open. */
|
|
const targetSelection = (options: {
|
|
readonly loadSelection?: NativeLoadSelection;
|
|
readonly espFlash?: EspFlashSelection;
|
|
}) => ({
|
|
...(options.loadSelection === undefined
|
|
? {}
|
|
: { loadSelection: options.loadSelection }),
|
|
...(options.espFlash === undefined ? {} : { espFlash: options.espFlash }),
|
|
});
|
|
|
|
/** Execute one provider-native semantic operation with atomic provenance. */
|
|
export const runProviderAnalysis = async (
|
|
dependencies: DirectAnalysisDependencies,
|
|
...[path, tool, arguments_, logger = silentLogger, signal, selection]:
|
|
| readonly [
|
|
path: string,
|
|
tool: NativeToolName | ArtifactAnalysisOperation | ManagedToolName,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
logger?: Logger | undefined,
|
|
signal?: AbortSignal | undefined,
|
|
]
|
|
| readonly [
|
|
path: string,
|
|
tool: ArtifactAnalysisOperation,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
logger: Logger | undefined,
|
|
signal: AbortSignal | undefined,
|
|
selection: ArtifactTargetSelection,
|
|
]
|
|
): Promise<Result<Evidence, JsonValue>> =>
|
|
withProcessCancellation(signal, async (operationSignal) => {
|
|
// Preserve the selected path and original arguments as request facts.
|
|
const evidenceParameters = { ...arguments_, input_path: path };
|
|
if (isManagedToolName(tool)) {
|
|
const evidence = await managedCallerEvidence(
|
|
dependencies,
|
|
path,
|
|
tool,
|
|
arguments_,
|
|
operationSignal,
|
|
);
|
|
// Completed Evidence already carries the caller's path.
|
|
return evidence.ok ? evidence : err(cliError(evidence.error, path));
|
|
}
|
|
const admitted = admitOneShotOperation(tool, arguments_, operationSignal);
|
|
if (!admitted.ok) return err(cliError(admitted.error, path));
|
|
return runAnalysis(
|
|
dependencies,
|
|
path,
|
|
admitted.value.name,
|
|
admitted.value.input,
|
|
{
|
|
logger,
|
|
snapshotPath: undefined,
|
|
signal: operationSignal,
|
|
evidenceParameters,
|
|
...targetSelection(selection ?? {}),
|
|
...(ARTIFACT_ANALYSIS_OPERATION_SET.has(tool)
|
|
? { createSession: dependencies.createArtifactBinarySession }
|
|
: NATIVE_INSPECTION_OPERATIONS.has(tool)
|
|
? { createSession: dependencies.createNativeBinarySession }
|
|
: {}),
|
|
},
|
|
);
|
|
});
|
|
|
|
/**
|
|
* Run one managed operation on a caller-selected path, keeping its typed
|
|
* failure so a composed command can retain earlier Evidence beside it.
|
|
*/
|
|
export const runManagedProviderEvidence = (
|
|
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
|
|
path: string,
|
|
tool: ManagedToolName,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
signal?: AbortSignal,
|
|
): Promise<Result<Evidence, AnalysisError>> =>
|
|
withProcessCancellation(signal, (operationSignal) =>
|
|
managedCallerEvidence(
|
|
dependencies,
|
|
path,
|
|
tool,
|
|
arguments_,
|
|
operationSignal,
|
|
),
|
|
);
|
|
|
|
/** Managed Evidence bound to the caller's path and its request facts. */
|
|
const managedCallerEvidence = async (
|
|
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
|
|
path: string,
|
|
tool: ManagedToolName,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
operationSignal: AbortSignal,
|
|
): Promise<Result<Evidence, AnalysisError>> => {
|
|
// Preserve the selected path and original arguments as request facts.
|
|
const original = await runManagedProviderAnalysis(
|
|
dependencies,
|
|
path,
|
|
tool,
|
|
arguments_,
|
|
{ ...arguments_, input_path: path },
|
|
operationSignal,
|
|
);
|
|
await dispatchQueuedInterrupts();
|
|
if (!original.ok)
|
|
return err(retainFinalCancellation(original.error, tool, operationSignal));
|
|
const evidence = withEvidenceCallerInputPath(original.value, path);
|
|
if (operationSignal.aborted)
|
|
return err(
|
|
cancelledBy(tool, operationSignal, {
|
|
partialObservation: evidence,
|
|
}),
|
|
);
|
|
return ok(evidence);
|
|
};
|
|
|
|
/** Execute managed metadata inspection in an isolated managed-only session. */
|
|
export const runManagedProviderExecution = async (
|
|
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
|
|
path: string,
|
|
tool: ManagedToolName,
|
|
signal?: AbortSignal,
|
|
parameters: Readonly<Record<string, JsonValue>> = {},
|
|
recoveryParameters?: Readonly<Record<string, JsonValue>>,
|
|
): Promise<Result<AnalysisExecution, AnalysisError>> =>
|
|
withProcessCancellation(signal, async (operationSignal) => {
|
|
const admitted = admitOneShotOperation(tool, parameters, operationSignal);
|
|
if (!admitted.ok) return admitted;
|
|
const session = await dependencies.createManagedBinarySession();
|
|
return withSessionCleanup(
|
|
session,
|
|
async () => {
|
|
const opened = await session.open(path, { signal: operationSignal });
|
|
if (!opened.ok) return opened;
|
|
return recoveryParameters === undefined ||
|
|
session.executeForDirectObservation === undefined
|
|
? await session.execute(admitted.value.name, admitted.value.input, {
|
|
signal: operationSignal,
|
|
})
|
|
: await session.executeForDirectObservation(
|
|
admitted.value.name,
|
|
admitted.value.input,
|
|
recoveryParameters,
|
|
{ signal: operationSignal },
|
|
);
|
|
},
|
|
managedAnalysisCleanupFailure,
|
|
);
|
|
});
|
|
|
|
/** Preserve typed managed Evidence before selecting its CLI delivery. */
|
|
const runManagedProviderAnalysis = async (
|
|
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
|
|
path: string,
|
|
tool: ManagedToolName,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
evidenceParameters: Readonly<Record<string, JsonValue>>,
|
|
signal?: AbortSignal,
|
|
): Promise<Result<Evidence, AnalysisError>> => {
|
|
const execution = await runManagedProviderExecution(
|
|
dependencies,
|
|
path,
|
|
tool,
|
|
signal,
|
|
arguments_,
|
|
evidenceParameters,
|
|
);
|
|
if (!execution.ok) return execution;
|
|
const value = execution.value;
|
|
return ok(
|
|
createAnalysisExecutionEvidence(
|
|
tool,
|
|
evidenceParameters,
|
|
value,
|
|
"observed",
|
|
{ immutable: true },
|
|
),
|
|
);
|
|
};
|
|
|
|
const runAnalysis = async (
|
|
dependencies: DirectAnalysisDependencies,
|
|
path: string,
|
|
tool:
|
|
| NativeToolName
|
|
| ArtifactAnalysisOperation
|
|
| ManagedToolName
|
|
| DirectAnalysisTool,
|
|
arguments_: Readonly<Record<string, JsonValue>>,
|
|
options: {
|
|
readonly logger: Logger;
|
|
readonly snapshotPath: string | undefined;
|
|
readonly signal: AbortSignal;
|
|
readonly evidenceParameters?: Readonly<Record<string, JsonValue>>;
|
|
readonly createSession?: () => BinarySession | Promise<BinarySession>;
|
|
readonly includeEvidenceSources?: boolean;
|
|
readonly progress?: ProgressReporter;
|
|
readonly providerId?: AnalysisProviderSelector;
|
|
readonly loadSelection?: NativeLoadSelection;
|
|
readonly espFlash?: EspFlashSelection;
|
|
},
|
|
): Promise<AnalysisResultWithSources<Evidence, JsonValue>> => {
|
|
const { logger, signal, snapshotPath } = options;
|
|
const evidenceParameters = options.evidenceParameters ?? arguments_;
|
|
let session: BinarySession;
|
|
if (options.createSession !== undefined) {
|
|
session = await options.createSession();
|
|
} else {
|
|
const config = dependencies.readConfiguration();
|
|
if (!config.ok) return err(cliError(config.error));
|
|
session = await (
|
|
tool === "inspect_native_dispatch_metadata" && snapshotPath === undefined
|
|
? dependencies.createNativeDispatchBinarySession
|
|
: dependencies.createBinarySession
|
|
)(config.value, logger);
|
|
}
|
|
let publishedSnapshot: PublishedEvidenceFile | undefined;
|
|
let sourceEvidence: readonly Evidence[] | undefined;
|
|
const captureSources = (
|
|
evidence: Evidence,
|
|
supplied: readonly Evidence[] = [],
|
|
): Result<null, AnalysisError> => {
|
|
if (!options.includeEvidenceSources) return ok(null);
|
|
const records = new Map(
|
|
supplied.map((record) => [record.evidence_id, record]),
|
|
);
|
|
const collected = collectInvestigationEvidenceClosure(
|
|
{
|
|
evidenceForAnalysis: (id) =>
|
|
records.get(id) ?? session.evidenceForAnalysis(id),
|
|
},
|
|
evidence.evidence_links,
|
|
);
|
|
sourceEvidence = collected.records;
|
|
return collected.result;
|
|
};
|
|
const execute = async (): Promise<Result<Evidence, AnalysisError>> => {
|
|
// A directory is inventoried as a tree, not opened as a session target.
|
|
const directory =
|
|
tool === "inspect_artifact" &&
|
|
dependencies.inspectArtifactDirectory !== undefined
|
|
? await selectedArtifactDirectory(path)
|
|
: undefined;
|
|
if (directory !== undefined && dependencies.inspectArtifactDirectory) {
|
|
const inspectDirectory = dependencies.inspectArtifactDirectory;
|
|
const execution = await runInRetainedArtifactScope(
|
|
session.resourceScope,
|
|
path,
|
|
() =>
|
|
inspectDirectory(
|
|
directory,
|
|
arguments_,
|
|
{ signal },
|
|
session.resourceScope,
|
|
),
|
|
);
|
|
if (!execution.ok) return execution;
|
|
const evidence = withEvidenceCallerInputPath(
|
|
createAnalysisExecutionEvidence(
|
|
tool,
|
|
evidenceParameters,
|
|
execution.value,
|
|
"observed",
|
|
),
|
|
path,
|
|
);
|
|
const captured = captureSources(evidence, execution.value.sourceEvidence);
|
|
if (!captured.ok)
|
|
return err(captured.error.retainPartialObservation(evidence));
|
|
return ok(evidence);
|
|
}
|
|
let isDirectory = false;
|
|
if (BUNDLE_RESOURCE_OPERATIONS.has(tool)) {
|
|
const inspected = await inspectBundleResourceInput(path);
|
|
if (!inspected.ok) return inspected;
|
|
isDirectory = inspected.value;
|
|
}
|
|
if (BUNDLE_RESOURCE_OPERATIONS.has(tool) && isDirectory) {
|
|
const opened = await session.openBundleResources(path, { signal });
|
|
if (!opened.ok) return opened;
|
|
const execution = await session.execute(tool, arguments_, { signal });
|
|
if (!execution.ok) return execution;
|
|
return ok(
|
|
withEvidenceCallerInputPath(
|
|
createAnalysisExecutionEvidence(
|
|
tool,
|
|
evidenceParameters,
|
|
execution.value,
|
|
"observed",
|
|
),
|
|
path,
|
|
),
|
|
);
|
|
}
|
|
const prepared = await prepareSnapshot({
|
|
session,
|
|
path,
|
|
snapshotPath,
|
|
signal,
|
|
...targetSelection(options),
|
|
});
|
|
if (!prepared.ok) return prepared;
|
|
const { snapshot } = prepared.value;
|
|
let resolvedTarget: ResolvedSessionOpen | undefined;
|
|
if (snapshot !== undefined && prepared.value.target !== undefined) {
|
|
const preview = await session.previewTarget(prepared.value.target, {
|
|
signal,
|
|
snapshot,
|
|
...targetSelection(options),
|
|
...(options.providerId === undefined
|
|
? {}
|
|
: { providerId: options.providerId }),
|
|
});
|
|
if (!preview.ok) return preview;
|
|
resolvedTarget = preview.value;
|
|
const route = preview.value.route;
|
|
const bindingProfile =
|
|
route.profile ?? nativeDispatchBindingProfile(route, tool);
|
|
const evidenceProfile = analysisProfileForRoute(route, tool);
|
|
// A parsed Windows path does not prove Ghidra's native snapshot owner
|
|
// admitted the selected source; CLI replay must wait for that client.
|
|
if (
|
|
bindingProfile !== undefined &&
|
|
evidenceProfile !== undefined &&
|
|
!requiresNativeSourceAdmissionBeforeReplay(
|
|
route.binding?.identity.id,
|
|
) &&
|
|
tool !== "trace_native_ui_action" &&
|
|
tool !== "decompile_all" &&
|
|
!requestsStandaloneDecompile(tool, arguments_) &&
|
|
routeAllowsSnapshotReplay(route, tool)
|
|
) {
|
|
const cached = snapshotEvidenceForQuery(snapshot, {
|
|
target: preview.value.target,
|
|
bindingProfile,
|
|
operation: tool,
|
|
parameters: arguments_,
|
|
provider: isWorkflowEvidenceTool(tool)
|
|
? REA_WORKFLOW_PROVIDER
|
|
: routeProviderIdentity(route, tool),
|
|
evidenceProfile,
|
|
});
|
|
if (cached !== undefined) {
|
|
const records = new Map(
|
|
snapshot.evidence_bundle.records.map((record) => [
|
|
record.evidence_id,
|
|
record,
|
|
]),
|
|
);
|
|
const checkClosure = createInvestigationEvidenceClosureChecker({
|
|
evidenceForAnalysis: (id) => records.get(id),
|
|
});
|
|
if (checkClosure(cached.evidence_links)) {
|
|
const evidence = withEvidenceCallerInputPath(cached, path);
|
|
const captured = captureSources(
|
|
evidence,
|
|
snapshot.evidence_bundle.records,
|
|
);
|
|
if (!captured.ok)
|
|
return err(captured.error.retainPartialObservation(evidence));
|
|
return ok(evidence);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const openOptions = {
|
|
signal,
|
|
...targetSelection(options),
|
|
...(snapshot === undefined ? {} : { snapshot }),
|
|
...(options.providerId === undefined
|
|
? {}
|
|
: { providerId: options.providerId }),
|
|
};
|
|
const opened =
|
|
resolvedTarget === undefined
|
|
? await session.open(path, openOptions)
|
|
: await session.openResolvedTarget(resolvedTarget, openOptions);
|
|
if (!opened.ok) return opened;
|
|
const evidenceProfile = analysisProfileForEvidence(session, tool);
|
|
const executed = await executeAnalysisTool({
|
|
session,
|
|
openedTarget: opened.value,
|
|
tool,
|
|
arguments: arguments_,
|
|
evidenceParameters,
|
|
signal,
|
|
evidenceProfile,
|
|
saveSnapshot: snapshotPath !== undefined,
|
|
...(options.progress === undefined ? {} : { progress: options.progress }),
|
|
});
|
|
if (!executed.ok) {
|
|
if (options.includeEvidenceSources) {
|
|
const partial = recognizeEvidence(executed.error.partialObservation);
|
|
if (!partial.ok) executed.error.retainSecondaryFailure(partial.error);
|
|
else if (partial.value !== undefined) {
|
|
const captured = captureSources(partial.value);
|
|
if (!captured.ok)
|
|
executed.error.retainSecondaryFailure(captured.error);
|
|
}
|
|
}
|
|
return executed;
|
|
}
|
|
const { cachePolicy } = executed.value;
|
|
const evidence = withEvidenceCallerInputPath(executed.value.evidence, path);
|
|
// Provider execution may have already recorded the same semantic Evidence
|
|
// without this invocation's request path. Import replaces that metadata
|
|
// while retaining the authenticated result and snapshot binding.
|
|
const captured = captureSources(evidence);
|
|
if (!captured.ok)
|
|
return err(captured.error.retainPartialObservation(evidence));
|
|
const recorded = session.importEvidenceBundle(
|
|
createImmutableEvidenceBundle([evidence]),
|
|
);
|
|
if (!recorded.ok)
|
|
return err(recorded.error.retainPartialObservation(evidence));
|
|
if (isWorkflowEvidenceTool(tool)) {
|
|
const unknowns = recordWorkflowUnknowns({
|
|
name: tool,
|
|
result: evidence.normalized_result,
|
|
evidenceId: evidence.evidence_id,
|
|
recordUnknown: (unknown) => session.recordUnknown(unknown),
|
|
evidenceRetained: true,
|
|
});
|
|
if (!unknowns.ok)
|
|
return err(unknowns.error.retainPartialObservation(evidence));
|
|
}
|
|
if (
|
|
isWorkflowEvidenceTool(tool) &&
|
|
tool !== "trace_native_ui_action" &&
|
|
snapshotPath !== undefined &&
|
|
session.allowsSnapshotReplay(tool)
|
|
) {
|
|
const workflowRecord = workflowSnapshotRecord(
|
|
evidence,
|
|
tool,
|
|
evidenceProfile,
|
|
cachePolicy,
|
|
);
|
|
if (workflowRecord !== undefined) {
|
|
const recorded = session.recordWorkflowSnapshot(workflowRecord);
|
|
if (!recorded.ok)
|
|
return err(recorded.error.retainPartialObservation(evidence));
|
|
}
|
|
}
|
|
if (!SNAPSHOT_UNWRITTEN_TOOLS.has(tool) && snapshotPath !== undefined) {
|
|
const snapshot = session.exportAnalysisSnapshot();
|
|
if (!snapshot.ok)
|
|
return err(snapshot.error.retainPartialObservation(evidence));
|
|
const written = await session.writeAnalysisSnapshot(
|
|
snapshot.value,
|
|
snapshotPath,
|
|
true,
|
|
);
|
|
if (written.ok) publishedSnapshot = written.value;
|
|
else {
|
|
const published =
|
|
written.error instanceof EvidenceFileError
|
|
? written.error.published
|
|
: undefined;
|
|
if (published?.path !== undefined)
|
|
publishedSnapshot = { path: published.path, bytes: published.bytes };
|
|
const released =
|
|
published !== undefined && (await session.closeFileResources()).ok;
|
|
if (!released || published?.path === undefined)
|
|
return err(written.error.retainPartialObservation(evidence));
|
|
}
|
|
}
|
|
return ok(evidence);
|
|
};
|
|
const outcome = await withSessionCleanup<{
|
|
readonly result: Result<Evidence, AnalysisError>;
|
|
readonly cleanupError?: AnalysisError;
|
|
}>(
|
|
session,
|
|
async () => {
|
|
const result = await execute();
|
|
if (
|
|
!result.ok &&
|
|
result.error.sourcePublicationRecovery?.completed.kind ===
|
|
"retained-evidence"
|
|
) {
|
|
const retained = session.evidenceForAnalysis(
|
|
result.error.sourcePublicationRecovery.completed.evidence_id,
|
|
);
|
|
if (retained !== undefined)
|
|
result.error.sourcePublicationRecovery = {
|
|
...result.error.sourcePublicationRecovery,
|
|
completed: {
|
|
kind: "inline-evidence",
|
|
retention: "one-shot-session",
|
|
source_closure: "not-established",
|
|
evidence: retained,
|
|
},
|
|
};
|
|
}
|
|
return { result };
|
|
},
|
|
(value, cleanupError) => ({ ...value, cleanupError }),
|
|
);
|
|
await dispatchQueuedInterrupts();
|
|
const result = outcome.result.ok
|
|
? completeProviderEvidence(outcome.result.value, signal)
|
|
: err(retainFinalCancellation(outcome.result.error, tool, signal));
|
|
if (!result.ok && publishedSnapshot !== undefined)
|
|
result.error.retainDiagnostics({
|
|
analysis_snapshot: { ...publishedSnapshot },
|
|
});
|
|
if (outcome.cleanupError !== undefined) {
|
|
// A committed snapshot remains published even when final close fails.
|
|
if (result.ok && publishedSnapshot !== undefined)
|
|
outcome.cleanupError.retainDiagnostics({
|
|
analysis_snapshot: { ...publishedSnapshot },
|
|
});
|
|
return {
|
|
...err(directAnalysisCleanupFailure(result, outcome.cleanupError, path)),
|
|
...(sourceEvidence === undefined ? {} : { sourceEvidence }),
|
|
};
|
|
}
|
|
return {
|
|
...(result.ok ? ok(result.value) : err(cliError(result.error, path))),
|
|
...(sourceEvidence === undefined ? {} : { sourceEvidence }),
|
|
};
|
|
};
|
|
|
|
/** Preserve an earlier failure and a cancellation observed during final cleanup. */
|
|
const retainFinalCancellation = (
|
|
failure: AnalysisError,
|
|
tool: string,
|
|
signal: AbortSignal,
|
|
): AnalysisError =>
|
|
signal.aborted
|
|
? analysisErrorWithCancellation(failure, cancelledBy(tool, signal))
|
|
: failure;
|
|
|
|
/** Composed commands whose one-shot call never writes the snapshot file. */
|
|
const SNAPSHOT_UNWRITTEN_TOOLS: ReadonlySet<string> = new Set([
|
|
"decompile_all",
|
|
"trace_native_ui_action",
|
|
]);
|
|
|
|
/**
|
|
* A composed answer is rebuilt, not re-observed: its source reads that the
|
|
* snapshot holds can still replay without starting the provider.
|
|
*/
|
|
const workflowSnapshotNotSavedLimitation = (reason: string): string =>
|
|
`Not saved for snapshot replay as a composed answer: ${reason}. The snapshot records this Evidence and the source reads it can replay; repeating the call composes the answer again, starting the provider only for reads the snapshot lacks.`;
|
|
|
|
const executeAnalysisTool = async (input: {
|
|
readonly session: BinarySession;
|
|
readonly openedTarget: BinaryTarget;
|
|
readonly tool:
|
|
| NativeToolName
|
|
| ArtifactAnalysisOperation
|
|
| ManagedToolName
|
|
| DirectAnalysisTool;
|
|
readonly arguments: Readonly<Record<string, JsonValue>>;
|
|
readonly evidenceParameters: Readonly<Record<string, JsonValue>>;
|
|
readonly signal: AbortSignal;
|
|
readonly evidenceProfile: AnalysisProfileCommitment | undefined;
|
|
readonly saveSnapshot: boolean;
|
|
readonly progress?: ProgressReporter;
|
|
}): Promise<
|
|
Result<
|
|
{
|
|
readonly evidence: Evidence;
|
|
readonly cachePolicy?: "live";
|
|
},
|
|
AnalysisError
|
|
>
|
|
> => {
|
|
const { session, tool, signal, evidenceProfile } = input;
|
|
if (tool === "analyze_function") {
|
|
const { executeFunctionAnalysisEvidence } =
|
|
await import("./FunctionAnalysisEvidence.js");
|
|
let result = await executeFunctionAnalysisEvidence(
|
|
session,
|
|
input.arguments,
|
|
input.openedTarget,
|
|
{
|
|
signal,
|
|
// The session reports when a saved one-shot answer cannot replay.
|
|
...(input.saveSnapshot
|
|
? { snapshotContext: "one-shot-target" as const }
|
|
: {}),
|
|
},
|
|
{
|
|
admitRecovery: session.admitRecoveryObservation.bind(session),
|
|
evidenceById: (id) => session.evidenceForAnalysis(id),
|
|
},
|
|
);
|
|
result = retainAnalysisResultSources(
|
|
tool,
|
|
(source) => session.recordEvidence(source),
|
|
result,
|
|
);
|
|
return result.ok ? ok({ evidence: result.value }) : result;
|
|
}
|
|
if (isWorkflowEvidenceTool(tool)) {
|
|
const { EnhancedTools } = await import("./EnhancedTools.js");
|
|
let result = await executeComposedWorkflow(
|
|
session,
|
|
(observed) =>
|
|
new EnhancedTools(observed).execute(
|
|
tool,
|
|
input.arguments,
|
|
signal,
|
|
input.progress,
|
|
),
|
|
composedLimitationBudget(tool),
|
|
);
|
|
retainPartialWorkflowEvidence(result, {
|
|
target: input.openedTarget,
|
|
operation: tool,
|
|
parameters: input.evidenceParameters,
|
|
upstreamProfile: evidenceProfile,
|
|
});
|
|
result = retainAnalysisResultSources(
|
|
tool,
|
|
(source) => session.recordEvidence(source),
|
|
result,
|
|
);
|
|
if (!result.ok) return result;
|
|
// Mirrors the workflow snapshot record DirectAnalysis keeps afterwards.
|
|
const workflowReplayRefusal = !input.saveSnapshot
|
|
? undefined
|
|
: SNAPSHOT_UNWRITTEN_TOOLS.has(tool)
|
|
? `Not saved: ${tool} does not write analysis snapshots, so --snapshot recorded nothing for this call.`
|
|
: session.allowsSnapshotReplay(tool) &&
|
|
evidenceProfile !== undefined &&
|
|
result.value.cachePolicy !== "live"
|
|
? undefined
|
|
: workflowSnapshotNotSavedLimitation(
|
|
result.value.cachePolicy === "live"
|
|
? "it depends on live provider answers"
|
|
: "it is not bound to a replayable provider profile",
|
|
);
|
|
const evidence = createWorkflowEvidence({
|
|
target: input.openedTarget,
|
|
operation: tool,
|
|
parameters: input.evidenceParameters,
|
|
result: result.value.result,
|
|
upstreamProfile: evidenceProfile,
|
|
upstreamLimitations:
|
|
workflowReplayRefusal === undefined
|
|
? result.value.limitations
|
|
: [...result.value.limitations, workflowReplayRefusal],
|
|
...(result.value.evidenceLinks === undefined
|
|
? {}
|
|
: { upstreamEvidenceLinks: result.value.evidenceLinks }),
|
|
});
|
|
return ok({
|
|
evidence,
|
|
...(result.value.cachePolicy === undefined
|
|
? {}
|
|
: { cachePolicy: result.value.cachePolicy }),
|
|
});
|
|
}
|
|
// A saved one-shot snapshot binds every read to this call's own target.
|
|
const executionOptions = {
|
|
signal,
|
|
...(input.saveSnapshot
|
|
? { snapshotContext: "one-shot-target" as const }
|
|
: {}),
|
|
};
|
|
const result = await executeWithNativeSymbolSelection(
|
|
session,
|
|
tool,
|
|
input.arguments,
|
|
(arguments_) =>
|
|
session.executeForDirectObservation(
|
|
tool,
|
|
arguments_,
|
|
input.evidenceParameters,
|
|
executionOptions,
|
|
),
|
|
executionOptions,
|
|
);
|
|
if (!result.ok) return result;
|
|
const evidence = completedOperationEvidence(
|
|
tool,
|
|
input.evidenceParameters,
|
|
result.value,
|
|
{
|
|
target: input.openedTarget,
|
|
admitRecovery: session.admitRecoveryObservation.bind(session),
|
|
evidenceById: (id) => session.evidenceForAnalysis(id),
|
|
},
|
|
);
|
|
return evidence.ok ? ok({ evidence: evidence.value }) : evidence;
|
|
};
|
|
|
|
const withProcessCancellation = async <Value>(
|
|
suppliedSignal: AbortSignal | undefined,
|
|
operation: (signal: AbortSignal) => Promise<Value>,
|
|
): Promise<Value> => {
|
|
if (suppliedSignal !== undefined) return operation(suppliedSignal);
|
|
const controller = new AbortController();
|
|
const interrupt = (): void =>
|
|
controller.abort(CallerAbort.forProcessSignal("SIGINT"));
|
|
const terminate = (): void =>
|
|
controller.abort(CallerAbort.forProcessSignal("SIGTERM"));
|
|
// Package runners can forward a terminal interrupt after REA already received
|
|
// it directly. Keep both guards installed until provider cleanup has settled.
|
|
process.on("SIGINT", interrupt);
|
|
process.on("SIGTERM", terminate);
|
|
try {
|
|
return await operation(controller.signal);
|
|
} finally {
|
|
process.off("SIGINT", interrupt);
|
|
process.off("SIGTERM", terminate);
|
|
}
|
|
};
|
|
|
|
const prepareSnapshot = async (options: {
|
|
readonly session: Pick<
|
|
BinarySession,
|
|
"readAnalysisSnapshot" | "resolveTarget"
|
|
>;
|
|
readonly path: string;
|
|
readonly loadSelection?: NativeLoadSelection;
|
|
readonly espFlash?: EspFlashSelection;
|
|
readonly snapshotPath: string | undefined;
|
|
readonly signal: AbortSignal;
|
|
}): Promise<
|
|
Result<
|
|
{ readonly snapshot?: AnalysisSnapshot; readonly target?: BinaryTarget },
|
|
AnalysisError
|
|
>
|
|
> => {
|
|
const { path, snapshotPath, session } = options;
|
|
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
|
|
return ok({});
|
|
const loaded = await session.readAnalysisSnapshot(
|
|
snapshotPath,
|
|
options.signal,
|
|
);
|
|
if (!loaded.ok) return loaded;
|
|
const target = await session.resolveTarget(path, {
|
|
signal: options.signal,
|
|
...targetSelection(options),
|
|
});
|
|
if (!target.ok) return target;
|
|
const mismatch = snapshotBindingMismatch(
|
|
loaded.value,
|
|
target.value,
|
|
undefined,
|
|
);
|
|
if (mismatch?.target !== undefined)
|
|
return err(
|
|
new AnalysisSnapshotMismatchError(
|
|
"Analysis snapshot target does not match the requested binary",
|
|
mismatch,
|
|
),
|
|
);
|
|
return ok({ snapshot: loaded.value, target: target.value });
|
|
};
|
|
|
|
const inspectBundleResourceInput = async (
|
|
path: string,
|
|
): Promise<Result<boolean, BinaryTargetError>> => {
|
|
const callerPath = absoluteCallerPath(path);
|
|
try {
|
|
return ok((await stat(callerPath)).isDirectory());
|
|
} catch (cause: unknown) {
|
|
const failure = classifyBinaryTargetFilesystemFailure(callerPath, cause);
|
|
if (failure !== undefined) return err(failure);
|
|
throw cause;
|
|
}
|
|
};
|
|
|
|
const analysisProfileForRoute = (
|
|
route: SessionProviderRoute,
|
|
tool:
|
|
| NativeToolName
|
|
| ArtifactAnalysisOperation
|
|
| ManagedToolName
|
|
| DirectAnalysisTool,
|
|
): AnalysisProfileCommitment | undefined => {
|
|
const profile = route.profile;
|
|
const nativeDispatchProfile =
|
|
profile === null || profile === undefined
|
|
? nativeDispatchBindingProfile(route, tool)
|
|
: undefined;
|
|
if (profile === null || profile === undefined) {
|
|
if (nativeDispatchProfile === undefined) return undefined;
|
|
return isWorkflowEvidenceTool(tool)
|
|
? workflowAnalysisProfile(nativeDispatchProfile, tool)
|
|
: nativeDispatchProfile;
|
|
}
|
|
if (isWorkflowEvidenceTool(tool))
|
|
return workflowAnalysisProfile(profile, tool);
|
|
const provider = routeProviderIdentity(route, tool);
|
|
return provider.id === profile.provider.id ? profile : undefined;
|
|
};
|
|
|
|
const nativeDispatchBindingProfile = (
|
|
route: SessionProviderRoute,
|
|
operation: string,
|
|
): AnalysisProfileCommitment | undefined => {
|
|
if (operation !== "inspect_native_dispatch_metadata") return undefined;
|
|
return profilelessNativeDispatchProfile(route);
|
|
};
|
|
|
|
const analysisProfileForEvidence = (
|
|
session: BinarySession,
|
|
tool:
|
|
| NativeToolName
|
|
| ArtifactAnalysisOperation
|
|
| ManagedToolName
|
|
| DirectAnalysisTool,
|
|
): AnalysisProfileCommitment | undefined => {
|
|
if (!isWorkflowEvidenceTool(tool)) return session.analysisProfile(tool);
|
|
return session.analysisProfile() ?? session.analysisProfile(tool);
|
|
};
|
|
|
|
const isWorkflowEvidenceTool = (
|
|
tool:
|
|
| NativeToolName
|
|
| ArtifactAnalysisOperation
|
|
| ManagedToolName
|
|
| DirectAnalysisTool,
|
|
): tool is DirectEnhancedToolName =>
|
|
tool === "binary_overview" ||
|
|
tool === "inspect_native_api" ||
|
|
tool === "inspect_native_dispatch_metadata" ||
|
|
tool === "trace_feature" ||
|
|
tool === "trace_native_values" ||
|
|
tool === "trace_native_ui_action" ||
|
|
tool === "decompile_all";
|
|
|
|
const fileExists = async (path: string): Promise<boolean> => {
|
|
try {
|
|
await access(path);
|
|
return true;
|
|
} catch (cause: unknown) {
|
|
if (
|
|
typeof cause === "object" &&
|
|
cause !== null &&
|
|
"code" in cause &&
|
|
cause.code === "ENOENT"
|
|
)
|
|
return false;
|
|
throw cause;
|
|
}
|
|
};
|
|
|
|
const cliError = (
|
|
error: AnalysisError,
|
|
callerInputPath?: string,
|
|
): JsonValue => ({
|
|
error: "Analysis failed",
|
|
...(callerInputPath === undefined
|
|
? projectInvocationFailure(error)
|
|
: projectDirectAnalysisFailure(error, callerInputPath)),
|
|
});
|