feat(javascript): expose bounded semantic tracing
This commit is contained in:
@@ -3,6 +3,7 @@ import { isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
|
||||
import { javaScriptSemanticGraphSchema } from "./javascriptSemanticGraph.js";
|
||||
|
||||
const MAX_GRAPH_NODES = 100_000;
|
||||
const MAX_GRAPH_EDGES = 200_000;
|
||||
@@ -155,8 +156,8 @@ const reconstructionStatisticsSchema = z.strictObject({
|
||||
truncated_scopes: countSchema,
|
||||
});
|
||||
|
||||
/** Strict high-level result returned inside Evidence v2. */
|
||||
export const javascriptApplicationAnalysisResultSchema = z.strictObject({
|
||||
/** Legacy structural JavaScript application analysis result. */
|
||||
export const javaScriptApplicationAnalysisResultV1Schema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
input_path: z.string().min(1).max(16_384),
|
||||
format: z.enum(["asar", "directory"]),
|
||||
@@ -169,6 +170,61 @@ export const javascriptApplicationAnalysisResultSchema = z.strictObject({
|
||||
limitations: z.array(z.string().min(1).max(4_096)).max(1_000),
|
||||
});
|
||||
|
||||
/** JavaScript application analysis with an authenticated semantic companion. */
|
||||
export const javaScriptApplicationAnalysisResultV2Schema =
|
||||
javaScriptApplicationAnalysisResultV1Schema
|
||||
.extend({
|
||||
schema_version: z.literal(2),
|
||||
semantic_graph: javaScriptSemanticGraphSchema,
|
||||
})
|
||||
.superRefine((result, context) => {
|
||||
if (result.semantic_graph.application_graph_id !== result.graph.graph_id)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["semantic_graph", "application_graph_id"],
|
||||
message:
|
||||
"Semantic graph must commit the containing application graph",
|
||||
});
|
||||
if (
|
||||
result.semantic_graph.root_artifact_sha256 !==
|
||||
result.root_artifact_sha256
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["semantic_graph", "root_artifact_sha256"],
|
||||
message: "Semantic graph must commit the containing root artifact",
|
||||
});
|
||||
const applicationNodeIds = new Set(
|
||||
result.graph.nodes.map(({ node_id }) => node_id),
|
||||
);
|
||||
for (const [nodeIndex, node] of result.semantic_graph.nodes.entries())
|
||||
for (const [
|
||||
identifierIndex,
|
||||
identifier,
|
||||
] of node.application_node_ids.entries())
|
||||
if (!applicationNodeIds.has(identifier))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [
|
||||
"semantic_graph",
|
||||
"nodes",
|
||||
nodeIndex,
|
||||
"application_node_ids",
|
||||
identifierIndex,
|
||||
],
|
||||
message: "Semantic node references an absent application node",
|
||||
});
|
||||
});
|
||||
|
||||
/** Strict versioned high-level result returned inside Evidence v2. */
|
||||
export const javascriptApplicationAnalysisResultSchema = z.discriminatedUnion(
|
||||
"schema_version",
|
||||
[
|
||||
javaScriptApplicationAnalysisResultV1Schema,
|
||||
javaScriptApplicationAnalysisResultV2Schema,
|
||||
],
|
||||
);
|
||||
|
||||
/** Parsed public JavaScript application analysis request. */
|
||||
export type AnalyzeJavaScriptApplicationInput = z.infer<
|
||||
typeof analyzeJavaScriptApplicationInputSchema
|
||||
|
||||
@@ -82,18 +82,18 @@ export const digestCanonical = (value: unknown): string => {
|
||||
|
||||
const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => {
|
||||
const evidence = parseEvidence(layer.analysis);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
assertEvidenceIdentity(evidence, {
|
||||
operation: "analyze_javascript_application",
|
||||
predicate: "rea.javascript-application-analysis/v1",
|
||||
predicate: `rea.javascript-application-analysis/v${String(result.schema_version)}`,
|
||||
providerId: "rea-javascript-application",
|
||||
providerName: "REA JavaScript application analyzer",
|
||||
providerVersion: "1",
|
||||
authority: "shipped-artifact",
|
||||
confidence: "derived",
|
||||
});
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
if (
|
||||
evidence.subject === null ||
|
||||
evidence.subject.digest.sha256 !== result.root_artifact_sha256 ||
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as t from "@babel/types";
|
||||
import type {
|
||||
JavaScriptSemanticArgumentFlow,
|
||||
JavaScriptSemanticCallable,
|
||||
JavaScriptSemanticCallResultFlow,
|
||||
JavaScriptSemanticCallReturnFlow,
|
||||
JavaScriptSemanticCallSite,
|
||||
JavaScriptSemanticClosureCapture,
|
||||
@@ -32,6 +33,7 @@ export interface JavaScriptSemanticCallAnalysis {
|
||||
readonly callSites: readonly JavaScriptSemanticCallSite[];
|
||||
readonly argumentFlows: readonly JavaScriptSemanticArgumentFlow[];
|
||||
readonly callReturnFlows: readonly JavaScriptSemanticCallReturnFlow[];
|
||||
readonly callResultFlows: readonly JavaScriptSemanticCallResultFlow[];
|
||||
readonly closureCaptures: readonly JavaScriptSemanticClosureCapture[];
|
||||
readonly frontiers: readonly JavaScriptSemanticFrontier[];
|
||||
}
|
||||
@@ -40,6 +42,7 @@ interface MutableCallAnalysis {
|
||||
readonly callSites: JavaScriptSemanticCallSite[];
|
||||
readonly argumentFlows: JavaScriptSemanticArgumentFlow[];
|
||||
readonly callReturnFlows: JavaScriptSemanticCallReturnFlow[];
|
||||
readonly callResultFlows: JavaScriptSemanticCallResultFlow[];
|
||||
readonly closureCaptures: JavaScriptSemanticClosureCapture[];
|
||||
readonly frontiers: JavaScriptSemanticFrontier[];
|
||||
retainedArguments: number;
|
||||
@@ -66,6 +69,7 @@ export const collectJavaScriptSemanticCalls = (
|
||||
callSites: [],
|
||||
argumentFlows: [],
|
||||
callReturnFlows: [],
|
||||
callResultFlows: [],
|
||||
closureCaptures: [],
|
||||
frontiers: [],
|
||||
retainedArguments: 0,
|
||||
@@ -95,7 +99,7 @@ export const collectJavaScriptSemanticCalls = (
|
||||
t.isOptionalCallExpression(node) ||
|
||||
t.isNewExpression(node)
|
||||
)
|
||||
collectCallSite(node, owner, context);
|
||||
collectCallSite(node, parent, owner, context);
|
||||
},
|
||||
exit: (node) => {
|
||||
const callableId = semanticCallableIdForNode(node);
|
||||
@@ -110,6 +114,7 @@ export const collectJavaScriptSemanticCalls = (
|
||||
callSites: output.callSites,
|
||||
argumentFlows: output.argumentFlows,
|
||||
callReturnFlows: output.callReturnFlows,
|
||||
callResultFlows: output.callResultFlows,
|
||||
closureCaptures: output.closureCaptures,
|
||||
frontiers: output.frontiers,
|
||||
};
|
||||
@@ -117,6 +122,7 @@ export const collectJavaScriptSemanticCalls = (
|
||||
|
||||
const collectCallSite = (
|
||||
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
|
||||
parent: t.Node | null,
|
||||
owner: JavaScriptSemanticCallable | undefined,
|
||||
context: CallCollectionContext,
|
||||
): void => {
|
||||
@@ -151,6 +157,7 @@ const collectCallSite = (
|
||||
arguments: argumentsValue,
|
||||
};
|
||||
output.callSites.push(site);
|
||||
collectCallResultFlow(site, node, parent, context);
|
||||
if (site.resolution !== "exact")
|
||||
addFrontier(
|
||||
{
|
||||
@@ -167,6 +174,44 @@ const collectCallSite = (
|
||||
collectReturnFlows(site, callableById, state, output);
|
||||
};
|
||||
|
||||
const collectCallResultFlow = (
|
||||
site: JavaScriptSemanticCallSite,
|
||||
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
|
||||
parent: t.Node | null,
|
||||
context: CallCollectionContext,
|
||||
): void => {
|
||||
const identifier =
|
||||
t.isVariableDeclarator(parent) &&
|
||||
parent.init === node &&
|
||||
t.isIdentifier(parent.id)
|
||||
? parent.id
|
||||
: t.isAssignmentExpression(parent) &&
|
||||
parent.right === node &&
|
||||
t.isIdentifier(parent.left)
|
||||
? parent.left
|
||||
: null;
|
||||
if (identifier === null) return;
|
||||
const binding = resolveSemanticBindingState(
|
||||
context.state,
|
||||
identifier,
|
||||
identifier.name,
|
||||
);
|
||||
const identifierRange = range(identifier);
|
||||
const definition = binding?.definitions.find(
|
||||
({ location }) =>
|
||||
location.start.line === identifierRange.start.line &&
|
||||
location.start.column === identifierRange.start.column &&
|
||||
location.end.line === identifierRange.end.line &&
|
||||
location.end.column === identifierRange.end.column,
|
||||
);
|
||||
if (binding === undefined || definition === undefined) return;
|
||||
context.output.callResultFlows.push({
|
||||
callSiteId: site.callSiteId,
|
||||
bindingId: binding.bindingId,
|
||||
definitionLocation: definition.location,
|
||||
});
|
||||
};
|
||||
|
||||
const retainedArguments = (
|
||||
nodes: readonly (
|
||||
| t.Expression
|
||||
|
||||
@@ -53,13 +53,10 @@ const normalizeEvidence = (
|
||||
evidence_ids: uniqueSorted(evidence.evidence_ids),
|
||||
});
|
||||
|
||||
const nodeIdentity = (
|
||||
node: Pick<JavaScriptSemanticGraphNode, "kind" | "identity">,
|
||||
) => ({ kind: node.kind, identity: node.identity });
|
||||
|
||||
const nodeId = (
|
||||
node: Pick<JavaScriptSemanticGraphNode, "kind" | "identity">,
|
||||
): string => `jsrg_node_${digestCanonical(nodeIdentity(node))}`;
|
||||
): string =>
|
||||
`jsrg_node_${digestCanonical({ kind: node.kind, identity: node.identity })}`;
|
||||
|
||||
/** Normalize one semantic entity and derive its artifact-version identifier. */
|
||||
export const createJavaScriptSemanticGraphNode = (
|
||||
@@ -362,6 +359,12 @@ const checkUnknowns = (
|
||||
path: ["unknowns", index, "node_id"],
|
||||
message: "Unknown frontier node is absent",
|
||||
});
|
||||
if (unknown.candidate_node_ids.some((nodeId) => !nodes.has(nodeId)))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["unknowns", index, "candidate_node_ids"],
|
||||
message: "Unknown frontier candidate node is absent",
|
||||
});
|
||||
if (
|
||||
unknown.relation_kinds.some(
|
||||
(kind) => JAVASCRIPT_SEMANTIC_RELATION_FAMILY[kind] !== unknown.family,
|
||||
@@ -516,31 +519,4 @@ export const createJavaScriptSemanticGraph = (
|
||||
});
|
||||
};
|
||||
|
||||
/** Parse a stored semantic graph and reject unsupported versions or stale IDs. */
|
||||
export const parseJavaScriptSemanticGraph = (
|
||||
input: unknown,
|
||||
): JavaScriptSemanticGraph => {
|
||||
const envelope = z
|
||||
.object({ schema: z.string(), schema_version: z.number() })
|
||||
.passthrough()
|
||||
.safeParse(input);
|
||||
if (
|
||||
envelope.success &&
|
||||
envelope.data.schema === "JavaScriptSemanticRelationGraph" &&
|
||||
envelope.data.schema_version !== 1
|
||||
)
|
||||
throw new TypeError(
|
||||
`Unsupported JavaScript Semantic Relation Graph schema version: ${String(envelope.data.schema_version)}`,
|
||||
);
|
||||
return javaScriptSemanticGraphSchema.parse(input);
|
||||
};
|
||||
|
||||
/** Serialize a verified semantic graph as canonical JSON. */
|
||||
export const serializeJavaScriptSemanticGraph = (input: unknown): string =>
|
||||
canonicalJson(parseJavaScriptSemanticGraph(input));
|
||||
|
||||
/** Compute the canonical SHA-256 commitment of a verified semantic graph. */
|
||||
export const computeJavaScriptSemanticGraphSha256 = (input: unknown): string =>
|
||||
digestCanonical(parseJavaScriptSemanticGraph(input));
|
||||
|
||||
export type { JavaScriptSemanticGraphNode, JavaScriptSemanticGraphRelation };
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
javaScriptSemanticGraphSchema,
|
||||
type JavaScriptSemanticGraph,
|
||||
} from "./javascriptSemanticGraph.js";
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError(
|
||||
"JavaScript semantic graph could not canonicalize data",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/** Parse a stored semantic graph and reject unsupported versions or stale IDs. */
|
||||
export const parseJavaScriptSemanticGraph = (
|
||||
input: unknown,
|
||||
): JavaScriptSemanticGraph => {
|
||||
const envelope = z
|
||||
.object({ schema: z.string(), schema_version: z.number() })
|
||||
.passthrough()
|
||||
.safeParse(input);
|
||||
if (
|
||||
envelope.success &&
|
||||
envelope.data.schema === "JavaScriptSemanticRelationGraph" &&
|
||||
envelope.data.schema_version !== 1
|
||||
)
|
||||
throw new TypeError(
|
||||
`Unsupported JavaScript Semantic Relation Graph schema version: ${String(envelope.data.schema_version)}`,
|
||||
);
|
||||
return javaScriptSemanticGraphSchema.parse(input);
|
||||
};
|
||||
|
||||
/** Serialize a verified semantic graph as canonical JSON. */
|
||||
export const serializeJavaScriptSemanticGraph = (input: unknown): string =>
|
||||
canonicalJson(parseJavaScriptSemanticGraph(input));
|
||||
@@ -153,6 +153,7 @@ export interface JavaScriptSemanticCallable {
|
||||
export interface JavaScriptSemanticReturnSite {
|
||||
readonly returnSiteId: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
readonly identityReferenceLocation: JavaScriptSourceRange | null;
|
||||
readonly value: JavaScriptSemanticValue;
|
||||
}
|
||||
|
||||
@@ -193,6 +194,13 @@ export interface JavaScriptSemanticCallReturnFlow {
|
||||
readonly returnLocation: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One local binding initialized or assigned from a retained call expression. */
|
||||
export interface JavaScriptSemanticCallResultFlow {
|
||||
readonly callSiteId: string;
|
||||
readonly bindingId: string;
|
||||
readonly definitionLocation: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One resolved outer lexical binding referenced by a nested callable. */
|
||||
export interface JavaScriptSemanticClosureCapture {
|
||||
readonly callableId: string;
|
||||
@@ -251,6 +259,7 @@ export interface JavaScriptSemanticIr {
|
||||
readonly callSites: readonly JavaScriptSemanticCallSite[];
|
||||
readonly argumentFlows: readonly JavaScriptSemanticArgumentFlow[];
|
||||
readonly callReturnFlows: readonly JavaScriptSemanticCallReturnFlow[];
|
||||
readonly callResultFlows: readonly JavaScriptSemanticCallResultFlow[];
|
||||
readonly closureCaptures: readonly JavaScriptSemanticClosureCapture[];
|
||||
readonly frontiers: readonly JavaScriptSemanticFrontier[];
|
||||
readonly coverage: JavaScriptSemanticCoverage;
|
||||
@@ -287,6 +296,7 @@ export const failedJavaScriptSemanticIr = (): JavaScriptSemanticIr => ({
|
||||
callSites: [],
|
||||
argumentFlows: [],
|
||||
callReturnFlows: [],
|
||||
callResultFlows: [],
|
||||
closureCaptures: [],
|
||||
frontiers: [],
|
||||
coverage: { status: "failed", omittedCount: null, limitsReached: [] },
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { compareCodePoints } from "./javascriptApplicationGraph.js";
|
||||
import type {
|
||||
JavaScriptSemanticGraph,
|
||||
JavaScriptSemanticGraphNode,
|
||||
JavaScriptSemanticGraphRelation,
|
||||
} from "./javascriptSemanticGraph.js";
|
||||
import {
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
|
||||
type JavaScriptSemanticGraphUnknown,
|
||||
} from "./javascriptSemanticGraphSchemas.js";
|
||||
import type { JavaScriptSemanticGraphUnknown } from "./javascriptSemanticGraphSchemas.js";
|
||||
import { isJavaScriptSemanticOwnershipRelation as ownershipRelation } from "./javascriptSemanticQueryRelations.js";
|
||||
import {
|
||||
javaScriptSemanticQueryInputSchema,
|
||||
javaScriptSemanticQueryResultSchema,
|
||||
@@ -22,6 +16,14 @@ import {
|
||||
assessJavaScriptSemanticQuery,
|
||||
type JavaScriptSemanticQueryFrontier,
|
||||
} from "./javascriptSemanticQueryAssessment.js";
|
||||
import {
|
||||
canonicalJavaScriptSemanticQueryJson as canonicalJson,
|
||||
createJavaScriptSemanticQueryCursor as createCursor,
|
||||
JavaScriptSemanticQueryCursorError,
|
||||
javaScriptSemanticQueryIdentifier as queryIdentifier,
|
||||
parseJavaScriptSemanticQueryCursor as parseCursor,
|
||||
resolveJavaScriptSemanticQuerySeeds as resolveSeeds,
|
||||
} from "./javascriptSemanticQueryIdentity.js";
|
||||
|
||||
interface TraversalEntry {
|
||||
readonly relation: JavaScriptSemanticGraphRelation;
|
||||
@@ -43,20 +45,22 @@ interface SeedAdmission {
|
||||
readonly frontier: QueryFrontier[];
|
||||
}
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError(
|
||||
"JavaScript semantic query could not canonicalize data",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
interface QueryPage {
|
||||
readonly retainedNodes: JavaScriptSemanticGraphNode[];
|
||||
readonly retainedRelations: JavaScriptSemanticGraphRelation[];
|
||||
readonly pageRelations: JavaScriptSemanticGraphRelation[];
|
||||
readonly pageNodes: JavaScriptSemanticGraphNode[];
|
||||
readonly nextCursor: string | null;
|
||||
}
|
||||
|
||||
const digest = (value: unknown): string =>
|
||||
createHash("sha256").update(canonicalJson(value)).digest("hex");
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): string[] =>
|
||||
[...new Set(values)].sort(compareCodePoints);
|
||||
interface QueryPageInput {
|
||||
readonly graph: JavaScriptSemanticGraph;
|
||||
readonly traversal: Traversal;
|
||||
readonly query: JavaScriptSemanticQueryInput;
|
||||
readonly queryId: string;
|
||||
readonly offset: number;
|
||||
readonly retainedSeeds: readonly string[];
|
||||
}
|
||||
|
||||
/** Run one deterministic bounded traversal over a verified semantic graph. */
|
||||
export const queryJavaScriptSemanticGraph = (
|
||||
@@ -75,41 +79,31 @@ export const queryJavaScriptSemanticGraph = (
|
||||
...traversal.frontier,
|
||||
...admission.frontier,
|
||||
]);
|
||||
const retainedNodes = graph.nodes.filter(({ node_id }) =>
|
||||
traversal.nodeIds.has(node_id),
|
||||
);
|
||||
const retainedRelations = graph.relations.filter(({ relation_id }) =>
|
||||
traversal.relationIds.has(relation_id),
|
||||
);
|
||||
if (offset > retainedRelations.length)
|
||||
throw new TypeError("Semantic query cursor is beyond the retained result");
|
||||
const pageRelations = retainedRelations.slice(
|
||||
const page = createQueryPage({
|
||||
graph,
|
||||
traversal,
|
||||
query: input,
|
||||
queryId,
|
||||
offset,
|
||||
offset + input.limits.page_size,
|
||||
);
|
||||
const pageNodeIds = new Set([
|
||||
...retainedSeeds,
|
||||
...pageRelations.flatMap(({ source_node_id, target_node_id }) => [
|
||||
source_node_id,
|
||||
target_node_id,
|
||||
]),
|
||||
]);
|
||||
const pageNodes = graph.nodes.filter(({ node_id }) =>
|
||||
pageNodeIds.has(node_id),
|
||||
);
|
||||
const relevantUnknowns = relevantUnknownFrontiers(
|
||||
retainedSeeds,
|
||||
});
|
||||
const allRelevantUnknowns = relevantUnknownFrontiers(
|
||||
graph,
|
||||
traversal.nodeIds,
|
||||
input,
|
||||
);
|
||||
const relevantUnknowns = allRelevantUnknowns.slice(
|
||||
0,
|
||||
input.limits.max_unknowns,
|
||||
);
|
||||
const candidateRelations = relevantCandidateRelationCount(
|
||||
graph,
|
||||
traversal.nodeIds,
|
||||
input,
|
||||
);
|
||||
const expectedMatches = expectedMatchesFor(
|
||||
retainedNodes,
|
||||
retainedRelations,
|
||||
page.retainedNodes,
|
||||
page.retainedRelations,
|
||||
input,
|
||||
);
|
||||
const assessment = assessJavaScriptSemanticQuery({
|
||||
@@ -121,12 +115,8 @@ export const queryJavaScriptSemanticGraph = (
|
||||
frontier,
|
||||
unknowns: relevantUnknowns,
|
||||
candidateRelations,
|
||||
unknownsTruncated: allRelevantUnknowns.length > relevantUnknowns.length,
|
||||
});
|
||||
const nextOffset = offset + pageRelations.length;
|
||||
const nextCursor =
|
||||
nextOffset < retainedRelations.length
|
||||
? createCursor(queryId, nextOffset)
|
||||
: null;
|
||||
return javaScriptSemanticQueryResultSchema.parse({
|
||||
schema_version: 1,
|
||||
query_id: queryId,
|
||||
@@ -135,8 +125,8 @@ export const queryJavaScriptSemanticGraph = (
|
||||
direction: input.direction,
|
||||
status: assessment.status,
|
||||
seed_node_ids: retainedSeeds,
|
||||
nodes: pageNodes,
|
||||
relations: pageRelations,
|
||||
nodes: page.pageNodes,
|
||||
relations: page.pageRelations,
|
||||
unknowns: relevantUnknowns,
|
||||
expected_match_node_ids: expectedMatches.map(({ node_id }) => node_id),
|
||||
summary: {
|
||||
@@ -146,13 +136,14 @@ export const queryJavaScriptSemanticGraph = (
|
||||
traversed_relations: traversal.relationIds.size,
|
||||
traversed_functions: traversal.functionIds.size,
|
||||
traversed_modules: traversal.modules.size,
|
||||
relevant_unknowns: relevantUnknowns.length,
|
||||
relevant_unknowns: allRelevantUnknowns.length,
|
||||
retained_unknowns: relevantUnknowns.length,
|
||||
},
|
||||
coverage: assessment.coverage,
|
||||
page: {
|
||||
offset,
|
||||
size: pageRelations.length,
|
||||
next_cursor: nextCursor,
|
||||
size: page.pageRelations.length,
|
||||
next_cursor: page.nextCursor,
|
||||
},
|
||||
applied_limits: input.limits,
|
||||
accepted_limit_ranges: assessment.acceptedLimitRanges,
|
||||
@@ -160,96 +151,49 @@ export const queryJavaScriptSemanticGraph = (
|
||||
});
|
||||
};
|
||||
|
||||
const queryIdentifier = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): string => {
|
||||
const { cursor: _cursor, ...semantic } = input;
|
||||
return `jsrq_${digest({
|
||||
source_graph_id: graph.graph_id,
|
||||
...semantic,
|
||||
allowed_relations:
|
||||
semantic.allowed_relations === undefined
|
||||
? undefined
|
||||
: uniqueSorted(semantic.allowed_relations),
|
||||
expected:
|
||||
semantic.expected === null
|
||||
? null
|
||||
: {
|
||||
...semantic.expected,
|
||||
classes: uniqueSorted(semantic.expected.classes),
|
||||
},
|
||||
})}`;
|
||||
};
|
||||
|
||||
const createCursor = (queryId: string, offset: number): string =>
|
||||
`jsrqc_${String(offset)}_${digest({ query_id: queryId, offset })}`;
|
||||
|
||||
const parseCursor = (cursor: string | null, queryId: string): number => {
|
||||
if (cursor === null) return 0;
|
||||
const match = /^jsrqc_([0-9]+)_([a-f0-9]{64})$/u.exec(cursor);
|
||||
const offsetText = match?.[1];
|
||||
const commitment = match?.[2];
|
||||
if (offsetText === undefined || commitment === undefined)
|
||||
throw new TypeError("Semantic query cursor is malformed");
|
||||
const offset = Number(offsetText);
|
||||
if (
|
||||
!Number.isSafeInteger(offset) ||
|
||||
offset < 0 ||
|
||||
commitment !== digest({ query_id: queryId, offset })
|
||||
)
|
||||
throw new TypeError("Semantic query cursor does not match this query");
|
||||
return offset;
|
||||
};
|
||||
|
||||
const resolveSeeds = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): string[] => {
|
||||
const fingerprintFunctions = new Set(
|
||||
input.seed.kind === "function"
|
||||
? graph.fingerprints
|
||||
.filter(({ fingerprint_sha256 }) => {
|
||||
const seed = input.seed;
|
||||
return (
|
||||
seed.kind === "function" &&
|
||||
fingerprint_sha256 === seed.fingerprint_sha256
|
||||
);
|
||||
})
|
||||
.map(({ function_node_id }) => function_node_id)
|
||||
: [],
|
||||
const createQueryPage = ({
|
||||
graph,
|
||||
traversal,
|
||||
query,
|
||||
queryId,
|
||||
offset,
|
||||
retainedSeeds,
|
||||
}: QueryPageInput): QueryPage => {
|
||||
const retainedNodes = graph.nodes.filter(({ node_id }) =>
|
||||
traversal.nodeIds.has(node_id),
|
||||
);
|
||||
return graph.nodes
|
||||
.filter((node) => seedMatches(node, input, fingerprintFunctions))
|
||||
.map(({ node_id }) => node_id)
|
||||
.sort(compareCodePoints);
|
||||
};
|
||||
|
||||
const seedMatches = (
|
||||
node: JavaScriptSemanticGraphNode,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
fingerprintFunctions: ReadonlySet<string>,
|
||||
): boolean => {
|
||||
const seed = input.seed;
|
||||
if (seed.kind === "semantic-node") return node.node_id === seed.node_id;
|
||||
if (seed.kind === "application-node")
|
||||
return node.application_node_ids.includes(seed.node_id);
|
||||
if (seed.kind === "function") return fingerprintFunctions.has(node.node_id);
|
||||
if (seed.kind === "literal")
|
||||
return (
|
||||
node.kind === "literal" &&
|
||||
canonicalJson(node.properties.value) === canonicalJson(seed.value)
|
||||
const retainedRelations = graph.relations.filter(({ relation_id }) =>
|
||||
traversal.relationIds.has(relation_id),
|
||||
);
|
||||
if (offset > retainedRelations.length)
|
||||
throw new JavaScriptSemanticQueryCursorError(
|
||||
"Semantic query cursor is beyond the retained result",
|
||||
);
|
||||
if (seed.kind === "property")
|
||||
return node.kind === "property-slot" && node.properties.name === seed.name;
|
||||
if (seed.kind === "endpoint")
|
||||
return node.kind === "request" && node.properties.endpoint === seed.value;
|
||||
if (seed.kind === "event")
|
||||
return (
|
||||
["event", "listener"].includes(node.kind) &&
|
||||
node.properties.event_name === seed.name
|
||||
);
|
||||
return node.kind === "boundary" && node.properties.field === seed.field;
|
||||
const pageRelations = retainedRelations.slice(
|
||||
offset,
|
||||
offset + query.limits.page_size,
|
||||
);
|
||||
const pageNodeIds = new Set([
|
||||
...retainedSeeds,
|
||||
...pageRelations.flatMap(({ source_node_id, target_node_id }) => [
|
||||
source_node_id,
|
||||
target_node_id,
|
||||
]),
|
||||
]);
|
||||
const pageNodes = graph.nodes.filter(({ node_id }) =>
|
||||
pageNodeIds.has(node_id),
|
||||
);
|
||||
const nextOffset = offset + pageRelations.length;
|
||||
return {
|
||||
retainedNodes,
|
||||
retainedRelations,
|
||||
pageRelations,
|
||||
pageNodes,
|
||||
nextCursor:
|
||||
nextOffset < retainedRelations.length
|
||||
? createCursor(queryId, nextOffset)
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
const admitSeeds = (
|
||||
@@ -395,23 +339,6 @@ const addDirectedEntries = (
|
||||
);
|
||||
};
|
||||
|
||||
const ownershipRelation = (
|
||||
relation: JavaScriptSemanticGraphRelation["relation"],
|
||||
): boolean =>
|
||||
[
|
||||
"acquires",
|
||||
"aggregates",
|
||||
"awaits",
|
||||
"chains",
|
||||
"connects-stdio",
|
||||
"creates-promise",
|
||||
"detaches-task",
|
||||
"owns",
|
||||
"releases",
|
||||
"returns-task",
|
||||
"spawns",
|
||||
].includes(relation);
|
||||
|
||||
const addEntry = (
|
||||
adjacency: Map<string, TraversalEntry[]>,
|
||||
from: string,
|
||||
@@ -585,8 +512,3 @@ const expectedMatchesFor = (
|
||||
({ kind, node_id }) => classes.has(kind) && !connected.has(node_id),
|
||||
);
|
||||
};
|
||||
|
||||
/** Return a relation's declared semantic coverage family. */
|
||||
export const javaScriptSemanticRelationFamily = (
|
||||
relation: JavaScriptSemanticGraphRelation["relation"],
|
||||
) => JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation];
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface JavaScriptSemanticQueryAssessmentInput {
|
||||
readonly frontier: readonly JavaScriptSemanticQueryFrontier[];
|
||||
readonly unknowns: readonly JavaScriptSemanticGraphUnknown[];
|
||||
readonly candidateRelations: number;
|
||||
readonly unknownsTruncated: boolean;
|
||||
}
|
||||
|
||||
/** Status, coverage, limits, and limitations derived from one traversal. */
|
||||
@@ -50,6 +51,7 @@ export const assessJavaScriptSemanticQuery = (
|
||||
max_depth: { minimum: 0, maximum: 64 },
|
||||
max_functions: { minimum: 1, maximum: 10_000 },
|
||||
max_modules: { minimum: 1, maximum: 10_000 },
|
||||
max_unknowns: { minimum: 0, maximum: 10_000 },
|
||||
page_size: { minimum: 1, maximum: 1_000 },
|
||||
},
|
||||
});
|
||||
@@ -60,7 +62,7 @@ const queryCoverage = (
|
||||
status:
|
||||
input.graph.coverage.status === "unavailable"
|
||||
? "unavailable"
|
||||
: input.frontier.length > 0
|
||||
: input.frontier.length > 0 || input.unknownsTruncated
|
||||
? "truncated"
|
||||
: input.unknowns.length > 0 ||
|
||||
input.candidateRelations > 0 ||
|
||||
@@ -74,15 +76,16 @@ const queryStatus = (
|
||||
input: JavaScriptSemanticQueryAssessmentInput,
|
||||
): JavaScriptSemanticQueryResult["status"] => {
|
||||
if (input.graph.coverage.status === "unavailable") return "unsupported";
|
||||
if (input.frontier.length > 0) return "truncated";
|
||||
if (input.unknowns.length > 0 || input.graph.coverage.status !== "complete")
|
||||
return "partial";
|
||||
if (input.frontier.length > 0 || input.unknownsTruncated) return "truncated";
|
||||
if (input.candidateRelations > 0) return "ambiguous";
|
||||
if (
|
||||
input.totalSeeds === 0 ||
|
||||
(input.hasExpectation && input.expectedMatches === 0)
|
||||
)
|
||||
return "no-match";
|
||||
return input.unknowns.length > 0 ||
|
||||
input.graph.coverage.status !== "complete"
|
||||
? "partial"
|
||||
: "no-match";
|
||||
return input.totalSeeds > 1 ? "ambiguous" : "found";
|
||||
};
|
||||
|
||||
@@ -107,6 +110,11 @@ const queryLimitations = (
|
||||
: [
|
||||
"Relevant dynamic, unsupported, incomplete, or ambiguous semantics remain unknown.",
|
||||
]),
|
||||
...(input.unknownsTruncated
|
||||
? [
|
||||
"Relevant unknown frontiers exceeded the caller limit; omitted unknowns remain unresolved.",
|
||||
]
|
||||
: []),
|
||||
...(input.candidateRelations === 0
|
||||
? []
|
||||
: [
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { compareCodePoints } from "./javascriptApplicationGraph.js";
|
||||
import type {
|
||||
JavaScriptSemanticGraph,
|
||||
JavaScriptSemanticGraphNode,
|
||||
} from "./javascriptSemanticGraph.js";
|
||||
import type { JavaScriptSemanticQueryInput } from "./javascriptSemanticQuerySchemas.js";
|
||||
|
||||
/** Caller cursor that cannot identify a page of the current semantic query. */
|
||||
export class JavaScriptSemanticQueryCursorError extends TypeError {}
|
||||
|
||||
/** Canonical JSON used by semantic query commitments and ordering. */
|
||||
export const canonicalJavaScriptSemanticQueryJson = (
|
||||
value: unknown,
|
||||
): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError(
|
||||
"JavaScript semantic query could not canonicalize data",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
|
||||
const digest = (value: unknown): string =>
|
||||
createHash("sha256")
|
||||
.update(canonicalJavaScriptSemanticQueryJson(value))
|
||||
.digest("hex");
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): string[] =>
|
||||
[...new Set(values)].sort(compareCodePoints);
|
||||
|
||||
/** Derive the stable identity for one graph-bound query without its cursor. */
|
||||
export const javaScriptSemanticQueryIdentifier = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): string => {
|
||||
const { cursor: _cursor, ...semantic } = input;
|
||||
return `jsrq_${digest({
|
||||
source_graph_id: graph.graph_id,
|
||||
...semantic,
|
||||
allowed_relations:
|
||||
semantic.allowed_relations === undefined
|
||||
? undefined
|
||||
: uniqueSorted(semantic.allowed_relations),
|
||||
expected:
|
||||
semantic.expected === null
|
||||
? null
|
||||
: {
|
||||
...semantic.expected,
|
||||
classes: uniqueSorted(semantic.expected.classes),
|
||||
},
|
||||
})}`;
|
||||
};
|
||||
|
||||
/** Commit one deterministic relation-page offset to a query identity. */
|
||||
export const createJavaScriptSemanticQueryCursor = (
|
||||
queryId: string,
|
||||
offset: number,
|
||||
): string => `jsrqc_${String(offset)}_${digest({ query_id: queryId, offset })}`;
|
||||
|
||||
/** Parse a query-bound cursor and reject stale, malformed, or foreign values. */
|
||||
export const parseJavaScriptSemanticQueryCursor = (
|
||||
cursor: string | null,
|
||||
queryId: string,
|
||||
): number => {
|
||||
if (cursor === null) return 0;
|
||||
const match = /^jsrqc_([0-9]+)_([a-f0-9]{64})$/u.exec(cursor);
|
||||
const offsetText = match?.[1];
|
||||
const commitment = match?.[2];
|
||||
if (offsetText === undefined || commitment === undefined)
|
||||
throw new JavaScriptSemanticQueryCursorError(
|
||||
"Semantic query cursor is malformed",
|
||||
);
|
||||
const offset = Number(offsetText);
|
||||
if (
|
||||
!Number.isSafeInteger(offset) ||
|
||||
offset < 0 ||
|
||||
commitment !== digest({ query_id: queryId, offset })
|
||||
)
|
||||
throw new JavaScriptSemanticQueryCursorError(
|
||||
"Semantic query cursor does not match this query",
|
||||
);
|
||||
return offset;
|
||||
};
|
||||
|
||||
/** Resolve deterministic seed candidates without applying traversal limits. */
|
||||
export const resolveJavaScriptSemanticQuerySeeds = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): string[] => {
|
||||
const fingerprintFunctions = new Set(
|
||||
input.seed.kind === "function"
|
||||
? graph.fingerprints
|
||||
.filter(
|
||||
({ fingerprint_sha256 }) =>
|
||||
input.seed.kind === "function" &&
|
||||
fingerprint_sha256 === input.seed.fingerprint_sha256,
|
||||
)
|
||||
.map(({ function_node_id }) => function_node_id)
|
||||
: [],
|
||||
);
|
||||
return graph.nodes
|
||||
.filter((node) => seedMatches(node, input, fingerprintFunctions))
|
||||
.map(({ node_id }) => node_id)
|
||||
.sort(compareCodePoints);
|
||||
};
|
||||
|
||||
const seedMatches = (
|
||||
node: JavaScriptSemanticGraphNode,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
fingerprintFunctions: ReadonlySet<string>,
|
||||
): boolean => {
|
||||
const seed = input.seed;
|
||||
if (seed.kind === "semantic-node") return node.node_id === seed.node_id;
|
||||
if (seed.kind === "application-node")
|
||||
return node.application_node_ids.includes(seed.node_id);
|
||||
if (seed.kind === "function") return fingerprintFunctions.has(node.node_id);
|
||||
if (seed.kind === "literal")
|
||||
return (
|
||||
node.kind === "literal" &&
|
||||
canonicalJavaScriptSemanticQueryJson(node.properties.value) ===
|
||||
canonicalJavaScriptSemanticQueryJson(seed.value)
|
||||
);
|
||||
if (seed.kind === "property")
|
||||
return node.kind === "property-slot" && node.properties.name === seed.name;
|
||||
if (seed.kind === "endpoint")
|
||||
return node.kind === "request" && node.properties.endpoint === seed.value;
|
||||
if (seed.kind === "event")
|
||||
return (
|
||||
["event", "listener"].includes(node.kind) &&
|
||||
node.properties.event_name === seed.name
|
||||
);
|
||||
return node.kind === "boundary" && node.properties.field === seed.field;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { JavaScriptSemanticGraphRelation } from "./javascriptSemanticGraph.js";
|
||||
|
||||
const OWNERSHIP_RELATIONS = new Set<
|
||||
JavaScriptSemanticGraphRelation["relation"]
|
||||
>([
|
||||
"acquires",
|
||||
"aggregates",
|
||||
"awaits",
|
||||
"chains",
|
||||
"connects-stdio",
|
||||
"creates-promise",
|
||||
"detaches-task",
|
||||
"owns",
|
||||
"releases",
|
||||
"returns-task",
|
||||
"spawns",
|
||||
]);
|
||||
|
||||
/** Whether one relation participates in bidirectional ownership traversal. */
|
||||
export const isJavaScriptSemanticOwnershipRelation = (
|
||||
relation: JavaScriptSemanticGraphRelation["relation"],
|
||||
): boolean => OWNERSHIP_RELATIONS.has(relation);
|
||||
@@ -11,18 +11,6 @@ import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const semanticNodeIdSchema = z.string().regex(/^jsrg_node_[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
|
||||
/** Exact accepted ranges and defaults for one semantic traversal. */
|
||||
export const JAVASCRIPT_SEMANTIC_QUERY_LIMIT_RANGES = {
|
||||
max_seed_matches: { minimum: 1, maximum: 1_000, default: 25 },
|
||||
max_nodes: { minimum: 1, maximum: 50_000, default: 2_000 },
|
||||
max_edges: { minimum: 1, maximum: 100_000, default: 4_000 },
|
||||
max_depth: { minimum: 0, maximum: 64, default: 12 },
|
||||
max_functions: { minimum: 1, maximum: 10_000, default: 500 },
|
||||
max_modules: { minimum: 1, maximum: 10_000, default: 500 },
|
||||
page_size: { minimum: 1, maximum: 1_000, default: 200 },
|
||||
} as const;
|
||||
|
||||
const literalSeedSchema = z.strictObject({
|
||||
kind: z.literal("literal"),
|
||||
@@ -77,17 +65,13 @@ export const javaScriptSemanticQueryLimitsSchema = z.strictObject({
|
||||
max_depth: z.number().int().min(0).max(64).default(12),
|
||||
max_functions: z.number().int().min(1).max(10_000).default(500),
|
||||
max_modules: z.number().int().min(1).max(10_000).default(500),
|
||||
max_unknowns: z.number().int().min(0).max(10_000).default(1_000),
|
||||
page_size: z.number().int().min(1).max(1_000).default(200),
|
||||
});
|
||||
|
||||
const sourceMapAuthoritySchema = z.discriminatedUnion("authority", [
|
||||
z.strictObject({ authority: z.literal("none") }),
|
||||
z.strictObject({
|
||||
authority: z.literal("authenticated"),
|
||||
evidence_id: evidenceIdSchema,
|
||||
source_map_sha256: digestSchema,
|
||||
}),
|
||||
]);
|
||||
const sourceMapAuthoritySchema = z.strictObject({
|
||||
authority: z.literal("none"),
|
||||
});
|
||||
|
||||
/** Parsed pure-domain query over one authenticated companion graph. */
|
||||
export const javaScriptSemanticQueryInputSchema = z.strictObject({
|
||||
@@ -96,7 +80,6 @@ export const javaScriptSemanticQueryInputSchema = z.strictObject({
|
||||
"backward-provenance",
|
||||
"forward-influence",
|
||||
"callers",
|
||||
"consumers",
|
||||
"ownership",
|
||||
]),
|
||||
allowed_relations: z
|
||||
@@ -120,6 +103,7 @@ export const javaScriptSemanticQueryInputSchema = z.strictObject({
|
||||
max_depth: 12,
|
||||
max_functions: 500,
|
||||
max_modules: 500,
|
||||
max_unknowns: 1_000,
|
||||
page_size: 200,
|
||||
}),
|
||||
cursor: z
|
||||
@@ -170,6 +154,7 @@ export const javaScriptSemanticQueryResultSchema = z.strictObject({
|
||||
traversed_functions: z.number().int().min(0),
|
||||
traversed_modules: z.number().int().min(0),
|
||||
relevant_unknowns: z.number().int().min(0),
|
||||
retained_unknowns: z.number().int().min(0).max(10_000),
|
||||
}),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete", "partial", "truncated", "unavailable"]),
|
||||
@@ -209,6 +194,10 @@ export const javaScriptSemanticQueryResultSchema = z.strictObject({
|
||||
minimum: z.literal(1),
|
||||
maximum: z.literal(10_000),
|
||||
}),
|
||||
max_unknowns: z.strictObject({
|
||||
minimum: z.literal(0),
|
||||
maximum: z.literal(10_000),
|
||||
}),
|
||||
page_size: z.strictObject({
|
||||
minimum: z.literal(1),
|
||||
maximum: z.literal(1_000),
|
||||
|
||||
@@ -60,6 +60,10 @@ export const collectSemanticReturns = (
|
||||
expression.location,
|
||||
),
|
||||
location: expression.location,
|
||||
identityReferenceLocation:
|
||||
expression.node !== null && t.isIdentifier(expression.node)
|
||||
? range(expression.node)
|
||||
: null,
|
||||
value:
|
||||
expression.node === null
|
||||
? { status: "unknown", reason: "Return has no value." }
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
import {
|
||||
javaScriptSemanticQueryInputSchema,
|
||||
javaScriptSemanticQueryResultSchema,
|
||||
} from "./javascriptSemanticQuerySchemas.js";
|
||||
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
|
||||
/** Authenticated application Evidence plus one bounded semantic query. */
|
||||
export const traceJavaScriptSemanticsInputSchema = z.strictObject({
|
||||
application: evidenceSchema,
|
||||
query: javaScriptSemanticQueryInputSchema,
|
||||
});
|
||||
|
||||
/** Evidence-linked semantic query result shared by CLI and MCP. */
|
||||
export const javaScriptSemanticTraceResultSchema =
|
||||
javaScriptSemanticQueryResultSchema.extend({
|
||||
source_evidence_id: evidenceIdSchema,
|
||||
evidence_links: z.array(evidenceIdSchema).length(1),
|
||||
});
|
||||
|
||||
/** Validated Evidence-linked semantic trace result. */
|
||||
export type JavaScriptSemanticTraceResult = z.infer<
|
||||
typeof javaScriptSemanticTraceResultSchema
|
||||
>;
|
||||
Reference in New Issue
Block a user