feat(javascript): report observed export property presence (#1160)

* feat(javascript): report observed export property presence

Extend compare_javascript_export_shapes so each retained return variant
lists observed property names and each change reports presence independently
of value resolution. Complete parent coverage classifies one-sided names as
added or removed even when static values stay unknown.

Fixes #725

* test(javascript): match unknown export-shape values by availability

Nested availability objects include a reason when values stay unresolved.
Assert availability through objectContaining so presence-only added and
removed rows still verify unknown values.

* fix(javascript): preserve uncertain export property presence and locations

* fix(javascript): normalize presence and preserve local property coverage

* fix(javascript): require present discriminants for return pairing

* fix(javascript): normalize retained shapes before comparison

* refactor(javascript): share return projection with executable examples

* fix(javascript): localize uncertainty for missing mutated slots

* fix(javascript): bind advertised export examples to exact artifacts

* fix(javascript): keep uncertain property flow as candidates

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-09 18:30:31 +08:00
committed by GitHub
co-authored by morluto
parent 04aef6df33
commit 45e3edc17f
25 changed files with 1552 additions and 113 deletions
@@ -0,0 +1,111 @@
import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js";
import {
partialApplicationCoverage,
truncatedApplicationCoverage,
type ApplicationCoverage,
} from "./javascriptApplicationEvidenceSchemas.js";
import type {
JavaScriptSemanticCallable,
JavaScriptSemanticModuleLink,
JavaScriptSemanticIr,
} from "./javascriptSemanticIr.js";
import { flattenSemanticReturnValue } from "./javascriptSemanticReturns.js";
import type { JavaScriptSourceRange } from "./javascriptStaticAnalysisTypes.js";
/** Return-shape facts and coverage inferred for one exported callable. */
export interface JavaScriptReturnShapeProjection {
readonly properties: ReturnType<typeof jsonObjectSchema.parse>;
readonly range: JavaScriptSourceRange;
readonly coverage: ApplicationCoverage;
readonly limitations: readonly string[];
}
/** Project one exact export/callable link into inert return-shape observations. */
export const projectJavaScriptExportReturnShapes = (input: {
readonly ir: Pick<JavaScriptSemanticIr, "callables" | "limitations">;
readonly link: JavaScriptSemanticModuleLink;
readonly modulePath: string;
readonly baseCoverage: ApplicationCoverage;
}): JavaScriptReturnShapeProjection | null => {
if (input.link.callableId === null || input.link.exportedName === null)
return null;
const callable = input.ir.callables.find(
({ callableId }) => callableId === input.link.callableId,
);
if (callable === undefined) return null;
const projection = projectReturnSites(callable);
const projectionOmitted =
projection.omittedSites +
projection.omittedFields +
projection.omittedCoverage;
const semanticOmitted = callable.returnCoverage.omittedCount;
const complete =
input.baseCoverage.status === "complete" &&
callable.returnCoverage.status === "complete" &&
projectionOmitted === 0;
const limits = input.baseCoverage.limits;
const omitted =
semanticOmitted === null ? null : semanticOmitted + projectionOmitted;
const coverage = complete
? input.baseCoverage
: projectionOmitted > 0
? truncatedApplicationCoverage(limits, omitted)
: partialApplicationCoverage(limits, omitted);
const limitations = [
...input.ir.limitations,
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
...(callable.returnSites.length === 0
? [
"No direct return value was retained; runtime return behavior remains unknown.",
]
: []),
];
return {
properties: jsonObjectSchema.parse({
semantic_role: "export-return-shapes",
module_path: input.modulePath,
exported_name: input.link.exportedName,
callable_id: callable.callableId,
callable_kind: callable.kind,
static_return_shapes: projection.shapes,
return_shape_coverage: {
status: callable.returnCoverage.status,
retained_return_sites: projection.shapes.length,
omitted_return_sites:
semanticOmitted === null
? null
: semanticOmitted + projection.omittedSites,
omitted_fields: projection.omittedFields,
omitted_property_coverage: projection.omittedCoverage,
projection_complete: projectionOmitted === 0,
},
}),
range: callable.location,
coverage,
limitations,
};
};
const projectReturnSites = (callable: JavaScriptSemanticCallable) => {
const retainedSites = callable.returnSites;
const shapes = retainedSites.map((site) => {
const flattened = flattenSemanticReturnValue(site.value);
const fields = flattened.fields.map((field) => ({
...field,
value: jsonValueSchema.parse(field.value),
}));
const propertyCoverage = flattened.propertyCoverage;
return {
source_range: site.location,
value_status: site.value.status,
fields,
property_coverage: propertyCoverage,
};
});
return {
shapes,
omittedSites: 0,
omittedFields: 0,
omittedCoverage: 0,
};
};
@@ -17,6 +17,7 @@ import {
} from "./javascriptExportShapeSelection.js";
import {
buildJavaScriptExportShapeChanges,
buildJavaScriptExportShapeInventories,
hasPartialJavaScriptExportPropertyCoverage,
pairJavaScriptExportShapeVariants,
type JavaScriptExportShapePairing,
@@ -56,6 +57,11 @@ export const compareJavaScriptExportShapes = (
);
const changes = allChanges;
const omittedChanges = 0;
const propertyInventories = buildJavaScriptExportShapeInventories({
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
});
const coverage = comparisonCoverage({
input,
left,
@@ -70,6 +76,7 @@ export const compareJavaScriptExportShapes = (
const semantic = {
left: left.selection,
right: right.selection,
property_inventories: propertyInventories,
summary: summarize(allChanges),
changes,
coverage,
@@ -2,7 +2,12 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
/** Canonically encode one export-shape comparison value. */
/**
* Canonically encode one export-shape comparison value.
*
* Comparison identifiers hash the full result semantics, including each
* change's presence object and the per-variant property inventories.
*/
export const canonicalExportShapeValue = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
@@ -1,6 +1,9 @@
import { expect, it } from "vitest";
import { projectedExportReturnShapesSchema } from "./javascriptExportShapeComparisonSchemas.js";
import {
javaScriptExportShapeComparisonChangeSchema,
projectedExportReturnShapesSchema,
} from "./javascriptExportShapeComparisonSchemas.js";
const projectionWithField = (field: unknown) => ({
semantic_role: "export-return-shapes",
@@ -29,6 +32,40 @@ const projectionWithField = (field: unknown) => ({
},
});
it("rejects a comparison change object missing presence", () => {
const digest = "a".repeat(64);
const change = {
change_id: `jesc_change_${digest}`,
status: "added",
path: "/total",
discriminant: { path: "/kind", value: "results" },
left: { availability: "absent" },
right: {
availability: "unknown",
reason: "Static field value is unknown.",
},
left_source_range: {
start: { line: 4, column: 9 },
end: { line: 4, column: 48 },
},
right_source_range: {
start: { line: 4, column: 9 },
end: { line: 4, column: 62 },
},
evidence_links: [`ev_${digest}`, `ev_${"b".repeat(64)}`],
limitations: [],
};
expect(
javaScriptExportShapeComparisonChangeSchema.safeParse(change).success,
).toBe(false);
expect(
javaScriptExportShapeComparisonChangeSchema.safeParse({
...change,
presence: { left: "absent", right: "present" },
}).success,
).toBe(true);
});
it("parses projected fields into literal, union, or unknown values", () => {
expect(
projectedExportReturnShapesSchema.safeParse(
@@ -73,7 +73,10 @@ export const compareJavaScriptExportShapesInputSchema = z
});
});
const projectedReturnFieldShape = { path: jsonPointerSchema };
const projectedReturnFieldShape = {
path: jsonPointerSchema,
presence: z.enum(["present", "absent", "unknown-coverage"]).optional(),
};
const projectedReturnFieldSchema = z.discriminatedUnion("state", [
z.strictObject({
...projectedReturnFieldShape,
@@ -229,11 +232,21 @@ const discriminantSchema = z.strictObject({
value: semanticPrimitiveSchema,
});
const propertyPresenceSchema = z.enum([
"present",
"absent",
"unknown-coverage",
]);
const comparisonChangeSchema = z.strictObject({
change_id: prefixedDigestSchema("jesc_change"),
status: z.enum(["added", "removed", "changed", "unknown"]),
path: jsonPointerSchema,
discriminant: discriminantSchema.nullable(),
presence: z.strictObject({
left: propertyPresenceSchema,
right: propertyPresenceSchema,
}),
left: valueAvailabilitySchema,
right: valueAvailabilitySchema,
left_source_range: sourceRangeSchema.nullable(),
@@ -242,11 +255,31 @@ const comparisonChangeSchema = z.strictObject({
limitations: z.array(textSchema),
});
/** One change row; presence is required even when values stay unknown. */
export const javaScriptExportShapeComparisonChangeSchema =
comparisonChangeSchema;
const inventoryPropertyCoverageSchema = z.strictObject({
path: jsonPointerSchema,
status: z.enum(["complete", "partial"]),
});
const propertyInventorySchema = z.strictObject({
side: z.enum(["left", "right"]),
variant_index: z.number().int().nonnegative(),
discriminant: discriminantSchema.nullable(),
paired: z.boolean(),
source_range: sourceRangeSchema,
properties: z.array(jsonPointerSchema),
property_coverage: z.array(inventoryPropertyCoverageSchema),
});
/** Static export-return comparison with explicit unknown semantics. */
export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
comparison_id: prefixedDigestSchema("jesc"),
left: selectorResultSchema,
right: selectorResultSchema,
property_inventories: z.array(propertyInventorySchema),
summary: z.strictObject({
added: z.number().int().min(0),
removed: z.number().int().min(0),
@@ -295,3 +328,6 @@ export type JavaScriptExportShapeComparisonResult = z.output<
export type JavaScriptExportShapeComparisonChange = z.output<
typeof comparisonChangeSchema
>;
export type JavaScriptExportShapePropertyInventory = z.output<
typeof propertyInventorySchema
>;
@@ -10,6 +10,9 @@ import {
import { compareCodePoints } from "../canonicalOrdering.js";
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
type Field = Shape["fields"][number];
type NormalizedField = Field & { presence: NonNullable<Field["presence"]> };
type NormalizedShape = Omit<Shape, "fields"> & { fields: NormalizedField[] };
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
type SelectorBase = Omit<SelectorResult, "status" | "selected_node_id">;
type ReturnShapeSelection =
@@ -55,7 +58,7 @@ export type SelectedJavaScriptExport =
/** Complete return-shape inventory retained from an authenticated projection. */
export interface RetainedJavaScriptExportShapes {
readonly shapes: readonly Shape[];
readonly shapes: readonly NormalizedShape[];
readonly omitted: number;
}
@@ -126,11 +129,22 @@ export const selectJavaScriptExport = (
};
};
/** Retain every projected return variant. */
/** Retain every variant and normalize legacy presence on comparison-owned copies. */
export const retainJavaScriptExportShapes = (
selection: SelectedJavaScriptExport,
): RetainedJavaScriptExportShapes => {
const shapes = selection.projection?.static_return_shapes ?? [];
const shapes = (
selection.projection?.static_return_shapes ?? []
).map<NormalizedShape>((shape) => ({
...shape,
fields: shape.fields.map<NormalizedField>((field) => ({
...field,
// Legacy unknown fields did not distinguish values from uncertain slots.
presence:
field.presence ??
(field.state === "unknown" ? "unknown-coverage" : "present"),
})),
}));
return { shapes, omitted: 0 };
};
@@ -5,19 +5,28 @@ import {
import type {
JavaScriptExportShapeComparisonChange,
JavaScriptExportShapeComparisonResult,
ProjectedExportReturnShapes,
JavaScriptExportShapePropertyInventory,
} from "./javascriptExportShapeComparisonSchemas.js";
import { compareCodePoints, uniqueSorted } from "../canonicalOrdering.js";
import type { SelectedJavaScriptExport } from "./javascriptExportShapeSelection.js";
import type {
SelectedJavaScriptExport,
RetainedJavaScriptExportShapes,
} from "./javascriptExportShapeSelection.js";
type Primitive = string | number | boolean | null;
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
type Shape = RetainedJavaScriptExportShapes["shapes"][number];
type Field = Shape["fields"][number];
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
type ValueAvailability = JavaScriptExportShapeComparisonChange["left"];
type PropertyPresence =
JavaScriptExportShapeComparisonChange["presence"]["left"];
type Discriminant = NonNullable<
JavaScriptExportShapeComparisonChange["discriminant"]
>;
const UNKNOWN_COVERAGE_PRESENCE = {
left: "unknown-coverage",
right: "unknown-coverage",
} as const satisfies JavaScriptExportShapeComparisonChange["presence"];
interface VariantPair {
readonly leftIndex: number;
@@ -112,12 +121,62 @@ export const buildJavaScriptExportShapeChanges = (
return [...paired, ...unpairedLeft, ...unpairedRight];
};
/** List observed property names per retained variant, including unknown values. */
export const buildJavaScriptExportShapeInventories = (input: {
readonly pairing: JavaScriptExportShapePairing;
readonly leftShapes: readonly Shape[];
readonly rightShapes: readonly Shape[];
}): JavaScriptExportShapePropertyInventory[] => {
const leftPairs = new Map(
input.pairing.pairs.map((pair) => [pair.leftIndex, pair]),
);
const rightPairs = new Map(
input.pairing.pairs.map((pair) => [pair.rightIndex, pair]),
);
return [
...input.leftShapes.map((shape, index) =>
inventoryFor("left", index, shape, leftPairs.get(index)),
),
...input.rightShapes.map((shape, index) =>
inventoryFor("right", index, shape, rightPairs.get(index)),
),
];
};
const inventoryFor = (
side: JavaScriptExportShapePropertyInventory["side"],
variantIndex: number,
shape: Shape,
pair: VariantPair | undefined,
): JavaScriptExportShapePropertyInventory => ({
side,
variant_index: variantIndex,
discriminant: pair?.discriminant ?? null,
paired: pair !== undefined,
source_range: shape.source_range,
properties: uniqueSorted([
...shape.fields
.filter((field) => fieldPresence(shape, field, field.path) === "present")
.map(({ path }) => path),
...shape.property_coverage.map(({ path }) => path),
]).filter((path) => path !== ""),
property_coverage: shape.property_coverage.map(({ path, status }) => ({
path,
status,
})),
});
/** Report whether any retained shape lacks complete property coverage. */
export const hasPartialJavaScriptExportPropertyCoverage = (
shapes: readonly Shape[],
): boolean =>
shapes.some((shape) =>
shape.property_coverage.some(({ status }) => status === "partial"),
shapes.some(
(shape) =>
shape.property_coverage.some(({ status }) => status === "partial") ||
shape.fields.some(
(field) =>
fieldPresence(shape, field, field.path) === "unknown-coverage",
),
);
interface DiscriminantOccurrence {
@@ -131,6 +190,7 @@ const discriminantOccurrences = (
const output = new Map<string, DiscriminantOccurrence>();
shapes.forEach((shape, index) => {
for (const field of shape.fields) {
if (fieldPresence(shape, field, field.path) !== "present") continue;
const value = literalValue(field);
if (!value.found) continue;
const discriminant = { path: field.path, value: value.value };
@@ -204,6 +264,7 @@ const selectionUnknownChange = (
status: "unknown",
path: "",
discriminant: null,
presence: UNKNOWN_COVERAGE_PRESENCE,
left: selectionAvailability(input.leftSelection.selection, "left"),
right: selectionAvailability(input.rightSelection.selection, "right"),
left_source_range: null,
@@ -221,6 +282,7 @@ const emptyShapeUnknownChange = (
status: "unknown",
path: "",
discriminant: null,
presence: UNKNOWN_COVERAGE_PRESENCE,
left: emptyShapeAvailability(input.leftShapes, "left"),
right: emptyShapeAvailability(input.rightShapes, "right"),
left_source_range: null,
@@ -261,6 +323,10 @@ const diffPair = (
status,
path,
discriminant,
presence: {
left: fieldPresence(left, leftField, path),
right: fieldPresence(right, rightField, path),
},
left: fieldAvailability(leftField),
right: fieldAvailability(rightField),
left_source_range: left.source_range,
@@ -288,6 +354,7 @@ const fieldAtPath = (
return undefined;
return {
path,
presence: "present",
state: "unknown",
value: null,
reason:
@@ -312,24 +379,40 @@ const fieldChangeStatus = ({
}: FieldChangeInput):
| JavaScriptExportShapeComparisonChange["status"]
| null => {
if (leftField !== undefined && rightField !== undefined) {
if (
canonicalExportShapeValue(leftField) ===
const leftPresence = fieldPresence(leftShape, leftField, path);
const rightPresence = fieldPresence(rightShape, rightField, path);
if (
leftField !== undefined &&
rightField !== undefined &&
canonicalExportShapeValue(leftField) ===
canonicalExportShapeValue(rightField)
)
return null;
)
return null;
if (leftPresence === "absent" && rightPresence === "absent") return null;
if (
leftPresence === "unknown-coverage" ||
rightPresence === "unknown-coverage"
)
return "unknown";
if (leftPresence === "absent") return "added";
if (rightPresence === "absent") return "removed";
if (leftField !== undefined && rightField !== undefined) {
return leftField.state === "unknown" || rightField.state === "unknown"
? "unknown"
: "changed";
}
const present = leftField ?? rightField;
if (present === undefined) return null;
const parent = parentPointer(path);
const parentsComplete =
propertyCoverageComplete(leftShape, parent) &&
propertyCoverageComplete(rightShape, parent);
if (present.state === "unknown" || !parentsComplete) return "unknown";
return leftField === undefined ? "added" : "removed";
return null;
};
const fieldPresence = (
shape: Shape,
field: Field | undefined,
path: string,
): PropertyPresence => {
if (field !== undefined) return field.presence;
return propertyCoverageComplete(shape, parentPointer(path))
? "absent"
: "unknown-coverage";
};
const propertyCoverageComplete = (shape: Shape, path: string | null): boolean =>
@@ -345,7 +428,8 @@ const parentPointer = (path: string): string | null => {
};
const fieldAvailability = (field: Field | undefined): ValueAvailability => {
if (field === undefined) return { availability: "absent" };
if (field === undefined || field.presence === "absent")
return { availability: "absent" };
if (field.state === "unknown")
return {
availability: "unknown",
@@ -390,6 +474,7 @@ const unpairedChange = (
status: "unknown",
path: "",
discriminant: null,
presence: UNKNOWN_COVERAGE_PRESENCE,
left: {
availability: "unknown",
reason:
@@ -63,9 +63,17 @@ it("invalidates a deep mutation while retaining unrelated literal properties", (
status: "object",
properties: [
{ name: "untouched", value: { status: "literal", value: "retained" } },
{
name: "next",
presence: "unknown-coverage",
value: {
status: "unknown",
reason: "This property may have been mutated.",
},
},
],
unknownProperties: true,
omittedProperties: null,
unknownProperties: false,
omittedProperties: 0,
});
expect(onlyBinding(ir, "value").value).toEqual({
status: "literal",
@@ -20,23 +20,16 @@ export const invalidateSemanticMutationPath = (
property.name === name
? {
...property,
...(remaining.length === 0
? { presence: "unknown-coverage" as const }
: {}),
value: invalidateSemanticMutationPath(property.value, remaining),
}
: property,
);
return value.unknownProperties || !observed
? {
status: "object",
properties,
unknownProperties: true,
omittedProperties: observed ? value.omittedProperties : null,
}
: {
status: "object",
properties,
unknownProperties: false,
omittedProperties: 0,
};
if (!observed)
properties.push({ name, value: unknown, presence: "unknown-coverage" });
return { ...value, properties };
}
if (value.status === "array") {
const index = typeof key === "number" ? key : Number(key);
@@ -46,20 +39,18 @@ export const invalidateSemanticMutationPath = (
String(index) !== String(key)
)
return unknown;
const observed = value.items[index] !== undefined;
const items = value.items.map((item, position) =>
position === index
? invalidateSemanticMutationPath(item, remaining)
: item,
);
return value.unknownItems || !observed
? {
status: "array",
items,
unknownItems: true,
omittedItems: observed ? value.omittedItems : null,
}
: { status: "array", items, unknownItems: false, omittedItems: 0 };
const itemPresence = {
...value.itemPresence,
...(remaining.length === 0 || value.items[index] === undefined
? { [index]: "unknown-coverage" as const }
: {}),
};
return { ...value, items, itemPresence };
}
return unknown;
};
@@ -211,14 +211,33 @@ const flattenValue = (
path: string,
fields: ProjectedReturnField[],
coverage: ProjectedPropertyCoverage[],
presence: "present" | "absent" | "unknown-coverage" = "present",
): void => {
if (presence !== "present") {
fields.push({
path,
presence,
state: "unknown",
value: null,
reason:
"reason" in value ? value.reason : "Property presence is uncertain.",
});
return;
}
if (value.status === "literal") {
fields.push({ path, state: "literal", value: value.value, reason: null });
fields.push({
path,
presence,
state: "literal",
value: value.value,
reason: null,
});
return;
}
if (value.status === "union") {
fields.push({
path,
presence,
state: "union",
value: [...value.values],
reason: null,
@@ -237,6 +256,7 @@ const flattenValue = (
`${path}/${escapePointer(property.name)}`,
fields,
coverage,
property.presence ?? "present",
);
return;
}
@@ -247,11 +267,30 @@ const flattenValue = (
: { path, status: "complete", omitted: 0 },
);
value.items.forEach((item, index) =>
flattenValue(item, `${path}/${String(index)}`, fields, coverage),
flattenValue(
item,
`${path}/${String(index)}`,
fields,
coverage,
value.itemPresence?.[index] ?? "present",
),
);
// Sparse mutation metadata retains uncertain slots without expanding arrays.
for (const [index, itemPresence] of Object.entries(
value.itemPresence ?? {},
)) {
if (Number(index) < value.items.length) continue;
flattenValue(value, `${path}/${index}`, fields, coverage, itemPresence);
}
return;
}
fields.push({ path, state: "unknown", value: null, reason: value.reason });
fields.push({
path,
presence,
state: "unknown",
value: null,
reason: value.reason,
});
};
const escapePointer = (value: string): string =>
@@ -24,6 +24,9 @@ type JavaScriptSemanticObjectValue = {
type JavaScriptSemanticArrayValue = {
readonly status: "array";
readonly items: readonly JavaScriptSemanticValue[];
readonly itemPresence?: Readonly<
Record<number, "absent" | "unknown-coverage">
>;
} & (
| {
readonly unknownItems: false;
@@ -57,4 +60,5 @@ export type JavaScriptSemanticValue =
export interface JavaScriptSemanticProperty {
readonly name: string;
readonly value: JavaScriptSemanticValue;
readonly presence?: "unknown-coverage";
}
@@ -299,6 +299,7 @@ const evaluateArray = (
context: EvaluationContext,
): JavaScriptSemanticValue => {
const items: JavaScriptSemanticValue[] = [];
const itemPresence: Record<number, "absent"> = {};
let unknownItems = false;
let omittedItems: number | null = 0;
for (const element of node.elements) {
@@ -309,8 +310,7 @@ const evaluateArray = (
break;
}
if (element === null) {
unknownItems = true;
if (omittedItems !== null) omittedItems += 1;
itemPresence[items.length] = "absent";
items.push({
status: "unknown",
reason: "Array hole has no primitive value.",
@@ -320,8 +320,14 @@ const evaluateArray = (
items.push(evaluateExpression(element, nestedContext(context)));
}
return unknownItems
? { status: "array", items, unknownItems: true, omittedItems }
: { status: "array", items, unknownItems: false, omittedItems: 0 };
? { status: "array", items, itemPresence, unknownItems: true, omittedItems }
: {
status: "array",
items,
itemPresence,
unknownItems: false,
omittedItems: 0,
};
};
const evaluateMember = (