Files
reverse-engineering-anything/src/server/registerApplicationTools/helpers.ts
T
morluto d5e0747025 refactor(process): build infrastructure cancellations with a required reason (#10595)
* refactor(errors): require a reason for every analysis cancellation

Add cancelledBy, the one constructor for AnalysisCancelledError. Its
reason argument is required: an aborted signal, an earlier cancellation,
a reason carried from an inner failure, or an OwnerCancellation when REA
closed the work's owner itself.

Closed adb, apktool, firmware, sqlite, gdb, web-bundle analyzer and
binary-session record owners now report OwnerCancellation.ownerClosed
instead of an absent reason. Firmware's predecessor wait returns its
cancellation as a Result, removing an unreachable reason-less fallback.

An architecture guard rejects new direct constructions, with a counted
per-file baseline that can only shrink.

* refactor(errors): share one aborted-signal predicate with cancelledBy

* refactor(process): return a departing caller's reason from a shared startup wait

* refactor(providers): build decompiler-provider cancellations with a required reason (#10587)

Migrate every AnalysisCancelledError construction under src/ghidra,
src/ida, src/cutter, src/jeb and src/kuna to cancelledBy and lower the
guard baseline from 671 to 572. Closed Kuna target commands report
OwnerCancellation.ownerClosed instead of an absent reason, and Kuna and
JEB close abort their lifetimes with that typed reason.

* refactor(process): build infrastructure cancellations with a required reason

Migrate every AnalysisCancelledError construction in shared process,
provider, artifact, domain, server and CLI code and in the smaller
providers to cancelledBy, lowering the guard baseline from 671 to 566.
Option bags that carried a cause are split so the cancellation branch
cannot receive one.

* fix(errors): read the reason of any signal-shaped cancellation source

* test(ci): cover the counted-baseline comparison behind the architecture guard
2026-11-15 17:05:23 +08:00

138 lines
5.1 KiB
TypeScript

import { setImmediate } from "node:timers/promises";
import type { CallToolResult } from "@modelcontextprotocol/server";
import type { ToolResultDelivery } from "../ToolResultDelivery.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js";
import { inspectAnalysisViewValidated } from "../../application/analysisView/AnalysisViewService.js";
import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js";
import { cancelledBy } from "../../domain/analysisErrorCore.js";
import type { AnalysisViewRequest } from "../../domain/analysisView/analysisViewRequest.js";
import type { Evidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { ok } from "../../domain/result.js";
import type { ApplicationToolRegistration } from "./types.js";
type UnknownKind =
| "application-version-comparison"
| "javascript-export-shape"
| "source-to-bundle-comparison";
export const recordResult = (
options: ApplicationToolRegistration & {
readonly delivery: ToolResultDelivery;
},
contract: (typeof APPLICATION_TOOL_CONTRACTS)[number],
evidence: Evidence,
unknownKind?: UnknownKind,
) => {
const recorded = recordApplicationResult(options, evidence, unknownKind);
return options.delivery.toEvidenceToolResult(evidence, contract, recorded);
};
/**
* Stage an optional caller-selected view against the completed parent, then
* commit its sources and the parent and deliver. A request cancelled before
* commit leaves the session unchanged; a delivered view that does not fit
* names the retained parent and a smaller page instead of its own record.
*/
export const deliverApplicationEvidence = async (
server: { readonly delivery: ToolResultDelivery },
options: ApplicationToolRegistration,
contract: (typeof APPLICATION_TOOL_CONTRACTS)[number],
execution: {
readonly evidence: Evidence;
readonly sources: readonly Evidence[];
},
view: AnalysisViewRequest | undefined,
signal: AbortSignal,
unknownKind?: UnknownKind,
): Promise<CallToolResult> => {
const { delivery } = server;
const parent = execution.evidence;
const selected =
view === undefined
? ok(parent)
: inspectAnalysisViewValidated(
{
source: {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
view,
},
(id) =>
id === parent.evidence_id ? parent : options.evidenceById?.(id),
);
await setImmediate();
if (signal.aborted)
return delivery.toErrorToolResult(
cancelledBy(contract.name, signal),
contract.returnsTargetContent,
);
if (!selected.ok) return delivery.toCallToolResult(selected, contract);
const sources = recordEvidenceSources(
options.recordEvidence,
execution.sources,
{ evidence: selected.value },
);
if (!sources.ok) return delivery.toCallToolResult(sources, contract);
const saved = recordApplicationResult(options, parent, unknownKind);
if (view === undefined)
return delivery.toEvidenceToolResult(parent, contract, saved);
if (saved !== undefined && !saved.ok)
return delivery.toCallToolResult(saved, contract);
return delivery.toSelectedViewToolResult(
selected.value,
{ parent, request: jsonValueSchema.parse(view) },
contract,
options.recordEvidence?.(selected.value),
);
};
/** Record the complete parent before choosing a delivery projection. */
export const recordApplicationResult = (
options: ApplicationToolRegistration,
evidence: Evidence,
unknownKind?: UnknownKind,
) =>
unknownKind === undefined
? options.recordEvidence?.(evidence)
: options.recordEvidenceWithUnknown?.(
evidence,
unknownRegistration(evidence, unknownKind),
);
const unknownRegistration = (evidence: Evidence, kind: UnknownKind) => ({
// Scope unknown identity to the comparison while keeping exact replays stable.
question: `${
kind === "application-version-comparison"
? "Which application entities remain unmatched or ambiguous across these versions?"
: kind === "source-to-bundle-comparison"
? "Which historical source files remain unmatched or ambiguously mapped to the shipped bundle?"
: "Which selected JavaScript export return shapes remain dynamic, incomplete, or ambiguously paired?"
} (comparison ${evidence.evidence_id})`,
severity: "medium" as const,
domain: kind,
supporting_evidence_ids: [evidence.evidence_id],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact" as const,
required_confidence: "observed" as const,
required_environment: null,
recommended_probes: [
{
operation: "analyze_javascript_application",
rationale:
"Repeat static reconstruction with complete artifacts and source maps when available.",
},
...(kind === "application-version-comparison"
? [
{
operation: "reconcile_javascript_runtime",
rationale:
"Add passive runtime Evidence without promoting it to static fact.",
},
]
: []),
],
relationships: [],
});