Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(javascript): name heap and semantic ceilings (#6022)

morlutoa0214e0e0e46
diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md
index c9d97e592..2e69b5111 100644
--- a/docs/javascript-artifact-reconstruction.md
+++ b/docs/javascript-artifact-reconstruction.md
@@ -597,8 +597,9 @@ The default semantic capacities are 100000 nodes across the application and
`--max-semantic-nodes-per-file`), each from 1 to 1000000. The per-file offer is
also bounded by the remaining application capacity. Raising these controls does
not bypass worker heap, execution deadline or parent result admission. Truncated
-coverage reports both effective node ceilings; omitted relationships remain
-unknown.
+coverage lists both effective ceilings, `max_semantic_nodes` and
+`max_semantic_nodes_per_file`. The limitation names only the ceiling that
+stopped retention. Omitted relationships remain unknown.
Unknown records have independent defaults of 100000 across the application and
20000 per source. Select `max_semantic_unknowns` and
@@ -606,8 +607,10 @@ Unknown records have independent defaults of 100000 across the application and
`--max-semantic-unknowns-per-file`), each from 1 to 1000000. The parent offers the
remaining capacity to the worker, and rejects excess records before adoption.
Unknown admission happens before canonical identity and provenance construction.
-When capacity is exhausted, coverage is partial and truncated and names both
-effective unknown ceilings. `coverage.omitted_unknown_occurrences` counts examined
+When capacity is exhausted, coverage is partial and truncated. Coverage lists
+both effective unknown ceilings, `max_semantic_unknowns` and
+`max_semantic_unknowns_per_file`. The limitation names only the ceiling that
+stopped retention. `coverage.omitted_unknown_occurrences` counts examined
emission occurrences by family and reason, including repeated emissions. It does
not claim distinct discarded identities or count frontiers in unexamined source.
Omitted unknown provenance and IDs are not retained. Existing source, node,
@@ -620,12 +623,35 @@ checkpoint at its 8 MiB bound with the same 6x retention expansion used at
admission. Earlier checkpoints are already charged to retained bytes; the
remaining inventory does not multiply the reserve. Streamed file transfers keep the default 512 MiB
allowance, and can grow with the parent's offered retention budget (8x byte
-expansion), up to 2 GiB. Individual records remain bounded to 8 MiB. The parent
+expansion), up to 2 GiB. Individual records remain bounded to 8 MiB. The 8 MiB
+record ceiling and the 2 GiB file maximum have no runtime override, and raising
+`max_heap_mb` does not raise them. The effective file ceiling follows the
+parent's offered result budget. On Node, a larger CLI/MCP process heap
+(`NODE_OPTIONS`, for example `--max-old-space-size=<MiB>`, after restarting that
+process) can raise it up to 2 GiB. Selecting fewer `source_paths` can also
+raise that effective allowance, because the reserve for remaining sources and
+earlier retained results reduce the offered budget. Neither change raises the
+record ceiling or the 2 GiB maximum. The parent
still independently checks actual bytes, record overhead, digests and source
identities before adopting results.
A source that exhausts the analyzer heap does not terminate the CLI/MCP
-process. Completed static facts are retained, other files can still be analyzed,
+process. On Node, the failure names `max_heap_mb` (CLI `--max-heap-mb`), the
+effective mebibytes, the inclusive range 128 to 16384, and the 1024 MiB
+default. A changed value applies on the next analysis, which starts a new
+worker. It does not change a worker that is already running and does not
+require restarting the REA server. On Bun, the same heap-exhaustion diagnostic
+is not attributed to that V8 old-space limit, because Bun ignores the flag.
+Raising `max_heap_mb` does not raise the parent result budget,
+the transfer record ceiling, the 2 GiB transfer file maximum, the CLI/MCP
+process heap, or fixed parser limits. The parent result budget follows that
+process heap. On Node, set `NODE_OPTIONS` (for example `--max-old-space-size=<MiB>`)
+in the environment that starts the CLI or MCP server, then restart that
+process, to raise the parent heap and the result budget. A completed static
+checkpoint that does not fit the parent's remaining heap names that parent
+process heap. Increasing `max_heap_mb` does not raise it. On Node, the same
+`NODE_OPTIONS` restart can raise the parent heap and admit the checkpoint.
+Completed static facts are retained, other files can still be analyzed,
and unexamined semantic relationships remain explicit unknowns. The parent
also checks transfer expansion and accumulated results against its remaining
heap before accepting semantic facts. A resource-limited result has partial
diff --git a/docs/javascript-recovery.md b/docs/javascript-recovery.md
index 3a10565f9..31594f3f3 100644
--- a/docs/javascript-recovery.md
+++ b/docs/javascript-recovery.md
@@ -129,10 +129,15 @@ equivalence remain unknown. No network fetching occurs.
## Resource policy and verification
-Each operation uses one worker, a 1 GiB address-space ceiling and a 120-second
-deadline; it accepts up to 64 MiB of total input across all selected files and
-128 MiB/10000 entries of staged
-output, with 8 MiB per diagnostic/report stream. Exceeding a limit is an explicit
+Each operation uses one worker, a 1 GiB address-space ceiling and a 120000 ms
+deadline. That deadline has no runtime override: raising `analysis_timeout_ms`
+or `max_heap_mb` does not raise it. An unchanged retry may hit the deadline
+again. The operation accepts up to 64 MiB of total
+input across all selected files and 128 MiB/10000 entries of staged output,
+with 8 MiB per diagnostic/report stream. A `provenance.json` over that report
+allowance names the fixed limit: this release has no runtime override, and
+raising `max_heap_mb` or `analysis_timeout_ms` does not raise it. Malformed
+reports stay distinct from that size refusal. Exceeding a limit is an explicit
failure with rollback. Selected inputs beyond the total input allowance return a
non-retryable `resource_constraint` with `resource: "file-size"` and
`reported_limits.maximum_input_bytes`/`remaining_input_bytes`; input that is not
diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
index ecf70049d..79226e184 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
@@ -748,6 +748,142 @@ it("bounds semantic node projection and reports the ceiling in coverage", () =>
({ name }) => name === "semantic_graph_node_ceiling",
),
).toBe(true);
+ expect(graph.coverage.limits).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: "max_semantic_nodes" }),
+ expect.objectContaining({ name: "max_semantic_nodes_per_file" }),
+ ]),
+ );
+ expect(graph.limitations.join("\n")).toContain(
+ "max_semantic_nodes_per_file is 20000",
+ );
+ expect(graph.limitations.join("\n")).not.toContain(
+ "max_semantic_nodes is 100000",
+ );
+ expect(graph.limitations.join("\n")).toContain("1 to 1000000");
+ expect(graph.coverage.limits).toEqual(
+ expect.arrayContaining([
+ { name: "semantic_graph_node_ceiling", value: 100_000, unit: "items" },
+ {
+ name: "semantic_graph_file_node_ceiling",
+ value: 20_000,
+ unit: "items",
+ },
+ { name: "max_semantic_nodes", value: 100_000, unit: "items" },
+ { name: "max_semantic_nodes_per_file", value: 20_000, unit: "items" },
+ ]),
+ );
+});
+
+const semanticApplication = {
+ graph_id: `jag_${"b".repeat(64)}`,
+ nodes: [],
+};
+
+const semanticFile = (path: string, value: string): JavaScriptArtifactFile => ({
+ path,
+ container_sha256: SHA256,
+ sha256: SHA256,
+ bytes: Buffer.byteLength(value),
+ inventory_artifact_id: `art_${SHA256}`,
+ kind: "javascript",
+ unpacked: false,
+ text: { included: true, value },
+});
+
+const finishSources = (
+ limits: {
+ readonly totalNodes: number;
+ readonly fileNodes: number;
+ },
+ sources: readonly { readonly path: string; readonly text: string }[],
+) => {
+ const projection = createJavaScriptSemanticGraphProjection(limits);
+ for (const source of sources)
+ projection.projectFile(
+ semanticFile(source.path, source.text),
+ analyzeJavaScriptSemantics(source.text),
+ );
+ return projection.finish(SHA256, semanticApplication);
+};
+
+it("names only the node ceiling that stopped retention", () => {
+ const references = (count: number) => "external;\n".repeat(count);
+ const perFile = finishSources({ totalNodes: 10, fileNodes: 3 }, [
+ { path: "only.js", text: references(5) },
+ ]);
+ expect(perFile.nodes).toHaveLength(3);
+ expect(perFile.limitations.join("\n")).toContain(
+ "max_semantic_nodes_per_file is 3",
+ );
+ expect(perFile.limitations.join("\n")).not.toContain(
+ "max_semantic_nodes is 10",
+ );
+ expect(perFile.coverage.limits).toEqual(
+ expect.arrayContaining([
+ { name: "semantic_graph_node_ceiling", value: 10, unit: "items" },
+ { name: "semantic_graph_file_node_ceiling", value: 3, unit: "items" },
+ { name: "max_semantic_nodes", value: 10, unit: "items" },
+ { name: "max_semantic_nodes_per_file", value: 3, unit: "items" },
+ ]),
+ );
+
+ const skipped = finishSources({ totalNodes: 4, fileNodes: 10 }, [
+ { path: "first.js", text: references(3) },
+ { path: "second.js", text: references(3) },
+ ]);
+ expect(skipped.nodes).toHaveLength(4);
+ expect(
+ skipped.nodes.filter((node) => node.identity.module_path === "second.js"),
+ ).toHaveLength(0);
+ expect(skipped.limitations.join("\n")).toContain("max_semantic_nodes is 4");
+ expect(skipped.limitations.join("\n")).not.toContain(
+ "max_semantic_nodes_per_file is 10",
+ );
+
+ const remaining = finishSources({ totalNodes: 5, fileNodes: 4 }, [
+ { path: "first.js", text: references(2) },
+ { path: "second.js", text: references(3) },
+ ]);
+ expect(remaining.nodes).toHaveLength(5);
+ expect(remaining.limitations.join("\n")).toContain("max_semantic_nodes is 5");
+ expect(remaining.limitations.join("\n")).not.toContain(
+ "max_semantic_nodes_per_file is 4",
+ );
+
+ const both = finishSources({ totalNodes: 5, fileNodes: 3 }, [
+ { path: "first.js", text: references(5) },
+ { path: "second.js", text: references(3) },
+ ]);
+ expect(both.nodes).toHaveLength(5);
+ expect(both.limitations.join("\n")).toContain("max_semantic_nodes is 5");
+ expect(both.limitations.join("\n")).toContain(
+ "max_semantic_nodes_per_file is 3",
+ );
+ expect(both.limitations.join("\n")).toContain(
+ "Set max_semantic_nodes and max_semantic_nodes_per_file",
+ );
+});
+
+it("attributes an adopted file to the ceiling that bounded its offer", () => {
+ const text = "external;\n".repeat(5);
+ const projection = createJavaScriptSemanticGraphProjection({
+ totalNodes: 10,
+ fileNodes: 3,
+ });
+ const steps = projectJavaScriptSemanticFileSteps(
+ semanticFile("adopted.js", text),
+ analyzeJavaScriptSemantics(text),
+ projection.remainingFileCapacity(),
+ );
+ let step = steps.next();
+ while (!step.done) step = steps.next();
+ projection.adoptFileProjection(step.value);
+ const limitation = projection
+ .finish(SHA256, semanticApplication)
+ .limitations.join("\n");
+ expect(limitation).toContain("max_semantic_nodes_per_file is 3");
+ expect(limitation).not.toContain("max_semantic_nodes is 10");
});
it("leaves a small application complete and untruncated", () => {
diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
index a890d5422..8e284ef25 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
@@ -53,6 +53,7 @@ import {
JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS,
JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM,
javaScriptAnalysisCoverageLimits,
+ javaScriptSemanticCeilingCoverage,
} from "../../domain/javascript/javascriptAnalysisResourceControls.js";
import { projectSemanticFunctionFingerprints } from "./JavaScriptSemanticGraphFingerprintProjection.js";
import {
@@ -205,6 +206,36 @@ export interface JavaScriptSemanticGraphProjection {
) => Generator<void, JavaScriptSemanticGraph>;
}
+/** Ceilings whose offered budget actually stopped retention. */
+interface SemanticCeilingReached {
+ total: boolean;
+ perFile: boolean;
+}
+
+/**
+ * Attribute a drop to the ceiling that bound this file's offer.
+ *
+ * The offer is the minimum of the per-file ceiling and the remaining
+ * application room. Only that smaller ceiling stopped retention. When the
+ * two values are equal, both did.
+ */
+const noteSemanticCeilingReached = (
+ reached: SemanticCeilingReached,
+ totalRoom: number,
+ perFileCeiling: number,
+): void => {
+ if (perFileCeiling <= totalRoom) reached.perFile = true;
+ if (totalRoom <= perFileCeiling) reached.total = true;
+};
+
+const semanticUnknownOccurrences = (
+ omissions: ReadonlyMap<string, { readonly occurrences: number }>,
+): number => {
+ let count = 0;
+ for (const omission of omissions.values()) count += omission.occurrences;
+ return count;
+};
+
/** Accumulate semantic nodes while each source IR is still file-local. */
export const createJavaScriptSemanticGraphProjection = (
limits: {
@@ -239,6 +270,14 @@ export const createJavaScriptSemanticGraphProjection = (
let truncatedFiles = 0;
let unavailableFiles = 0;
let resourceTruncatedFiles = 0;
+ const nodeCeilingsReached: SemanticCeilingReached = {
+ total: false,
+ perFile: false,
+ };
+ const unknownCeilingsReached: SemanticCeilingReached = {
+ total: false,
+ perFile: false,
+ };
const executionLimits = new Map<
string,
ApplicationCoverage["limits"][number]
@@ -250,20 +289,40 @@ export const createJavaScriptSemanticGraphProjection = (
): Generator<void, void> {
if (state.nodes.size >= nodeCeiling) {
truncatedFiles += 1;
+ noteSemanticCeilingReached(
+ nodeCeilingsReached,
+ nodeCeiling - state.nodes.size,
+ fileNodeCeiling,
+ );
return;
}
const remainingTreeBudget = nodeCeiling - state.nodes.size;
+ const unknownsBefore = state.unknowns.size;
+ const omissionsBefore = semanticUnknownOccurrences(state.unknownOmissions);
state.fileNodeBudget = Math.min(fileNodeCeiling, remainingTreeBudget);
state.fileNodesDropped = false;
state.unknownCapacity = Math.min(
unknownCeiling,
- state.unknowns.size + fileUnknownCeiling,
+ unknownsBefore + fileUnknownCeiling,
);
fingerprints.push(...(yield* projectFileSteps(file, ir, state, paths)));
// Nodes were dropped only if the budget actually blocked creation. A file
// that exactly fills its share ends with a zero budget without dropping
// anything, so the remaining budget alone cannot decide truncation.
- if (state.fileNodesDropped) truncatedFiles += 1;
+ if (state.fileNodesDropped) {
+ truncatedFiles += 1;
+ noteSemanticCeilingReached(
+ nodeCeilingsReached,
+ remainingTreeBudget,
+ fileNodeCeiling,
+ );
+ }
+ if (semanticUnknownOccurrences(state.unknownOmissions) > omissionsBefore)
+ noteSemanticCeilingReached(
+ unknownCeilingsReached,
+ unknownCeiling - unknownsBefore,
+ fileUnknownCeiling,
+ );
state.fileNodeBudget = null;
state.unknownCapacity = null;
};
@@ -291,6 +350,23 @@ export const createJavaScriptSemanticGraphProjection = (
unknownIdsByFamily.set(unknown.family, [unknown.unknown_id]);
else identifiers.push(unknown.unknown_id);
}
+ const unknownCeilingCoverage = unknownsDropped
+ ? javaScriptSemanticCeilingCoverage(
+ "unknowns",
+ unknownCeiling,
+ fileUnknownCeiling,
+ unknownCeilingsReached,
+ )
+ : undefined;
+ const nodeCeilingCoverage =
+ truncatedFiles > 0
+ ? javaScriptSemanticCeilingCoverage(
+ "nodes",
+ nodeCeiling,
+ fileNodeCeiling,
+ nodeCeilingsReached,
+ )
+ : undefined;
const graph = factory({
schema: "JavaScriptSemanticRelationGraph",
root_artifact_sha256: rootArtifactSha256,
@@ -317,34 +393,8 @@ export const createJavaScriptSemanticGraphProjection = (
truncatedFiles > 0 || unavailableFiles > 0 ? null : 0,
limits: [
...executionLimits.values(),
- ...(unknownsDropped
- ? [
- {
- name: "semantic_graph_unknown_ceiling",
- value: unknownCeiling,
- unit: "items" as const,
- },
- {
- name: "semantic_graph_file_unknown_ceiling",
- value: fileUnknownCeiling,
- unit: "items" as const,
- },
- ]
- : []),
- ...(truncatedFiles > 0
- ? [
- {
- name: "semantic_graph_node_ceiling",
- value: nodeCeiling,
- unit: "items" as const,
- },
- {
- name: "semantic_graph_file_node_ceiling",
- value: fileNodeCeiling,
- unit: "items" as const,
- },
- ]
- : []),
+ ...(unknownCeilingCoverage?.limits ?? []),
+ ...(nodeCeilingCoverage?.limits ?? []),
],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
@@ -356,11 +406,14 @@ export const createJavaScriptSemanticGraphProjection = (
})),
},
limitations: [
- ...(unknownsDropped
- ? [
- "Semantic unknown retention reached an effective capacity. Omission coverage counts examined emission occurrences by family and reason, including repeats; it does not count unexamined source frontiers or distinct discarded identities.",
- ]
- : []),
+ ...(unknownCeilingCoverage === undefined
+ ? []
+ : [
+ `${unknownCeilingCoverage.limitation} Omission coverage counts examined emission occurrences by family and reason, including repeats; it does not count unexamined source frontiers or distinct discarded identities.`,
+ ]),
+ ...(nodeCeilingCoverage === undefined
+ ? []
+ : [nodeCeilingCoverage.limitation]),
"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.",
@@ -395,6 +448,10 @@ export const createJavaScriptSemanticGraphProjection = (
),
}),
adoptFileProjection: (projection) => {
+ // Production offers remainingFileCapacity(), already the minimum of
+ // the per-file ceiling and the room left in the application total.
+ const remainingNodes = nodeCeiling - state.nodes.size;
+ const remainingUnknowns = unknownCeiling - state.unknowns.size;
const newNodes = projection.nodes.filter(
({ node_id }) => !state.nodes.has(node_id),
);
@@ -426,7 +483,20 @@ export const createJavaScriptSemanticGraphProjection = (
state.unknowns.set(unknown.unknown_id, unknown);
for (const root of projection.roots) state.roots.add(root);
fingerprints.push(...projection.fingerprints);
- if (projection.nodesTruncated) truncatedFiles += 1;
+ if (projection.nodesTruncated) {
+ truncatedFiles += 1;
+ noteSemanticCeilingReached(
+ nodeCeilingsReached,
+ remainingNodes,
+ fileNodeCeiling,
+ );
+ }
+ if ((projection.omittedUnknownOccurrences?.length ?? 0) > 0)
+ noteSemanticCeilingReached(
+ unknownCeilingsReached,
+ remainingUnknowns,
+ fileUnknownCeiling,
+ );
},
recordUnavailableFile: (file, reason, limits, unknownReason) => {
// Both full and incremental construction enter here. Metadata/native
@@ -460,9 +530,13 @@ export const createJavaScriptSemanticGraphProjection = (
coverage: partialApplicationCoverage(retainedLimits, null),
limitations: [reason],
};
+ const unknownsBefore = state.unknowns.size;
+ const omissionsBefore = semanticUnknownOccurrences(
+ state.unknownOmissions,
+ );
state.unknownCapacity = Math.min(
unknownCeiling,
- state.unknowns.size + fileUnknownCeiling,
+ unknownsBefore + fileUnknownCeiling,
);
for (const family of JAVASCRIPT_SEMANTIC_RELATION_FAMILIES) {
addSemanticGraphUnknown(state, {
@@ -479,6 +553,12 @@ export const createJavaScriptSemanticGraphProjection = (
});
}
state.unknownCapacity = null;
+ if (semanticUnknownOccurrences(state.unknownOmissions) > omissionsBefore)
+ noteSemanticCeilingReached(
+ unknownCeilingsReached,
+ unknownCeiling - unknownsBefore,
+ fileUnknownCeiling,
+ );
unavailableFiles += 1;
if (unknownReason === "resource-limit" && retainedLimits.length > 0)
resourceTruncatedFiles += 1;
diff --git a/src/application/javascript/JavaScriptSemanticUnknownCapacity.test.ts b/src/application/javascript/JavaScriptSemanticUnknownCapacity.test.ts
index c8d3999c0..40fd99fde 100644
--- a/src/application/javascript/JavaScriptSemanticUnknownCapacity.test.ts
+++ b/src/application/javascript/JavaScriptSemanticUnknownCapacity.test.ts
@@ -70,8 +70,17 @@ it("bounds unknowns independently of retained nodes and accounts for examined om
expect.arrayContaining([
{ name: "semantic_graph_unknown_ceiling", value: 2, unit: "items" },
{ name: "semantic_graph_file_unknown_ceiling", value: 2, unit: "items" },
+ { name: "max_semantic_unknowns", value: 2, unit: "items" },
+ { name: "max_semantic_unknowns_per_file", value: 2, unit: "items" },
]),
);
+ expect(graph.limitations.join("\n")).toContain("max_semantic_unknowns is 2");
+ expect(graph.limitations.join("\n")).toContain(
+ "max_semantic_unknowns_per_file is 2",
+ );
+ expect(graph.limitations.join("\n")).toContain(
+ "Omission coverage counts examined emission occurrences",
+ );
expect(javaScriptSemanticGraphSchema.parse(graph)).toEqual(graph);
expect(
queryJavaScriptSemanticGraph(graph, {
@@ -123,6 +132,70 @@ it("enforces per-file and total unknown capacities across transferred files", ()
0,
),
).toBe(fileProjection().unknowns.length * 3 - 3);
+ expect(graph.limitations.join("\n")).toContain("max_semantic_unknowns is 3");
+ expect(graph.limitations.join("\n")).toContain(
+ "max_semantic_unknowns_per_file is 2",
+ );
+ expect(graph.coverage.limits).toEqual(
+ expect.arrayContaining([
+ { name: "semantic_graph_unknown_ceiling", value: 3, unit: "items" },
+ { name: "semantic_graph_file_unknown_ceiling", value: 2, unit: "items" },
+ { name: "max_semantic_unknowns", value: 3, unit: "items" },
+ { name: "max_semantic_unknowns_per_file", value: 2, unit: "items" },
+ ]),
+ );
+});
+
+it("names only the unknown ceiling that stopped retention", () => {
+ const perFile = createJavaScriptSemanticGraphProjection({
+ totalUnknowns: 50,
+ fileUnknowns: 2,
+ });
+ perFile.projectFile(source(), analyzeJavaScriptSemantics(text));
+ const perFileGraph = perFile.finish(digest, application);
+ expect(perFileGraph.limitations.join("\n")).toContain(
+ "max_semantic_unknowns_per_file is 2",
+ );
+ expect(perFileGraph.limitations.join("\n")).not.toContain(
+ "max_semantic_unknowns is 50",
+ );
+ expect(perFileGraph.coverage.limits).toEqual(
+ expect.arrayContaining([
+ { name: "semantic_graph_unknown_ceiling", value: 50, unit: "items" },
+ { name: "semantic_graph_file_unknown_ceiling", value: 2, unit: "items" },
+ { name: "max_semantic_unknowns", value: 50, unit: "items" },
+ { name: "max_semantic_unknowns_per_file", value: 2, unit: "items" },
+ ]),
+ );
+
+ const total = createJavaScriptSemanticGraphProjection({
+ totalUnknowns: 2,
+ fileUnknowns: 50,
+ });
+ total.projectFile(source(), analyzeJavaScriptSemantics(text));
+ const totalLimitation = total
+ .finish(digest, application)
+ .limitations.join("\n");
+ expect(totalLimitation).toContain("max_semantic_unknowns is 2");
+ expect(totalLimitation).not.toContain("max_semantic_unknowns_per_file is 50");
+
+ const unavailable = createJavaScriptSemanticGraphProjection({
+ totalUnknowns: 20,
+ fileUnknowns: 2,
+ });
+ unavailable.recordUnavailableFile(
+ source(),
+ "Source unavailable",
+ null,
+ "incomplete-module",
+ );
+ const unavailableLimitation = unavailable
+ .finish(digest, application)
+ .limitations.join("\n");
+ expect(unavailableLimitation).toContain(
+ "max_semantic_unknowns_per_file is 2",
+ );
+ expect(unavailableLimitation).not.toContain("max_semantic_unknowns is 20");
});
it("rejects excess transferred unknowns before adopting any file facts", () => {
diff --git a/src/domain/explicitSensitiveFailure.test.ts b/src/domain/explicitSensitiveFailure.test.ts
index aedb79d44..727b455b1 100644
--- a/src/domain/explicitSensitiveFailure.test.ts
+++ b/src/domain/explicitSensitiveFailure.test.ts
@@ -166,6 +166,26 @@ it("redacts cleanup primaries and mirrors the source error's live status", () =>
});
});
+it("keeps a named timeout control through explicit-value redaction", () => {
+ const error = new AnalysisTimeoutError(
+ "analyze_javascript_application",
+ 300000,
+ {
+ userMessage:
+ "JavaScript source analysis reached its 300000ms per-source server/provider deadline (analysis_timeout_ms) for explicit-secret, not the MCP client deadline.",
+ remediationAction:
+ "Increase analysis_timeout_ms through MCP for explicit-secret, or use rea analyze-javascript-application <input_path> --analysis-timeout-ms <milliseconds> on the CLI.",
+ },
+ );
+ const redacted = redactExplicitFailure(error, ["explicit-secret"]);
+ const projected = projectAnalysisError(redacted);
+ expect(projected.message).toContain("analysis_timeout_ms");
+ expect(projected.message).toContain("300000");
+ expect(projected.remediation.action).toContain("analysis_timeout_ms");
+ expect(projected.remediation.action).toContain("--analysis-timeout-ms");
+ expect(JSON.stringify(projected)).not.toContain("explicit-secret");
+});
+
it("keeps unsupported profile reasons distinct from malformed input", () => {
const error = new AnalysisCapabilityUnavailableError(
"mitmproxy",
diff --git a/src/domain/explicitSensitiveFailure.ts b/src/domain/explicitSensitiveFailure.ts
index 5cdd9ae3b..8acf9d5fa 100644
--- a/src/domain/explicitSensitiveFailure.ts
+++ b/src/domain/explicitSensitiveFailure.ts
@@ -127,6 +127,12 @@ const redactFailure = (
if (error instanceof AnalysisTimeoutError)
return new AnalysisTimeoutError(error.operation, error.timeoutMs, {
...context,
+ ...(error.userMessage === undefined
+ ? {}
+ : { userMessage: text(error.userMessage) }),
+ ...(error.remediationAction === undefined
+ ? {}
+ : { remediationAction: text(error.remediationAction) }),
});
if (error instanceof AnalysisAccessDeniedError)
return new AnalysisAccessDeniedError(
diff --git a/src/domain/javascript/javascriptAnalysisResourceControls.test.ts b/src/domain/javascript/javascriptAnalysisResourceControls.test.ts
index 8d04b603d..20584bf3d 100644
--- a/src/domain/javascript/javascriptAnalysisResourceControls.test.ts
+++ b/src/domain/javascript/javascriptAnalysisResourceControls.test.ts
@@ -1,5 +1,18 @@
import { expect, it } from "vitest";
-import { javaScriptAnalysisResourceControlsSchema } from "./javascriptAnalysisResourceControls.js";
+import { AnalysisResourceConstraintError } from "../analysisErrorCore.js";
+import { projectAnalysisError } from "../analysisErrorProjection.js";
+import {
+ JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS,
+ JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION,
+ JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION,
+ JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM,
+ JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM,
+ JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM,
+ javaScriptAnalysisResourceControlsSchema,
+ javaScriptWorkerHeapExhaustionRecovery,
+ javaScriptSemanticCeilingCoverage,
+ javaScriptWorkerHeapRemediation,
+} from "./javascriptAnalysisResourceControls.js";
it("keeps omitted operational choices absent and validates explicit semantic budgets", () => {
expect(javaScriptAnalysisResourceControlsSchema.parse({})).toEqual({});
@@ -29,3 +42,183 @@ it("keeps omitted operational choices absent and validates explicit semantic bud
).toBe(false);
}
});
+
+it("names max_heap_mb, its range, and the budgets it does not raise", () => {
+ const heapMb = JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.heapMb;
+ const error = new AnalysisResourceConstraintError(
+ "analyze_javascript_application",
+ "memory",
+ `Owned JavaScript worker exhausted its ${String(heapMb)} MiB V8 old-space heap (max_heap_mb) while analyzing app.js during static`,
+ { worker_old_space_mb: heapMb },
+ { remediationAction: javaScriptWorkerHeapRemediation(heapMb) },
+ );
+ const projected = projectAnalysisError(error);
+ expect(projected.message).toContain(`max_heap_mb`);
+ expect(projected.message).toContain(`${String(heapMb)} MiB`);
+ expect(projected.remediation.action).toContain("max_heap_mb");
+ expect(projected.remediation.action).toContain(
+ String(JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM),
+ );
+ expect(projected.remediation.action).toContain(
+ String(JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM),
+ );
+ expect(projected.remediation.action).toContain("--max-heap-mb");
+ expect(projected.remediation.action).toContain("next analysis");
+ expect(projected.remediation.action).toContain("new worker");
+ expect(projected.remediation.action).toContain("parent result budget");
+ expect(projected.remediation.action).toContain("transfer");
+ expect(projected.remediation.action).not.toMatch(/available host memory/u);
+ const maximum = projectAnalysisError(
+ new AnalysisResourceConstraintError(
+ "analyze_javascript_application",
+ "memory",
+ "heap",
+ null,
+ {
+ remediationAction: javaScriptWorkerHeapRemediation(
+ JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM,
+ ),
+ },
+ ),
+ );
+ expect(maximum.remediation.action).toContain("Do not increase it further");
+});
+
+it("names the parent heap control for the parent result budget", () => {
+ expect(JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION).toContain(
+ "parent result budget",
+ );
+ expect(JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION).toContain("NODE_OPTIONS");
+ expect(JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION).toContain(
+ "--max-old-space-size=<MiB>",
+ );
+ expect(JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION).toContain("max_heap_mb");
+ expect(JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION).not.toContain(
+ "no runtime override",
+ );
+});
+
+it("names the parent heap control for checkpoint decode", () => {
+ expect(JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION).toContain(
+ "parent process heap",
+ );
+ expect(JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION).toContain(
+ "NODE_OPTIONS",
+ );
+ expect(JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION).toContain(
+ "--max-old-space-size=<MiB>",
+ );
+ expect(JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION).toContain(
+ "admit this checkpoint",
+ );
+ expect(JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION).toContain(
+ "Increasing max_heap_mb does not raise it",
+ );
+});
+
+it("attributes V8 heap exhaustion to max_heap_mb only when that flag is enforced", () => {
+ const node = javaScriptWorkerHeapExhaustionRecovery({
+ heapFlagsEnforced: true,
+ heapMb: 1024,
+ path: "app.js",
+ phase: "static",
+ });
+ expect(node.reason).toContain(
+ "exhausted its 1024 MiB V8 old-space heap (max_heap_mb)",
+ );
+ expect(node.remediationAction).toContain("max_heap_mb");
+ expect(node.remediationAction).toContain("--max-heap-mb");
+ const bun = javaScriptWorkerHeapExhaustionRecovery({
+ heapFlagsEnforced: false,
+ heapMb: 1024,
+ path: "app.js",
+ phase: "static",
+ });
+ expect(bun.reason).toContain("Bun ignores the V8 old-space flag");
+ expect(bun.reason).not.toContain(
+ "exhausted its 1024 MiB V8 old-space heap (max_heap_mb)",
+ );
+ expect(bun.remediationAction).toContain("Bun ignores V8 heap flags");
+ expect(bun.remediationAction).not.toContain("Increase max_heap_mb");
+});
+
+it("names the four semantic arguments on ceiling coverage", () => {
+ const both = { total: true, perFile: true };
+ const nodes = javaScriptSemanticCeilingCoverage("nodes", 50, 30, both);
+ const unknowns = javaScriptSemanticCeilingCoverage("unknowns", 3, 2, both);
+ const perFileOnly = javaScriptSemanticCeilingCoverage("nodes", 50, 30, {
+ total: false,
+ perFile: true,
+ });
+ const totalOnly = javaScriptSemanticCeilingCoverage("unknowns", 3, 2, {
+ total: true,
+ perFile: false,
+ });
+ expect(nodes.limits).toEqual(perFileOnly.limits);
+ expect(nodes.limits).toEqual(
+ expect.arrayContaining([
+ { name: "semantic_graph_node_ceiling", value: 50, unit: "items" },
+ { name: "semantic_graph_file_node_ceiling", value: 30, unit: "items" },
+ { name: "max_semantic_nodes", value: 50, unit: "items" },
+ { name: "max_semantic_nodes_per_file", value: 30, unit: "items" },
+ ]),
+ );
+ expect(unknowns.limits).toEqual(totalOnly.limits);
+ expect(unknowns.limits).toEqual(
+ expect.arrayContaining([
+ { name: "semantic_graph_unknown_ceiling", value: 3, unit: "items" },
+ { name: "semantic_graph_file_unknown_ceiling", value: 2, unit: "items" },
+ { name: "max_semantic_unknowns", value: 3, unit: "items" },
+ { name: "max_semantic_unknowns_per_file", value: 2, unit: "items" },
+ ]),
+ );
+ expect(nodes.limitation).toContain("1 to");
+ expect(nodes.limitation).toContain(String(JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM));
+ expect(nodes.limitation).toContain(
+ "CLI: --max-semantic-nodes and --max-semantic-nodes-per-file",
+ );
+ expect(nodes.limitation).toContain(
+ "Set max_semantic_nodes and max_semantic_nodes_per_file",
+ );
+ expect(nodes.limitation).toContain("Raising them does not raise");
+ expect(nodes.limitation).toContain("next analysis");
+ expect(unknowns.limitation).toContain(
+ "CLI: --max-semantic-unknowns and --max-semantic-unknowns-per-file",
+ );
+ expect(unknowns.limitation).toContain("max_semantic_nodes");
+ expect(perFileOnly.limitation).toContain("max_semantic_nodes_per_file is 30");
+ expect(perFileOnly.limitation).toContain(
+ "Set max_semantic_nodes_per_file on the next",
+ );
+ expect(perFileOnly.limitation).toContain(
+ "CLI: --max-semantic-nodes-per-file",
+ );
+ expect(perFileOnly.limitation).toContain("Raising it does not raise");
+ expect(perFileOnly.limitation).not.toContain("max_semantic_nodes is 50");
+ expect(perFileOnly.limitation).not.toContain("--max-semantic-nodes and");
+ expect(totalOnly.limitation).toContain("max_semantic_unknowns is 3");
+ expect(totalOnly.limitation).toContain(
+ "Set max_semantic_unknowns on the next",
+ );
+ expect(totalOnly.limitation).toContain("CLI: --max-semantic-unknowns)");
+ expect(totalOnly.limitation).not.toContain(
+ "max_semantic_unknowns_per_file is 2",
+ );
+ expect(totalOnly.limitation).not.toContain(
+ "--max-semantic-unknowns-per-file",
+ );
+ const capped = javaScriptSemanticCeilingCoverage(
+ "nodes",
+ JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM,
+ 30,
+ { total: true, perFile: false },
+ );
+ expect(capped.limitation).toContain("Do not increase it further");
+ expect(capped.limitation).not.toContain("max_semantic_nodes_per_file is 30");
+ expect(() =>
+ javaScriptSemanticCeilingCoverage("nodes", 50, 30, {
+ total: false,
+ perFile: false,
+ }),
+ ).toThrow("ceiling that stopped retention");
+});
diff --git a/src/domain/javascript/javascriptAnalysisResourceControls.ts b/src/domain/javascript/javascriptAnalysisResourceControls.ts
index deec5b821..c6b9d59f5 100644
--- a/src/domain/javascript/javascriptAnalysisResourceControls.ts
+++ b/src/domain/javascript/javascriptAnalysisResourceControls.ts
@@ -12,9 +12,160 @@ export const JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS = {
semanticUnknownsPerFile: 20_000,
} as const;
+/** Inclusive `max_heap_mb` range. The worker reads it only when that process starts. */
+export const JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM = 128;
+export const JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM = 16_384;
+
/** Maximum caller-selected retained record capacity; heap and transfer admission still apply. */
export const JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM = 1_000_000;
+const HEAP_DOES_NOT_RAISE =
+ "Raising max_heap_mb does not raise the parent result budget, transfer record or transfer file byte ceilings, the CLI/MCP process heap, or fixed parser limits.";
+
+/**
+ * Recovery for the isolated analyzer heap. A changed value applies on the next
+ * analysis because the V8 flag is fixed at worker launch and a different heap
+ * is not reused.
+ */
+export const javaScriptWorkerHeapRemediation = (heapMb: number): string => {
+ const bounds = `an integer from ${String(JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM)} to ${String(JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM)} (default ${String(JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.heapMb)} MiB)`;
+ const adjustment =
+ heapMb >= JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM
+ ? `max_heap_mb is already ${String(heapMb)} MiB, the maximum ${String(JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM)}. Do not increase it further.`
+ : `Increase max_heap_mb (CLI: rea analyze-javascript-application <input_path> --max-heap-mb <mebibytes>), ${bounds}.`;
+ return `${adjustment} The effective worker heap for this analysis is ${String(heapMb)} MiB. A changed max_heap_mb applies on the next analysis, which starts a new worker. It does not change a worker that is already running, and it does not require restarting the REA server. ${HEAP_DOES_NOT_RAISE} On Bun, V8 heap flags are ignored: Windows limits the analyzer's committed memory to max_heap_mb plus a 512 MiB reserve, and other Bun hosts enforce no analyzer heap limit.`;
+};
+
+/**
+ * Node control for the CLI/MCP process heap. The old-space flag requires a
+ * mebibyte value; a bare name is an illegal V8 option and prevents Node from
+ * starting.
+ */
+export const JAVASCRIPT_PARENT_HEAP_NODE_OPTIONS =
+ "On Node, set NODE_OPTIONS (for example --max-old-space-size=<MiB>) in the environment that starts the CLI or MCP server, then restart that process,";
+
+/** Parent admission follows the CLI/MCP heap, not the isolated worker heap argument. */
+export const JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION = `This limit belongs to the parent result budget. That budget follows the parent V8 heap limit. Increasing max_heap_mb does not raise it. ${JAVASCRIPT_PARENT_HEAP_NODE_OPTIONS} to raise the parent heap and this budget. Use the retained static facts or analyze fewer source files.`;
+
+/** Checkpoint decode uses the parent heap, not the isolated worker heap argument. */
+export const JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION = `This limit belongs to the parent process heap. Increasing max_heap_mb does not raise it. max_heap_mb changes only the isolated analyzer, on the next analysis, by starting a new worker. ${JAVASCRIPT_PARENT_HEAP_NODE_OPTIONS} to raise the parent heap and admit this checkpoint.`;
+
+/**
+ * Heap-exhaustion exit text. Node exhausted the configured V8 old-space.
+ * Bun ignores that flag, so the same diagnostic must not name it as the cause.
+ */
+export const javaScriptWorkerHeapExhaustionRecovery = (input: {
+ readonly heapFlagsEnforced: boolean;
+ readonly heapMb: number;
+ readonly path: string;
+ readonly phase: string;
+}): { readonly reason: string; readonly remediationAction: string } => {
+ if (input.heapFlagsEnforced)
+ return {
+ reason: `Owned JavaScript worker exhausted its ${String(input.heapMb)} MiB V8 old-space heap (max_heap_mb) while analyzing ${input.path} during ${input.phase}`,
+ remediationAction: javaScriptWorkerHeapRemediation(input.heapMb),
+ };
+ return {
+ reason: `Owned JavaScript worker ran out of memory while analyzing ${input.path} during ${input.phase}. Bun ignores the V8 old-space flag, so this exit is not the configured max_heap_mb limit of ${String(input.heapMb)} MiB.`,
+ remediationAction:
+ "Bun ignores V8 heap flags, so raising max_heap_mb does not change this exit. Windows limits the analyzer's committed memory to max_heap_mb plus a 512 MiB reserve and reports that separately as a process memory limit. Other Bun hosts enforce no analyzer heap limit. Reduce the analysis instead of increasing max_heap_mb.",
+ };
+};
+
+const semanticControl = {
+ nodes: {
+ total: "max_semantic_nodes",
+ perFile: "max_semantic_nodes_per_file",
+ ceiling: "semantic_graph_node_ceiling",
+ fileCeiling: "semantic_graph_file_node_ceiling",
+ totalDefault: JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.semanticNodes,
+ perFileDefault: JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.semanticNodesPerFile,
+ cliTotal: "--max-semantic-nodes",
+ cliPerFile: "--max-semantic-nodes-per-file",
+ doesNotRaise:
+ "max_semantic_unknowns, max_heap_mb, transfer ceilings, or the parent result budget",
+ },
+ unknowns: {
+ total: "max_semantic_unknowns",
+ perFile: "max_semantic_unknowns_per_file",
+ ceiling: "semantic_graph_unknown_ceiling",
+ fileCeiling: "semantic_graph_file_unknown_ceiling",
+ totalDefault: JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.semanticUnknowns,
+ perFileDefault:
+ JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.semanticUnknownsPerFile,
+ cliTotal: "--max-semantic-unknowns",
+ cliPerFile: "--max-semantic-unknowns-per-file",
+ doesNotRaise:
+ "max_semantic_nodes, max_heap_mb, transfer ceilings, or the parent result budget",
+ },
+} as const;
+
+const semanticAdjustment = (
+ name: string,
+ value: number,
+ fallback: number,
+): string =>
+ value >= JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM
+ ? `${name} is already ${String(value)}, the maximum ${String(JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM)}. Do not increase it further.`
+ : `${name} is ${String(value)} (default ${String(fallback)}; an integer from 1 to ${String(JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM)})`;
+
+/**
+ * Name the caller arguments for one semantic retention ceiling.
+ * Coverage limits list both effective values. The limitation claims only
+ * the ceilings that stopped retention.
+ */
+export const javaScriptSemanticCeilingCoverage = (
+ kind: "nodes" | "unknowns",
+ total: number,
+ perFile: number,
+ reached: { readonly total: boolean; readonly perFile: boolean },
+): {
+ readonly limits: ApplicationCoverage["limits"];
+ readonly limitation: string;
+} => {
+ const control = semanticControl[kind];
+ const limits: ApplicationCoverage["limits"] = [
+ { name: control.ceiling, value: total, unit: "items" },
+ { name: control.fileCeiling, value: perFile, unit: "items" },
+ { name: control.total, value: total, unit: "items" },
+ { name: control.perFile, value: perFile, unit: "items" },
+ ];
+ const reachedControls = [
+ ...(reached.total
+ ? [
+ {
+ name: control.total,
+ value: total,
+ fallback: control.totalDefault,
+ cli: control.cliTotal,
+ },
+ ]
+ : []),
+ ...(reached.perFile
+ ? [
+ {
+ name: control.perFile,
+ value: perFile,
+ fallback: control.perFileDefault,
+ cli: control.cliPerFile,
+ },
+ ]
+ : []),
+ ];
+ if (reachedControls.length === 0)
+ throw new RangeError(
+ "Semantic ceiling coverage requires a ceiling that stopped retention",
+ );
+ const reachedText = reachedControls
+ .map((item) => semanticAdjustment(item.name, item.value, item.fallback))
+ .join(" and ");
+ const names = reachedControls.map((item) => item.name).join(" and ");
+ const cli = reachedControls.map((item) => item.cli).join(" and ");
+ const raising = reachedControls.length === 1 ? "Raising it" : "Raising them";
+ const limitation = `Semantic ${kind === "nodes" ? "node" : "unknown"} retention reached ${reachedText}. Set ${names} on the next analyze_javascript_application call (CLI: ${cli}). The change applies to that next analysis and does not restart the worker or the REA server. ${raising} does not raise ${control.doesNotRaise}. Coverage reports the same effective values as ${control.ceiling} and ${control.fileCeiling}.`;
+ return { limits, limitation };
+};
+
/** Project observed execution limits without inventing unmeasured values. */
export const javaScriptAnalysisCoverageLimits = (
limits: Readonly<Record<string, JsonValue>> | null,
@@ -83,8 +234,8 @@ export const javaScriptAnalysisResourceControlsSchema = z.strictObject({
max_heap_mb: z
.number()
.int()
- .min(128)
- .max(16_384)
+ .min(JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM)
+ .max(JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM)
.optional()
.describe(
"Maximum V8 old-space heap in MiB for the isolated JavaScript source analyzer; defaults to 1024. This does not change the CLI/MCP process heap. When REA runs on Bun, which ignores V8 heap flags, Windows instead limits the analyzer's committed memory to this budget plus a 512 MiB runtime reserve; other Bun hosts enforce no limit.",
diff --git a/src/javascript/analysis/JavaScriptAnalysisTransfer.recovery.test.ts b/src/javascript/analysis/JavaScriptAnalysisTransfer.recovery.test.ts
new file mode 100644
index 000000000..e93aa4694
--- /dev/null
+++ b/src/javascript/analysis/JavaScriptAnalysisTransfer.recovery.test.ts
@@ -0,0 +1,68 @@
+import { expect, it } from "vitest";
+import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
+import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
+import { projectJavaScriptModuleSemantics } from "../../domain/javascript/javascriptModuleSemanticIr.js";
+import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
+import {
+ javaScriptForwardedTransferRemediation,
+ javaScriptTransferCeilingRemediation,
+ measureJavaScriptModuleTransfer,
+} from "./JavaScriptAnalysisTransfer.js";
+
+it("distinguishes the adjustable transfer file ceiling from the fixed record and maximum ceilings", () => {
+ const ir = analyzeJavaScriptSemantics(
+ "export function add(value) { return value + 1; }",
+ );
+ const module = projectJavaScriptModuleSemantics(ir);
+ const measured = measureJavaScriptModuleTransfer(module);
+ let caught: unknown;
+ try {
+ measureJavaScriptModuleTransfer(module, measured.bytes - 1);
+ } catch (cause) {
+ caught = cause;
+ }
+ if (!(caught instanceof AnalysisResourceConstraintError))
+ throw new Error("Expected a transfer ceiling refusal");
+ const projected = projectAnalysisError(caught);
+ expect(projected.message).toContain("no runtime override");
+ expect(projected.message).toContain(
+ String(caught.reportedLimits?.transfer_file_bytes),
+ );
+ expect(projected.remediation.action).toContain("no runtime override");
+ expect(projected.remediation.action).toContain("max_heap_mb");
+ expect(projected.remediation.action).toContain("8388608");
+ expect(projected.remediation.action).toContain("2147483648");
+ expect(projected.remediation.action).toContain("NODE_OPTIONS");
+ expect(projected.remediation.action).toContain("--max-old-space-size=<MiB>");
+ expect(projected.remediation.action).toContain(
+ "Selecting fewer source_paths can",
+ );
+ expect(projected.remediation.action).not.toContain(
+ "Selecting fewer source_paths does not raise them",
+ );
+ expect(projected.remediation.action).not.toContain("get_evidence_bundle");
+ expect(projected.message).toContain("can rise until the maximum");
+ const forwarded = javaScriptForwardedTransferRemediation(
+ caught.reportedLimits,
+ );
+ expect(forwarded).toContain("NODE_OPTIONS");
+ expect(forwarded).toContain("Selecting fewer source_paths can");
+ const recordOnly = javaScriptForwardedTransferRemediation({
+ transfer_record_bytes: 8_388_608,
+ });
+ expect(recordOnly).toContain("NODE_OPTIONS");
+ expect(recordOnly).toContain("can be lower than the maximum");
+ expect(recordOnly).not.toContain(
+ "The effective transfer file ceiling is the 2147483648-byte maximum",
+ );
+});
+
+it("keeps the 2 GiB transfer file maximum fixed", () => {
+ const remediation = javaScriptTransferCeilingRemediation(2_147_483_648);
+ expect(remediation).toContain("2147483648");
+ expect(remediation).toContain("no runtime override");
+ expect(remediation).not.toContain("NODE_OPTIONS");
+ expect(remediation).toContain(
+ "Selecting fewer source_paths does not raise the record ceiling",
+ );
+});
diff --git a/src/javascript/analysis/JavaScriptAnalysisTransfer.ts b/src/javascript/analysis/JavaScriptAnalysisTransfer.ts
index 1ca11334e..6a20ca412 100644
--- a/src/javascript/analysis/JavaScriptAnalysisTransfer.ts
+++ b/src/javascript/analysis/JavaScriptAnalysisTransfer.ts
@@ -3,10 +3,14 @@ import { createReadStream } from "node:fs";
import { open, stat } from "node:fs/promises";
import { z } from "zod";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
+import type { JsonValue } from "../../domain/jsonValue.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import type { JavaScriptModuleSemanticIr } from "../../domain/javascript/javascriptModuleSemanticIr.js";
-import { JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM } from "../../domain/javascript/javascriptAnalysisResourceControls.js";
+import {
+ JAVASCRIPT_PARENT_HEAP_NODE_OPTIONS,
+ JAVASCRIPT_SEMANTIC_ITEM_MAXIMUM,
+} from "../../domain/javascript/javascriptAnalysisResourceControls.js";
import type {
JavaScriptSemanticFileProjection,
JavaScriptSemanticProjectionCapacity,
@@ -66,6 +70,54 @@ export const javaScriptTransferByteBudget = (
Math.max(TRANSFER_BYTES, Math.floor(resultBudgetBytes / 8)),
);
+/**
+ * The record ceiling and the 2 GiB file maximum are fixed. The effective file
+ * ceiling follows the parent offered result budget and can rise until that maximum.
+ */
+export const javaScriptTransferCeilingRemediation = (
+ transferFileBytes: number | undefined,
+): string => {
+ const recordBytes = String(JAVASCRIPT_ANALYSIS_TRANSFER_RECORD_BYTES);
+ const maximumBytes = String(MAX_TRANSFER_BYTES);
+ const fixed = `The ${recordBytes}-byte transfer record ceiling and the ${maximumBytes}-byte transfer file maximum have no runtime override. Raising max_heap_mb does not raise either fixed ceiling. A request that exceeds the record ceiling or that maximum fails the same way when repeated unchanged.`;
+ const adjustable = `${JAVASCRIPT_PARENT_HEAP_NODE_OPTIONS} to raise the effective file ceiling up to ${maximumBytes} bytes. Selecting fewer source_paths can also raise this effective file allowance, because earlier retained results and the reserve for remaining sources reduce the offered budget. Neither change raises the record ceiling or the maximum.`;
+ if (
+ transferFileBytes !== undefined &&
+ transferFileBytes >= MAX_TRANSFER_BYTES
+ )
+ return `${fixed} The effective transfer file ceiling is the ${maximumBytes}-byte maximum. Selecting fewer source_paths does not raise the record ceiling or that maximum.`;
+ const effective =
+ transferFileBytes === undefined
+ ? "The effective transfer file ceiling follows the parent offered result budget, which follows the CLI/MCP process heap, and can be lower than the maximum."
+ : `The effective transfer file ceiling is ${String(transferFileBytes)} bytes. It follows the parent offered result budget, which follows the CLI/MCP process heap.`;
+ return `${fixed} ${effective} ${adjustable}`;
+};
+
+/** Reattach transfer recovery after a worker protocol frame drops remediation. */
+export const javaScriptForwardedTransferRemediation = (
+ limits: Readonly<Record<string, JsonValue>> | null,
+): string | undefined => {
+ const transferFileBytes = limits?.transfer_file_bytes;
+ if (
+ typeof limits?.transfer_record_bytes !== "number" &&
+ typeof transferFileBytes !== "number"
+ )
+ return undefined;
+ return javaScriptTransferCeilingRemediation(
+ typeof transferFileBytes === "number" ? transferFileBytes : undefined,
+ );
+};
+
+const javaScriptTransferCeilingReason = (
+ recordBytes: number,
+ transferFileBytes: number,
+): string =>
+ recordBytes > FRAME_BYTES
+ ? `A complete JavaScript fact exceeds the ${String(FRAME_BYTES)}-byte transfer record ceiling. This release has no runtime override.`
+ : transferFileBytes >= MAX_TRANSFER_BYTES
+ ? `Complete JavaScript file facts exceed the ${String(MAX_TRANSFER_BYTES)}-byte transfer file maximum. This release has no runtime override.`
+ : `Complete JavaScript file facts exceed the effective transfer file ceiling of ${String(transferFileBytes)} bytes (maximum ${String(MAX_TRANSFER_BYTES)} bytes). That effective ceiling follows the parent offered result budget and can rise until the maximum. The record ceiling and that maximum have no runtime override.`;
+
const assertTransferByteBudget = (transferBytes: number): void => {
if (
!Number.isSafeInteger(transferBytes) ||
@@ -89,15 +141,16 @@ const encodeTransferRecord = (
throw new AnalysisResourceConstraintError(
"analyze_javascript_application",
"transport",
- size > FRAME_BYTES
- ? "A complete JavaScript fact exceeds the transfer record byte budget"
- : "Complete JavaScript file facts exceed the transfer byte budget",
+ javaScriptTransferCeilingReason(size, transferBytes),
{
transfer_record_bytes: FRAME_BYTES,
transfer_file_bytes: transferBytes,
record_bytes: size,
transfer_bytes_at_least: previousBytes + size,
},
+ {
+ remediationAction: javaScriptTransferCeilingRemediation(transferBytes),
+ },
);
return { line, size, kind: record.kind };
};
diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts
index ca7a22f2a..3eab48aef 100644
--- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts
+++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts
@@ -47,11 +47,21 @@ import {
import {
readJavaScriptAnalysisTransfer,
JAVASCRIPT_ANALYSIS_TRANSFER_RECORD_BYTES,
+ javaScriptForwardedTransferRemediation,
javaScriptTransferRetentionBytes,
} from "./JavaScriptAnalysisTransfer.js";
+import {
+ JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION,
+ JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION,
+ JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM,
+ JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM,
+ javaScriptWorkerHeapExhaustionRecovery,
+ javaScriptWorkerHeapRemediation,
+} from "../../domain/javascript/javascriptAnalysisResourceControls.js";
import { javaScriptWorkerStaticAnalysisSchema } from "./JavaScriptAnalysisWorkerSchemas.js";
import {
JAVASCRIPT_ANALYSIS_WORKER_DEFAULTS as DEFAULTS,
+ javaScriptCheckpointCeilingRemediation,
javaScriptWorkerMessageSchema,
javaScriptWorkerRequestSchema,
javaScriptWorkerAdmissionSchema,
@@ -159,8 +169,8 @@ export class JavaScriptAnalysisWorker {
});
if (
!Number.isSafeInteger(limits.heapMb) ||
- limits.heapMb < 128 ||
- limits.heapMb > 16_384 ||
+ limits.heapMb < JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM ||
+ limits.heapMb > JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM ||
!Number.isSafeInteger(limits.timeoutMs) ||
limits.timeoutMs <= 0 ||
limits.timeoutMs > 2_147_483_647
@@ -303,8 +313,11 @@ export class JavaScriptAnalysisWorker {
throw new AnalysisResourceConstraintError(
OPERATION,
"transport",
- `Source identity for ${file.path} exceeds the worker request byte budget`,
+ `Source identity for ${file.path} exceeds the ${String(DEFAULTS.protocolBytes)}-byte worker request ceiling. This release has no runtime override.`,
{ worker_request_bytes: DEFAULTS.protocolBytes },
+ {
+ remediationAction: `This release has no runtime override for the ${String(DEFAULTS.protocolBytes)}-byte JavaScript worker request ceiling. Raising max_heap_mb does not raise it. Repeating the unchanged request fails the same way.`,
+ },
);
const stdin = supervisor.launch.process.stdin;
if (stdin === undefined || stdin === null)
@@ -422,8 +435,7 @@ export class JavaScriptAnalysisWorker {
module_retention_estimate_bytes: moduleEstimate,
},
{
- remediationAction:
- "Use the retained static facts or analyze fewer source files. This limit belongs to the parent result budget; increasing the worker heap alone does not increase it.",
+ remediationAction: `Use the retained static facts or analyze fewer source files. ${JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION}`,
},
),
});
@@ -462,8 +474,7 @@ export class JavaScriptAnalysisWorker {
graph_records: descriptor.graph_records,
},
{
- remediationAction:
- "Use the retained static and module facts or analyze fewer source files. This limit belongs to the parent result budget; increasing the worker heap alone does not increase it.",
+ remediationAction: `Use the retained static and module facts or analyze fewer source files. ${JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION}`,
},
),
});
@@ -685,6 +696,9 @@ export class JavaScriptAnalysisWorker {
"memory",
"The parent's remaining heap cannot safely decode the completed JavaScript static checkpoint",
{ ...this.#limits(), checkpoint_bytes: bytes },
+ {
+ remediationAction: JAVASCRIPT_PARENT_CHECKPOINT_HEAP_REMEDIATION,
+ },
);
const text = await readFile(path, "utf8");
if (
@@ -720,8 +734,7 @@ export class JavaScriptAnalysisWorker {
application_projection_required_bytes: expandedBytes,
},
{
- remediationAction:
- "Read the complete static facts on the file node or analyze fewer source files. Expanded application relationships exceed the parent result budget; increasing the worker heap alone does not increase it.",
+ remediationAction: `Read the complete static facts on the file node or analyze fewer source files. Expanded application relationships exceed the parent result budget. ${JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION}`,
},
);
return facts;
@@ -753,9 +766,12 @@ export class JavaScriptAnalysisWorker {
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
- `Owned JavaScript worker reached its ${this.#processMemoryLimitBytes === null ? "" : `${String(this.#processMemoryLimitBytes)}-byte `}process memory limit while analyzing ${path} during ${this.#phase}`,
+ `Owned JavaScript worker reached its ${this.#processMemoryLimitBytes === null ? "" : `${String(this.#processMemoryLimitBytes)}-byte `}process memory limit while analyzing ${path} during ${this.#phase}. That limit is max_heap_mb ${String(this.limits.heapMb)} MiB plus a 512 MiB Bun runtime reserve`,
this.#limits(),
- { capturedOutput: this.#captured() },
+ {
+ capturedOutput: this.#captured(),
+ remediationAction: javaScriptWorkerHeapRemediation(this.limits.heapMb),
+ },
);
}
#remainingResultBudget(): number {
@@ -990,14 +1006,24 @@ export class JavaScriptAnalysisWorker {
path: string,
failure: Extract<WorkerPrimaryFailure, { kind: "exit" }>,
): AnalysisError {
- if (failure.heapExhaustion)
+ if (failure.heapExhaustion) {
+ const recovery = javaScriptWorkerHeapExhaustionRecovery({
+ heapFlagsEnforced: WORKER_HEAP_FLAGS_ENFORCED,
+ heapMb: this.limits.heapMb,
+ path,
+ phase: this.#phase,
+ });
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
- `Owned JavaScript worker exhausted its heap while analyzing ${path} during ${this.#phase}`,
+ recovery.reason,
this.#limits(),
- { capturedOutput: this.#captured() },
+ {
+ capturedOutput: this.#captured(),
+ remediationAction: recovery.remediationAction,
+ },
);
+ }
return new ProviderAdapterError(PROVIDER, OPERATION, {
capturedOutput: this.#captured(),
diagnostics: {
@@ -1031,13 +1057,33 @@ export class JavaScriptAnalysisWorker {
response: Extract<JavaScriptWorkerMessage, { kind: "failure" }>,
phase: string,
): AnalysisError {
- if (response.reason === "resource")
+ if (response.reason === "resource") {
+ const reported = response.limits;
+ const limits = { ...this.#limits(), ...reported };
+ const transferRemediation =
+ javaScriptForwardedTransferRemediation(reported);
+ const checkpointBytes = reported?.checkpoint_limit_bytes;
+ const checkpointRemediation =
+ typeof checkpointBytes === "number"
+ ? javaScriptCheckpointCeilingRemediation(checkpointBytes)
+ : undefined;
+ const parentBudget =
+ reported?.semantic_result_budget_bytes !== undefined ||
+ reported?.parent_result_budget_bytes !== undefined;
+ const remediationAction =
+ transferRemediation ??
+ checkpointRemediation ??
+ (parentBudget
+ ? JAVASCRIPT_PARENT_RESULT_BUDGET_REMEDIATION
+ : undefined);
return new AnalysisResourceConstraintError(
OPERATION,
response.resource ?? "memory",
response.message,
- { ...this.#limits(), ...response.limits },
+ limits,
+ remediationAction === undefined ? undefined : { remediationAction },
);
+ }
return new AnalysisOutputError(
OPERATION,
`${path} during ${phase}: ${response.message}`,
diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerProtocol.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerProtocol.ts
index b054e6ba8..c24cadbbf 100644
--- a/src/javascript/analysis/JavaScriptAnalysisWorkerProtocol.ts
+++ b/src/javascript/analysis/JavaScriptAnalysisWorkerProtocol.ts
@@ -15,6 +15,12 @@ export const JAVASCRIPT_ANALYSIS_WORKER_DEFAULTS = {
protocolBytes: 64 * 1024,
} as const;
+/** The static checkpoint byte ceiling has no caller argument. */
+export const javaScriptCheckpointCeilingRemediation = (
+ checkpointBytes: number,
+): string =>
+ `The JavaScript static checkpoint ceiling is ${String(checkpointBytes)} bytes. This release has no runtime override. Raising max_heap_mb does not raise it. Paging or exporting session Evidence does not admit the omitted checkpoint.`;
+
/** Caller-selected artifact identity, separate from the decoded source-text digest. */
export const javaScriptWorkerRequestSchema = z.strictObject({
id: z.uuid(),
diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts
index 08c8f45fb..480b103b8 100644
--- a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts
+++ b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts
@@ -17,6 +17,7 @@ import {
import { javaScriptWorkerStaticAnalysisSchema } from "./JavaScriptAnalysisWorkerSchemas.js";
import {
JAVASCRIPT_ANALYSIS_WORKER_DEFAULTS as DEFAULTS,
+ javaScriptCheckpointCeilingRemediation,
javaScriptWorkerRequestSchema,
javaScriptWorkerAdmissionSchema,
javaScriptWorkerMessageSchema,
@@ -123,11 +124,16 @@ const analyzeJob = async (
throw new AnalysisResourceConstraintError(
"analyze_javascript_application",
"transport",
- "JavaScript static checkpoint exceeds its complete-fact byte budget",
+ `JavaScript static checkpoint exceeds its ${String(DEFAULTS.checkpointBytes)}-byte complete-fact ceiling. This release has no runtime override.`,
{
checkpoint_bytes: bytes,
checkpoint_limit_bytes: DEFAULTS.checkpointBytes,
},
+ {
+ remediationAction: javaScriptCheckpointCeilingRemediation(
+ DEFAULTS.checkpointBytes,
+ ),
+ },
);
await writeFile(join(root, `${request.id}.static.json`), text, {
flag: "wx",
diff --git a/src/javascript/recovery/RecoveryFiles.ts b/src/javascript/recovery/RecoveryFiles.ts
index fc1a988a1..cfc4c7ef3 100644
--- a/src/javascript/recovery/RecoveryFiles.ts
+++ b/src/javascript/recovery/RecoveryFiles.ts
@@ -16,7 +16,7 @@ import {
openRegularFile,
RegularFileAdmissionFailure,
} from "../../filesystem/RegularFile.js";
-import { RECOVERY_LIMITS } from "./WakaruRelease.js";
+import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js";
const OPERATION = "recover_javascript_sources";
@@ -34,6 +34,14 @@ class RecoveryFileSizeError extends AnalysisOutputError {
}
}
+/** A bounded read stopped because the regular file exceeded the caller's maximum. */
+export const isRecoveryFileSizeError = (
+ cause: unknown,
+ maximum?: number,
+): boolean =>
+ cause instanceof RecoveryFileSizeError &&
+ (maximum === undefined || cause.maximum === maximum);
+
/** Read a stable regular file without retaining bytes during engine fingerprinting. */
const scanRecoveryFile = async (
path: string,
@@ -165,8 +173,7 @@ const snapshotRecoveryInput = async (
{
cause,
retryable: false,
- remediationAction:
- "Select JavaScript inputs whose combined size is within maximum_input_bytes. Do not truncate required source; retrying the unchanged selection will fail again.",
+ remediationAction: `Select JavaScript inputs whose combined size is within the ${String(RECOVERY_LIMITS.inputBytes)}-byte total input allowance (maximum_input_bytes). This release has no runtime override. Raising max_heap_mb does not raise it. Do not truncate required source; retrying the unchanged selection will fail again.`,
},
);
throw recoveryInputFailure(
@@ -291,6 +298,9 @@ export const inventoryRecoveryFiles = async (
throw new AnalysisOutputError(
OPERATION,
"Recovery staging exceeds the 10000-entry resource limit",
+ wakaruFixedLimitRecovery(
+ `Recovery staging exceeds the ${String(RECOVERY_LIMITS.outputEntries)}-entry resource limit`,
+ ),
);
children.push(entry.name);
}
@@ -314,6 +324,9 @@ export const inventoryRecoveryFiles = async (
throw new AnalysisOutputError(
OPERATION,
"Recovery staging exceeds the 128 MiB resource limit",
+ wakaruFixedLimitRecovery(
+ `Recovery staging exceeds the ${String(RECOVERY_LIMITS.outputBytes)}-byte output allowance`,
+ ),
);
files.push({ relativePath, path, bytes: info.size });
}
@@ -349,5 +362,8 @@ export const checkRecoveryDeadline = (
): void => {
checkRecoveryCancellation(signal);
if (performance.now() >= deadline)
- throw new AnalysisTimeoutError(OPERATION, RECOVERY_LIMITS.timeoutMs);
+ throw new AnalysisTimeoutError(OPERATION, RECOVERY_LIMITS.timeoutMs, {
+ userMessage: `JavaScript source recovery reached its ${String(RECOVERY_LIMITS.timeoutMs)} ms Wakaru adapter deadline. This is REA's fixed per-operation deadline, not the MCP client deadline.`,
+ remediationAction: `This release has no runtime override for the ${String(RECOVERY_LIMITS.timeoutMs)} ms Wakaru recovery deadline. Raising analysis_timeout_ms or max_heap_mb does not raise it. A smaller complete input may finish inside this deadline. An unchanged retry may hit this deadline again. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
+ });
};
diff --git a/src/javascript/recovery/WakaruCommand.test.ts b/src/javascript/recovery/WakaruCommand.test.ts
index 8dcb74be4..fd8825497 100644
--- a/src/javascript/recovery/WakaruCommand.test.ts
+++ b/src/javascript/recovery/WakaruCommand.test.ts
@@ -1,7 +1,10 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { expect, it } from "vitest";
-import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
+import {
+ AnalysisCapabilityUnavailableError,
+ AnalysisTimeoutError,
+} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import {
resolveWakaruCommand,
@@ -41,9 +44,36 @@ it("rejects an exhausted shared execution budget before launching the next comma
).rejects.toMatchObject({
_tag: "AnalysisTimeoutError",
operation: "recover_javascript_sources",
+ timeoutMs: RECOVERY_LIMITS.timeoutMs,
});
});
+it("says the Wakaru deadline has no runtime override", async () => {
+ const refusal: unknown = await runWakaruCommand({
+ command: "/selected/wakaru",
+ limiter: "/usr/bin/prlimit",
+ arguments: ["--version"],
+ cwd: "/tmp/unused",
+ environment: {},
+ deadline: performance.now() - 1,
+ launcher: async () => {
+ throw new Error("An expired budget must not launch");
+ },
+ }).catch((cause: unknown) => cause);
+ if (!(refusal instanceof AnalysisTimeoutError))
+ throw new Error("Expected the Wakaru deadline");
+ const projected = projectAnalysisError(refusal);
+ expect(projected.message).toContain(String(RECOVERY_LIMITS.timeoutMs));
+ expect(projected.message).toContain("Wakaru");
+ expect(projected.remediation.action).toContain("no runtime override");
+ expect(projected.remediation.action).toContain("analysis_timeout_ms");
+ expect(projected.remediation.action).toContain("max_heap_mb");
+ expect(projected.remediation.action).toContain(
+ "An unchanged retry may hit this deadline again",
+ );
+ expect(projected.remediation.action).not.toContain("fails the same way");
+});
+
it("preserves caller cancellation before acquiring an expired execution budget", async () => {
await expect(
runWakaruCommand({
diff --git a/src/javascript/recovery/WakaruCommand.ts b/src/javascript/recovery/WakaruCommand.ts
index fe4500ba9..3ec17a9c8 100644
--- a/src/javascript/recovery/WakaruCommand.ts
+++ b/src/javascript/recovery/WakaruCommand.ts
@@ -22,7 +22,7 @@ import {
fingerprintRecoveryFile,
recoveryFailureMessage,
} from "./RecoveryFiles.js";
-import { RECOVERY_LIMITS } from "./WakaruRelease.js";
+import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js";
const OPERATION = "recover_javascript_sources";
const WAKARU_REQUIREMENT =
@@ -170,6 +170,9 @@ export const runWakaruCommand = async (context: WakaruCommandContext) => {
throw new AnalysisOutputError(
OPERATION,
"Wakaru diagnostic stream exceeds 8 MiB",
+ wakaruFixedLimitRecovery(
+ `Wakaru diagnostic stream exceeds the ${String(RECOVERY_LIMITS.reportBytes)}-byte report allowance`,
+ ),
);
if (context.staging !== undefined)
await inventoryRecoveryFiles(context.staging, context.signal);
@@ -179,6 +182,9 @@ export const runWakaruCommand = async (context: WakaruCommandContext) => {
throw new AnalysisOutputError(
OPERATION,
"Wakaru diagnostic stream exceeds 8 MiB",
+ wakaruFixedLimitRecovery(
+ `Wakaru diagnostic stream exceeds the ${String(RECOVERY_LIMITS.reportBytes)}-byte report allowance`,
+ ),
);
} catch (cause: unknown) {
failure = cause;
diff --git a/src/javascript/recovery/WakaruRelease.ts b/src/javascript/recovery/WakaruRelease.ts
index 71073b395..561d5b48b 100644
--- a/src/javascript/recovery/WakaruRelease.ts
+++ b/src/javascript/recovery/WakaruRelease.ts
@@ -20,6 +20,14 @@ export const WAKARU_PROVIDER_IDENTITY = {
version: WAKARU_RELEASE.version,
} as const;
+/** Fixed Wakaru allowance. This release has no caller setting that raises it. */
+export const wakaruFixedLimitRecovery = (
+ allowance: string,
+): { readonly userMessage: string; readonly remediationAction: string } => ({
+ userMessage: `${allowance}. This release has no runtime override.`,
+ remediationAction: `${allowance}. This release has no runtime override. Raising max_heap_mb or analysis_timeout_ms does not raise it. Repeating the unchanged request fails the same way.`,
+});
+
/** Per-operation resource bounds for the verified Linux adapter. */
export const RECOVERY_LIMITS = {
inputBytes: 64 * 1024 * 1024,
diff --git a/src/javascript/recovery/WakaruReport.test.ts b/src/javascript/recovery/WakaruReport.test.ts
new file mode 100644
index 000000000..b6682d705
--- /dev/null
+++ b/src/javascript/recovery/WakaruReport.test.ts
@@ -0,0 +1,75 @@
+import { truncate, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
+import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { parseWakaruReports } from "./WakaruReport.js";
+import { RECOVERY_LIMITS } from "./WakaruRelease.js";
+
+const reportStdout = JSON.stringify({
+ detected_formats: ["unknown"],
+ safety: "safe",
+ modules: [],
+ warnings: [],
+ total: 0,
+ failed: 0,
+ elapsed_ms: 1,
+});
+
+const execution = {
+ exit_code: 0,
+ signal: null,
+ stdout: reportStdout,
+ stderr: "",
+ command: "/selected/wakaru",
+ arguments: ["--json"],
+ resource_limiter: "/usr/bin/prlimit",
+};
+
+it("names the fixed report allowance when provenance.json exceeds 8 MiB", async () => {
+ const root = await createTestTempDirectory("rea-wakaru-provenance-size-");
+ const provenancePath = join(root, "provenance.json");
+ await writeFile(provenancePath, "");
+ await truncate(provenancePath, RECOVERY_LIMITS.reportBytes + 1);
+ const refusal: unknown = await parseWakaruReports({
+ execution,
+ provenancePath,
+ snapshots: new Map(),
+ files: [],
+ }).catch((cause: unknown) => cause);
+ if (!(refusal instanceof ProviderAdapterError))
+ throw new Error("Expected a wrapped Wakaru report refusal");
+ const projected = projectAnalysisError(refusal);
+ expect(projected.message).toContain(String(RECOVERY_LIMITS.reportBytes));
+ expect(projected.message).toContain("no runtime override");
+ expect(projected.remediation.action).toContain("no runtime override");
+ expect(projected.remediation.action).toContain("max_heap_mb");
+ expect(projected.remediation.action).toContain("analysis_timeout_ms");
+ expect(projected.remediation.action).toContain(
+ "Repeating the unchanged request fails the same way",
+ );
+});
+
+it("keeps a malformed provenance report distinct from the fixed report allowance", async () => {
+ const root = await createTestTempDirectory(
+ "rea-wakaru-provenance-malformed-",
+ );
+ const provenancePath = join(root, "provenance.json");
+ await writeFile(provenancePath, "{");
+ const refusal: unknown = await parseWakaruReports({
+ execution,
+ provenancePath,
+ snapshots: new Map(),
+ files: [],
+ }).catch((cause: unknown) => cause);
+ if (!(refusal instanceof ProviderAdapterError))
+ throw new Error("Expected a wrapped Wakaru report refusal");
+ const projected = projectAnalysisError(refusal);
+ expect(projected.message).toBe(
+ "Analysis could not complete. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
+ );
+ expect(projected.remediation.action).toBe(projected.message);
+ expect(JSON.stringify(projected)).not.toContain("report allowance");
+ expect(JSON.stringify(projected)).not.toContain("no runtime override");
+});
diff --git a/src/javascript/recovery/WakaruReport.ts b/src/javascript/recovery/WakaruReport.ts
index 7ba9866b8..76ef2fb48 100644
--- a/src/javascript/recovery/WakaruReport.ts
+++ b/src/javascript/recovery/WakaruReport.ts
@@ -6,8 +6,12 @@ import {
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import type { JavaScriptRecoveryResult } from "../../domain/javascript/javascriptRecovery.js";
-import { readRecoveryFile, recoveryFailureMessage } from "./RecoveryFiles.js";
-import { RECOVERY_LIMITS } from "./WakaruRelease.js";
+import {
+ isRecoveryFileSizeError,
+ readRecoveryFile,
+ recoveryFailureMessage,
+} from "./RecoveryFiles.js";
+import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js";
import type { runWakaruCommand } from "./WakaruCommand.js";
const warningSchema = z.looseObject({
@@ -75,9 +79,7 @@ export const parseWakaruReports = async (context: ReportContext) => {
const report = reportSchema.parse(JSON.parse(execution.stdout));
const provenance = provenanceSchema.parse(
JSON.parse(
- (
- await readRecoveryFile(provenancePath, RECOVERY_LIMITS.reportBytes)
- ).toString("utf8"),
+ (await readWakaruProvenanceReport(provenancePath)).toString("utf8"),
),
);
if (report.total !== report.modules.length || report.failed > report.total)
@@ -104,6 +106,7 @@ export const parseWakaruReports = async (context: ReportContext) => {
} catch (cause: unknown) {
throw new ProviderAdapterError("wakaru", OPERATION, {
cause,
+ ...wakaruReportGuidance(cause),
diagnostics: {
reason: `Unusable Wakaru recovery report: ${recoveryFailureMessage(cause)}`,
exit_code: execution.exit_code,
@@ -115,6 +118,41 @@ export const parseWakaruReports = async (context: ReportContext) => {
}
};
+const PROVENANCE_REPORT_ALLOWANCE = `Wakaru provenance report exceeds the ${String(RECOVERY_LIMITS.reportBytes)}-byte report allowance`;
+
+/** Report-size refusals name the fixed allowance; other read failures stay unchanged. */
+const readWakaruProvenanceReport = async (path: string): Promise<Buffer> => {
+ try {
+ return await readRecoveryFile(path, RECOVERY_LIMITS.reportBytes);
+ } catch (cause: unknown) {
+ if (!isRecoveryFileSizeError(cause, RECOVERY_LIMITS.reportBytes))
+ throw cause;
+ throw new AnalysisOutputError(OPERATION, PROVENANCE_REPORT_ALLOWANCE, {
+ cause,
+ ...wakaruFixedLimitRecovery(PROVENANCE_REPORT_ALLOWANCE),
+ });
+ }
+};
+
+/** Keep fixed-limit guidance when the report parser wraps the producing error. */
+const wakaruReportGuidance = (
+ cause: unknown,
+): { readonly userMessage?: string; readonly remediationAction?: string } => {
+ if (typeof cause !== "object" || cause === null) return {};
+ const userMessage =
+ "userMessage" in cause && typeof cause.userMessage === "string"
+ ? cause.userMessage
+ : undefined;
+ const remediationAction =
+ "remediationAction" in cause && typeof cause.remediationAction === "string"
+ ? cause.remediationAction
+ : undefined;
+ return {
+ ...(userMessage === undefined ? {} : { userMessage }),
+ ...(remediationAction === undefined ? {} : { remediationAction }),
+ };
+};
+
const validateModuleSet = (
report: z.output<typeof reportSchema>,
provenance: z.output<typeof provenanceSchema>,
diff --git a/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts b/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts
index a70eb463b..3008954f0 100644
--- a/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts
+++ b/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts
@@ -197,7 +197,24 @@ cliTest(
expect.arrayContaining([
{ name: "semantic_graph_node_ceiling", value: 50 },
{ name: "semantic_graph_file_node_ceiling", value: 30 },
+ { name: "max_semantic_nodes", value: 50 },
+ { name: "max_semantic_nodes_per_file", value: 30 },
]),
);
+ const limitation = z
+ .object({
+ normalized_result: z.object({
+ semantic_graph: z.object({
+ limitations: z.array(z.string()),
+ }),
+ }),
+ })
+ .parse(output.json);
+ expect(
+ limitation.normalized_result.semantic_graph.limitations.join("\n"),
+ ).toContain("max_semantic_nodes");
+ expect(
+ limitation.normalized_result.semantic_graph.limitations.join("\n"),
+ ).toContain("1 to 1000000");
},
);
diff --git a/tests/boundary/javascript/workerOrderAudit.test.ts b/tests/boundary/javascript/workerOrderAudit.test.ts
index 869994abb..86e1c45b9 100644
--- a/tests/boundary/javascript/workerOrderAudit.test.ts
+++ b/tests/boundary/javascript/workerOrderAudit.test.ts
@@ -7,7 +7,10 @@ import { expect, it } from "vitest";
import {
AnalysisCancelledError,
AnalysisOutputError,
+ AnalysisResourceConstraintError,
} from "../../../src/domain/analysisErrorCore.js";
+import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
+import { javaScriptRuntime } from "../../../src/domain/runtimeVersion.js";
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
import {
javaScriptWorkerMessageSchema,
@@ -777,11 +780,28 @@ it("retains the owned worker's V8 heap exhaustion classification", async () => {
try {
const result = await worker.analyze(file, { nodes: 100, unknowns: 100 });
expect(result.ok).toBe(false);
- if (!result.ok)
- expect(result.error.error).toMatchObject({
- _tag: "AnalysisResourceConstraintError",
- resource: "memory",
- });
+ if (!result.ok) {
+ expect(result.error.error).toBeInstanceOf(
+ AnalysisResourceConstraintError,
+ );
+ const projected = projectAnalysisError(result.error.error);
+ if (javaScriptRuntime(process.versions).id === "node") {
+ expect(projected.message).toContain(
+ "128 MiB V8 old-space heap (max_heap_mb)",
+ );
+ expect(projected.remediation.action).toContain("--max-heap-mb");
+ } else {
+ expect(projected.message).toContain(
+ "Bun ignores the V8 old-space flag",
+ );
+ expect(projected.message).not.toContain(
+ "128 MiB V8 old-space heap (max_heap_mb)",
+ );
+ expect(projected.remediation.action).not.toContain(
+ "Increase max_heap_mb",
+ );
+ }
+ }
} finally {
await worker.close();
}