Compare commits

...
Author SHA1 Message Date
Kaoru0822andClaude Opus 5.5 bf34d0d2fc perf(native): add opt-in Mach-O summary delivery and retained pages (#2634)
* perf(native): add opt-in Mach-O summary delivery and retained pages

inspect_macho returns every import and export inline. For VS Code's
Electron Framework one MCP call carries 2.5 MB of text (about 828k o200k
tokens), and the same again as structuredContent; the MCP response
budget admits it. Agents asking for slice identity, UUID or dependency
counts paid that cost on every first call.

Add the established opt-in detail selection: omitted or complete keeps
the existing complete result and Evidence identity, while summary
retains the complete Evidence and returns slice identity with
per-collection returned/total/exhaustive counts (956 tokens).
inspect_analysis_view kind macho pages the original rows of any
collection or the command provenance, repeating the producer's own
total and exhaustive flag so page exhaustion is never read as absence.

Delivery detail never reaches the native tools or the source Evidence
ID: registerEvidenceTools gains a parametersForEvidence hook, so the
summary's parent is the same Evidence as a complete call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(mcp): refuse unretainable summary delivery before analysis

A server without Evidence retention (a fixed analysis source) ran the
complete inspect_macho or inspect_artifact analysis for detail summary
and only then refused it in summarizeRetainedAnalysis, paying the very
cost summary delivery exists to avoid. registerEvidenceTools gains a
preflight hook; both registrations check retention there, as the WASM,
EVM, managed, pcap and capture handlers already do before dispatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(native): keep whole rows in Mach-O architecture and segment pages

The page item union listed plain-object row arrays, and zod returns the
first union member that parses while dropping unknown keys. Entrypoint
rows declare only file_offset, so every architecture and segment row
(which also carry a numeric file_offset) matched it and lost its name,
CPU fields, permissions and sections. Rows now use exact key sets, and
imports/exports share one member. The MCP test pages every facet of a
real /bin/ls and compares it with the unparsed complete rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 00:13:12 -07:00
morluto e802441bce Merge remote-tracking branch 'origin/main' 2026-10-13 15:12:34 +08:00
morluto e7882b34f4 fix(artifacts): honor cancellation at the output publication boundary 2026-10-13 15:12:17 +08:00
morluto 9049dbaf0c fix(process): preserve monotonic capture timing and observed wall dates 2026-10-13 15:12:08 +08:00
morluto 7fc0b5ec9c fix(mcp): join owned doctor shutdown without signaling saved PIDs 2026-10-13 15:12:08 +08:00
Kaoru0822andClaude Opus 5.5 6a05248d46 perf(frida): evict captured messages without copying the whole queue (#2628)
Once a Frida session reached its 16 MiB capture budget, every new message
evicted the oldest one with Array#shift, re-serialized it to recover its
byte charge, and searched and spliced its per-script array. Each of
those is linear in the retained messages, so with about 188k small
messages retained the cost per message rose from 0.14 µs to 32 µs and
capped the main thread at roughly 31k messages per second, which a
hooked hot function can exceed.

Keep both queues as head-offset FIFOs that compact once half their slots
are evicted, and record each message's charge when it is admitted.
Arrival order already makes the globally oldest message the oldest one
of its script, so per-script eviction becomes a head check. Eviction is
now amortized O(1) at about 0.14 µs per message; retained messages,
their order and the truncation flag are unchanged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 00:11:38 -07:00
Kaoru0822andClaude Opus 5.5 20f51d7286 fix(native): name the ownership helper prerequisite in command failures (#2506)
* fix(native): name the ownership helper prerequisite in command failures

Every supervised native command launch needs the Darwin process-ownership
helper. When that helper cannot be compiled (relative REA_DARWIN_SWIFTC_PATH,
missing SDKROOT, a missing compiler, or an SDK/compiler mismatch), the
runner reduced the typed DarwinProcessOwnershipInspectionError to a bare
`io` failure. inspect_macho then reported `execution_failure` with no hint,
and inspect_artifact on any universal Mach-O said only "lipo could not
enumerate universal Mach-O slices".

The runner now keeps the inspection message as the failure's `detail` at
the launch boundary and carries it through xcrun resolution. The native
provider adds it to its diagnostics and the slice reader appends it to its
message, matching what the SQLite and capture providers already report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(native): cover the provider's ownership helper diagnostics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 00:10:58 -07:00
morluto 6bd2b28161 fix(browser): keep elapsed capture timing independent of wall-clock changes 2026-10-13 15:02:54 +08:00
morluto d9e9fb2273 fix(process): use monotonic time for provider execution budgets 2026-10-13 15:01:59 +08:00
morluto b953f96c0a fix(ghidra): share Java properties semantics with PSP extension admission 2026-10-13 15:00:14 +08:00
morluto fe8d0bdd36 fix(android): reject malformed UTF-8 at the JADX protocol boundary 2026-10-13 14:56:04 +08:00
58 changed files with 1737 additions and 368 deletions
@@ -83,6 +83,14 @@ names, the native API record, and value-flow summaries. Pseudocode offsets and l
code units; use the returned `next_offset` for continuation. Provider limitations
and unavailable facts remain explicit; the complete parent Evidence is retained.
`inspect_macho` on a large framework returns megabytes of imports and exports.
Select `detail: "summary"` for slice identity, UUID and per-collection counts,
then page rows with `view: {kind: "macho", facet: "exports", offset: 0, limit: 64}`
and `normalized_result.parent_evidence_id`. Facets are entrypoints,
architectures, build_metadata, load_commands, dependencies, imports, exports,
segments and provenance. `source_exhaustive: false` means unreturned symbols
may exist.
To see which functions or Objective-C methods a Mach-O actually calls in one
run, use `observe_native_calls` with explicit breakpoints and a bounded
`duration_ms`/`max_events`. It launches a new process under LLDB, so the target
+15 -2
View File
@@ -147,8 +147,8 @@ after target content was read.
## Retained application Evidence inputs
`analyze_javascript_application`, `inspect_binary_layout`, `inspect_artifact`, and
`inspect_wasm_artifact` accept `detail`:
`analyze_javascript_application`, `inspect_binary_layout`, `inspect_artifact`,
`inspect_wasm_artifact`, and `inspect_macho` accept `detail`:
`complete` (default) returns the complete analysis Evidence; `summary` records
that complete Evidence in the session and returns the derived
`inspect_analysis_view` summary Evidence instead. Its
@@ -218,6 +218,19 @@ attempting oversized delivery, and returns the same summary with an exact
`parent_evidence_id` for later export or facet reads. Delivery detail does not
reach WABT or change the original source Evidence ID.
Completed `inspect_macho` Evidence supports a summary and
`view: {kind: "macho", facet: "exports", offset: 0, limit: 64}`. Facets are
`entrypoints`, `architectures`, `build_metadata`, `load_commands`,
`dependencies`, `imports`, `exports`, `segments`, and `provenance`; pages return
the original rows. The summary keeps the selected slice, header fields and UUID,
and replaces each collection with its returned count, reported total and
`exhaustive` flag. Each page repeats the paged collection's `source_total` and
`source_exhaustive`; exhausting a non-exhaustive collection does not establish
that unreturned symbols are absent. Large frameworks return megabytes of
symbols (Electron Framework: 2.5 MB of imports and exports, 3.3 KB as a
summary), so select `detail: "summary"` on the first call. Delivery detail
never reaches the native tools or changes the source Evidence ID.
`trace_application_feature`, `trace_javascript_semantics`,
`compare_application_versions`, `compare_source_to_bundle`, and
`compare_javascript_export_shapes` accept complete inline application Evidence
+5 -3
View File
@@ -199,9 +199,11 @@ export class JadxMcpTransport implements Transport {
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
this.#appendFrame(fragment, frameBytes);
if (newline === -1) return;
const line = this.#frameBuffer
.subarray(0, this.#frameLength)
.toString("utf8");
const line = new TextDecoder("utf-8", {
fatal: true,
// Preserve a leading BOM so the JSON-RPC parser can reject it.
ignoreBOM: true,
}).decode(this.#frameBuffer.subarray(0, this.#frameLength));
this.#frameBuffer = Buffer.alloc(0);
this.#frameLength = 0;
this.onmessage?.(deserializeMessage(line));
@@ -809,6 +809,42 @@ it("keeps an active script message bucket after its last message is evicted", as
await manager.closeAll();
});
it("retains the newest contiguous messages across repeated budget evictions", async () => {
const { bindings, manager, started } = await startLocalAttachedSession();
expect(started.ok).toBe(true);
if (!started.ok) return;
bindings.device.session.nextPayload = { index: -1 };
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({index: -1});",
});
expect(loaded.ok).toBe(true);
const script = bindings.device.session.scripts[0];
expect(script).toBeDefined();
if (script === undefined) return;
// About 500 of these fit the 16 MiB budget, so 2,000 sends evict and
// compact the queue several times.
const filler = "x".repeat(32_000);
for (let index = 0; index < 2_000; index += 1)
script.message.emit({ type: "send", payload: { index, filler } }, null);
const status = manager.status(started.value.sessionId);
expect(status?.messagesTruncated).toBe(true);
const indexes = (status?.messages ?? []).map(
(message) => (message as { payload: { index: number } }).payload.index,
);
expect(indexes.length).toBeGreaterThan(400);
expect(indexes.at(-1)).toBe(1_999);
expect(indexes).toEqual(
Array.from(
{ length: indexes.length },
(_, offset) => 2_000 - indexes.length + offset,
),
);
await manager.closeAll();
});
it("serializes a final remote release against a new same-endpoint session", async () => {
const bindings = new FakeDeviceManager();
let enteredRemoval: (() => void) | undefined;
+3 -1
View File
@@ -81,7 +81,9 @@ export class MachOSliceArtifactReader implements ArtifactReader {
if (!captured.ok)
throw new ArtifactReaderFailure(
captured.error.reason === "cancelled" ? "cancelled" : "unavailable",
"lipo could not enumerate universal Mach-O slices",
captured.error.detail === null
? "lipo could not enumerate universal Mach-O slices"
: `lipo could not enumerate universal Mach-O slices: ${captured.error.detail}`,
{
cause: captured.error,
...(captured.error.cleanupFailure === null &&
+22 -11
View File
@@ -280,9 +280,11 @@ export class SafeOutputTree {
}
/** Sync the owned output tree and prevent further writes through this instance. */
async commit(): Promise<void> {
async commit(signal?: AbortSignal): Promise<void> {
this.#assertWritable();
abortIfNeeded(signal);
await this.#assertOwnedDirectories();
abortIfNeeded(signal);
// Windows has no directory fsync; file contents are already synced in write().
if (this.platform === "win32") {
this.#published = true;
@@ -315,6 +317,7 @@ export class SafeOutputTree {
);
await output.handle.sync();
await parent.handle.sync();
abortIfNeeded(signal);
this.#published = true;
} catch (cause: unknown) {
sync = { kind: "failed", cause };
@@ -336,23 +339,26 @@ export class SafeOutputTree {
closeFailure,
this.#outputRoot,
);
if (sync.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
),
cleanup,
);
if (sync.kind === "failed") {
const primary = isCancellationFailure(sync.cause)
? sync.cause
: new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
);
throw ArtifactReaderFailure.withCleanup(primary, cleanup);
}
throw ArtifactReaderFailure.withCleanup(closeFailure, cleanup);
}
if (sync.kind === "failed")
if (sync.kind === "failed") {
if (isCancellationFailure(sync.cause)) throw sync.cause;
throw new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
);
}
}
/** Remove only this operation's unsealed tree and verify absence. */
@@ -590,6 +596,11 @@ const abortIfNeeded = (signal?: AbortSignal): void => {
);
};
const isCancellationFailure = (
cause: unknown,
): cause is ArtifactReaderFailure =>
cause instanceof ArtifactReaderFailure && cause.reason === "cancelled";
const isAlreadyExists = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
@@ -249,7 +249,7 @@ const materializeSelection = async ({
compareUnicodeCodePoints(left.relative_path, right.relative_path),
);
completed = createExtractionResult(input, inventory, selected, extracted);
await output.commit();
await output.commit(signal);
return completed;
} catch (cause: unknown) {
const cleanupFailures = await releaseExtractionOwners(
@@ -91,7 +91,7 @@ export const browserScenarioCaptureData = (input: {
network_content: input.scenario.capture.network,
event_families: [...new Set(input.scenario.capture.events)].sort(),
},
duration_ms: Date.now() - input.startedAt,
duration_ms: Math.max(0, Math.round(performance.now() - input.startedAt)),
steps: [...input.steps],
events,
limitations: [
@@ -303,6 +303,7 @@ describe("PlaywrightBrowserScenarioProvider", () => {
});
expect(result.value.limitations).toContain(session.eventGaps[0]);
});
it("returns an initial state and every step beyond the former action ceiling", async () => {
const session = new FakeSession("launch");
const provider = new PlaywrightBrowserScenarioProvider(() =>
@@ -376,6 +377,35 @@ describe("PlaywrightBrowserScenarioProvider", () => {
});
});
describe("PlaywrightBrowserScenarioProvider timing", () => {
it("keeps capture elapsed values valid across a backward wall-clock jump", async () => {
let wallClock = 10_000;
vi.spyOn(Date, "now").mockImplementation(() => wallClock);
const session = new FakeSession("launch");
session.onPerform = () => {
wallClock = 1;
};
const provider = new PlaywrightBrowserScenarioProvider(() =>
Promise.resolve(session),
);
try {
const result = await provider.captureScenario(scenario());
if (!result.ok) throw result.error;
expect(wallClock).toBe(1);
expect(Number.isInteger(result.value.duration_ms)).toBe(true);
expect(result.value.duration_ms).toBeGreaterThanOrEqual(0);
expect(
result.value.steps.every(
({ elapsed_ms }) => Number.isInteger(elapsed_ms) && elapsed_ms >= 0,
),
).toBe(true);
} finally {
vi.restoreAllMocks();
}
});
});
describe("PlaywrightBrowserScenarioProvider comparison coverage", () => {
it("keeps quiet captures with different event families from comparing unchanged", async () => {
const capture = async (events: readonly BrowserScenarioEventFamily[]) => {
@@ -172,7 +172,7 @@ const executeStep = async (input: {
),
});
const actionStartedAt = Date.now();
const actionStartedAt = performance.now();
session.setStep(stepIndex);
const requestCancelled = (): boolean => signal?.aborted === true;
let outcome: BrowserScenarioStepOutcome = {
@@ -200,7 +200,7 @@ const executeStep = async (input: {
stepId: action.step_id,
action: action.action,
...outcome,
elapsedMs: Date.now() - actionStartedAt,
elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),
beforeUrl,
afterUrl: session.sanitizeUrl(session.currentUrl()),
eventStart,
@@ -233,7 +233,7 @@ const runScenario = async (
): Promise<BrowserScenarioCapture> => {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const startedAt = Date.now();
const startedAt = performance.now();
const session = await openSession(scenario, {
...(options.signal === undefined ? {} : { signal: options.signal }),
retainCleanup,
@@ -250,7 +250,7 @@ const runScenario = async (
await initialStep({
session,
scenario,
elapsedMs: Date.now() - startedAt,
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
signal: options.signal,
}),
);
+10 -4
View File
@@ -72,7 +72,7 @@ export const runElectronActions = async (
): Promise<ElectronActions> => {
const actions: ElectronActions = [];
for (const action of input.actions) {
const actionStartedAt = Date.now();
const actionStartedAt = performance.now();
const windowIndex = actionWindowIndex(action);
let selectedWindow: Page | undefined;
try {
@@ -107,7 +107,10 @@ export const runElectronActions = async (
target:
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
status: "completed",
elapsed_ms: Date.now() - actionStartedAt,
elapsed_ms: Math.max(
0,
Math.round(performance.now() - actionStartedAt),
),
error: null,
});
} catch (cause: unknown) {
@@ -118,7 +121,10 @@ export const runElectronActions = async (
target:
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
status: options.signal?.aborted ? "cancelled" : "failed",
elapsed_ms: Date.now() - actionStartedAt,
elapsed_ms: Math.max(
0,
Math.round(performance.now() - actionStartedAt),
),
error: safeActionErrorMessage(cause),
});
break;
@@ -366,7 +372,7 @@ export const runWithExecutionLimits = async <Value>(
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new BrowserObservationError(OPERATION, "timeout")),
Math.max(1, deadline - Date.now()),
Math.max(1, deadline - performance.now()),
);
}),
);
@@ -86,7 +86,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
await prepareProcessOwnershipInspection(options.signal);
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
const startupDeadline = performance.now() + STARTUP_TIMEOUT_MS;
paths = {
executable: input.executable_path,
application: input.application_path,
@@ -101,7 +101,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
cwd: paths.root,
env: safeElectronEnvironment(this.environment, runId),
args: ["-r", hookPath, paths.application, ...input.args],
timeout: Math.max(1, startupDeadline - Date.now()),
timeout: Math.max(1, startupDeadline - performance.now()),
});
const leaderPid = application.process().pid;
if (
@@ -128,7 +128,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
const state = await runWithExecutionLimits(
readApplicationState(application),
undefined,
options.signal?.aborted ? Date.now() + 5_000 : undefined,
options.signal?.aborted ? performance.now() + 5_000 : undefined,
);
capture = projectElectronActiveCapture(paths, actions, state);
outcome = options.signal?.aborted
@@ -187,7 +187,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
await runWithExecutionLimits(
application.close(),
undefined,
Date.now() + 5_000,
performance.now() + 5_000,
);
} catch (cause: unknown) {
closeError = cause;
@@ -7,7 +7,10 @@ import {
} from "../domain/analysisErrorCore.js";
describe("withPlaywrightExecutionBoundary", () => {
afterEach(() => vi.useRealTimers());
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("rejects work that exceeds its absolute remaining duration", async () => {
vi.useFakeTimers();
@@ -31,4 +34,20 @@ describe("withPlaywrightExecutionBoundary", () => {
controller.abort();
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
});
it("keeps its timeout stable across a wall-clock jump", async () => {
vi.spyOn(Date, "now")
.mockReturnValueOnce(1_000)
.mockReturnValue(10_000_000);
await expect(
withPlaywrightExecutionBoundary(
() =>
new Promise<string>((resolve) =>
setTimeout(() => resolve("done"), 5),
),
1_000,
),
).resolves.toBe("done");
});
});
+2 -2
View File
@@ -19,10 +19,10 @@ export const withPlaywrightExecutionBoundary = <Value>(
let settled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline =
timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
timeoutMs === undefined ? undefined : performance.now() + timeoutMs;
const scheduleTimeout = (): void => {
if (deadline === undefined) return;
const remaining = deadline - Date.now();
const remaining = deadline - performance.now();
if (remaining <= 0) {
fail(new AnalysisTimeoutError(OPERATION, timeoutMs ?? 0));
return;
+1 -1
View File
@@ -133,7 +133,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
if (secrets === undefined)
throw new BrowserObservationError(OPERATION, "secret_unavailable");
const startedAt = Date.now();
const startedAt = performance.now();
const opening = openPlaywrightScenarioBrowser(scenario, environment, {
signal: options.signal,
...(options.retainCleanup === undefined
+3 -3
View File
@@ -86,7 +86,7 @@ export const fetchWebSourceMaps = async (
signal?.addEventListener("abort", abortFromCaller, { once: true });
const operationSignal = operationController.signal;
const deadlineAt =
Date.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
performance.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
const budget = {
retainedBytes: 0,
deadlineAt,
@@ -110,7 +110,7 @@ export const fetchWebSourceMaps = async (
}
const expandedBytesBeforeItem = budget.decodedRecords.expandedBytes;
budget.decodedRecords.expandedBytes += reservation;
if (operationSignal.aborted || Date.now() >= deadlineAt) {
if (operationSignal.aborted || performance.now() >= deadlineAt) {
items.push(
emptySourceMapItem(
request,
@@ -789,7 +789,7 @@ const checkOperation = (
): void => {
if (callerSignal?.aborted === true) throw callerSignal.reason;
if (operationSignal?.aborted === true) throw operationSignal.reason;
if (Date.now() >= deadlineAt) throw new SourceMapDeadlineError();
if (performance.now() >= deadlineAt) throw new SourceMapDeadlineError();
};
const approvedUrl = (
+1 -1
View File
@@ -113,7 +113,7 @@ export const publishWebScripts = async (
options.signal,
);
options.signal?.throwIfAborted();
await tree.commit();
await tree.commit(options.signal);
return result;
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
File diff suppressed because one or more lines are too long
+10 -2
View File
@@ -11,6 +11,7 @@ import { jsonValueSchema } from "../../domain/jsonValue.js";
import { localPathStringSchema } from "../../domain/localPath.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
import { analysisDetailSchema } from "../analysisDetail.js";
const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
inspect_macho: {},
@@ -94,8 +95,15 @@ export const NATIVE_TOOL_CONTRACTS = [
),
native(
"inspect_macho",
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper.",
z.object({}),
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper. Large frameworks return megabytes of symbols; detail summary retains the complete Evidence and returns slice identity with per-collection counts, then page rows with inspect_analysis_view kind macho.",
z.object({
detail: analysisDetailSchema
.unwrap()
.optional()
.describe(
"Omitted or complete returns the complete inspection Evidence. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; use normalized_result.parent_evidence_id for macho pages.",
),
}),
),
native(
"inspect_signature",
+4 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import {
artifactInventorySummaryViewResultSchema,
machoSummaryViewResultSchema,
managedArtifactSummaryViewResultSchema,
} from "../domain/analysisView/analysisView.js";
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
@@ -381,7 +382,9 @@ export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
observe_native_ui: evidenceResultOf(nativeUiResultSchema),
capture_native_ui_scenario: evidenceResultOf(nativeUiResultSchema),
observe_native_calls: evidenceResultOf(nativeCallObservationResultSchema),
inspect_macho: evidenceResultOf(inspectMachoSchema),
inspect_macho: evidenceResultOf(
z.union([inspectMachoSchema, machoSummaryViewResultSchema]),
),
inspect_signature: evidenceResultOf(inspectSignatureSchema),
inspect_plist: evidenceResultOf(inspectPlistSchema),
list_architectures: evidenceResultOf(listArchitecturesSchema),
+28 -1
View File
@@ -55,6 +55,13 @@ import {
wasmViewItemSchema,
wasmSummarySchema,
} from "./wasmArtifactView.js";
import {
machoSummarySchema,
machoViewContextSchema,
machoViewItemSchema,
machoViewRequestSchema,
projectMachoView,
} from "./machoView.js";
import {
projectWebNetworkCaptureView,
captureViewRequestSchema,
@@ -196,6 +203,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
nativeViewSchema,
inventoryViewSchema,
wasmViewRequestSchema,
machoViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
androidViewRequestSchema,
@@ -315,6 +323,7 @@ const viewResultBase = {
"inspect_artifact",
"inventory_artifact",
"inspect_wasm_artifact",
"inspect_macho",
"inspect_evm_interface",
"inspect_managed_artifact",
"inspect_web_network_capture",
@@ -364,6 +373,13 @@ export const wasmArtifactSummaryViewResultSchema = z.strictObject({
summary: wasmSummarySchema,
});
/** Exact slice identity and collection counts for Mach-O's selected delivery. */
export const machoSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_macho"),
summary: machoSummarySchema,
});
/** Exact inferred-interface summary for EVM's caller-selected delivery. */
export const evmInterfaceSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -425,6 +441,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
javascriptSummarySchema,
inventorySummarySchema,
wasmSummarySchema,
machoSummarySchema,
evmSummarySchema,
managedSummarySchema,
captureSummarySchema,
@@ -487,6 +504,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
item: wasmViewItemSchema,
...viewResultBase,
}),
z.strictObject({
kind: z.literal("macho"),
view: machoViewRequestSchema,
item: machoViewItemSchema,
...viewResultBase,
...machoViewContextSchema.shape,
parent_operation: z.literal("inspect_macho"),
}),
z.strictObject({
kind: z.literal("evm"),
view: evmViewRequestSchema,
@@ -583,6 +608,7 @@ export type UnsignedAnalysisView =
"view_digest"
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "macho" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "pcap" }>, "view_digest">
@@ -646,7 +672,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, Mach-O, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -673,6 +699,7 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
/** Named source owners for views that need no extra decoder or accumulator. */
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_macho", projectMachoView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_android_package", projectAndroidPackageView],
+246
View File
@@ -0,0 +1,246 @@
import { describe, expect, it } from "vitest";
import {
projectAnalysisView,
type AnalysisViewParent,
} from "./analysisView.js";
const symbol = (name: string) => ({
name,
address: null,
weak: null,
reexport: null,
source: "libSystem",
});
const coverage = <T>(items: T[], exhaustive = true) => ({
items,
total: exhaustive ? items.length : null,
exhaustive,
limitations: exhaustive ? [] : ["nm output may omit stripped symbols."],
});
const report = {
format: "mach-o",
selected_architecture: { name: "arm64", container_file_offset: 0 },
endian: null,
word_size: 64,
file_type: "2",
flags: ["0x00200085"],
uuid: "4C4C44E9-5555-3144-A1E9-D858E24A1CCE",
entrypoints: coverage([{ file_offset: 16384 }]),
architectures: coverage([
{
name: "arm64",
cpu_type: "16777228",
cpu_subtype: "0",
file_offset: 0,
size: 4096,
alignment: 14,
},
]),
build_metadata: coverage([
{ platform: "1", minimum_os: "14.0", sdk: "15.0", tools: [] },
]),
load_commands: coverage([{ index: 0, kind: "LC_MAIN", fields: {} }]),
dependencies: coverage([
{
path: "/usr/lib/libSystem.B.dylib",
kind: "LC_LOAD_DYLIB",
current_version: "1351.0.0",
compatibility_version: "1.0.0",
},
]),
imports: coverage(
["_malloc", "_free", "_open"].map((name) => symbol(name)),
false,
),
exports: coverage([symbol("__mh_execute_header")]),
segments: coverage([
{
name: "__TEXT",
vm_address: "0x100000000",
vm_size: 16384,
file_offset: 0,
file_size: 16384,
maximum_permissions: {
read: true,
write: false,
execute: true,
raw: "5",
},
initial_permissions: {
read: true,
write: false,
execute: true,
raw: "5",
},
sections: coverage([]),
},
]),
provenance: [
{
tool: "nm",
command: ["/usr/bin/nm", "$ARTIFACT"],
tool_version: null,
version_reason: "fixture",
executable_sha256: "a".repeat(64),
exit: { code: 0, signal: null },
stdout_bytes: 10,
stderr_bytes: 0,
},
],
limitations: ["Imports and exports combine dyld_info and nm."],
};
const parent = (
normalizedResult: unknown = report,
subject: AnalysisViewParent["subject"] = {
name: "tool",
digest: { sha256: "b".repeat(64) },
format: "mach-o",
architecture: "arm64",
local_path: "/bin/tool",
},
): AnalysisViewParent => ({
evidenceId: `ev_${"c".repeat(64)}`,
operation: "inspect_macho",
normalizedResult,
subject,
limitations: ["Parent limitation."],
});
describe("Mach-O analysis views", () => {
it("summarizes slice identity and collection counts without rows", () => {
const projected = projectAnalysisView(parent(), { kind: "summary" });
if (!projected.ok) throw projected.error;
expect(projected.value).toMatchObject({
kind: "summary",
parent_operation: "inspect_macho",
artifact: { path: "/bin/tool", sha256: "b".repeat(64) },
summary: {
selected_architecture: { name: "arm64", container_file_offset: 0 },
uuid: report.uuid,
collections: {
imports: { returned: 3, total: null, exhaustive: false },
exports: { returned: 1, total: 1, exhaustive: true },
segments: { returned: 1, total: 1, exhaustive: true },
},
provenance_count: 1,
limitation_count: 3,
},
coverage: { status: "complete-within-view", examined: 10, total: 10 },
limitations: [
"Imports and exports combine dyld_info and nm.",
"Parent limitation.",
"nm output may omit stripped symbols.",
],
unknowns: [expect.stringContaining("exhaustive imports;")],
});
expect(JSON.stringify(projected.value)).not.toContain("_malloc");
});
it("pages original rows with the producer's own coverage", () => {
const first = projectAnalysisView(parent(), {
kind: "macho",
facet: "imports",
offset: 1,
limit: 1,
});
if (!first.ok) throw first.error;
expect(first.value).toMatchObject({
kind: "macho",
item: [symbol("_free")],
source_total: null,
source_exhaustive: false,
coverage: { status: "page", examined: 1, total: 3, next_offset: 2 },
});
expect(first.value.limitations).toContain(
"nm output may omit stripped symbols.",
);
// Rows whose keys include an earlier row shape's keys stay whole.
for (const facet of ["architectures", "segments"] as const) {
const page = projectAnalysisView(parent(), {
kind: "macho",
facet,
offset: 0,
limit: 64,
});
if (!page.ok) throw page.error;
expect(page.value.kind === "macho" && page.value.item).toEqual(
report[facet].items,
);
}
const provenance = projectAnalysisView(parent(), {
kind: "macho",
facet: "provenance",
offset: 0,
limit: 64,
});
if (!provenance.ok) throw provenance.error;
expect(provenance.value).toMatchObject({
item: report.provenance,
source_total: 1,
source_exhaustive: true,
coverage: { exhausted: true, next_offset: null },
});
const past = projectAnalysisView(parent(), {
kind: "macho",
facet: "exports",
offset: 5,
limit: 64,
});
if (!past.ok) throw past.error;
expect(past.value.coverage).toMatchObject({
status: "empty",
exhausted: true,
});
});
it("keeps a missing subject unknown instead of inventing identity", () => {
const projected = projectAnalysisView(parent(report, null), {
kind: "summary",
});
if (!projected.ok) throw projected.error;
expect(projected.value.artifact).toEqual({ path: "", sha256: null });
expect(projected.value.unknowns).toContain(
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
);
});
it("rejects other view kinds and malformed retained results", () => {
const wrongKind = projectAnalysisView(parent(), {
kind: "wasm",
facet: "exports",
offset: 0,
limit: 64,
});
if (wrongKind.ok) throw new Error("expected a view-kind refusal");
expect(wrongKind.error).toMatchObject({
_tag: "AnalysisInputError",
issues: [
{
path: ["view"],
message: "Mach-O inspection supports summary and macho views.",
},
],
});
const contradictory = projectAnalysisView(
parent(report, {
name: "tool",
digest: { sha256: "b".repeat(64) },
format: "elf",
architecture: null,
local_path: "/bin/tool",
}),
{ kind: "summary" },
);
if (contradictory.ok) throw new Error("expected a subject refusal");
expect(contradictory.error).toMatchObject({
issues: [{ path: ["source", "subject"] }],
});
const malformed = projectAnalysisView(
parent({ ...report, imports: { items: "x" } }),
{ kind: "summary" },
);
expect(malformed.ok).toBe(false);
if (!malformed.ok) expect(malformed.error._tag).toBe("AnalysisInputError");
});
});
+247
View File
@@ -0,0 +1,247 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { isMachOFormat } from "../binaryTargetTypes.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { inspectMachoSchema } from "../native/nativeInspection.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const MACHO_COLLECTIONS = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
] as const;
type MachoCollection = (typeof MACHO_COLLECTIONS)[number];
/** Original inspect_macho rows; offsets count rows in the retained collection. */
export const machoViewRequestSchema = z.strictObject({
kind: z.literal("macho"),
facet: z.enum([...MACHO_COLLECTIONS, "provenance"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
const { shape } = inspectMachoSchema;
/**
* Union members are tried in order and plain objects drop unknown keys, so a
* segment or architecture row would otherwise match the entrypoint row and
* lose every field but file_offset. Exact key sets keep each page's rows whole.
*/
const exactRows = <Shape extends z.ZodRawShape>(
rows: z.ZodArray<z.ZodObject<Shape>>,
) => z.array(z.strictObject(rows.element.shape));
export const machoViewItemSchema = z.union([
exactRows(shape.entrypoints.shape.items),
exactRows(shape.architectures.shape.items),
exactRows(shape.build_metadata.shape.items),
exactRows(shape.load_commands.shape.items),
exactRows(shape.dependencies.shape.items),
// Imports and exports share one row shape.
exactRows(shape.imports.shape.items),
exactRows(shape.segments.shape.items),
exactRows(shape.provenance),
]);
/** The producer's own coverage of the paged collection, not of this page. */
export const machoViewContextSchema = z.strictObject({
source_total: z.number().int().nonnegative().nullable(),
source_exhaustive: z.boolean(),
});
const collectionCountSchema = z.strictObject({
returned: z.number().int().nonnegative(),
total: z.number().int().nonnegative().nullable(),
exhaustive: z.boolean(),
});
/** Slice identity and per-collection counts without the collections themselves. */
export const machoSummarySchema = z.strictObject({
format: shape.format,
selected_architecture: shape.selected_architecture,
endian: shape.endian,
word_size: shape.word_size,
file_type: shape.file_type,
flags: shape.flags,
uuid: shape.uuid,
collections: z.strictObject(
Object.fromEntries(
MACHO_COLLECTIONS.map((name) => [name, collectionCountSchema]),
) as Record<MachoCollection, typeof collectionCountSchema>,
),
provenance_count: z.number().int().nonnegative(),
limitation_count: z.number().int().nonnegative(),
});
type MachoReport = z.output<typeof inspectMachoSchema>;
/** Admit a well-formed report whose recorded subject, if any, is a Mach-O. */
const parseMachoReport = (
parent: AnalysisViewParent,
): Result<MachoReport, AnalysisError> => {
const parsed = inspectMachoSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
if (parent.subject != null && !isMachOFormat(parent.subject.format))
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Mach-O parent Evidence subject must identify a thin or universal Mach-O.",
},
]),
);
return ok(parsed.data);
};
/** Counts replace rows; every collection caveat stays in the limitations. */
const summarizeMacho = (
report: MachoReport,
parentLimitations: readonly string[],
) => {
const limitations = uniqueSorted([
...parentLimitations,
...report.limitations,
...MACHO_COLLECTIONS.flatMap((name) => report[name].limitations),
]);
const collections = Object.fromEntries(
MACHO_COLLECTIONS.map((name) => [
name,
{
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
},
]),
) as Record<MachoCollection, z.output<typeof collectionCountSchema>>;
return {
limitations,
returned: MACHO_COLLECTIONS.reduce(
(sum, name) => sum + report[name].items.length,
0,
),
summary: {
format: report.format,
selected_architecture: report.selected_architecture,
endian: report.endian,
word_size: report.word_size,
file_type: report.file_type,
flags: report.flags,
uuid: report.uuid,
collections,
provenance_count: report.provenance.length,
limitation_count: limitations.length,
},
};
};
/** Project retained inspect_macho Evidence without rerunning native tools. */
export const projectMachoView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "macho")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message: "Mach-O inspection supports summary and macho views.",
},
]),
);
const parsed = parseMachoReport(parent);
if (!parsed.ok) return parsed;
const report = parsed.value;
const incomplete = MACHO_COLLECTIONS.filter(
(name) => !report[name].exhaustive,
);
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_macho" as const,
parent_digest: parent.evidenceId.slice(3),
artifact:
parent.subject == null
? { path: "", sha256: null }
: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
},
unknowns: [
...(incomplete.length === 0
? []
: [
`Native tools did not report exhaustive ${incomplete.join(", ")}; page exhaustion does not establish absence of unreturned rows.`,
]),
...(parent.subject == null
? [
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
]
: []),
],
};
if (view.kind === "summary") {
const { summary, limitations, returned } = summarizeMacho(
report,
parent.limitations,
);
return ok({
kind: "summary",
view,
...shared,
limitations,
summary,
coverage: completeWithinViewCoverage(returned, returned),
});
}
const source =
view.facet === "provenance"
? {
items: report.provenance,
total: report.provenance.length,
exhaustive: true,
limitations: [],
}
: report[view.facet];
const item = source.items.slice(view.offset, view.offset + view.limit);
return ok({
kind: "macho",
view,
item,
...shared,
limitations: uniqueSorted([
...parent.limitations,
...report.limitations,
...source.limitations,
]),
source_total: source.total,
source_exhaustive: source.exhaustive,
coverage: pageViewCoverage(view.offset, item.length, source.items.length),
});
};
@@ -47,10 +47,6 @@ const validateCommitments = (
digestProcessCommitment(
value,
), `manifest.${field}`, "commitment does not match its canonical value");
require(Date.parse(manifest.started_at) <=
Date.parse(
manifest.completed_at,
), "manifest.completed_at", "completion precedes start");
};
const validateOrdering = (
+2 -2
View File
@@ -176,11 +176,11 @@ export const runFirmwareCommand = async (context: {
};
let failure: unknown;
try {
const deadline = Date.now() + FIRMWARE_LIMITS.timeoutMs;
const deadline = performance.now() + FIRMWARE_LIMITS.timeoutMs;
while (!(await supervisor.waitForOutputClose(100))) {
checkDiagnostics();
if (signal.aborted) throw new AnalysisCancelledError(operation);
if (Date.now() >= deadline)
if (performance.now() >= deadline)
throw new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs);
if (context.outputBudget !== undefined)
await inventoryFirmwareOutput(
+1 -1
View File
@@ -96,7 +96,7 @@ export const publishFirmwareExtraction = async (context: {
published_bytes: files.reduce((sum, file) => sum + file.size, 0),
});
context.signal.throwIfAborted();
await tree.commit();
await tree.commit(context.signal);
return result;
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
+62 -23
View File
@@ -83,8 +83,8 @@ interface ManagedSession extends ManagedRemoteConnection {
readonly pid: number;
readonly mode: "attach" | "spawn";
readonly scripts: Map<string, ManagedScript>;
readonly messages: JsonValue[];
readonly messagesByScript: Map<string, JsonValue[]>;
readonly messages: MessageFifo<CapturedMessage>;
readonly messagesByScript: Map<string, MessageFifo<JsonValue>>;
state: "paused" | "running" | "detached";
targetResumeObserved: boolean;
resumeAfterDetachPending: boolean;
@@ -277,7 +277,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
pid,
mode: input.mode,
scripts: new Map(),
messages: [],
messages: new MessageFifo(),
messagesByScript: new Map(),
state: input.mode === "spawn" ? "paused" : "running",
targetResumeObserved: false,
@@ -373,7 +373,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
.digest("hex");
const scriptId = randomUUID();
const scriptName = `rea-${scriptId}`;
managed.messagesByScript.set(scriptId, []);
managed.messagesByScript.set(scriptId, new MessageFifo());
let nativeScript: Script | undefined;
const onMessage = (message: FridaMessage, data: Buffer | null): void => {
this.#recordMessage(managed, scriptId, message, data);
@@ -397,7 +397,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
sourceKind: source.sourceKind,
sourcePath: source.sourceKind === "file" ? source.path : null,
sourceSha256,
messages: [...(managed.messagesByScript.get(scriptId) ?? [])],
messages: managed.messagesByScript.get(scriptId)?.toArray() ?? [],
messagesTruncated: managed.messagesTruncated,
});
} catch (cause: unknown) {
@@ -517,7 +517,9 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
scriptId: id,
name,
})),
messages: [...managed.messages],
messages: managed.messages
.toArray()
.map(({ observation }) => observation),
messagesTruncated: managed.messagesTruncated,
};
}
@@ -851,30 +853,21 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
return;
}
while (
managed.messages.length > 0 &&
managed.messages.size > 0 &&
managed.capturedBytes + charge > MAX_SESSION_CAPTURE_BYTES
) {
const removed = managed.messages.shift();
if (removed !== undefined) {
managed.capturedBytes -= Buffer.byteLength(JSON.stringify(removed));
if (
typeof removed === "object" &&
removed !== null &&
!Array.isArray(removed) &&
typeof removed.script_id === "string"
) {
const scriptMessages = managed.messagesByScript.get(
removed.script_id,
);
const index = scriptMessages?.indexOf(removed) ?? -1;
if (scriptMessages !== undefined && index >= 0) {
scriptMessages.splice(index, 1);
}
}
managed.capturedBytes -= removed.charge;
// Both queues are in arrival order, so the globally oldest message is
// also the oldest one retained for its script.
const scriptMessages = managed.messagesByScript.get(removed.scriptId);
if (scriptMessages?.peek() === removed.observation)
scriptMessages.shift();
}
managed.messagesTruncated = true;
}
managed.messages.push(observation);
managed.messages.push({ observation, scriptId, charge });
managed.messagesByScript.get(scriptId)?.push(observation);
managed.capturedBytes += charge;
}
@@ -1240,3 +1233,49 @@ const providerError = (
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
interface CapturedMessage {
readonly observation: JsonValue;
readonly scriptId: string;
/** Serialized bytes charged against the session capture budget. */
readonly charge: number;
}
/**
* Arrival-ordered queue whose eviction advances a head offset. A full capture
* budget evicts on every message, and `Array#shift` would copy every retained
* message each time.
*/
class MessageFifo<T> {
#items: (T | undefined)[] = [];
#head = 0;
get size(): number {
return this.#items.length - this.#head;
}
push(item: T): void {
this.#items.push(item);
}
peek(): T | undefined {
return this.#items[this.#head];
}
shift(): T | undefined {
if (this.#head >= this.#items.length) return undefined;
const item = this.#items[this.#head];
this.#items[this.#head] = undefined;
this.#head += 1;
// Compacting once half the slots are evicted keeps eviction amortized O(1).
if (this.#head * 2 >= this.#items.length) {
this.#items = this.#items.slice(this.#head);
this.#head = 0;
}
return item;
}
toArray(): T[] {
return this.#items.slice(this.#head) as T[];
}
}
+2 -114
View File
@@ -1,4 +1,4 @@
import { err, ok, type Result } from "../domain/result.js";
import { parseGhidraJavaProperties } from "./GhidraJavaProperties.js";
/** Ghidra build whose bridge behavior this REA release verifies. */
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
@@ -61,7 +61,7 @@ const GHIDRA_RELEASE_PATTERN = /^(\d+)\.(\d+)(?:\.(\d+))?([-+].*)?$/u;
export const ghidraApplicationProperties = (
content: string,
): GhidraApplicationProperties => {
const parsed = parseJavaProperties(content);
const parsed = parseGhidraJavaProperties(content);
if (!parsed.ok)
return {
providerVersion: null,
@@ -274,115 +274,3 @@ const unresolvedJavaRequirement = (
});
/** Parse Java Properties.load(InputStream) syntax from its ISO-8859-1 text. */
const parseJavaProperties = (
content: string,
): Result<ReadonlyMap<string, string>, string> => {
const values = new Map<string, string>();
for (const line of logicalPropertyLines(content)) {
let start = 0;
while (isPropertyWhitespace(line[start])) start += 1;
if (start === line.length || line[start] === "#" || line[start] === "!")
continue;
let end = start;
let escaped = false;
while (end < line.length) {
const character = line[end];
if (
!escaped &&
(character === "=" ||
character === ":" ||
isPropertyWhitespace(character))
)
break;
if (character === "\\") escaped = !escaped;
else escaped = false;
end += 1;
}
let valueStart = end;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
if (line[valueStart] === "=" || line[valueStart] === ":") valueStart += 1;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
const key = decodePropertyEscapes(line.slice(start, end));
if (!key.ok) return err(key.error);
const value = decodePropertyEscapes(line.slice(valueStart));
if (!value.ok) return err(value.error);
values.set(key.value, value.value);
}
return ok(values);
};
const isPropertyWhitespace = (value: string | undefined): boolean =>
value === " " || value === "\t" || value === "\f";
/** Join odd-backslash continuations while stripping leading continuation space. */
function* logicalPropertyLines(content: string): Generator<string> {
let physicalStart = 0;
let logical = "";
let continuing = false;
while (physicalStart <= content.length) {
let physicalEnd = physicalStart;
while (
physicalEnd < content.length &&
content[physicalEnd] !== "\n" &&
content[physicalEnd] !== "\r"
)
physicalEnd += 1;
let line = content.slice(physicalStart, physicalEnd);
let leading = 0;
while (isPropertyWhitespace(line[leading])) leading += 1;
const comment =
!continuing && (line[leading] === "#" || line[leading] === "!");
if (continuing) line = line.slice(leading);
let continued = false;
if (!comment) {
let slashes = 0;
for (
let index = line.length - 1;
index >= 0 && line[index] === "\\";
index -= 1
)
slashes += 1;
continued = slashes % 2 === 1;
logical += continued ? line.slice(0, -1) : line;
}
if (!continued) {
yield logical;
logical = "";
}
continuing = continued;
if (physicalEnd === content.length) break;
physicalStart =
content[physicalEnd] === "\r" && content[physicalEnd + 1] === "\n"
? physicalEnd + 2
: physicalEnd + 1;
}
// Properties.load still consumes the accumulated line when EOF follows a
// continuation marker; the marker itself was already removed above.
if (continuing) yield logical;
}
const decodePropertyEscapes = (value: string): Result<string, string> => {
let result = "";
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (character !== "\\") {
result += character;
continue;
}
const escaped = value[++index];
if (escaped === undefined)
return err("Trailing escape in Java properties value");
if (escaped === "t") result += "\t";
else if (escaped === "n") result += "\n";
else if (escaped === "r") result += "\r";
else if (escaped === "f") result += "\f";
else if (escaped === "u") {
const digits = value.slice(index + 1, index + 5);
if (digits.length !== 4 || !/^[0-9a-f]{4}$/iu.test(digits))
return err("Malformed Unicode escape in Java properties file");
result += String.fromCharCode(Number.parseInt(digits, 16));
index += 4;
} else result += escaped;
}
return ok(result);
};
+115
View File
@@ -0,0 +1,115 @@
import { err, ok, type Result } from "../domain/result.js";
/** Parse Java Properties.load(InputStream) syntax from its ISO-8859-1 text. */
export const parseGhidraJavaProperties = (
content: string,
): Result<ReadonlyMap<string, string>, string> => {
const values = new Map<string, string>();
for (const line of logicalPropertyLines(content)) {
let start = 0;
while (isPropertyWhitespace(line[start])) start += 1;
if (start === line.length || line[start] === "#" || line[start] === "!")
continue;
let end = start;
let escaped = false;
while (end < line.length) {
const character = line[end];
if (
!escaped &&
(character === "=" ||
character === ":" ||
isPropertyWhitespace(character))
)
break;
if (character === "\\") escaped = !escaped;
else escaped = false;
end += 1;
}
let valueStart = end;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
if (line[valueStart] === "=" || line[valueStart] === ":") valueStart += 1;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
const key = decodePropertyEscapes(line.slice(start, end));
if (!key.ok) return err(key.error);
const value = decodePropertyEscapes(line.slice(valueStart));
if (!value.ok) return err(value.error);
values.set(key.value, value.value);
}
return ok(values);
};
const isPropertyWhitespace = (value: string | undefined): boolean =>
value === " " || value === "\t" || value === "\f";
/** Join odd-backslash continuations while stripping leading continuation space. */
function* logicalPropertyLines(content: string): Generator<string> {
let physicalStart = 0;
let logical = "";
let continuing = false;
while (physicalStart <= content.length) {
let physicalEnd = physicalStart;
while (
physicalEnd < content.length &&
content[physicalEnd] !== "\n" &&
content[physicalEnd] !== "\r"
)
physicalEnd += 1;
let line = content.slice(physicalStart, physicalEnd);
let leading = 0;
while (isPropertyWhitespace(line[leading])) leading += 1;
const comment =
!continuing && (line[leading] === "#" || line[leading] === "!");
if (continuing) line = line.slice(leading);
let continued = false;
if (!comment) {
let slashes = 0;
for (
let index = line.length - 1;
index >= 0 && line[index] === "\\";
index -= 1
)
slashes += 1;
continued = slashes % 2 === 1;
logical += continued ? line.slice(0, -1) : line;
}
if (!continued) {
yield logical;
logical = "";
}
continuing = continued;
if (physicalEnd === content.length) break;
physicalStart =
content[physicalEnd] === "\r" && content[physicalEnd + 1] === "\n"
? physicalEnd + 2
: physicalEnd + 1;
}
// Properties.load still consumes the accumulated line when EOF follows a
// continuation marker; the marker itself was already removed above.
if (continuing) yield logical;
}
const decodePropertyEscapes = (value: string): Result<string, string> => {
let result = "";
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (character !== "\\") {
result += character;
continue;
}
const escaped = value[++index];
if (escaped === undefined)
return err("Trailing escape in Java properties value");
if (escaped === "t") result += "\t";
else if (escaped === "n") result += "\n";
else if (escaped === "r") result += "\r";
else if (escaped === "f") result += "\f";
else if (escaped === "u") {
const digits = value.slice(index + 1, index + 5);
if (digits.length !== 4 || !/^[0-9a-f]{4}$/iu.test(digits))
return err("Malformed Unicode escape in Java properties file");
result += String.fromCharCode(Number.parseInt(digits, 16));
index += 4;
} else result += escaped;
}
return ok(result);
};
+12 -11
View File
@@ -13,6 +13,7 @@ import {
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
import { parseGhidraJavaProperties } from "./GhidraJavaProperties.js";
/** Installed processor code and data, distinct from REA's analysis-extension ABI. */
export const ghidraPspExtensionSchema = z.strictObject({
@@ -88,7 +89,7 @@ export const inspectGhidraPspExtension = async (
throw new Error("The installed Allegrex extension has no loader JAR.");
const hash = createHash("sha256");
let bytesRead = 0;
let properties = "";
let properties = Buffer.alloc(0);
for (const relative of files) {
signal?.throwIfAborted();
const path = join(root, relative);
@@ -135,22 +136,22 @@ export const inspectGhidraPspExtension = async (
);
bytesRead += before.size;
if (relative === "extension.properties")
properties = Buffer.concat(chunks).toString("utf8");
properties = Buffer.concat(chunks);
} finally {
await handle.close();
}
}
// Ghidra's extension.properties version is the compatible Ghidra version,
// not the extension release (e.g. v21.4); content identity supplies the latter.
const property = (name: string): string => {
const values = properties.split(/\r?\n/u).flatMap((line) => {
const match = /^\s*([A-Za-z][A-Za-z0-9]*)\s*=\s*(.*?)\s*$/u.exec(line);
return match?.[1] === name ? [match[2] ?? ""] : [];
});
if (values.length !== 1)
throw new Error(`Allegrex extension must declare exactly one ${name}.`);
return values[0] ?? "";
};
const parsedProperties = parseGhidraJavaProperties(
properties.toString("latin1"),
);
if (!parsedProperties.ok)
throw new Error(
`Invalid Allegrex extension properties: ${parsedProperties.error}`,
);
const property = (name: string): string | undefined =>
parsedProperties.value.get(name);
if (
property("name") !== "ghidra-allegrex" ||
property("version") !== ghidraVersion
+1 -1
View File
@@ -279,6 +279,6 @@ export const checkRecoveryDeadline = (
signal?: AbortSignal,
): void => {
checkRecoveryCancellation(signal);
if (Date.now() >= deadline)
if (performance.now() >= deadline)
throw new AnalysisTimeoutError(OPERATION, RECOVERY_LIMITS.timeoutMs);
};
@@ -33,7 +33,7 @@ it("rejects an exhausted shared execution budget before launching the next comma
arguments: ["--version"],
cwd: "/tmp/unused",
environment: {},
deadline: Date.now() - 1,
deadline: performance.now() - 1,
launcher: async () => {
throw new Error("An expired budget must not launch");
},
@@ -52,7 +52,7 @@ it("preserves caller cancellation before acquiring an expired execution budget",
arguments: ["--version"],
cwd: "/tmp/unused",
environment: {},
deadline: Date.now() - 1,
deadline: performance.now() - 1,
signal: AbortSignal.abort(),
launcher: async () => {
throw new Error("A cancelled request must not launch");
@@ -86,7 +86,7 @@ const commandFixture = (
arguments: ["--version"],
cwd: "/tmp/unused",
environment: {},
deadline: Date.now() + 5_000,
deadline: performance.now() + 5_000,
launcher,
},
};
@@ -140,7 +140,7 @@ it("enforces the shared deadline while exited output streams remain open", async
});
try {
await expect(
runWakaruCommand({ ...context, deadline: Date.now() + 50 }),
runWakaruCommand({ ...context, deadline: performance.now() + 50 }),
).rejects.toMatchObject({
_tag: "AnalysisTimeoutError",
operation: "recover_javascript_sources",
+2 -2
View File
@@ -100,7 +100,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
let tree: SafeOutputTree | undefined;
let failed: { readonly cause: unknown } | undefined;
let execution: AnalysisExecution | undefined;
const deadline = Date.now() + RECOVERY_LIMITS.timeoutMs;
const deadline = performance.now() + RECOVERY_LIMITS.timeoutMs;
try {
checkRecoveryCancellation(options?.signal);
const engine = await resolveWakaruCommand(this.environment);
@@ -139,7 +139,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
await rm(root, { recursive: true, force: true });
root = undefined;
checkRecoveryDeadline(deadline, options?.signal);
await tree.commit();
await tree.commit(options?.signal);
} catch (cause: unknown) {
failed = { cause };
}
+73 -73
View File
@@ -1,6 +1,7 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { Formatter, Help, z } from "incur";
import { performance } from "node:perf_hooks";
import { resolve } from "node:path";
import { CATALOG_IDENTITY } from "./catalogIdentity.js";
@@ -74,14 +75,15 @@ interface McpDoctorCheck {
/** Diagnose the actual production stdio adapter with one startup-bounded SDK session. */
export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
const deadline =
Date.now() + (options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs);
performance.now() +
(options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs);
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(new Error("Production MCP doctor deadline expired")),
Math.max(1, deadline - Date.now()),
Math.max(1, Math.ceil(deadline - performance.now())),
);
const stderr = captureStderr();
const transport = new TrackedStdioClientTransport({
const transport = new OwnedStdioClientTransport({
command: options.command,
args: [...options.args],
cwd: options.cwd,
@@ -90,21 +92,20 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
});
transport.stderr?.on("data", stderr.append);
const client = new Client({ name: "rea-mcp-doctor", version: "1" });
let result: ProductionMcpDoctorResult;
let cleanupFailure: { readonly cause: unknown } | undefined;
try {
await client.connect(
transport,
requestOptions(deadline, controller.signal),
);
return {
...(await inspectProductionMcpSession(
client,
deadline,
controller.signal,
)),
diagnostics: stderr.value(),
};
result = await inspectProductionMcpSession(
client,
deadline,
controller.signal,
);
} catch (cause: unknown) {
return {
result = {
healthy: false,
adapter: "production-stdio" as const,
server: null,
@@ -118,14 +119,71 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
detail: errorMessage(cause),
},
],
diagnostics: stderr.value(),
};
} finally {
clearTimeout(timer);
await closeMcpChild(client, transport);
try {
await client.close();
} catch (cause: unknown) {
cleanupFailure = { cause };
}
try {
// An interrupted connect can clear the client's transport reference
// before its startup child is closed. The transport retains that child.
await transport.close();
} catch (cause: unknown) {
cleanupFailure = {
cause:
cleanupFailure === undefined || cleanupFailure.cause === cause
? cause
: new AggregateError(
[cleanupFailure.cause, cause],
`MCP client and transport cleanup failed: ${errorMessage(cleanupFailure.cause)}; ${errorMessage(cause)}`,
),
};
}
}
if (cleanupFailure !== undefined)
result = {
...result,
healthy: false,
checks: [
...result.checks,
{
name: "cleanup",
ok: false,
detail: `MCP stdio cleanup failed: ${errorMessage(cleanupFailure.cause)}`,
},
],
};
return { ...result, diagnostics: stderr.value() };
};
type ProductionMcpDoctorResult =
| Awaited<ReturnType<typeof inspectProductionMcpSession>>
| {
readonly healthy: false;
readonly adapter: "production-stdio";
readonly server: null;
readonly inventory: null;
readonly identity: null;
readonly request_flow: {
readonly tool: "binary_session";
readonly ok: false;
};
readonly checks: readonly McpDoctorCheck[];
};
/** Join SDK-triggered and caller-triggered close calls for the same child. */
class OwnedStdioClientTransport extends StdioClientTransport {
#closePromise: Promise<void> | undefined;
override close(): Promise<void> {
this.#closePromise ??= super.close();
return this.#closePromise;
}
}
const inspectProductionMcpSession = async (
client: Client,
deadline: number,
@@ -385,7 +443,7 @@ const isOutputFormat = (value: string | undefined): value is OutputFormat =>
const requestOptions = (deadline: number, signal: AbortSignal) => ({
signal,
timeout: Math.max(1, deadline - Date.now()),
timeout: Math.max(1, Math.ceil(deadline - performance.now())),
});
const targetFreeEnvironment = (
@@ -428,61 +486,3 @@ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
class TrackedStdioClientTransport extends StdioClientTransport {
spawnedPid: number | null = null;
override async start(): Promise<void> {
await super.start();
this.spawnedPid = this.pid;
}
}
const closeMcpChild = async (
client: Client,
transport: TrackedStdioClientTransport,
): Promise<void> => {
const pid = transport.spawnedPid ?? transport.pid;
await Promise.allSettled([client.close()]);
await Promise.allSettled([transport.close()]);
if (pid === null || !(await processExists(pid))) return;
await terminateProcess(pid, "SIGTERM");
if (await waitForProcessExit(pid, 1_000)) return;
await terminateProcess(pid, "SIGKILL");
await waitForProcessExit(pid, 1_000);
};
const terminateProcess = async (
pid: number,
signal: NodeJS.Signals,
): Promise<void> => {
try {
process.kill(pid, signal);
} catch (cause: unknown) {
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
throw cause;
}
};
const waitForProcessExit = async (
pid: number,
timeoutMs: number,
): Promise<boolean> => {
const deadline = Date.now() + timeoutMs;
do {
if (!(await processExists(pid))) return true;
await new Promise<void>((resolve) => setTimeout(resolve, 20));
} while (Date.now() < deadline);
return !(await processExists(pid));
};
const processExists = async (pid: number): Promise<boolean> => {
try {
process.kill(pid, 0);
return true;
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ESRCH")
return false;
throw cause;
}
};
+18 -1
View File
@@ -4,6 +4,7 @@ import { createReadStream } from "node:fs";
import { realpath } from "node:fs/promises";
import { err, ok, type Result } from "../domain/result.js";
import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js";
import {
OwnedCommandFailure,
runOwnedCommand,
@@ -39,6 +40,7 @@ export interface NativeCommandCapture {
export class NativeCommandFailure extends Error {
readonly cleanupOwner: ProviderProcessSupervisor | undefined;
readonly cleanupFailures: readonly NativeCommandCleanupFailure[];
readonly detail: string | null;
constructor(
readonly tool: string,
@@ -58,6 +60,7 @@ export class NativeCommandFailure extends Error {
super(`Native command ${tool} failed: ${reason}`, options);
this.cleanupOwner = options?.cleanupOwner;
this.cleanupFailures = options?.cleanupFailures ?? [];
this.detail = options?.detail ?? null;
}
}
@@ -67,6 +70,8 @@ export interface NativeCommandFailureOptions extends ErrorOptions {
readonly cleanupOwner?: ProviderProcessSupervisor;
/** All owners still incomplete after a preflight retry blocked this command. */
readonly cleanupFailures?: readonly NativeCommandCleanupFailure[];
/** Host-side reason the command could not be supervised, such as a missing ownership helper compiler. */
readonly detail?: string;
}
/** One failed cleanup attempt; the runner retains `owner` until it is verified stopped. */
@@ -310,6 +315,9 @@ export const resolveXcrunTool = async (
...(found.error.cleanupFailures.length === 0
? {}
: { cleanupFailures: found.error.cleanupFailures }),
...(found.error.detail === null
? {}
: { detail: found.error.detail }),
},
found.error.capture,
found.error.cleanupFailure,
@@ -449,7 +457,16 @@ const captureProcess = async (
),
);
}
return err(new NativeCommandFailure(tool, "io", null, { cause }));
return err(
new NativeCommandFailure(tool, "io", null, {
cause,
// Process supervision needs the Darwin ownership helper; its typed
// message names the compiler or SDK prerequisite to fix.
...(cause instanceof DarwinProcessOwnershipInspectionError
? { detail: cause.message }
: {}),
}),
);
}
};
+1
View File
@@ -966,6 +966,7 @@ const translateCommandFailure = (
signal: failure.capture?.signal ?? null,
stdout_bytes: failure.capture?.stdoutBytes ?? 0,
stderr_bytes: failure.capture?.stderrBytes ?? 0,
...(failure.detail === null ? {} : { detail: failure.detail }),
},
});
};
+35
View File
@@ -0,0 +1,35 @@
import { afterEach, expect, it, vi } from "vitest";
import { ProviderStartupDeadline } from "./ProviderDeadline.js";
afterEach(() => {
vi.restoreAllMocks();
});
it("keeps remaining time and cancellation classification stable across wall-clock jumps", () => {
const dateNow = vi.spyOn(Date, "now").mockReturnValue(10_000);
const caller = new AbortController();
const deadline = new ProviderStartupDeadline(10_000, caller.signal);
try {
dateNow.mockReturnValue(9_000_000_000_000);
const remaining = deadline.remainingMs();
expect(remaining).toBeGreaterThan(0);
expect(remaining).toBeLessThanOrEqual(10_000);
expect(Number.isInteger(remaining)).toBe(true);
expect(deadline.interruption).toBeUndefined();
caller.abort(new Error("caller stopped startup"));
expect(deadline.interruption).toBe("cancelled");
} finally {
deadline.dispose();
}
});
it("aborts a bounded wait when its real monotonic deadline expires", async () => {
const deadline = new ProviderStartupDeadline(40);
try {
await expect(deadline.wait(500)).resolves.toBe("aborted");
expect(deadline.interruption).toBe("timeout");
expect(deadline.remainingMs()).toBe(0);
} finally {
deadline.dispose();
}
});
+4 -4
View File
@@ -42,11 +42,11 @@ export class ProviderStartupDeadline {
) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
throw new RangeError("Provider startup timeout must be positive");
this.#deadlineAt = Date.now() + timeoutMs;
this.#deadlineAt = performance.now() + timeoutMs;
this.#externalSignal = signal;
this.#onExternalAbort = () => {
if (this.#controller.signal.aborted) return;
if (Date.now() >= this.#deadlineAt) {
if (performance.now() >= this.#deadlineAt) {
this.#interruption = "timeout";
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
@@ -79,13 +79,13 @@ export class ProviderStartupDeadline {
get interruption(): "cancelled" | "timeout" | undefined {
return (
this.#interruption ??
(Date.now() >= this.#deadlineAt ? "timeout" : undefined)
(performance.now() >= this.#deadlineAt ? "timeout" : undefined)
);
}
/** Milliseconds still available to the next startup phase. */
remainingMs(): number {
return Math.max(0, this.#deadlineAt - Date.now());
return Math.max(0, Math.ceil(this.#deadlineAt - performance.now()));
}
/** Wait for at most one polling interval under the shared deadline signal. */
@@ -0,0 +1,3 @@
/** Keep wall-clock timestamps separate from capture-relative elapsed time. */
export const monotonicProcessCaptureClock = (): number =>
Math.floor(performance.now());
+5 -1
View File
@@ -13,6 +13,7 @@ import type {
ProcessCaptureEventJournalEntry,
RecordProcessCaptureEvent,
} from "../../domain/process/processCapture.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
/** Mutable observation-order ledger whose writer is shared by capture producers. */
export interface ProcessCaptureJournal {
readonly entries: readonly ProcessCaptureEventJournalEntry[];
@@ -55,7 +56,10 @@ export const scheduleScenarioInteractions = (
const timer = scheduleProcessDelay(event.at_ms, () => {
options.dispatchedEventIndexes.add(eventIndex);
const terminal = getTerminal();
const dispatchedAt = Math.max(0, Date.now() - started);
const dispatchedAt = Math.max(
0,
monotonicProcessCaptureClock() - started,
);
let outcome: InteractionEvent["outcome"] = "dispatched";
if (terminal === undefined) outcome = "target_exited";
else {
@@ -5,6 +5,7 @@ import { parseProcessScenario } from "../../domain/process/processScenario.js";
import type { ProcessCaptureFinalization } from "../../domain/process/processCapture.js";
import { awaitTerminalExit } from "./ProcessCaptureLifecycle.js";
import type { ProcessTimer } from "./ProcessTimer.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
type Delivery = ProcessCaptureFinalization["signals"][number]["delivery"];
@@ -79,8 +80,8 @@ const start = (
idle_timeout_ms: 10_000,
...scenario,
}),
started: Date.now(),
lastOutput: () => Date.now(),
started: monotonicProcessCaptureClock(),
lastOutput: monotonicProcessCaptureClock,
signal,
signalTarget: fake.signalTarget,
recordFinalization: (snapshot) => {
+53 -21
View File
@@ -48,6 +48,7 @@ import {
type ProcessCaptureTruncationDetails,
} from "../../domain/process/processCaptureCoverage.js";
import { scheduleProcessInterval, type ProcessTimer } from "./ProcessTimer.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
import type {
FilesystemCheckpoint,
@@ -266,10 +267,10 @@ export const settleProcessCaptureJournal = async (
quietMs = 25,
maxWaitMs = 500,
): Promise<void> => {
const deadline = Date.now() + maxWaitMs;
const deadline = monotonicProcessCaptureClock() + maxWaitMs;
let observed = journal.length;
let lastChangeAt = Date.now();
while (Date.now() < deadline) {
let lastChangeAt = monotonicProcessCaptureClock();
while (monotonicProcessCaptureClock() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 4));
// A stalled event loop can leave timer and poll callbacks that were already
// due queued behind this wake-up. Drain them before judging silence so a
@@ -277,8 +278,8 @@ export const settleProcessCaptureJournal = async (
await setImmediate();
if (journal.length !== observed) {
observed = journal.length;
lastChangeAt = Date.now();
} else if (Date.now() - lastChangeAt >= quietMs) return;
lastChangeAt = monotonicProcessCaptureClock();
} else if (monotonicProcessCaptureClock() - lastChangeAt >= quietMs) return;
}
};
@@ -337,6 +338,12 @@ export const buildCaptureResult = (
truncation_details: options.truncationDetails,
limitations: [
"The executable digest is a prelaunch file sample; matching path metadata immediately after spawn does not prove an atomic operating-system image binding.",
...(Date.parse(options.manifest.completed_at) <
Date.parse(options.manifest.started_at)
? [
"Wall-clock completion time precedes start time; elapsed capture timing is recorded separately and remains monotonic.",
]
: []),
"Process trees are sampled and may omit short-lived descendants.",
...(options.samplingPartial
? ["Process-tree sampling ended with an incomplete observation."]
@@ -660,7 +667,7 @@ export const observeSettlement = async (
recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: 0 };
}
const started = Date.now();
const started = monotonicProcessCaptureClock();
let consecutiveEmpty = 0;
let sawLive = false;
let deadlineReached = false;
@@ -678,19 +685,25 @@ export const observeSettlement = async (
[...observations.values()].some(({ state }) => state === "unverifiable")
) {
recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: Date.now() - started };
return {
state: "unverifiable",
elapsed_ms: monotonicProcessCaptureClock() - started,
};
}
if ([...observations.values()].every(({ state }) => state === "empty")) {
consecutiveEmpty += 1;
if (consecutiveEmpty >= 2) {
recordEvent("lifecycle", 1);
return { state: "quiesced", elapsed_ms: Date.now() - started };
return {
state: "quiesced",
elapsed_ms: monotonicProcessCaptureClock() - started,
};
}
} else {
consecutiveEmpty = 0;
sawLive = true;
}
deadlineReached = Date.now() - started >= settleMs;
deadlineReached = monotonicProcessCaptureClock() - started >= settleMs;
if (deadlineReached) break;
await delay(50, undefined, { signal });
}
@@ -698,8 +711,14 @@ export const observeSettlement = async (
// A lone empty observation proves neither liveness nor quiescence; only an
// observed live member justifies alive_at_deadline.
return sawLive
? { state: "alive_at_deadline", elapsed_ms: Date.now() - started }
: { state: "unverifiable", elapsed_ms: Date.now() - started };
? {
state: "alive_at_deadline",
elapsed_ms: monotonicProcessCaptureClock() - started,
}
: {
state: "unverifiable",
elapsed_ms: monotonicProcessCaptureClock() - started,
};
};
/** Name why an attempt is unverified; a blank message never reaches the capture schema. */
@@ -786,7 +805,10 @@ export const awaitTerminalExit = async ({
if (finalizationStartedAt === undefined) return;
const record: (typeof finalizationSignals)[number] = {
signal: finalizationSignal,
sent_at_ms: Math.round(performance.now() - finalizationStartedAt),
sent_at_ms: Math.max(
0,
monotonicProcessCaptureClock() - finalizationStartedAt,
),
delivery: "unverified" as FinalizationDelivery,
reason: "delivery had not settled when the record was published",
};
@@ -856,7 +878,7 @@ export const awaitTerminalExit = async ({
terminal.kill("SIGKILL");
return;
}
finalizationStartedAt = performance.now();
finalizationStartedAt = monotonicProcessCaptureClock();
attempt("SIGTERM");
};
terminal.onExit((exit) => {
@@ -867,7 +889,7 @@ export const awaitTerminalExit = async ({
const finalizationElapsedMs =
finalizationStartedAt === undefined
? undefined
: Math.round(performance.now() - finalizationStartedAt);
: Math.max(0, monotonicProcessCaptureClock() - finalizationStartedAt);
recordEvent("lifecycle", 0);
for (const [eventIndex, event] of scenario.events.entries()) {
if (dispatchedEventIndexes.has(eventIndex)) continue;
@@ -875,7 +897,10 @@ export const awaitTerminalExit = async ({
interactions.push({
sequence,
scheduled_at_ms: event.at_ms,
dispatched_at_ms: Math.max(0, Date.now() - started),
dispatched_at_ms: Math.max(
0,
monotonicProcessCaptureClock() - started,
),
type: event.type,
data:
event.type === "input"
@@ -935,14 +960,20 @@ export const awaitTerminalExit = async ({
forceKill();
} else if (finalizationStartedAt !== undefined) {
if (
performance.now() - finalizationStartedAt >=
monotonicProcessCaptureClock() - finalizationStartedAt >=
scenario.finalization_ms
)
forceKill();
} else if (Date.now() - started >= scenario.timeout_ms) {
} else if (
monotonicProcessCaptureClock() - started >=
scenario.timeout_ms
) {
reason = "timeout";
terminateAtDeadline();
} else if (Date.now() - lastOutput() >= scenario.idle_timeout_ms) {
} else if (
monotonicProcessCaptureClock() - lastOutput() >=
scenario.idle_timeout_ms
) {
reason = "idle_timeout";
terminateAtDeadline();
}
@@ -971,10 +1002,11 @@ const PROCESS_CLEANUP_VERIFICATION_INTERVAL_MS = 25;
const verifyTokenOwnedProcessesUntilSettled = async (
verify: () => Promise<ProcessCleanupResult>,
): Promise<ProcessCleanupResult> => {
const deadline = Date.now() + PROCESS_CLEANUP_VERIFICATION_GRACE_MS;
const deadline =
monotonicProcessCaptureClock() + PROCESS_CLEANUP_VERIFICATION_GRACE_MS;
let result = await verify();
while (!result.cleaned) {
const remaining = deadline - Date.now();
const remaining = deadline - monotonicProcessCaptureClock();
if (remaining <= 0) return result;
await new Promise<void>((resolve) =>
setTimeout(
@@ -1288,7 +1320,7 @@ export const captureTerminalFrames = (options: {
}
outputBytes += bytes;
const atMs = normalizeProcessElapsedTime(
Date.now() - options.started,
monotonicProcessCaptureClock() - options.started,
options.scenario.normalization.time_bucket_ms,
);
const normalized = normalizeProcessText(
@@ -1,4 +1,5 @@
import type { ProcessCaptureCleanupReport } from "../../domain/process/processCapture.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
/**
* Progress port accepted by process capture.
@@ -61,7 +62,7 @@ const formatProgressMessage = (
/** Serialize observed capture status through one rate-limited reporter. */
export const createProcessCaptureProgressTracker = (
progress: ProcessCaptureProgress | undefined,
now: () => number = Date.now,
now: () => number = monotonicProcessCaptureClock,
) => {
const started = now();
let completed = 0;
+4 -3
View File
@@ -70,6 +70,7 @@ import {
observeProcessStartIdentity,
signalProcessWithStartIdentity,
} from "../ProcessOwnershipObservation.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
interface StartedCaptureRuntime {
readonly renderer: TerminalRenderer;
@@ -268,7 +269,7 @@ const startCaptureRuntime = async (
options.signal,
);
const startedAt = new Date();
const started = Date.now();
const started = monotonicProcessCaptureClock();
let lastOutput = started;
renderer = createTerminalRenderer(
scenario,
@@ -296,7 +297,7 @@ const startCaptureRuntime = async (
...options,
terminal,
started,
onOutput: () => (lastOutput = Date.now()),
onOutput: () => (lastOutput = monotonicProcessCaptureClock()),
renderer,
});
scheduleScenarioInteractions({
@@ -541,7 +542,7 @@ const completeCapture = async (options: {
},
{
name: "after_settlement",
at_ms: Math.max(0, Date.now() - runtime.started),
at_ms: Math.max(0, monotonicProcessCaptureClock() - runtime.started),
files: after.files,
effects: classifyFilesystemEffects(options.before, after),
truncated: after.truncated,
+2 -1
View File
@@ -6,6 +6,7 @@ import type {
} from "../../domain/process/processCapture.js";
import { execFileOutput } from "../ExecFileOutput.js";
import { readProcessRunId } from "../ProcessOwnership.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
const PROC_READ_CONCURRENCY = 64;
interface ProcessRow {
@@ -491,7 +492,7 @@ export const startProcessSampler = (options: {
}
return sampleProcesses({
rootPid,
elapsedMs: Date.now() - started,
elapsedMs: monotonicProcessCaptureClock() - started,
limit: limit + 1,
identities,
signal: controller.signal,
+2 -3
View File
@@ -54,6 +54,7 @@ import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
import { registerApplicationTools } from "./registerApplicationTools.js";
import { registerArtifactTools } from "./registerArtifactTools.js";
import { registerNativeTools } from "./registerNativeTools.js";
import { registerBrowserScenarioTool } from "./registerBrowserScenarioTool.js";
import { registerBrowserTools } from "./registerBrowserTools.js";
import { registerWebScriptTool } from "./registerWebScriptTool.js";
@@ -107,8 +108,6 @@ import type { AdbDeviceAnalysisPort } from "../application/adb/AdbDeviceAnalysis
import { AdbDeviceAnalysisService } from "../application/adb/AdbDeviceAnalysisService.js";
import { createAdbDeviceAnalysisProvider } from "../composition/adb.js";
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js";
import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js";
import { registerEvidenceTools } from "./registerEvidenceTools.js";
import { registerOfficialTools } from "./registerOfficialTools.js";
import { registerGuidedPrompts } from "./registerPrompts.js";
import { registerSessionTools } from "./registerSessionTools.js";
@@ -725,7 +724,7 @@ const registerBinaryAnalysisTools = ({
recordEvidence,
withAdmittedAnalysis,
};
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, evidenceOptions);
registerNativeTools(server, { ...evidenceOptions, evidenceById });
registerArtifactTools(server, { ...evidenceOptions, evidenceById });
registerManagedTools(server, { ...evidenceOptions, evidenceById });
if (session !== undefined)
+13 -5
View File
@@ -6,7 +6,10 @@ import {
artifactInspectionInputSchema,
} from "../contracts/artifactToolContracts.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import { summarizeRetainedAnalysis } from "../application/analysisView/AnalysisViewService.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
import { ok } from "../domain/result.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
@@ -25,6 +28,10 @@ export const registerArtifactTools = (
readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis;
},
): void => {
const retention = {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
};
registerEvidenceTools(server, ARTIFACT_TOOL_CONTRACTS, {
...options,
parametersForExecution: (operation, parameters) => {
@@ -37,12 +44,13 @@ export const registerArtifactTools = (
? { ...parameters, output_root: createArtifactExtractionDestination() }
: parameters;
},
preflight: (operation, parameters) =>
operation === "inspect_artifact" && parameters.detail === "summary"
? requireAnalysisViewRetention(operation, retention)
: ok(null),
projectEvidence: (operation, parameters, evidence) =>
operation === "inspect_artifact" && parameters.detail === "summary"
? summarizeRetainedAnalysis(evidence, {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
})
? summarizeRetainedAnalysis(evidence, retention)
: ok(evidence),
sourceEvidence: (operation, result) =>
operation === "inspect_artifact"
+19 -1
View File
@@ -33,6 +33,16 @@ interface EvidenceToolRegistration {
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
) => Readonly<Record<string, JsonValue>>;
/** Exclude adapter-only selections, such as delivery detail, from Evidence identity. */
readonly parametersForEvidence?: (
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
) => Readonly<Record<string, JsonValue>>;
/** Refuse an unsatisfiable delivery selection before any analysis runs. */
readonly preflight?: (
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
) => Result<unknown, AnalysisError>;
readonly projectEvidence?: (
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
@@ -51,6 +61,12 @@ export const registerEvidenceTools = (
contract.name,
toolRegistrationOptions(contract),
async (input, context) => {
const ready = options.preflight?.(
contract.name,
jsonObjectSchema.parse(input),
);
if (ready !== undefined && !ready.ok)
return server.delivery.toCallToolResult(ready, contract);
const admitted = await options.withAdmittedAnalysis(
contract.name,
context.mcpReq.signal,
@@ -95,7 +111,9 @@ export const registerEvidenceTools = (
execution.value.provider,
{
operation: contract.name,
parameters,
parameters:
options.parametersForEvidence?.(contract.name, parameters) ??
parameters,
result: execution.value.result,
...(execution.value.analysisProfile === undefined
? {}
+54
View File
@@ -0,0 +1,54 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ok } from "../domain/result.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { Logger } from "pino";
import { registerEvidenceTools } from "./registerEvidenceTools.js";
/** Delivery detail selects a response shape; it never reaches the tools or Evidence identity. */
const withoutDelivery = (
operation: string,
parameters: Readonly<Record<string, JsonValue>>,
): Readonly<Record<string, JsonValue>> => {
if (operation !== "inspect_macho") return parameters;
const { detail: _detail, ...selected } = parameters;
return selected;
};
/** Register macOS native contracts; Mach-O inspection can deliver a retained summary. */
export const registerNativeTools = (
server: EvidenceMcpServer,
options: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly evidenceById?: EvidenceLookup | undefined;
readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis;
},
): void => {
const retention = {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
};
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, {
...options,
parametersForExecution: withoutDelivery,
parametersForEvidence: withoutDelivery,
preflight: (operation, parameters) =>
operation === "inspect_macho" && parameters.detail === "summary"
? requireAnalysisViewRetention(operation, retention)
: ok(null),
projectEvidence: (operation, parameters, evidence) =>
operation === "inspect_macho" && parameters.detail === "summary"
? summarizeRetainedAnalysis(evidence, retention)
: ok(evidence),
});
};
+56 -38
View File
@@ -26,6 +26,26 @@ class FixtureProcess extends EventEmitter implements ProviderProcessHandle {
}
}
const fixtureLauncher =
(process: FixtureProcess): JadxLauncher =>
async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
it("joins pending input errors before detaching the owned protocol stream", async () => {
let completeWrite: ((cause: Error) => void) | undefined;
const failure = new Error("owned pipe closed during cancellation");
@@ -70,26 +90,9 @@ it("joins pending input errors before detaching the owned protocol stream", asyn
it("decodes split UTF-8 and newline bytes, then routes multiple complete frames", async () => {
const process = new FixtureProcess();
const launcher: JadxLauncher = async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
launcher,
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
transport.onmessage = (message) => received.push(message);
@@ -98,7 +101,9 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
const first = {
jsonrpc: "2.0",
id: 1,
result: { content: [{ type: "text", text: "snow 雪 🦊" }] },
result: {
content: [{ type: "text", text: "snow 雪 🦊 and literal �" }],
},
} satisfies JSONRPCMessage;
const second = {
jsonrpc: "2.0",
@@ -120,28 +125,41 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
await transport.close();
});
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
it.each([
["invalid UTF-8 byte", Buffer.from([0xff])],
["truncated UTF-8 sequence", Buffer.from([0xe2, 0x82])],
])("rejects %s in a complete JSON-RPC frame", async (_label, invalid) => {
const process = new FixtureProcess();
const launcher: JadxLauncher = async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
launcher,
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
const errors: Error[] = [];
transport.onmessage = (message) => received.push(message);
transport.onerror = (cause) => errors.push(cause);
await transport.start();
process.stdout.write(
Buffer.concat([
Buffer.from('{"jsonrpc":"2.0","id":1,"result":{"text":"'),
invalid,
Buffer.from('"}}\n'),
]),
);
await new Promise<void>((resolve) => setImmediate(resolve));
await transport.close();
expect(received).toEqual([]);
expect(errors).toHaveLength(1);
expect(errors[0]?.message).toMatch(/encoded data was not valid/i);
});
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
const process = new FixtureProcess();
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
transport.onmessage = (message) => received.push(message);
@@ -191,12 +191,9 @@ describe.skipIf(process.platform === "win32")(
it.each([
["name=other\nversion=12.1.3\n", "does not match"],
["name=ghidra-allegrex\nversion=12.1.4\n", "does not match"],
[
"name=ghidra-allegrex\nversion=12.1.3\nversion=12.1.3\n",
"exactly one version",
],
["name=ghidra-allegrex\nversion=12.1.\\uZZZZ\n", "Unicode escape"],
])(
"rejects incompatible or ambiguous extension metadata %s",
"rejects mismatched or malformed extension metadata %s",
async (properties, reason) => {
const { root } = await installation();
await writeFile(join(root, "extension.properties"), properties);
@@ -504,3 +501,38 @@ describe.skipIf(process.platform === "win32")(
});
},
);
describe.skipIf(process.platform === "win32")(
"PSP extension property syntax",
() => {
it.each([
{
form: "escaped key and value with colon separator",
properties: "n\\u0061me : ghidra-allegrex\nver\\u0073ion=12.1.3\n",
},
{
form: "continued key and value lines",
properties: "name=ghidra-\\\n allegrex\nversion=12.1.\\\n 3\n",
},
{
form: "duplicate keys use the last value",
properties:
"name=wrong\nname=ghidra-allegrex\nversion=12.1.4\nversion=12.1.3\n",
},
])(
"accepts Java Properties $form and hashes raw bytes",
async ({ properties }) => {
const { root } = await installation();
const canonical = await inspectGhidraPspExtension(root, "12.1.3");
const latin1Properties = Buffer.from(
`${properties}author=caf\u00e9\n`,
"latin1",
);
await writeFile(join(root, "extension.properties"), latin1Properties);
const extension = await inspectGhidraPspExtension(root, "12.1.3");
expect(extension.id).toBe("ghidra-allegrex");
expect(extension.sha256).not.toBe(canonical.sha256);
},
);
},
);
@@ -10,6 +10,8 @@ const injectedFilesystemFailures = vi.hoisted(() => ({
closeNext: false,
blockCloseRetries: false,
chmodNext: false,
syncAbortAfter: undefined as AbortController | undefined,
syncCount: 0,
rootIdentityPath: undefined as string | undefined,
}));
@@ -44,6 +46,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
await close();
};
}
if (injectedFilesystemFailures.syncAbortAfter !== undefined) {
const sync = handle.sync.bind(handle);
handle.sync = async () => {
await sync();
injectedFilesystemFailures.syncCount += 1;
if (injectedFilesystemFailures.syncCount === 2)
injectedFilesystemFailures.syncAbortAfter?.abort();
};
}
return handle;
},
};
@@ -82,6 +93,34 @@ describe("safe artifact output close failures", () => {
},
);
it.skipIf(process.platform === "win32")(
"keeps the tree unpublished when cancellation arrives during commit durability",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-cancel-");
const output = join(parent, "unpublished");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("pending output");
await tree.write("file.txt", Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
const controller = new AbortController();
injectedFilesystemFailures.syncCount = 0;
injectedFilesystemFailures.syncAbortAfter = controller;
try {
await expect(tree.commit(controller.signal)).rejects.toMatchObject({
reason: "cancelled",
});
expect(tree.published).toBe(false);
} finally {
injectedFilesystemFailures.syncAbortAfter = undefined;
injectedFilesystemFailures.syncCount = 0;
}
expect(await tree.rollback()).toMatchObject({ status: "complete" });
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.skipIf(process.platform === "win32")(
"preserves setup failure when closing the staging handle also fails",
async () => {
@@ -0,0 +1,216 @@
import { silentLogger } from "../../../src/logger.js";
import { copyFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { inspectMachoSchema } from "../../../src/domain/native/nativeInspection.js";
import { createServer } from "../../../src/server/createServer.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { ok } from "../../../src/domain/result.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const evidenceOf = <Schema extends z.ZodType>(schema: Schema) =>
z.object({
evidence_id: z.string(),
parameters: z.record(z.string(), z.unknown()),
normalized_result: schema,
});
const countSchema = z.object({
returned: z.number(),
total: z.number().nullable(),
exhaustive: z.boolean(),
});
const summarySchema = z.object({
kind: z.literal("summary"),
parent_evidence_id: z.string(),
summary: z.object({
uuid: z.string().nullable(),
collections: z.record(z.string(), countSchema),
provenance_count: z.number(),
}),
});
const pageSchema = z.object({
kind: z.literal("macho"),
item: z.array(z.unknown()),
coverage: z.object({ next_offset: z.number().nullable() }),
});
describe.skipIf(process.platform !== "darwin")(
"Mach-O summary delivery through MCP",
() => {
mcpTest(
"retains complete inspect_macho Evidence and pages its exact rows",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-macho-summary-mcp-"),
"ls",
);
await copyFile("/bin/ls", target);
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: target },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const complete = await client.callTool({
name: "inspect_macho",
arguments: {},
});
expect(complete.isError, JSON.stringify(complete.content)).not.toBe(
true,
);
const full = evidenceOf(inspectMachoSchema).parse(
complete.structuredContent,
);
// Omitted detail keeps the default Evidence parameters unchanged.
expect(full.parameters).toEqual({});
const summarized = await client.callTool({
name: "inspect_macho",
arguments: { detail: "summary" },
});
expect(summarized.isError, JSON.stringify(summarized.content)).not.toBe(
true,
);
const summary = evidenceOf(summarySchema).parse(
summarized.structuredContent,
).normalized_result;
// Delivery detail never reaches the tools or the source Evidence ID.
expect(summary.parent_evidence_id).toBe(full.evidence_id);
const report = full.normalized_result;
expect(summary.summary.uuid).toBe(report.uuid);
expect(summary.summary.provenance_count).toBe(report.provenance.length);
for (const name of ["imports", "exports", "dependencies"] as const)
expect(summary.summary.collections[name]).toEqual({
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
});
expect(JSON.stringify(summarized.structuredContent)).not.toContain(
report.imports.items[0]?.name ?? "_",
);
// Every facet must reassemble the unparsed complete rows exactly.
const raw = z
.object({ normalized_result: z.record(z.string(), z.unknown()) })
.parse(complete.structuredContent).normalized_result;
const facets = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
"provenance",
] as const;
for (const facet of facets) {
const rows: unknown[] = [];
let offset: number | null = 0;
while (offset !== null) {
const paged = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "macho", facet, offset, limit: 16 },
},
});
expect(paged.isError, JSON.stringify(paged.content)).not.toBe(true);
const page = evidenceOf(pageSchema).parse(
paged.structuredContent,
).normalized_result;
rows.push(...page.item);
offset = page.coverage.next_offset;
}
expect(rows, facet).toEqual(
facet === "provenance"
? raw.provenance
: z.object({ items: z.array(z.unknown()) }).parse(raw[facet])
.items,
);
}
const wrongKind = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "wasm", facet: "exports" },
},
});
expect(wrongKind.isError).toBe(true);
expect(JSON.stringify(wrongKind.content)).toContain(
"Mach-O inspection supports summary and macho views.",
);
},
);
},
);
mcpTest(
"refuses summary delivery before analysis when the server retains no Evidence",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-summary-preflight-"),
"tool",
);
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const executed: string[] = [];
const session = createTestBinarySession(() => ({
execute: (operation) => {
executed.push(operation);
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(ok(null)),
}));
onTestFinished(async () => {
await session.close();
});
const opened = await session.open(target);
if (!opened.ok) throw opened.error;
const client = await mcp.connect(
createServer({ kind: "fixed", analysis: session }),
);
const refused = [];
for (const name of ["inspect_macho", "inspect_artifact"])
refused.push(
await client.callTool({ name, arguments: { detail: "summary" } }),
);
// Neither analysis ran only to be discarded by the delivery refusal.
expect(executed.filter((operation) => operation !== "health")).toEqual([]);
for (const result of refused)
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
},
);
@@ -4,7 +4,7 @@ import { access, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect } from "vitest";
import { expect, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
@@ -123,6 +123,93 @@ const terminateFixtureProcess = async (pid: number): Promise<void> => {
await waitForProcessExit(pid);
};
itWithCaptureCapability(
"keeps the process deadline bounded when the wall clock moves backward",
async () => {
const wallStart = Date.now();
let wallReads = 0;
const now = vi.spyOn(Date, "now").mockImplementation(() => {
wallReads += 1;
return wallReads === 1 ? wallStart : wallStart - 60_000 + wallReads;
});
const controller = new AbortController();
const fallback = setTimeout(() => controller.abort(), 1_500);
try {
const result = await captureProcessScenario(
parseProcessScenario({
executable: process.execPath,
arguments: [processFixture, "hang"],
working_directory: dirname(processFixture),
timeout_ms: 100,
idle_timeout_ms: 5_000,
}),
controller.signal,
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.exit.reason).toBe("timeout");
} finally {
clearTimeout(fallback);
now.mockRestore();
}
},
10_000,
);
itWithCaptureCapability(
"preserves reversed wall-clock observations and monotonic frames across capture",
async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-01-02T00:00:00.000Z"));
try {
const result = await captureProcessScenario(
parseProcessScenario({
executable: process.execPath,
arguments: [processFixture, "partial"],
working_directory: dirname(processFixture),
settle_ms: 0,
timeout_ms: 5_000,
idle_timeout_ms: 5_000,
}),
undefined,
process.platform,
process.env,
undefined,
undefined,
{
async report(update) {
if (update.phase === "running")
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
},
},
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.frames.length).toBeGreaterThan(0);
expect(Date.parse(result.value.manifest.completed_at)).toBeLessThan(
Date.parse(result.value.manifest.started_at),
);
expect(result.value.limitations).toContain(
"Wall-clock completion time precedes start time; elapsed capture timing is recorded separately and remains monotonic.",
);
expect(
result.value.frames.map(({ at_ms }) => at_ms),
"capture-relative frame times stay ordered and nonnegative",
).toEqual(
[...result.value.frames.map(({ at_ms }) => at_ms)].sort(
(left, right) => left - right,
),
);
expect(result.value.frames.every(({ at_ms }) => at_ms >= 0)).toBe(true);
expect(result.value.exit.reason).toBe("exited");
expect(result.value.settlement.elapsed_ms).toBeGreaterThan(0);
} finally {
vi.useRealTimers();
}
},
10_000,
);
itWithCaptureCapability(
"cleans detached run-token children omitted by sampling and preserves an unowned neighbor",
async () => {
@@ -3,7 +3,7 @@ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackage, createPackageWithOptions } from "@electron/asar";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import {
@@ -13,6 +13,7 @@ import {
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { DirectoryArtifactReader } from "../../../../src/artifacts/DirectoryArtifactReader.js";
it.each(["file", "directory"] as const)(
"rolls back when an inventoried %s disappears before extraction",
@@ -61,6 +62,42 @@ it("still refuses a regular file added after inventory and rolls back", async ()
await expect(access(output)).rejects.toThrow();
});
it("rolls back when cancellation arrives while closing the materialization reader", async () => {
const root = await createTestTempDirectory("rea-extract-cancel-close-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "payload.txt"), "complete payload\n");
const snapshot = await scanArtifactInventory(source);
const output = join(root, "output");
const controller = new AbortController();
const close = DirectoryArtifactReader.prototype.close;
const closeSpy = vi
.spyOn(DirectoryArtifactReader.prototype, "close")
.mockImplementation(async function (this: DirectoryArtifactReader) {
controller.abort();
await close.call(this);
});
try {
await expect(
materializeArtifactInventory(
{
inputPath: source,
inputFormat: "asar",
outputRoot: output,
environment: process.env,
integrityPolicy: "fail",
},
source,
snapshot,
controller.signal,
),
).rejects.toMatchObject({ reason: "cancelled" });
await expect(access(output)).rejects.toThrow();
} finally {
closeSpy.mockRestore();
}
});
it("preserves every equal-content occurrence and copies a nested ASAR as its containing file", async () => {
const root = await createTestTempDirectory("rea-extract-nested-");
const source = join(root, "source");
@@ -3,6 +3,8 @@ import { readFile } from "node:fs/promises";
import { describe, expect, it, onTestFinished } from "vitest";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
/**
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
@@ -20,6 +22,26 @@ const fatSlices = async (
};
describe("Mach-O slice reader with system lipo", () => {
it("names the process ownership helper prerequisite when lipo cannot be supervised", async () => {
const prerequisite =
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.";
const reader = new MachOSliceArtifactReader(
process.execPath,
{},
new XcrunCommandRunner({}, undefined, () =>
Promise.reject(new DarwinProcessOwnershipInspectionError(prerequisite)),
),
);
onTestFinished(() => reader.close());
const enumerate = async () => {
for await (const _entry of reader.entries()) continue;
};
await expect(enumerate()).rejects.toMatchObject({
reason: "unavailable",
message: `lipo could not enumerate universal Mach-O slices: ${prerequisite}`,
});
});
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls slice ranges against its FAT table",
async () => {
@@ -8,6 +8,7 @@ import {
type NativeCommandLauncher,
} from "../../../../src/native/CommandRunner.js";
import { ok } from "../../../../src/domain/result.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
afterEach(() => vi.unstubAllEnvs());
@@ -210,3 +211,23 @@ it.skipIf(process.platform === "win32")(
if (!killed.ok) expect(killed.error.reason).toBe("nonzero-exit");
},
);
it("keeps the ownership helper prerequisite when xcrun cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
);
const runner = new XcrunCommandRunner({}, undefined, () =>
Promise.reject(inspection),
);
const result = await runner.run("file", [], {});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
tool: "file",
reason: "io",
detail: inspection.message,
cause: { tool: "xcrun", detail: inspection.message, cause: inspection },
});
});
@@ -1,4 +1,5 @@
import { createHash } from "node:crypto";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
import { EventEmitter } from "node:events";
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -280,6 +281,30 @@ describe("native command failure capture and limits", () => {
stderr_bytes: expect.any(Number),
},
});
expect(projectAnalysisError(result.error).details).not.toHaveProperty(
"diagnostics.detail",
);
});
it("projects the ownership helper prerequisite when a command cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.",
);
const runner = new XcrunCommandRunner(
{},
() =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
() => Promise.reject(inspection),
);
const result = await new NativeMacOSProvider({}, runner, "darwin")
.createClient(machoTarget("/private/fixture"))
.execute("demangle_swift", { symbols: ["fixture-symbol"] });
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: { reason: "io", detail: inspection.message },
});
});
it("retains output written before cancellation and reaps the stalled command", async () => {