feat(analysis): add bounded memory and call tracing

This commit is contained in:
morluto
2026-07-24 13:14:01 +00:00
parent 205bf1529b
commit 8e7709d35a
21 changed files with 1025 additions and 188 deletions
+244
View File
@@ -0,0 +1,244 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { projectAnalysisError, type AnalysisError } from "../domain/errors.js";
import { parseRelatedAddresses } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ok, type Result } from "../domain/result.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
type AnalysisCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
export interface CallPathTraceInput {
readonly start: string;
readonly goal?: string | undefined;
readonly direction: "forward" | "backward";
readonly max_depth: number;
readonly max_nodes: number;
readonly max_operations: number;
}
interface TraceState {
readonly visited: Map<
string,
{ readonly depth: number; readonly path: string[] }
>;
readonly queue: string[];
readonly edges: Map<
string,
{
readonly source_address: string;
readonly target_address: string;
readonly discovery_depth: number;
}
>;
readonly failures: Array<{
readonly address: string;
readonly error: ReturnType<typeof projectAnalysisError>;
}>;
readonly frontier: Set<string>;
readonly residual: Set<string>;
operations: number;
queueIndex: number;
traversalPath: string[];
}
interface AddressExpansion {
readonly input: CallPathTraceInput;
readonly state: TraceState;
readonly address: string;
readonly current: { readonly depth: number; readonly path: string[] };
readonly signal?: AbortSignal;
}
interface DiscoveredEdge {
readonly address: string;
readonly relatedAddress: string;
readonly discoveryDepth: number;
}
/** Trace one deterministic bounded direct caller/callee path. */
export const traceCallPath = async (
call: AnalysisCall,
input: CallPathTraceInput,
signal?: AbortSignal,
): EnhancedResult => {
const state = createTraceState(input);
while (
state.queueIndex < state.queue.length &&
state.traversalPath.length === 0
) {
const address = state.queue[state.queueIndex++];
if (address === undefined) break;
const current = state.visited.get(address);
if (current === undefined) continue;
if (current.depth >= input.max_depth) {
state.frontier.add(address);
state.residual.add("Call-path traversal reached the depth limit.");
continue;
}
if (state.operations >= input.max_operations) {
recordPendingFrontier(state, input);
state.residual.add("Call-path traversal reached the operation budget.");
break;
}
state.operations += 1;
const found = await expandAddress(call, {
input,
state,
address,
current,
...(signal === undefined ? {} : { signal }),
});
if (found) break;
}
return ok(projectTrace(input, state));
};
const createTraceState = (input: CallPathTraceInput): TraceState => ({
visited: new Map([[input.start, { depth: 0, path: [input.start] }]]),
queue: [input.start],
edges: new Map(),
failures: [],
frontier: new Set(),
residual: new Set(),
operations: 0,
queueIndex: 0,
traversalPath: input.goal === input.start ? [input.start] : [],
});
const expandAddress = async (
call: AnalysisCall,
expansion: AddressExpansion,
): Promise<boolean> => {
const { input, state, address, current, signal } = expansion;
const relation = input.direction === "forward" ? "callees" : "callers";
const tool =
input.direction === "forward" ? "procedure_callees" : "procedure_callers";
const result = await call(tool, { procedure: address }, signal);
if (!result.ok) {
state.failures.push({
address,
error: projectAnalysisError(result.error),
});
state.residual.add(`Call relationships were unavailable for ${address}.`);
return false;
}
const related = parseRelatedAddresses(result.value, relation);
if (!related.ok) {
state.failures.push({
address,
error: projectAnalysisError(related.error),
});
state.residual.add(`Call relationships were unreadable for ${address}.`);
return false;
}
for (const relatedAddress of sortedUniqueAddresses(related.value)) {
recordEdge(input, state, {
address,
relatedAddress,
discoveryDepth: current.depth + 1,
});
const path = state.visited.get(relatedAddress)?.path ?? [
...current.path,
relatedAddress,
];
if (state.visited.has(relatedAddress)) {
if (relatedAddress === input.goal) {
state.traversalPath = path;
return true;
}
continue;
}
if (state.visited.size >= input.max_nodes) {
if (state.frontier.size < input.max_nodes)
state.frontier.add(relatedAddress);
state.residual.add("Call-path traversal reached the node limit.");
continue;
}
state.visited.set(relatedAddress, {
depth: current.depth + 1,
path,
});
if (relatedAddress === input.goal) {
state.traversalPath = path;
return true;
}
state.queue.push(relatedAddress);
}
return false;
};
const recordEdge = (
input: CallPathTraceInput,
state: TraceState,
edge: DiscoveredEdge,
): void => {
const sourceAddress =
input.direction === "forward" ? edge.address : edge.relatedAddress;
const targetAddress =
input.direction === "forward" ? edge.relatedAddress : edge.address;
const edgeKey = `${sourceAddress}\u0000${targetAddress}`;
if (state.edges.has(edgeKey) || state.edges.size >= input.max_nodes) return;
state.edges.set(edgeKey, {
source_address: sourceAddress,
target_address: targetAddress,
discovery_depth: edge.discoveryDepth,
});
};
const recordPendingFrontier = (
state: TraceState,
input: CallPathTraceInput,
): void => {
for (const pending of state.queue.slice(state.queueIndex - 1))
if (state.frontier.size < input.max_nodes) state.frontier.add(pending);
};
const projectTrace = (input: CallPathTraceInput, state: TraceState) => ({
start: input.start,
goal: input.goal ?? null,
direction: input.direction,
goal_status:
input.goal === undefined
? "not_requested"
: state.traversalPath.length > 0
? "reached"
: "not_reached",
nodes: [...state.visited.entries()]
.map(([address, { depth }]) => ({ address, depth }))
.sort(
(left, right) =>
left.depth - right.depth || compareAddress(left.address, right.address),
),
edges: [...state.edges.values()].sort(
(left, right) =>
left.discovery_depth - right.discovery_depth ||
compareAddress(left.source_address, right.source_address) ||
compareAddress(left.target_address, right.target_address),
),
traversal_path: state.traversalPath,
failures: state.failures,
frontier: [...state.frontier].sort(compareAddress),
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_operations: input.max_operations,
nodes_visited: state.visited.size,
operations_used: state.operations,
},
truncated: state.residual.size > 0,
residual_unknowns: [...state.residual],
limitations: [
"Direct provider call relationships may omit unresolved indirect calls.",
"A not_reached goal is only absent from this bounded traversal, not from the complete program.",
],
});
const compareAddress = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const sortedUniqueAddresses = (addresses: readonly string[]): string[] =>
[...new Set(addresses)].sort(compareAddress);
+185
View File
@@ -0,0 +1,185 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { AnalysisOutputError, type AnalysisError } from "../domain/errors.js";
import { parseAddressedPage } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
EnhancedResult,
TraceMatch,
TraceReference,
} from "./EnhancedToolTypes.js";
type AnalysisCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
type LiteralSearchSource = readonly [
"list_strings" | "list_procedures",
"string" | "procedure",
];
interface ReferenceTraceRequest {
readonly matches: readonly TraceMatch[];
readonly limit: number;
readonly operationBudget: number;
readonly signal?: AbortSignal;
}
const FEATURE_SEARCH_SOURCES: readonly LiteralSearchSource[] = [
["list_strings", "string"],
["list_procedures", "procedure"],
];
const STRING_SEARCH_SOURCES: readonly LiteralSearchSource[] = [
["list_strings", "string"],
];
export interface LiteralTraceInput {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
}
/** Trace a bounded feature or string literal through provider xrefs. */
export const traceLiteralFeature = async (
call: AnalysisCall,
input: LiteralTraceInput,
scope: "feature" | "string",
signal?: AbortSignal,
): EnhancedResult => {
const sources =
scope === "feature" ? FEATURE_SEARCH_SOURCES : STRING_SEARCH_SOURCES;
const searched = await literalMatches(call, input, sources, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await traceReferences(call, {
matches: searched.value.matches,
limit: input.limit,
operationBudget: input.max_operations - searched.value.operations,
...(signal === undefined ? {} : { signal }),
});
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
};
const literalMatches = async (
call: AnalysisCall,
input: LiteralTraceInput,
sources: readonly LiteralSearchSource[],
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> => {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive ? input.query : input.query.toLowerCase();
for (const [tool, type] of sources) {
let offset = 0;
while (operations < input.max_operations && matches.length < input.limit) {
operations += 1;
const result = await call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
};
const traceReferences = async (
call: AnalysisCall,
request: ReferenceTraceRequest,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> => {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of request.matches) {
if (operations >= request.operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await call(
"xrefs",
{ address: match.address },
request.signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-address value",
),
);
if (operations >= request.operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await call(
"resolve_containing_procedure",
{ address: source },
request.signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= request.limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= request.limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
};
+54 -165
View File
@@ -12,7 +12,6 @@ import {
} from "../domain/errors.js";
import {
addressDistance,
parseAddressedPage,
parseDocuments,
parseFunctionDossier,
parseListCount,
@@ -31,11 +30,11 @@ import type { JsonValue } from "../domain/jsonValue.js";
import {
invalidEnhancedInput,
type EnhancedResult,
type TraceMatch,
type TraceReference,
type ValidatedEnhancedCall,
} from "./EnhancedToolTypes.js";
import { readAllAddressed } from "./EnhancedToolPagination.js";
import { traceCallPath } from "./CallPathTracing.js";
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
export type { ValidatedEnhancedCall } from "./EnhancedToolTypes.js";
/**
@@ -52,6 +51,12 @@ export class EnhancedTools {
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
if (
name === "trace_feature" ||
name === "find_code_for_string" ||
name === "trace_call_path"
)
return this.#executeTracing(name, input, signal);
switch (name) {
case "swift_classes": {
const parsed = enhancedInputSchemas.swift_classes.safeParse(input);
@@ -99,12 +104,6 @@ export class EnhancedTools {
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
case "trace_feature": {
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
}
}
@@ -133,10 +132,55 @@ export class EnhancedTools {
case "analyze_function":
return this.#analyzeFunction(call.input, signal);
case "trace_feature":
return this.#traceFeature(call.input, signal);
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
"feature",
signal,
);
case "find_code_for_string":
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
"string",
signal,
);
case "trace_call_path":
return traceCallPath(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
signal,
);
}
}
#executeTracing(
name: "trace_feature" | "find_code_for_string" | "trace_call_path",
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
const parsed = enhancedInputSchemas[name].safeParse(input);
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
if (name === "trace_call_path")
return this.executeValidated(
{
name,
input: enhancedInputSchemas.trace_call_path.parse(parsed.data),
},
signal,
);
return this.executeValidated(
{
name,
input: enhancedInputSchemas[name].parse(parsed.data),
},
signal,
);
}
async #analyzeFunction(
input: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
@@ -346,161 +390,6 @@ export class EnhancedTools {
});
}
async #traceFeature(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): EnhancedResult {
const searched = await this.#literalMatches(input, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await this.#traceReferences(
searched.value.matches,
input.limit,
input.max_operations - searched.value.operations,
signal,
);
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
}
async #literalMatches(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive
? input.query
: input.query.toLowerCase();
for (const [tool, type] of [
["list_strings", "string"],
["list_procedures", "procedure"],
] as const) {
let offset = 0;
while (
operations < input.max_operations &&
matches.length < input.limit
) {
operations += 1;
const result = await this.#call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
}
async #traceReferences(
matches: readonly TraceMatch[],
limit: number,
operationBudget: number,
signal?: AbortSignal,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of matches) {
if (operations >= operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await this.#call(
"xrefs",
{ address: match.address },
signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-address value",
),
);
if (operations >= operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await this.#call(
"resolve_containing_procedure",
{ address: source },
signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
}
async #allAddressed(
tool: "list_names" | "list_procedures",
signal?: AbortSignal,