mirror of
https://github.com/morluto/rea.git
synced 2026-11-30 18:39:24 +00:00
feat(javascript): add semantic_analysis structure-only mode to analyze_javascript_application (#14117)
* feat(javascript): add semantic_analysis structure-only mode to analyze_javascript_application On large Electron apps the default analysis runs full semantic analysis per file (364 s measured in #14100) although first questions are application-graph facts. semantic_analysis: structure-only returns static and application-graph facts without semantic IR, graph content or traces: the worker purpose protocol gains structure-only (full static checkpoint, semantic phase skipped, no semantic result budget consumed), adoption records the mode once as a limitation, and Evidence parameters record the selection. Default complete behavior is unchanged. Closes #14116. Verified: javascriptArtifactReconstruction, electronApplicationAnalysis and javascriptApplicationService suites (75 tests incl. new structure-only e2e), worker server/schema tests, check:fast, docs:check, advertised schema summary regenerated. * test(javascript): assert semantic relations in the structure-only test * fix(javascript): record structure-only semantic coverage as incomplete and retain refusal facts Structure-only files now record a semantic unavailable reason so graph coverage cannot claim complete examination (comparisons will not report skipped bindings as removed), member-mutation refusal checkpoints cross for structure-only as they do for complete analysis, and the e2e control asserts real semantic content under the default. * docs(javascript): document semantic_analysis and expose --semantic-analysis The owning reconstruction guide now describes the complete default, what structure-only returns and skips, and how to follow up with complete analysis of selected sources. The CLI projection declares the field so --semantic-analysis <complete|structure-only> is accepted with the contract enum. * fix(javascript): record structure-only application coverage as partial Structure-only omits source-module and export-binding nodes. The application graph now reports partial coverage with a null omission count, so a comparison of an unchanged application treats those bindings as unknown rather than removed. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
1 parent
fba6b6f9ae
commit
eccd18a2cc
15 files changed
+212
-16
No files matched your search
@@ -884,6 +884,23 @@ caller can change the resource actually exhausted. Finite inline literal object
|
||||
spreads use iterative syntax traversal and no longer inherit a duplicate
|
||||
semantic-depth cut.
|
||||
|
||||
`semantic_analysis` selects how much of each source is examined. The default,
|
||||
`complete`, parses, static-analyzes and semantic-analyzes every selected
|
||||
source. `structure-only` returns the static and application-graph facts —
|
||||
package and Electron roles, preload and renderer structure, IPC and route
|
||||
structure — without building semantic IR, semantic graph content, semantic
|
||||
traces, or the application-graph source-module and export-binding nodes those
|
||||
facts feed. Each file's semantic coverage is recorded as not examined with
|
||||
that reason. The application graph's `coverage` is `partial`, with
|
||||
`truncated: false`, `omitted_count: null` and no extra limits: the number of
|
||||
omitted module and export nodes is not known, so a comparison reports those
|
||||
nodes as unknown rather than removed or added. The result states the omission
|
||||
once in `limitations`.
|
||||
Use it for a first pass over a large application when the structural surface
|
||||
is the question; request `complete` analysis afterwards, narrowed with
|
||||
`source_paths`, for semantic detail. The selection stays in Evidence
|
||||
parameters. The CLI accepts `--semantic-analysis structure-only`.
|
||||
|
||||
Member-mutation analysis also has a work allowance of 524,288 alias states
|
||||
per source, selected by the `javascript.member_mutation_alias_states` setting
|
||||
(1 to 8,388,608). Change it with `update_analysis_settings` on MCP, or with
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "990f691d36bfeeec",
|
||||
"input compact": "5410f29d6d7195f1",
|
||||
"output compact": "4bda7c3651bfc579"
|
||||
},
|
||||
"patterns": {}
|
||||
|
||||
@@ -93,6 +93,9 @@ const parameters = (
|
||||
...(input.semantic_precision === undefined
|
||||
? {}
|
||||
: { semantic_precision: input.semantic_precision }),
|
||||
...(input.semantic_analysis === undefined
|
||||
? {}
|
||||
: { semantic_analysis: input.semantic_analysis }),
|
||||
format: input.format,
|
||||
integrity_policy: input.integrity_policy,
|
||||
...(input.max_semantic_nodes === undefined
|
||||
|
||||
@@ -84,6 +84,8 @@ export const analyzeAndAdoptJavaScriptArtifactFiles = async (
|
||||
preloadPaths: ReadonlySet<string> = new Set(),
|
||||
/** Discovery gaps that may leave a declared preload in its package scope. */
|
||||
preloadLimitations: readonly string[] = [],
|
||||
/** Return static and application facts without semantic analysis. */
|
||||
structureOnly: boolean = false,
|
||||
): Promise<{
|
||||
readonly analysis: JavaScriptArtifactAnalysis;
|
||||
readonly interruption: AnalysisError | null;
|
||||
@@ -130,6 +132,7 @@ export const analyzeAndAdoptJavaScriptArtifactFiles = async (
|
||||
posix.extname(file.path) === ".js"
|
||||
? "commonjs"
|
||||
: packageTypeFor(file),
|
||||
structureOnly ? "structure-only" : "analysis",
|
||||
);
|
||||
const facts = result.ok ? result.value : result.error;
|
||||
for (const revoked of facts.revokedStaticProjections ?? []) {
|
||||
@@ -186,10 +189,12 @@ export const analyzeAndAdoptJavaScriptArtifactFiles = async (
|
||||
});
|
||||
const semanticUnavailableReason =
|
||||
failure?.reason ??
|
||||
javaScriptSemanticSourceExclusion(
|
||||
file,
|
||||
facts.javascript?.parse_status ?? null,
|
||||
);
|
||||
(structureOnly && file.kind === "javascript" && file.text.included
|
||||
? "Semantic analysis was not requested (structure-only)"
|
||||
: javaScriptSemanticSourceExclusion(
|
||||
file,
|
||||
facts.javascript?.parse_status ?? null,
|
||||
));
|
||||
if (facts.projection === null && semanticUnavailableReason !== null)
|
||||
projection.recordUnavailableFile(
|
||||
file,
|
||||
@@ -308,7 +313,11 @@ export const analyzeAndAdoptJavaScriptArtifactFiles = async (
|
||||
}
|
||||
restoreInventoryOrder(fileSet.files, state.files);
|
||||
return {
|
||||
analysis: finalizeArtifactAnalysis(state, preloadLimitations),
|
||||
analysis: finalizeArtifactAnalysis(
|
||||
state,
|
||||
preloadLimitations,
|
||||
structureOnly,
|
||||
),
|
||||
interruption,
|
||||
};
|
||||
};
|
||||
@@ -352,6 +361,7 @@ const restoreInventoryOrder = (
|
||||
const finalizeArtifactAnalysis = (
|
||||
state: MutableArtifactAnalysis,
|
||||
preloadLimitations: readonly string[],
|
||||
structureOnly: boolean = false,
|
||||
): JavaScriptArtifactAnalysis => {
|
||||
return {
|
||||
jsonDocuments: state.jsonDocuments,
|
||||
@@ -371,9 +381,15 @@ const finalizeArtifactAnalysis = (
|
||||
),
|
||||
modules: state.modules,
|
||||
parse_failures: state.parseFailures,
|
||||
...(structureOnly ? { semantic_analysis: "structure-only" as const } : {}),
|
||||
limitations: [
|
||||
"JavaScript and HTML were parsed as inert text; bundle bootstrap code was never executed.",
|
||||
"Static paths and relationships may remain unresolved when expressions are dynamic or obfuscated.",
|
||||
...(structureOnly
|
||||
? [
|
||||
"Semantic analysis was not requested (semantic_analysis: structure-only): no semantic IR, semantic graph or semantic traces were produced. Request semantic_analysis: complete for selected sources to obtain them.",
|
||||
]
|
||||
: []),
|
||||
...state.htmlInlineScripts.map(htmlInlineScriptLimitation),
|
||||
...state.files.flatMap(
|
||||
({ analysis_failure, application_projection_failure }) =>
|
||||
|
||||
@@ -225,4 +225,11 @@ export interface JavaScriptArtifactAnalysis {
|
||||
readonly modules: number;
|
||||
readonly parse_failures: number;
|
||||
readonly limitations: readonly string[];
|
||||
/**
|
||||
* Set when the caller skipped semantic analysis. Omitted for a complete
|
||||
* pass. Application-graph coverage reads this rather than guessing from
|
||||
* absent module IR: source-module and export-binding nodes are not built,
|
||||
* so the graph cannot claim those facts were examined.
|
||||
*/
|
||||
readonly semantic_analysis?: "structure-only";
|
||||
}
|
||||
@@ -371,6 +371,12 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
|
||||
);
|
||||
return partialApplicationCoverage([], nestedArchiveWasOpaque ? null : 0);
|
||||
}
|
||||
// Structure-only keeps static and Electron facts and does not build
|
||||
// source-module or export-binding nodes. The omitted node count is unknown
|
||||
// without semantic analysis. Complete coverage would let a comparison treat
|
||||
// those unchanged bindings as removed.
|
||||
if (context.analysis.semantic_analysis === "structure-only")
|
||||
return partialApplicationCoverage([], null);
|
||||
return completeApplicationCoverage();
|
||||
};
|
||||
|
||||
|
||||
@@ -262,6 +262,7 @@ export const reconstructJavaScriptArtifact = async (
|
||||
},
|
||||
preloads.paths,
|
||||
preloads.limitations,
|
||||
input.semantic_analysis === "structure-only",
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
analysisFailure = { cause };
|
||||
|
||||
@@ -205,6 +205,10 @@ export const javaScriptApplicationCliProjection = (target: string) =>
|
||||
description:
|
||||
"Inline JSON or JSON file with per-source semantic_precision evaluator budgets; independent of graph retention and worker memory.",
|
||||
},
|
||||
semantic_analysis: {
|
||||
description:
|
||||
"complete (default) builds semantic analysis for every selected source; structure-only returns static and application-graph facts without semantic analysis.",
|
||||
},
|
||||
},
|
||||
jsonInputs: {
|
||||
semantic_precision:
|
||||
|
||||
@@ -48,7 +48,9 @@ const analyze: JavaScriptSourceWorkerAnalyzer = async (
|
||||
precision,
|
||||
memberMutationAllowance,
|
||||
);
|
||||
if (static_ === null) return null;
|
||||
// Structure-only keeps the full static facts and skips semantic analysis;
|
||||
// no semantic result budget is consumed.
|
||||
if (static_ === null || purpose === "structure-only") return null;
|
||||
const { resultBudgetBytes, callPaths } = static_;
|
||||
if (resultBudgetBytes === 0)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
@@ -95,7 +97,9 @@ const analyze: JavaScriptSourceWorkerAnalyzer = async (
|
||||
/**
|
||||
* Checkpoint static facts, reusing the ones preload discovery retained for
|
||||
* this exact request. Null ends the job: discovery returns only declarations,
|
||||
* and a failed parse has no semantic phase.
|
||||
* and a failed parse has no semantic phase. The caller stops after this
|
||||
* checkpoint for structure-only, so that pass reuses the same facts and
|
||||
* still does not start semantic analysis.
|
||||
*/
|
||||
const staticCheckpoint = async (
|
||||
source: string,
|
||||
@@ -108,7 +112,8 @@ const staticCheckpoint = async (
|
||||
readonly resultBudgetBytes: number;
|
||||
readonly callPaths: JavaScriptStaticAnalysis["electron"]["call_paths"];
|
||||
} | null> => {
|
||||
const reused = purpose === "analysis" ? callbacks.reusedStatic() : undefined;
|
||||
const reused =
|
||||
purpose === "preload-discovery" ? undefined : callbacks.reusedStatic();
|
||||
if (reused !== undefined) {
|
||||
const resultBudgetBytes = await callbacks.checkpointReused(reused);
|
||||
return reused.parse_status === "failed"
|
||||
@@ -128,7 +133,13 @@ const staticCheckpoint = async (
|
||||
} catch (cause: unknown) {
|
||||
// The semantic phase indexes the same mutations under the same
|
||||
// allowance, so it is not started; the syntax facts cross first.
|
||||
if (purpose === "analysis" && isJavaScriptMemberMutationRefusal(cause))
|
||||
// Structure-only has no later semantic phase, so the same refusal must
|
||||
// still cross the syntax facts. Discovery leaves that report to the
|
||||
// normal pass, which recomputes this source.
|
||||
if (
|
||||
purpose !== "preload-discovery" &&
|
||||
isJavaScriptMemberMutationRefusal(cause)
|
||||
)
|
||||
await callbacks.checkpoint(
|
||||
memberMutationRefusedJavaScriptStaticAnalysis(source, parsed, cause),
|
||||
);
|
||||
|
||||
@@ -220,6 +220,13 @@ export const javaScriptAnalysisCoverageLimits = (
|
||||
|
||||
/** Optional operational choices; omission keeps them out of Evidence parameters. */
|
||||
export const javaScriptAnalysisResourceControlsSchema = z.strictObject({
|
||||
// domain-vocabulary: caller-selected analysis depth, not a coverage status.
|
||||
semantic_analysis: z
|
||||
.enum(["complete", "structure-only"])
|
||||
.optional()
|
||||
.describe(
|
||||
"complete (default) parses, static-analyzes and semantic-analyzes every selected source. structure-only returns static and application-graph facts without semantic analysis: no semantic IR, semantic graph or semantic traces are produced, which bounds large-application analysis time and retention; request complete analysis of selected sources afterwards for semantic detail.",
|
||||
),
|
||||
semantic_precision: javaScriptSemanticPrecisionSchema.optional().describe(
|
||||
`Per-source evaluator budgets. Omitted fields preserve defaults: ${Object.entries(
|
||||
JAVASCRIPT_SEMANTIC_PRECISION_DEFAULTS,
|
||||
|
||||
@@ -70,8 +70,8 @@ export interface JavaScriptSourceAnalysisPort {
|
||||
onPhase?: (phase: string) => Promise<void>,
|
||||
/** Effective package/loader context; declared .js preloads use commonjs. */
|
||||
packageType?: JavaScriptPackageType,
|
||||
/** Discover loader declarations without retaining semantic projections. */
|
||||
purpose?: "analysis" | "preload-discovery",
|
||||
/** Discover loader declarations, or return static facts without semantic analysis. */
|
||||
purpose?: "analysis" | "preload-discovery" | "structure-only",
|
||||
): Promise<Result<JavaScriptAnalyzedSource, JavaScriptSourceAnalysisFailure>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
@@ -148,7 +148,7 @@ type WorkerPrimaryFailure =
|
||||
* static checkpoints discovery retained survive.
|
||||
*/
|
||||
export const isRecoverableJavaScriptWorkerFailure = (
|
||||
purpose: "analysis" | "preload-discovery",
|
||||
purpose: "analysis" | "preload-discovery" | "structure-only",
|
||||
result: Result<JavaScriptAnalyzedSource, JavaScriptSourceAnalysisFailure>,
|
||||
): boolean =>
|
||||
purpose === "preload-discovery" &&
|
||||
@@ -348,7 +348,7 @@ export class JavaScriptAnalysisWorker {
|
||||
signal?: AbortSignal,
|
||||
onPhase?: (phase: string) => Promise<void>,
|
||||
packageType: JavaScriptPackageType = "unknown",
|
||||
purpose: "analysis" | "preload-discovery" = "analysis",
|
||||
purpose: "analysis" | "preload-discovery" | "structure-only" = "analysis",
|
||||
): Promise<
|
||||
Result<JavaScriptAnalyzedSource, JavaScriptSourceAnalysisFailure>
|
||||
> {
|
||||
|
||||
@@ -43,7 +43,7 @@ export const javaScriptWorkerRequestSchema = z.strictObject({
|
||||
}),
|
||||
/** Type of the source's inventoried package scope, observed by the parent. */
|
||||
package_type: z.enum(["module", "commonjs", "unspecified", "unknown"]),
|
||||
purpose: z.enum(["analysis", "preload-discovery"]),
|
||||
purpose: z.enum(["analysis", "preload-discovery", "structure-only"]),
|
||||
});
|
||||
|
||||
/** Parent admission after validated static observations have been retained. */
|
||||
|
||||
@@ -63,7 +63,7 @@ export interface JavaScriptSourceWorkerAnalyzer {
|
||||
) => Promise<number>;
|
||||
},
|
||||
packageType: JavaScriptPackageType,
|
||||
purpose: "analysis" | "preload-discovery",
|
||||
purpose: "analysis" | "preload-discovery" | "structure-only",
|
||||
precision: JavaScriptSemanticPrecisionInput | undefined,
|
||||
memberMutationAllowance: JavaScriptMemberMutationAllowance,
|
||||
): Promise<{
|
||||
|
||||
+124
@@ -47,6 +47,7 @@ import {
|
||||
parseJavaScriptApplicationGraph,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { compareJavaScriptApplicationVersions } from "../../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import {
|
||||
createJavaScriptSemanticGraph,
|
||||
@@ -93,6 +94,129 @@ it("does not let a known-absent optional import erase another application's page
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
const moduleFactRoles = (graph: JavaScriptApplicationGraph): string[] =>
|
||||
graph.nodes.flatMap(({ observations }) =>
|
||||
observations.flatMap(({ properties }) => {
|
||||
const role = properties.semantic_role;
|
||||
return role === "source-module" || role === "export-binding"
|
||||
? [role]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
|
||||
it("returns static and application facts without semantic analysis in structure-only mode", async () => {
|
||||
const root = await createTestTempDirectory("rea-structure-only-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": JSON.stringify({ main: "main.cjs" }),
|
||||
"main.cjs":
|
||||
'const {BrowserWindow} = require("electron"); const w = new BrowserWindow(); w.loadFile("index.html"); module.exports = { open() { return w; } };',
|
||||
"index.html": "valid page",
|
||||
});
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
semantic_analysis: "structure-only",
|
||||
});
|
||||
// Application structure is still derived from static facts.
|
||||
expect(
|
||||
result.graph.nodes.some(({ kind }) => kind === "electron-renderer"),
|
||||
).toBe(true);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
// No semantic content beyond module scaffolding, and the omission is stated.
|
||||
expect(
|
||||
result.semantic_graph.nodes.every(({ kind }) => kind === "module"),
|
||||
).toBe(true);
|
||||
expect(result.semantic_graph.relations).toEqual([]);
|
||||
expect(
|
||||
result.limitations.some((text) => text.includes("structure-only")),
|
||||
).toBe(true);
|
||||
// Skipped semantic facts stay partial in structured coverage, including the
|
||||
// application graph that would otherwise claim the missing exports examined.
|
||||
expect(result.semantic_graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_nodes: null,
|
||||
omitted_relations: null,
|
||||
});
|
||||
expect(moduleFactRoles(result.graph)).toEqual([]);
|
||||
expect(result.graph.coverage).toEqual({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
});
|
||||
const complete = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
expect(
|
||||
complete.semantic_graph.nodes.some(({ kind }) => kind !== "module"),
|
||||
).toBe(true);
|
||||
expect(complete.semantic_graph.relations.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
complete.limitations.some((text) => text.includes("structure-only")),
|
||||
).toBe(false);
|
||||
expect(complete.graph.coverage).toEqual({
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
});
|
||||
const roles = moduleFactRoles(complete.graph);
|
||||
expect(roles).toContain("source-module");
|
||||
expect(roles).toContain("export-binding");
|
||||
const moduleNodeIds = new Set(
|
||||
complete.graph.nodes.flatMap((node) =>
|
||||
node.observations.some(({ properties }) => {
|
||||
const role = properties.semantic_role;
|
||||
return role === "source-module" || role === "export-binding";
|
||||
})
|
||||
? [node.node_id]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
const comparison = compareJavaScriptApplicationVersions({
|
||||
left: {
|
||||
evidenceId: `ev_${"1".repeat(64)}`,
|
||||
rootArtifactSha256: complete.root_artifact_sha256,
|
||||
graph: complete.graph,
|
||||
},
|
||||
right: {
|
||||
evidenceId: `ev_${"2".repeat(64)}`,
|
||||
rootArtifactSha256: result.root_artifact_sha256,
|
||||
graph: result.graph,
|
||||
},
|
||||
leftNativeEvidence: [],
|
||||
rightNativeEvidence: [],
|
||||
});
|
||||
expect(comparison.coverage).toEqual({
|
||||
status: "partial",
|
||||
left_graph_status: "complete",
|
||||
right_graph_status: "partial",
|
||||
left_graph_omitted_count: 0,
|
||||
right_graph_omitted_count: null,
|
||||
});
|
||||
const moduleItems = comparison.items.filter(
|
||||
(item) =>
|
||||
item.left_node_id !== null && moduleNodeIds.has(item.left_node_id),
|
||||
);
|
||||
expect(moduleItems.length).toBeGreaterThan(0);
|
||||
expect(moduleItems).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
right_node_id: null,
|
||||
dimensions: ["availability", "coverage"],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(moduleItems.every((item) => item.status === "unknown")).toBe(true);
|
||||
expect(comparison.items.some((item) => item.status === "removed")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(comparison.summary.removed).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"unselected",
|
||||
"unavailable",
|
||||
|
||||
Reference in new issue
Block a user