refactor(tools): remove artificial analysis ceilings

This commit is contained in:
morluto
2026-09-29 16:29:23 +08:00
parent 36aeec9586
commit 2f08c7c932
202 changed files with 2314 additions and 3072 deletions
+1 -2
View File
@@ -88,8 +88,7 @@ export interface ProviderRequestActivitySnapshot {
readonly requestId: number;
readonly operation: string;
readonly elapsedMs: number;
readonly timeoutMs: number;
readonly callerState: "waiting" | "timed_out" | "cancelled";
readonly callerState: "waiting" | "cancelled";
} | null;
readonly queuedRequests: number;
}
@@ -1,267 +0,0 @@
import { z } from "zod";
import {
compareApplicationVersionsRequestSchema,
compareJavaScriptExportShapesRequestSchema,
compareSourceToBundleRequestSchema,
traceApplicationFeatureRequestSchema,
traceJavaScriptSemanticsRequestSchema,
type CompareApplicationVersionsRequest,
type CompareJavaScriptExportShapesRequest,
type CompareSourceToBundleRequest,
type TraceApplicationFeatureRequest,
type TraceJavaScriptSemanticsRequest,
} from "../contracts/applicationWorkflowInputContracts.js";
import type { Evidence } from "../domain/evidence.js";
import { AnalysisInputError, type AnalysisError } from "../domain/errors.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { traceJavaScriptSemanticsInputSchema } from "../domain/javascriptSemanticTraceSchemas.js";
import { compareSourceToBundleInputSchema } from "../domain/sourceToBundleComparisonSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import {
resolveEvidenceReferences,
type EvidenceLookup,
type EvidenceSemanticIdentity,
} from "./EvidenceReferenceResolver.js";
const APPLICATION_GRAPH_IDENTITIES = [
{
operation: "analyze_javascript_application",
predicate: "rea.javascript-application-analysis",
},
{
operation: "reconcile_javascript_runtime",
predicate: "rea.javascript-runtime-reconciliation",
},
{
operation: "project_managed_application_graph",
predicate: "rea.managed-application-graph",
},
] as const satisfies readonly EvidenceSemanticIdentity[];
type TraceInput = z.output<typeof traceApplicationFeatureInputSchema>;
type SemanticTraceInput = z.output<typeof traceJavaScriptSemanticsInputSchema>;
type ComparisonInput = z.output<typeof compareApplicationVersionsInputSchema>;
type ExportShapeComparisonInput = z.output<
typeof compareJavaScriptExportShapesInputSchema
>;
type SourceToBundleInput = z.output<typeof compareSourceToBundleInputSchema>;
/** Parse and resolve one trace adapter request into its canonical domain input. */
export const resolveTraceApplicationFeatureRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<TraceInput, AnalysisError> => {
const parsed = traceApplicationFeatureRequestSchema.safeParse(input);
return parsed.success
? resolveTraceApplicationFeatureRequestValidated(parsed.data, lookup)
: invalid("trace_application_feature", parsed.error, input);
};
/** Resolve a trace request already parsed by the caller-facing contract. */
export const resolveTraceApplicationFeatureRequestValidated = (
input: TraceApplicationFeatureRequest,
lookup?: EvidenceLookup,
): Result<TraceInput, AnalysisError> => {
const application = graphEvidence(input, lookup);
if (!application.ok) return application;
const native = resolveEvidenceReferences(
lookup,
input.native_observation_evidence_ids,
);
if (!native.ok) return native;
const raw = {
application: application.value,
native_observations: [...input.native_observations, ...native.value],
seed: input.seed,
direction: input.direction,
};
const parsed = traceApplicationFeatureInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("trace_application_feature", parsed.error, raw);
};
/** Parse and resolve one semantic trace adapter request. */
export const resolveTraceJavaScriptSemanticsRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<SemanticTraceInput, AnalysisError> => {
const parsed = traceJavaScriptSemanticsRequestSchema.safeParse(input);
return parsed.success
? resolveTraceJavaScriptSemanticsRequestValidated(parsed.data, lookup)
: invalid("trace_javascript_semantics", parsed.error, input);
};
/** Resolve a semantic trace request already parsed by its public contract. */
export const resolveTraceJavaScriptSemanticsRequestValidated = (
input: TraceJavaScriptSemanticsRequest,
lookup?: EvidenceLookup,
): Result<SemanticTraceInput, AnalysisError> => {
const application = graphEvidence(input, lookup);
if (!application.ok) return application;
const raw = { application: application.value, query: input.query };
const parsed = traceJavaScriptSemanticsInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("trace_javascript_semantics", parsed.error, raw);
};
/** Parse and resolve one comparison adapter request into canonical input. */
export const resolveCompareApplicationVersionsRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<ComparisonInput, AnalysisError> => {
const parsed = compareApplicationVersionsRequestSchema.safeParse(input);
return parsed.success
? resolveCompareApplicationVersionsRequestValidated(parsed.data, lookup)
: invalid("compare_application_versions", parsed.error, input);
};
/** Resolve a comparison request parsed by the caller-facing contract. */
export const resolveCompareApplicationVersionsRequestValidated = (
input: CompareApplicationVersionsRequest,
lookup?: EvidenceLookup,
): Result<ComparisonInput, AnalysisError> => {
const left = resolveApplicationGraphReference(input.left, lookup);
if (!left.ok) return left;
const right = resolveApplicationGraphReference(input.right, lookup);
if (!right.ok) return right;
const leftNative = resolveEvidenceReferences(
lookup,
input.left_native_observation_evidence_ids,
);
if (!leftNative.ok) return leftNative;
const rightNative = resolveEvidenceReferences(
lookup,
input.right_native_observation_evidence_ids,
);
if (!rightNative.ok) return rightNative;
const raw = {
left: left.value,
right: right.value,
left_native_observations: [
...input.left_native_observations,
...leftNative.value,
],
right_native_observations: [
...input.right_native_observations,
...rightNative.value,
],
};
const parsed = compareApplicationVersionsInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_application_versions", parsed.error, raw);
};
/** Parse and resolve one historical-source comparison adapter request. */
export const resolveCompareSourceToBundleRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<SourceToBundleInput, AnalysisError> => {
const parsed = compareSourceToBundleRequestSchema.safeParse(input);
return parsed.success
? resolveCompareSourceToBundleRequestValidated(parsed.data, lookup)
: invalid("compare_source_to_bundle", parsed.error, input);
};
/** Resolve a historical-source comparison request parsed by its public contract. */
export const resolveCompareSourceToBundleRequestValidated = (
input: CompareSourceToBundleRequest,
lookup?: EvidenceLookup,
): Result<SourceToBundleInput, AnalysisError> => {
const application = graphEvidence(input, lookup);
if (!application.ok) return application;
const raw = {
reference: input.reference,
application: application.value,
};
const parsed = compareSourceToBundleInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_source_to_bundle", parsed.error, raw);
};
/** Parse and resolve an export-shape adapter request into canonical input. */
export const resolveCompareJavaScriptExportShapesRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<ExportShapeComparisonInput, AnalysisError> => {
const parsed = compareJavaScriptExportShapesRequestSchema.safeParse(input);
return parsed.success
? resolveCompareJavaScriptExportShapesRequestValidated(parsed.data, lookup)
: invalid("compare_javascript_export_shapes", parsed.error, input);
};
/** Resolve an export-shape request already parsed by the adapter contract. */
export const resolveCompareJavaScriptExportShapesRequestValidated = (
input: CompareJavaScriptExportShapesRequest,
lookup?: EvidenceLookup,
): Result<ExportShapeComparisonInput, AnalysisError> => {
const left = graphEvidence(
typeof input.left === "string"
? { application_evidence_id: input.left }
: { application: input.left },
lookup,
);
if (!left.ok) return left;
const right = graphEvidence(
typeof input.right === "string"
? { application_evidence_id: input.right }
: { application: input.right },
lookup,
);
if (!right.ok) return right;
const raw = {
left: left.value,
right: right.value,
left_module_path: input.left_module_path,
left_export_name: input.left_export_name,
right_module_path: input.right_module_path,
right_export_name: input.right_export_name,
};
const parsed = compareJavaScriptExportShapesInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_javascript_export_shapes", parsed.error, raw);
};
const graphEvidence = (
source:
| { readonly application: Evidence }
| { readonly application_evidence_id: string },
lookup: EvidenceLookup | undefined,
) => {
if ("application" in source) return ok(source.application);
const resolved = resolveEvidenceReferences(
lookup,
[source.application_evidence_id],
APPLICATION_GRAPH_IDENTITIES,
);
return resolved.ok ? ok(resolved.value[0]) : resolved;
};
const resolveApplicationGraphReference = (
reference: Evidence | string,
lookup: EvidenceLookup | undefined,
) =>
typeof reference === "string"
? graphEvidence({ application_evidence_id: reference }, lookup)
: graphEvidence({ application: reference }, lookup);
const invalid = <Value>(
operation: string,
cause: z.ZodError,
input: unknown,
): Result<Value, AnalysisInputError> =>
err(
new AnalysisInputError(
operation,
undefined,
projectInputIssues(cause.issues, input),
),
);
+3 -6
View File
@@ -114,7 +114,6 @@ const requestActivityStatus = (
request_id: active.requestId,
operation: active.operation,
elapsed_ms: active.elapsedMs,
timeout_ms: active.timeoutMs,
caller_state: active.callerState,
},
queued_requests: queuedRequests,
@@ -126,11 +125,9 @@ const requestActivityStatus = (
status:
snapshots.length === 0
? "not_observed"
: active.some(({ callerState }) => callerState === "timed_out")
? "timed_out_busy"
: active.length > 0
? "busy"
: "idle",
: active.length > 0
? "busy"
: "idle",
providers,
};
};
+2 -2
View File
@@ -236,7 +236,7 @@ const policyAvailability = ({
: {
reason: "policy_disabled",
remediation:
"Enable V8 Inspector observation and configure exact loopback endpoints plus canonical file roots or exact origins.",
"Enable V8 Inspector observation; pass the user's literal-loopback Inspector endpoint to the tool.",
};
if (kind === "session") return { reason: "available", remediation: null };
return null;
@@ -261,7 +261,7 @@ const electronPolicyAvailability = (
: {
reason: "policy_disabled",
remediation:
"Enable Electron observation and configure a loopback CDP endpoint and canonical file roots.",
"Enable Electron observation; pass the user's literal-loopback CDP endpoint to the tool.",
};
};
+14 -1
View File
@@ -24,6 +24,19 @@ export interface CommandShimReplay {
}
const RUNNER = `const command = process.argv[2];
const maximumTimerDelay = 2147483647;
const delay = milliseconds => new Promise(resolve => {
let remaining = milliseconds;
const schedule = () => {
const interval = Math.min(remaining, maximumTimerDelay);
setTimeout(() => {
remaining -= interval;
if (remaining === 0) resolve();
else schedule();
}, interval);
};
schedule();
});
const response = await fetch(process.env.REA_SHIM_LEDGER_URL, {
method: "POST",
headers: { "content-type": "application/json" },
@@ -34,7 +47,7 @@ const route = await response.json();
let elapsed = 0;
for (const output of route.outputs) {
const wait = Math.max(0, output.at_ms - elapsed);
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
if (wait > 0) await delay(wait);
elapsed = output.at_ms;
(output.stream === "stdout" ? process.stdout : process.stderr).write(output.data);
}
-1
View File
@@ -47,7 +47,6 @@ const parameters = (
input: ListElectronTargetsInput | InspectElectronPageInput,
): EvidenceObservation["parameters"] => ({
cdp_endpoint: input.cdp_endpoint,
allowed_file_roots: input.allowed_file_roots,
...("target_id" in input
? {
target_id: input.target_id,
@@ -14,7 +14,7 @@ import {
import { err, ok, type Result } from "../domain/result.js";
import { createElectronEvidence } from "./ElectronEvidence.js";
/** Authorize and list root-confined Electron page targets. */
/** Authorize and list Electron file pages exposed by the selected endpoint. */
export const listElectronTargets = async (
provider: ElectronObservationPort | undefined,
authority: PermissionAuthority | undefined,
@@ -85,10 +85,9 @@ const prepare = async (
const authorized = await authority.authorize(
{
capability: "electron_observe",
roots: input.allowed_file_roots,
roots: [],
executables: [],
environment_names: [],
origins: [input.cdp_endpoint],
network: "loopback",
mount: false,
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.cdp_endpoint}`,
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { ok } from "../domain/result.js";
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
describe("literal feature tracing", () => {
it("searches procedure and string names before following references", async () => {
const calls: string[] = [];
const result = await traceLiteralFeature(
async (name) => {
calls.push(name);
if (name === "search_strings")
return ok([{ address: "0x1000", value: "launch feature" }]);
if (name === "search_procedures")
return ok([{ address: "0x2000", value: "launchFeature" }]);
if (name === "xrefs") return ok([]);
if (name === "resolve_containing_procedure") return ok(null);
throw new Error(`Unexpected analysis call: ${name}`);
},
{ query: "launch feature", case_sensitive: false },
"feature",
);
expect(result).toMatchObject({
ok: true,
value: {
matches: [
{ type: "string", address: "0x1000", value: "launch feature" },
{ type: "procedure", address: "0x2000", value: "launchFeature" },
],
references: [],
},
});
expect(calls).toEqual([
"search_strings",
"search_procedures",
"search_strings",
"search_procedures",
"xrefs",
"xrefs",
]);
});
it("keeps string-code tracing scoped to string labels", async () => {
const calls: string[] = [];
await traceLiteralFeature(
async (name) => {
calls.push(name);
if (name === "search_strings")
return ok([{ address: "0x1000", value: "launch feature" }]);
if (name === "xrefs") return ok([]);
throw new Error(`Unexpected analysis call: ${name}`);
},
{ query: "launch", case_sensitive: false },
"string",
);
expect(calls).toEqual(["search_strings", "xrefs"]);
});
});
@@ -47,8 +47,6 @@ const parameters = (
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
): EvidenceObservation["parameters"] => ({
inspector_endpoint: input.inspector_endpoint,
allowed_file_roots: input.allowed_file_roots,
allowed_origins: input.allowed_origins,
...("target_id" in input
? {
target_id: input.target_id,
@@ -85,10 +85,9 @@ const prepare = async (
const authorized = await authority.authorize(
{
capability: "v8_inspector_observe",
roots: input.allowed_file_roots,
roots: [],
executables: [],
environment_names: [],
origins: [input.inspector_endpoint, ...input.allowed_origins],
network: "loopback",
mount: false,
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.inspector_endpoint}`,
@@ -89,7 +89,6 @@ export const buildJavaScriptSemanticGraph = ({
);
}
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const truncated = false;
const unknowns = [...state.unknowns.values()];
return createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
@@ -101,19 +100,19 @@ export const buildJavaScriptSemanticGraph = ({
fingerprints,
unknowns,
coverage: {
status: truncated ? "partial" : "unknown",
truncated,
omitted_nodes: truncated ? null : 0,
omitted_relations: truncated ? null : 0,
status: "unknown",
truncated: false,
omitted_nodes: 0,
omitted_relations: 0,
limits: [],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: semanticFamilyStatus(family, analysis, truncated),
status: semanticFamilyStatus(family, analysis),
retained_relations: [...state.relations.values()].filter(
(relation) =>
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] === family,
).length,
omitted_relations: truncated ? null : 0,
omitted_relations: 0,
unknown_ids: unknowns
.filter((unknown) => unknown.family === family)
.map(({ unknown_id: identifier }) => identifier),
@@ -123,7 +122,7 @@ export const buildJavaScriptSemanticGraph = ({
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
"Local data flow does not claim control-flow-sensitive reaching definitions or arbitrary dynamic property resolution.",
"Promise ownership covers explicit unshadowed Promise construction, static factories, aggregation, chaining, and await syntax only.",
"Function fingerprints are bounded static candidates; equal digests can remain ambiguous and do not prove behavioral equivalence.",
"Function fingerprints are static candidates; equal digests can remain ambiguous and do not prove behavioral equivalence.",
"Event extraction covers EventEmitter-style literal registrations, removals, and dispatch candidates; dynamic names remain unknown.",
"Timer extraction covers global or node:timers scheduling and exact local-handle cancellation.",
"Child-process extraction covers asynchronous node:child_process creation, literal argv/env/stdio options, exit/error listeners, and kill signals.",
@@ -4,7 +4,7 @@ import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTy
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
const INFERENCE_LIMITATION =
"This relationship is a bounded static candidate; it does not prove runtime execution or causal flow.";
"This relationship is a conservative static candidate; it does not prove runtime execution or causal flow.";
/** Exact artifact-backed syntax evidence for one semantic graph node. */
export const observedSemanticEvidence = (
@@ -39,7 +39,6 @@ export const semanticNodesWithinRange = (
export const semanticFamilyStatus = (
family: (typeof JAVASCRIPT_SEMANTIC_RELATION_FAMILIES)[number],
analysis: JavaScriptArtifactAnalysis,
truncated: boolean,
): "complete" | "partial" | "unknown" | "unsupported" => {
if (
![
@@ -58,7 +57,6 @@ export const semanticFamilyStatus = (
].includes(family)
)
return "unsupported";
if (truncated) return "unknown";
return analysis.truncated_scopes === 0 ? "partial" : "unknown";
};
+42 -25
View File
@@ -20,8 +20,8 @@ import {
recordMachineEvent,
readReplayRequestBody,
ReplayRecorder,
ReplayDelayScheduler,
requestHeaders,
waitForReplayDelay,
} from "./LoopbackReplayRecorder.js";
/** Owned loopback replay endpoints and their bounded protocol observations. */
@@ -63,6 +63,7 @@ const recordHttpResponse = (
const handleMachineHttp = async (
recorder: ReplayRecorder,
request: HttpReplayRequest,
delays: ReplayDelayScheduler,
): Promise<void> => {
const machine = recorder.machine;
if (machine === undefined) return;
@@ -94,7 +95,7 @@ const handleMachineHttp = async (
return;
}
for (const action of decision.actions) {
if (action.type === "delay") await waitForReplayDelay(action.duration_ms);
if (action.type === "delay") await delays.wait(action.duration_ms);
else if (action.type === "disconnect") {
request.response.destroy();
recordHttpResponse(recorder, request, "", "disconnected");
@@ -118,6 +119,7 @@ const handleStaticHttp = async (
recorder: ReplayRecorder,
request: HttpReplayRequest,
calls: Map<number, number>,
delays: ReplayDelayScheduler,
): Promise<void> => {
const index = recorder.scenario.replay.http.findIndex((route) =>
route.method !== request.method || route.path !== request.path
@@ -152,7 +154,7 @@ const handleStaticHttp = async (
return;
}
calls.set(index, used + 1);
if (route.delay_ms > 0) await waitForReplayDelay(route.delay_ms);
if (route.delay_ms > 0) await delays.wait(route.delay_ms);
if (route.disconnect) {
request.response.destroy();
recordHttpResponse(recorder, request, "", "disconnected");
@@ -170,6 +172,7 @@ const handleHttpRequest = async (
request: IncomingMessage,
response: ServerResponse,
calls: Map<number, number>,
delays: ReplayDelayScheduler,
): Promise<void> => {
const body = await readReplayRequestBody(
request,
@@ -202,25 +205,28 @@ const handleHttpRequest = async (
recordedAtMs: recorder.atMs(),
};
await (recorder.machine === undefined
? handleStaticHttp(recorder, replayRequest, calls)
? handleStaticHttp(recorder, replayRequest, calls, delays)
: recorder.enqueueMachine(() =>
handleMachineHttp(recorder, replayRequest),
handleMachineHttp(recorder, replayRequest, delays),
));
};
const createHttpHandler = (
recorder: ReplayRecorder,
delays: ReplayDelayScheduler,
): ((request: IncomingMessage, response: ServerResponse) => void) => {
const calls = new Map<number, number>();
return (request, response) => {
void handleHttpRequest(recorder, request, response, calls).catch(() => {
recorder.truncated = true;
if (response.headersSent) response.destroy();
else {
response.statusCode = 500;
response.end();
}
});
void handleHttpRequest(recorder, request, response, calls, delays).catch(
() => {
recorder.truncated = true;
if (response.headersSent) response.destroy();
else {
response.statusCode = 500;
response.end();
}
},
);
};
};
@@ -228,6 +234,7 @@ const sendWebSocketScript = async (
client: WebSocket,
connection: number,
recorder: ReplayRecorder,
delays: ReplayDelayScheduler,
): Promise<void> => {
const scripts = recorder.scenario.replay.websocket_connections;
const script = scripts[connection - 1];
@@ -251,10 +258,7 @@ const sendWebSocketScript = async (
delay_ms: 0,
}));
for (const message of messages) {
if (message.delay_ms > 0)
await new Promise((resolveDelay) =>
setTimeout(resolveDelay, message.delay_ms),
);
if (message.delay_ms > 0) await delays.wait(message.delay_ms);
if (client.readyState !== 1) return;
client.send(message.data);
recorder.record({
@@ -286,10 +290,11 @@ const runWebSocketActions = async (
recorder: ReplayRecorder,
decision: Extract<ReplayMachineDecision, { readonly outcome: "matched" }>,
path: string,
delays: ReplayDelayScheduler,
): Promise<void> => {
for (const action of decision.actions) {
if (action.type === "delay") {
await waitForReplayDelay(action.duration_ms);
await delays.wait(action.duration_ms);
continue;
}
if (action.type === "disconnect") {
@@ -325,6 +330,7 @@ const handleStaticWebSocket = (
recorder: ReplayRecorder,
connection: number,
path: string,
delays: ReplayDelayScheduler,
): void => {
client.on("message", (value) =>
recorder.record({
@@ -337,7 +343,7 @@ const handleStaticWebSocket = (
outcome: "matched",
}),
);
void sendWebSocketScript(client, connection, recorder);
void sendWebSocketScript(client, connection, recorder, delays);
};
const handleMachineWebSocket = (options: {
@@ -346,8 +352,9 @@ const handleMachineWebSocket = (options: {
readonly recorder: ReplayRecorder;
readonly connection: number;
readonly path: string;
readonly delays: ReplayDelayScheduler;
}): void => {
const { client, request, recorder, connection, path } = options;
const { client, request, recorder, connection, path, delays } = options;
const machine = recorder.machine;
if (machine === undefined) return;
void recorder
@@ -376,7 +383,13 @@ const handleMachineWebSocket = (options: {
connectionDecision,
);
if (connectionDecision.outcome === "matched")
await runWebSocketActions(client, recorder, connectionDecision, path);
await runWebSocketActions(
client,
recorder,
connectionDecision,
path,
delays,
);
else client.close();
})
.catch(() => {
@@ -412,7 +425,7 @@ const handleMachineWebSocket = (options: {
decision,
);
if (decision.outcome === "matched")
await runWebSocketActions(client, recorder, decision, path);
await runWebSocketActions(client, recorder, decision, path, delays);
})
.catch(() => {
recorder.truncated = true;
@@ -424,6 +437,7 @@ const handleMachineWebSocket = (options: {
const createWebSocketReplay = (
server: Server,
recorder: ReplayRecorder,
delays: ReplayDelayScheduler,
): WebSocketServer => {
let connections = 0;
const websocket = new WebSocketServer({
@@ -453,7 +467,7 @@ const createWebSocketReplay = (
client.on("error", () => undefined);
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
if (recorder.machine === undefined)
handleStaticWebSocket(client, recorder, connections, path);
handleStaticWebSocket(client, recorder, connections, path, delays);
else
handleMachineWebSocket({
client,
@@ -461,6 +475,7 @@ const createWebSocketReplay = (
recorder,
connection: connections,
path,
delays,
});
});
return websocket;
@@ -472,8 +487,9 @@ export const startLoopbackReplay = async (
recordEvent: RecordProcessCaptureEvent = () => undefined,
): Promise<LoopbackReplay> => {
const recorder = new ReplayRecorder(scenario, recordEvent);
const server = createServer(createHttpHandler(recorder));
const websocket = createWebSocketReplay(server, recorder);
const delays = new ReplayDelayScheduler();
const server = createServer(createHttpHandler(recorder, delays));
const websocket = createWebSocketReplay(server, recorder, delays);
let closePromise: Promise<void> | undefined;
let port: number;
try {
@@ -499,6 +515,7 @@ export const startLoopbackReplay = async (
},
async close() {
closePromise ??= (async () => {
delays.close();
recorder.stopMachineAdmission();
await recorder.drainMachine();
for (const client of websocket.clients) client.terminate();
+29 -2
View File
@@ -9,6 +9,7 @@ import {
type ReplayMachineDecision,
type ReplayTransitionRecord,
} from "../domain/replayMachineRuntime.js";
import { scheduleProcessDelay, type ProcessTimer } from "./ProcessTimer.js";
/** Bounded protocol and replay-machine observations for one process run. */
export class ReplayRecorder {
@@ -128,8 +129,34 @@ export const recordMachineEvent = (
recorder.recordTransition(decision);
};
export const waitForReplayDelay = (durationMs: number): Promise<void> =>
new Promise((resolveDelay) => setTimeout(resolveDelay, durationMs));
/** Owns replay delays so endpoint shutdown can release every waiting handler. */
export class ReplayDelayScheduler {
readonly #pending = new Map<ProcessTimer, () => void>();
#closed = false;
wait(durationMs: number): Promise<void> {
if (this.#closed) return Promise.resolve();
return new Promise((resolveDelay) => {
let timer: ProcessTimer;
const finish = (): void => {
this.#pending.delete(timer);
resolveDelay();
};
timer = scheduleProcessDelay(durationMs, finish);
this.#pending.set(timer, finish);
});
}
close(): void {
if (this.#closed) return;
this.#closed = true;
for (const [timer, finish] of this.#pending) {
timer.cancel();
finish();
}
this.#pending.clear();
}
}
export const listenOnLoopback = async (server: Server): Promise<number> => {
await new Promise<void>((resolveListen, rejectListen) => {
+4 -3
View File
@@ -11,6 +11,7 @@ import {
normalizeProcessText,
} from "./ProcessNormalization.js";
import type { TerminalRenderer } from "./TerminalRenderer.js";
import { scheduleProcessDelay, type ProcessTimer } from "./ProcessTimer.js";
/** Mutable observation-order ledger whose writer is shared by capture producers. */
export interface ProcessCaptureJournal {
@@ -79,7 +80,7 @@ export const createProcessCaptureJournal = (): ProcessCaptureJournal => {
interface ScenarioInteractionOptions {
readonly scenario: ProcessScenario;
readonly getTerminal: () => IPty | undefined;
readonly timers: Set<NodeJS.Timeout>;
readonly timers: Set<ProcessTimer>;
readonly interactions: InteractionEvent[];
readonly renderer: TerminalRenderer;
readonly started: number;
@@ -94,7 +95,7 @@ export const scheduleScenarioInteractions = (
const { scenario, getTerminal, timers, interactions, renderer, started } =
options;
for (const [eventIndex, event] of scenario.events.entries()) {
const timer = setTimeout(() => {
const timer = scheduleProcessDelay(event.at_ms, () => {
options.dispatchedEventIndexes.add(eventIndex);
const terminal = getTerminal();
const dispatchedAt = Math.max(0, Date.now() - started);
@@ -140,7 +141,7 @@ export const scheduleScenarioInteractions = (
outcome,
});
options.recordEvent("interaction_events", sequence);
}, event.at_ms);
});
timers.add(timer);
}
};
+6 -6
View File
@@ -51,6 +51,7 @@ import {
import type { CommandShimReplay } from "./CommandShimReplay.js";
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import { scheduleProcessInterval, type ProcessTimer } from "./ProcessTimer.js";
interface TerminalExitOptions {
readonly terminal: IPty;
@@ -58,7 +59,7 @@ interface TerminalExitOptions {
readonly started: number;
readonly lastOutput: () => number;
readonly signal: AbortSignal | undefined;
readonly timers: Set<NodeJS.Timeout>;
readonly timers: Set<ProcessTimer>;
readonly interactions: InteractionEvent[];
readonly dispatchedEventIndexes: ReadonlySet<number>;
readonly recordEvent: RecordProcessCaptureEvent;
@@ -285,13 +286,12 @@ export const awaitTerminalExit = async ({
recordEvent("interaction_events", sequence);
}
for (const timer of timers) {
clearTimeout(timer);
clearInterval(timer);
timer.cancel();
}
timers.clear();
resolveExit({ ...exit, reason });
});
const timeout = setInterval(() => {
const timeout = scheduleProcessInterval(() => {
if (signal?.aborted === true) {
reason = "cancelled";
terminal.kill("SIGKILL");
@@ -307,7 +307,7 @@ export const awaitTerminalExit = async ({
});
export const releaseProcessResources = async (options: {
readonly timers: ReadonlySet<NodeJS.Timeout>;
readonly timers: ReadonlySet<ProcessTimer>;
readonly replay: LoopbackReplay | undefined;
readonly terminal: IPty | undefined;
readonly renderer: TerminalRenderer | undefined;
@@ -317,7 +317,7 @@ export const releaseProcessResources = async (options: {
readonly temporaryRoot: string;
readonly capturedProcessGroupIds: readonly number[];
}): Promise<string | undefined> => {
for (const timer of options.timers) clearTimeout(timer);
for (const timer of options.timers) timer.cancel();
let failure: string | undefined;
try {
await options.replay?.close();
+6 -6
View File
@@ -5,6 +5,7 @@ import type {
RecordProcessCaptureEvent,
} from "../domain/processCapture.js";
import { snapshotRoots, type SnapshotResult } from "./FilesystemSnapshot.js";
import { scheduleProcessDelay, type ProcessTimer } from "./ProcessTimer.js";
/** Classify path-stable filesystem effects between two bounded states. */
export const classifyFilesystemEffects = (
@@ -53,7 +54,7 @@ export class ProcessCheckpoints {
readonly #captured = new Set<string>();
readonly #terminalCounts = new Map<string, number>();
readonly #terminalTails = new Map<string, string>();
readonly #timers = new Set<NodeJS.Timeout>();
readonly #timers = new Set<ProcessTimer>();
readonly #signal: AbortSignal | undefined;
readonly #recordEvent: RecordProcessCaptureEvent;
#pending: Promise<void> = Promise.resolve();
@@ -80,9 +81,8 @@ export class ProcessCheckpoints {
this.#captured.add("before");
for (const checkpoint of scenario.checkpoints) {
if (checkpoint.trigger.type !== "time") continue;
const timer = setTimeout(
() => this.capture(checkpoint.name),
checkpoint.trigger.at_ms,
const timer = scheduleProcessDelay(checkpoint.trigger.at_ms, () =>
this.capture(checkpoint.name),
);
this.#timers.add(timer);
}
@@ -180,7 +180,7 @@ export class ProcessCheckpoints {
async finish(
after: SnapshotResult,
): Promise<readonly FilesystemCheckpoint[]> {
for (const timer of this.#timers) clearTimeout(timer);
for (const timer of this.#timers) timer.cancel();
await this.#pending;
const previous = this.#captures.at(-1)?.files ?? [];
const index = this.#captures.length;
@@ -197,7 +197,7 @@ export class ProcessCheckpoints {
/** Cancel scheduled captures and await any snapshot already in progress. */
async dispose(): Promise<void> {
for (const timer of this.#timers) clearTimeout(timer);
for (const timer of this.#timers) timer.cancel();
this.#timers.clear();
await this.#pending;
}
-7
View File
@@ -24,8 +24,6 @@ import {
} from "./ProcessEvidence.js";
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
const MAX_INPUT_BYTES = 64 * 1024 * 1024;
/** Safe process-command failure returned to the CLI adapter. */
export interface ProcessCliErrorOutput {
readonly error: "Process command failed";
@@ -165,11 +163,6 @@ const readJson = async (path: string): Promise<unknown> => {
"Process input file could not be read. Check that the path exists and is readable.",
);
}
if (bytes.length > MAX_INPUT_BYTES)
throw new ProcessCliFailure(
"truncated",
"Process input file is too large. Reduce it below 64 MiB, then try again.",
);
try {
const parsed: unknown = JSON.parse(bytes.toString("utf8"));
return parsed;
+5 -4
View File
@@ -22,6 +22,7 @@ import { startProcessSampler } from "./ProcessSampling.js";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import { ProcessCheckpoints } from "./ProcessCheckpoints.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import type { ProcessTimer } from "./ProcessTimer.js";
import {
startCommandShimReplay,
type CommandShimReplay,
@@ -73,7 +74,7 @@ interface StartedCaptureRuntime {
const cleanupFailedStartup = async (options: {
readonly cause: unknown;
readonly timers: Set<NodeJS.Timeout>;
readonly timers: Set<ProcessTimer>;
readonly replay: LoopbackReplay | undefined;
readonly terminal: IPty | undefined;
readonly renderer: TerminalRenderer | undefined;
@@ -121,7 +122,7 @@ interface StartCaptureRuntimeOptions {
readonly frames: TerminalFrame[];
readonly samples: ProcessSample[];
readonly interactions: InteractionEvent[];
readonly timers: Set<NodeJS.Timeout>;
readonly timers: Set<ProcessTimer>;
readonly dispatchedEventIndexes: Set<number>;
readonly recordEvent: RecordProcessCaptureEvent;
readonly journal: ProcessCaptureJournal;
@@ -253,7 +254,7 @@ const normalizedShimEvents = (
const finishProcessRun = async (options: {
readonly runtime: StartedCaptureRuntime | undefined;
readonly timers: Set<NodeJS.Timeout>;
readonly timers: Set<ProcessTimer>;
readonly runId: string;
readonly temporaryRoot: string;
readonly samples: readonly ProcessSample[];
@@ -416,7 +417,7 @@ const runProcessScenario = async (
const journal = createProcessCaptureJournal();
const { entries: eventJournal, recordEvent } = journal;
let runtime: StartedCaptureRuntime | undefined;
const timers = new Set<NodeJS.Timeout>();
const timers = new Set<ProcessTimer>();
let capture: PendingProcessCapture | undefined;
let executionFailure: unknown;
let stopSampler = async () => ({ partial: false });
+3 -25
View File
@@ -11,6 +11,7 @@ import type {
ProcessReactiveAction,
ProcessReactiveScenario,
} from "../domain/processReactiveScenario.js";
import { scheduleProcessDelay } from "./ProcessTimer.js";
/** Effect boundary owned by the serialized reactive coordinator. */
export interface ProcessReactiveExecutor {
@@ -21,9 +22,7 @@ export interface ProcessReactiveExecutor {
}
/** Cancel handle for one coordinator-owned deadline. */
export interface ProcessReactiveTimer {
cancel(): void;
}
export type ProcessReactiveTimer = ReturnType<typeof scheduleProcessDelay>;
/** Injectable deadline scheduler used by deterministic coordinator tests. */
export interface ProcessReactiveTimerHost {
@@ -34,28 +33,7 @@ export interface ProcessReactiveTimerHost {
}
const systemTimerHost: ProcessReactiveTimerHost = {
schedule: (callback, delayMs) => {
const maximumTimerDelay = 2_147_483_647;
let remaining = Math.max(0, delayMs);
let timer: NodeJS.Timeout | undefined;
let cancelled = false;
const scheduleNext = (): void => {
if (cancelled) return;
const interval = Math.min(remaining, maximumTimerDelay);
timer = setTimeout(() => {
remaining -= interval;
if (remaining === 0) callback();
else scheduleNext();
}, interval);
};
scheduleNext();
return {
cancel: () => {
cancelled = true;
if (timer !== undefined) clearTimeout(timer);
},
};
},
schedule: (callback, delayMs) => scheduleProcessDelay(delayMs, callback),
};
/**
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { ReplayDelayScheduler } from "./LoopbackReplayRecorder.js";
import { scheduleProcessDelay } from "./ProcessTimer.js";
describe("process delay scheduling", () => {
it("splits long delays into timer-sized chunks and can cancel the next chunk", () => {
const scheduled: Array<{
readonly delayMs: number;
readonly callback: () => void;
cancelled: boolean;
}> = [];
const schedule = (callback: () => void, delayMs: number) => {
const entry = { delayMs, callback, cancelled: false };
scheduled.push(entry);
return { cancel: () => (entry.cancelled = true) };
};
let fired = false;
const timer = scheduleProcessDelay(
2_147_483_647 + 25,
() => {
fired = true;
},
schedule,
);
expect(scheduled.map(({ delayMs }) => delayMs)).toEqual([2_147_483_647]);
scheduled[0]?.callback();
expect(scheduled.map(({ delayMs }) => delayMs)).toEqual([
2_147_483_647, 25,
]);
expect(fired).toBe(false);
timer.cancel();
expect(scheduled[1]?.cancelled).toBe(true);
scheduled[1]?.callback();
expect(fired).toBe(false);
});
it("releases owned replay delays when the endpoint closes", async () => {
const scheduler = new ReplayDelayScheduler();
const waiting = scheduler.wait(Number.MAX_SAFE_INTEGER);
scheduler.close();
scheduler.close();
await waiting;
await scheduler.wait(Number.MAX_SAFE_INTEGER);
});
});
+57
View File
@@ -0,0 +1,57 @@
/** A timer owned by one process capture or replay endpoint. */
export interface ProcessTimer {
cancel(): void;
}
/** Injectable timer primitive for deterministic long-delay tests. */
export type ProcessTimerScheduler = (
callback: () => void,
delayMs: number,
) => ProcessTimer;
const systemTimerScheduler: ProcessTimerScheduler = (callback, delayMs) => {
const timer = setTimeout(callback, delayMs);
return { cancel: () => clearTimeout(timer) };
};
/** Schedule a delay using consecutive Node timers without shortening long waits. */
export const scheduleProcessDelay = (
delayMs: number,
callback: () => void,
schedule: ProcessTimerScheduler = systemTimerScheduler,
): ProcessTimer => {
if (!Number.isSafeInteger(delayMs) || delayMs < 0)
throw new RangeError("Process delay must be a nonnegative safe integer");
const maximumTimerDelay = 2_147_483_647;
let remaining = delayMs;
let timer: ProcessTimer | undefined;
let cancelled = false;
const scheduleNext = (): void => {
if (cancelled) return;
const interval = Math.min(remaining, maximumTimerDelay);
timer = schedule(() => {
if (cancelled) return;
remaining -= interval;
if (remaining === 0) callback();
else scheduleNext();
}, interval);
};
scheduleNext();
return {
cancel: () => {
cancelled = true;
timer?.cancel();
},
};
};
/** Create an owned interval that shares process-capture cancellation handling. */
export const scheduleProcessInterval = (
callback: () => void,
intervalMs: number,
): ProcessTimer => {
const timer = setInterval(callback, intervalMs);
return { cancel: () => clearInterval(timer) };
};
+1 -1
View File
@@ -41,7 +41,7 @@ const grantSchema = z.object({
const storeSchema = z.object({
project_id: z.string().regex(/^project_[a-f0-9]{64}$/u),
project_root: z.string(),
grants: z.array(grantSchema).max(1_000),
grants: z.array(grantSchema),
});
export type ProjectPermissionStore = z.infer<typeof storeSchema>;
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { completeReconstructionCoverageData } from "../domain/reconstructionCoverage.fixture.js";
import { reconstructionCoverageEvaluationInputSchema } from "./ReconstructionCoverageService.js";
describe("reconstruction coverage service input", () => {
it("accepts caller boundary identifiers longer than the former schema ceiling", () => {
const boundaryId = "b".repeat(1_000);
const parsed = reconstructionCoverageEvaluationInputSchema.parse({
coverage: completeReconstructionCoverageData(),
boundary_id: boundaryId,
});
expect(parsed.boundary_id).toBe(boundaryId);
});
});
@@ -10,7 +10,7 @@ import { err, ok, type Result } from "../domain/result.js";
export const reconstructionCoverageEvaluationInputSchema = z.strictObject({
coverage: reconstructionCoverageDataSchema,
boundary_id: z.string().min(1).max(200),
boundary_id: z.string().min(1),
});
/** Evaluate inline reconstruction coverage against a named boundary. */