From e19dbcf857e98f402b61b1ef793dd62d9929426a Mon Sep 17 00:00:00 2001 From: gensokyo-dev Date: Mon, 23 Nov 2026 15:36:28 +0000 Subject: [PATCH] feat(analysis-view): count distinct retained JavaScript fact values Counting the distinct IPC channels of one operation meant paging every observation, each with its full Evidence, and deduplicating by hand; real clients miscounted send channels on a large Electron app. Add the javascript-fact-groups view: with the javascript-facts selectors and group_by property names, it returns each distinct combination with its observation and node counts, ordered by canonical JSON, and its total. A missing key stays omitted, distinct from a retained null such as an unresolved dynamic channel. The analyze_javascript_application description names the IPC grouping. Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --- .../javascript-application-workflows.md | 20 ++ src/contracts/analysisViewToolContracts.ts | 17 ++ .../javascript/electronToolContracts.ts | 2 +- .../analysisView/analysisViewRequest.ts | 6 +- src/domain/analysisView/analysisViewResult.ts | 13 ++ .../analysisView/javascriptApplicationView.ts | 33 ++- .../analysisView/javascriptFactsView.ts | 82 ++++++++ .../mcp/javascriptFactGroupsMcp.test.ts | 198 ++++++++++++++++++ 8 files changed, 366 insertions(+), 5 deletions(-) create mode 100644 tests/boundary/mcp/javascriptFactGroupsMcp.test.ts diff --git a/docs/guides/javascript/javascript-application-workflows.md b/docs/guides/javascript/javascript-application-workflows.md index 5241a8497b..ddf694cf9c 100644 --- a/docs/guides/javascript/javascript-application-workflows.md +++ b/docs/guides/javascript/javascript-application-workflows.md @@ -150,6 +150,26 @@ semantic unknown records remain in complete parent Evidence and trace tools. with one of its JSON scalar values; a missing key or non-scalar value never matches, and `values: []` matches none. +To count distinct values instead of paging observations, use +`javascript-fact-groups` with the same `where` and the property names to group +by: + +```json +{ + "kind": "javascript-fact-groups", + "where": { "paths": ["preload.js"], "kinds": ["ipc-channel"] }, + "group_by": ["operation", "channel"] +} +``` + +Each row reports one distinct combination with its `observation_count` and +`node_count`. A missing key is omitted from the combination, distinct from a +retained null such as an unresolved dynamic channel. Rows are ordered by the +canonical JSON of their values; the default offset/limit is 0/256 and the page +total counts distinct combinations. Read a group's observations, with +provenance, through `javascript-facts` and the same `where` plus matching +`where.properties`. + Rows follow retained node/observation order. The default offset/limit is 0/64; follow `coverage.next_offset`. Page totals count matching retained observations, while `source_coverage` preserves caller selection and application/semantic diff --git a/src/contracts/analysisViewToolContracts.ts b/src/contracts/analysisViewToolContracts.ts index 5b5207c88b..9a2111a1b3 100644 --- a/src/contracts/analysisViewToolContracts.ts +++ b/src/contracts/analysisViewToolContracts.ts @@ -172,6 +172,23 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [ }, }, }, + { + title: + "Count distinct IPC channels per operation in one retained source", + input: { + source: { + kind: "retained-evidence", + evidence_id: RETAINED_EXAMPLE_ID, + }, + view: { + kind: "javascript-fact-groups", + where: { paths: ["preload.js"], kinds: ["ipc-channel"] }, + group_by: ["operation", "channel"], + offset: 0, + limit: 256, + }, + }, + }, { title: "Read typed module reference facts from retained application Evidence", diff --git a/src/contracts/javascript/electronToolContracts.ts b/src/contracts/javascript/electronToolContracts.ts index e885f37060..f385096c23 100644 --- a/src/contracts/javascript/electronToolContracts.ts +++ b/src/contracts/javascript/electronToolContracts.ts @@ -128,7 +128,7 @@ export const ELECTRON_TOOL_CONTRACTS = [ }), ), description: - 'Build a static application graph from a local ASAR or extracted JavaScript app without executing it. Supply input_path, e.g. {input_path:"/apps/client",source_paths:["main.js"],detail:"summary"}. Copy source_paths exactly from the inventory, not host-absolute paths inferred from input_path. Returns nodes, edges, semantic relations, integrity contradictions, coverage and unknowns. source_paths limits source analysis to exact inventoried paths without narrowing inventory or artifact identity; dependencies are not implicitly analyzed and unselected sources remain unknown. detail summary reduces delivery, retaining complete Evidence for inspect_analysis_view; it does not reduce analysis. With summary detail, view {kind:"javascript-routes",collection:"routes",offset:0,limit:64} selects static route patterns; static routes do not prove reachability or the complete route set. Integrity mismatches fail by default; record-and-continue retains untrusted observed bytes and partial coverage. analysis_timeout_ms is a per-source provider budget. A host-only timeout needs a longer client deadline, not that budget; do not repeat unchanged work or assume it stopped. If configuration cannot be edited, report the host setting (Codex: mcp_servers..tool_timeout_sec, seconds).', + 'Build a static application graph from a local ASAR or extracted JavaScript app without executing it. Supply input_path, e.g. {input_path:"/apps/client",source_paths:["main.js"],detail:"summary"}. Copy source_paths exactly from the inventory, not host-absolute paths inferred from input_path. Returns nodes, edges, semantic relations, integrity contradictions, coverage and unknowns. source_paths limits source analysis to exact inventoried paths without narrowing inventory or artifact identity; dependencies are not implicitly analyzed and unselected sources remain unknown. detail summary reduces delivery, retaining complete Evidence for inspect_analysis_view; it does not reduce analysis. With summary detail, view {kind:"javascript-routes",collection:"routes",offset:0,limit:64} selects static route patterns; static routes do not prove reachability or the complete route set; {kind:"javascript-fact-groups",where:{kinds:["ipc-channel"]},group_by:["operation","channel"]} counts distinct IPC channels, and javascript-facts with the same where reads their observations. Integrity mismatches fail by default; record-and-continue retains untrusted observed bytes and partial coverage. analysis_timeout_ms is a per-source provider budget. A host-only timeout needs a longer client deadline, not that budget; do not repeat unchanged work or assume it stopped. If configuration cannot be edited, report the host setting (Codex: mcp_servers..tool_timeout_sec, seconds).', kind: "electron-provider", inputSchema: analyzeJavaScriptApplicationRequestSchema, outputSchema: applicationOutputSchema, diff --git a/src/domain/analysisView/analysisViewRequest.ts b/src/domain/analysisView/analysisViewRequest.ts index a41200e22b..5cd5cae39f 100644 --- a/src/domain/analysisView/analysisViewRequest.ts +++ b/src/domain/analysisView/analysisViewRequest.ts @@ -41,7 +41,10 @@ import { browserScenarioViewRequestSchema } from "./browserScenarioViewSchemas.j import { nativeLoadImageViewRequestSchema } from "./nativeLoadImageView.js"; import { desktopViewRequestSchema } from "./desktopApplicationView.js"; import { javascriptModuleReferencesRequestSchema } from "./javascriptModuleReferences.js"; -import { javascriptFactsViewRequestSchema } from "./javascriptFactsView.js"; +import { + javascriptFactGroupsViewRequestSchema, + javascriptFactsViewRequestSchema, +} from "./javascriptFactsView.js"; import { evidenceSchema } from "../evidence.js"; import { declareEvidenceReferenceAlternative } from "../evidenceInputContract.js"; import { apiSurfaceViewSchema } from "./apiSurfaceSchema.js"; @@ -115,6 +118,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [ pageViewSchema, javascriptModuleReferencesRequestSchema, javascriptFactsViewRequestSchema, + javascriptFactGroupsViewRequestSchema, nativeViewSchema, nativeInventoryViewRequestSchema, nativeProcedureReferencesViewRequestSchema, diff --git a/src/domain/analysisView/analysisViewResult.ts b/src/domain/analysisView/analysisViewResult.ts index a1e6fb397a..31105ad11d 100644 --- a/src/domain/analysisView/analysisViewResult.ts +++ b/src/domain/analysisView/analysisViewResult.ts @@ -103,6 +103,8 @@ import { } from "./interfaceBuilderView.js"; import { javascriptApplicationSourceCoverageSchema } from "./javascriptApplicationCoverage.js"; import { + javascriptFactGroupRowSchema, + javascriptFactGroupsViewRequestSchema, javascriptFactRowSchema, javascriptFactsViewRequestSchema, } from "./javascriptFactsView.js"; @@ -511,6 +513,16 @@ const javascriptFactsViewResultSchema = z.strictObject({ source_coverage: javascriptApplicationSourceCoverageSchema, }); +/** Distinct selected property combinations over retained observations. */ +const javascriptFactGroupsViewResultSchema = z.strictObject({ + ...viewResultBase, + kind: z.literal("javascript-fact-groups"), + view: javascriptFactGroupsViewRequestSchema, + parent_operation: z.literal("analyze_javascript_application"), + rows: z.array(javascriptFactGroupRowSchema), + source_coverage: javascriptApplicationSourceCoverageSchema, +}); + const androidPackageViewResultSchema = z.discriminatedUnion("facet", [ androidManifestViewResultSchema, androidComponentsViewResultSchema, @@ -895,6 +907,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ }), javascriptModuleReferencesViewResultSchema, javascriptFactsViewResultSchema, + javascriptFactGroupsViewResultSchema, z.strictObject({ kind: z.literal("native"), view: nativeViewSchema, diff --git a/src/domain/analysisView/javascriptApplicationView.ts b/src/domain/analysisView/javascriptApplicationView.ts index a58cccefaf..802aa193d0 100644 --- a/src/domain/analysisView/javascriptApplicationView.ts +++ b/src/domain/analysisView/javascriptApplicationView.ts @@ -22,7 +22,9 @@ import { type JavaScriptApplicationSourceCoverage, } from "./javascriptApplicationCoverage.js"; import { + projectJavaScriptFactGroups, projectJavaScriptFacts, + javascriptFactGroupsViewRequestSchema, javascriptFactsViewRequestSchema, } from "./javascriptFactsView.js"; import { @@ -457,11 +459,12 @@ export const projectJavaScriptApplicationView = ( view.kind !== "item" && view.kind !== "page" && view.kind !== "javascript" && - view.kind !== "javascript-facts" + view.kind !== "javascript-facts" && + view.kind !== "javascript-fact-groups" ) return err( jsIncompatible( - "JavaScript application Evidence supports summary, module item/page, typed module references or selected JavaScript facts.", + "JavaScript application Evidence supports summary, module item/page, typed module references, selected JavaScript facts or JavaScript fact groups.", ), ); assertOwnedView< @@ -470,13 +473,37 @@ export const projectJavaScriptApplicationView = ( | PageAnalysisView | z.output | z.output - >(view, "summary", "item", "page", "javascript", "javascript-facts"); + | z.output + >( + view, + "summary", + "item", + "page", + "javascript", + "javascript-facts", + "javascript-fact-groups", + ); const sourceCoverage = javascriptApplicationSourceCoverage(analysis); const { fields: shared, limitationCount } = parentFields( parent, analysis, sourceCoverage, ); + if (view.kind === "javascript-fact-groups") { + const { rows, total } = projectJavaScriptFactGroups( + analysis.graph.nodes, + view, + isImmutableJsonSnapshot(analysis) ? analysis : undefined, + ); + return ok({ + ...shared, + kind: "javascript-fact-groups" as const, + view, + rows, + source_coverage: sourceCoverage, + coverage: pageCoverage(view.offset, rows.length, total), + }); + } if (view.kind === "javascript-facts") { const { rows, total } = projectJavaScriptFacts( analysis.graph.nodes, diff --git a/src/domain/analysisView/javascriptFactsView.ts b/src/domain/analysisView/javascriptFactsView.ts index 4d129d9d66..2f77596fd2 100644 --- a/src/domain/analysisView/javascriptFactsView.ts +++ b/src/domain/analysisView/javascriptFactsView.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { canonicalJson } from "../comparisonSemantics.js"; import { isImmutableJsonSnapshot } from "../immutableJson.js"; import { applicationNodeSchema, @@ -74,8 +75,31 @@ export const javascriptFactRowSchema = applicationNodeSchema available_property_keys: z.array(propertyKeySchema).exactOptional(), }); +/** Distinct retained property-value combinations, counted without materializing rows. */ +export const javascriptFactGroupsViewRequestSchema = z.strictObject({ + kind: z.literal("javascript-fact-groups"), + where: javascriptFactsWhereSchema, + group_by: z + .array(propertyKeySchema) + .min(1) + .describe( + 'Exact retained property names whose value combinations form groups, e.g. ["operation", "channel"]. A missing key is omitted from the group, distinct from retained null. Rows are ordered by the canonical JSON of their values. Read matching observations with javascript-facts and the same where plus where.properties.', + ), + offset: z.number().int().nonnegative().default(0), + limit: z.number().int().positive().default(256), +}); + +/** One distinct combination; rows are ordered by the canonical JSON of their group_by values. */ +export const javascriptFactGroupRowSchema = z.strictObject({ + properties: applicationNodeObservationSchema.shape.properties, + observation_count: z.int().positive(), + node_count: z.int().positive(), +}); + type FactRequest = z.infer; +type FactGroupsRequest = z.infer; type FactRow = z.infer; +type FactGroupRow = z.infer; type FactWhere = FactRequest["where"]; const observationPath = ( @@ -545,3 +569,61 @@ export const projectJavaScriptFacts = ( } return { rows, total }; }; + +/** Count distinct selected property combinations over every matching observation. */ +export const projectJavaScriptFactGroups = ( + nodes: readonly ApplicationNode[], + view: FactGroupsRequest, + cacheOwner?: object, +): { readonly rows: FactGroupRow[]; readonly total: number } => { + const keys = [...new Set(view.group_by)]; + const groups = new Map< + string, + { + readonly properties: FactGroupRow["properties"]; + observations: number; + readonly nodes: Set; + } + >(); + forEachMatchingFact( + nodes, + view.where, + cacheOwner, + ({ node, observation }) => { + const properties = Object.fromEntries( + keys.flatMap((key) => + Object.hasOwn(observation.properties, key) + ? [[key, observation.properties[key]!] as const] + : [], + ), + ); + // Key order follows group_by, so canonical JSON identifies the combination. + const identity = canonicalJson( + keys.map((key) => + Object.hasOwn(properties, key) ? [properties[key]] : [], + ), + "JavaScript fact group", + ); + const existing = groups.get(identity); + if (existing === undefined) + groups.set(identity, { + properties, + observations: 1, + nodes: new Set([node.node_id]), + }); + else { + existing.observations += 1; + existing.nodes.add(node.node_id); + } + }, + ); + const rows = [...groups] + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + .slice(view.offset, view.offset + view.limit) + .map(([, group]) => ({ + properties: group.properties, + observation_count: group.observations, + node_count: group.nodes.size, + })); + return { rows, total: groups.size }; +}; diff --git a/tests/boundary/mcp/javascriptFactGroupsMcp.test.ts b/tests/boundary/mcp/javascriptFactGroupsMcp.test.ts new file mode 100644 index 0000000000..7dd13df578 --- /dev/null +++ b/tests/boundary/mcp/javascriptFactGroupsMcp.test.ts @@ -0,0 +1,198 @@ +import { withCanonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.js"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it, onTestFinished } from "vitest"; +import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; +import { analysisViewResultSchema } from "../../../src/domain/analysisView/analysisViewResult.js"; + +const preload = `const { contextBridge, ipcRenderer } = require("electron"); +const dynamic = globalThis.channelName; +contextBridge.exposeInMainWorld("bridge", { + ready: () => ipcRenderer.send("ready"), + readyAgain: () => ipcRenderer.send("ready"), + close: () => ipcRenderer.send("window-close"), + info: () => ipcRenderer.invoke("get-info"), + any: () => ipcRenderer.send(dynamic), +});`; + +const main = `const { app, BrowserWindow, ipcMain } = require("electron"); +const path = require("path"); +ipcMain.on("ready", () => {}); +ipcMain.handle("get-info", () => ({})); +app.whenReady().then(() => new BrowserWindow({ + webPreferences: { preload: path.join(__dirname, "preload.js") }, +}));`; + +const connect = async () => { + const harness = await createApplicationMcpHarness({ + session: createTestBinarySession(() => { + throw new Error("Reading retained facts must not start a deep provider"); + }), + }); + onTestFinished(() => harness.close()); + return harness; +}; + +it("counts distinct retained IPC channels per operation and reads one group's observations", async () => { + const root = await createTestTempDirectory("rea-js-fact-groups-"); + await Promise.all([ + writeFile( + join(root, "package.json"), + '{"name":"fact-groups","main":"main.js"}', + ), + writeFile(join(root, "main.js"), main), + writeFile(join(root, "preload.js"), preload), + ]); + const harness = await connect(); + const analyzed = await harness.client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, detail: "summary" }, + }); + expect(analyzed.isError).not.toBe(true); + const summary = analysisViewResultSchema.parse( + parseEvidence(analyzed.structuredContent).normalized_result, + ); + if (summary.kind !== "summary") throw new Error("Expected summary view"); + const source = { + kind: "retained-evidence", + evidence_id: summary.parent_evidence_id, + }; + const [definition] = (await harness.client.listTools()).tools.filter( + (tool) => tool.name === "inspect_analysis_view", + ); + if (definition === undefined) throw new Error("Missing view tool"); + const { ajv, inputSchema } = await advertisedMcpToolSchemas( + harness.client, + "inspect_analysis_view", + ); + const view = async (selected: unknown) => { + expect(ajv.validate(inputSchema, { source, view: selected })).toBe(true); + const wire = await harness.client.callTool( + { name: "inspect_analysis_view", arguments: { source, view: selected } }, + { toolDefinition: withCanonicalOutputSchema(definition) }, + ); + expect(wire.isError).not.toBe(true); + return analysisViewResultSchema.parse( + parseEvidence(wire.structuredContent).normalized_result, + ); + }; + + const where = { paths: ["preload.js"], kinds: ["ipc-channel"] }; + const groups = await view({ + kind: "javascript-fact-groups", + where, + group_by: ["operation", "channel"], + }); + if (groups.kind !== "javascript-fact-groups") + throw new Error("Expected fact groups"); + // The repeated send is one group with two observations; the dynamic channel + // keeps its retained null rather than disappearing or merging. + expect(groups.rows).toEqual([ + { + properties: { operation: "invoke", channel: "get-info" }, + observation_count: 1, + node_count: 1, + }, + { + properties: { operation: "send", channel: "ready" }, + observation_count: 2, + node_count: expect.any(Number), + }, + { + properties: { operation: "send", channel: "window-close" }, + observation_count: 1, + node_count: 1, + }, + { + properties: { operation: "send", channel: null }, + observation_count: 1, + node_count: 1, + }, + ]); + expect(groups.coverage).toMatchObject({ total: 4, exhausted: true }); + + const sends = await view({ + kind: "javascript-fact-groups", + where: { + ...where, + properties: [{ key: "operation", values: ["send"] }], + }, + group_by: ["channel"], + limit: 2, + }); + if (sends.kind !== "javascript-fact-groups") + throw new Error("Expected fact groups"); + expect(sends.rows.map((row) => row.properties)).toEqual([ + { channel: "ready" }, + { channel: "window-close" }, + ]); + expect(sends.coverage).toMatchObject({ + examined: 2, + total: 3, + next_offset: 2, + }); + + // The same selector reads the grouped observations with provenance. + const ready = await view({ + kind: "javascript-facts", + where: { + ...where, + properties: [ + { key: "operation", values: ["send"] }, + { key: "channel", values: ["ready"] }, + ], + }, + property_keys: ["channel"], + }); + if (ready.kind !== "javascript-facts") throw new Error("Expected facts"); + expect(ready.rows).toHaveLength(2); + for (const row of ready.rows) { + expect(row.properties).toEqual({ channel: "ready" }); + expect(row.evidence.location).toMatchObject({ + available: true, + value: { source: "preload.js" }, + }); + } + + // A missing key never matches, and empty values select nothing. + for (const properties of [ + [{ key: "not_retained", values: [null] }], + [{ key: "operation", values: [] }], + [ + { key: "operation", values: ["send"] }, + { key: "operation", values: ["invoke"] }, + ], + ]) { + const none = await view({ + kind: "javascript-facts", + where: { ...where, properties }, + property_keys: [], + }); + if (none.kind !== "javascript-facts") throw new Error("Expected facts"); + expect(none.rows).toEqual([]); + expect(none.coverage).toMatchObject({ total: 0 }); + } + + const rejected = await harness.client.callTool({ + name: "inspect_analysis_view", + arguments: { + source, + view: { kind: "javascript-fact-groups", where, group_by: [] }, + }, + }); + expect(parseMcpToolError(rejected)).toMatchObject({ + error: { + code: "invalid_request", + details: { + issues: [ + { path: ["view", "group_by"], reason: "out_of_range", minimum: 1 }, + ], + }, + }, + }); +});