fix(javascript): preserve uncertainty after references escape to calls (#1292)

* fix(javascript): preserve uncertainty after references escape to calls

* fix(javascript): track iterator root escapes and preserve static captures

* fix(javascript): scope comparison unknowns to their evidence

* fix(javascript): track parameter origins at function body entry

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
You Wish
2026-10-10 06:53:42 +08:00
committed by GitHub
co-authored by morluto
parent d0e606930a
commit 355a292198
17 changed files with 2574 additions and 220 deletions
@@ -457,7 +457,205 @@ describe("application workflow CLI input", () => {
});
});
describe("application workflow CLI copy boundaries", () => {
it("compares source values excluded from escaped rest and spread copies", async () => {
const root = await createTestTempDirectory("rea-copy-boundary-cli-");
temporary.push(root);
const sources = [
`export default function make() {
function mutate(value) { value.changed = true; }
const objectRest = { only: { value: "TOKEN" } };
const { only, ...restObject } = objectRest;
mutate(restObject);
const arrayRest = [{ value: "TOKEN" }];
const [head, ...restArray] = arrayRest;
mutate(restArray);
const objectSpread = { child: { value: "TOKEN" } };
const spreadObject = { ...objectSpread, child: {} };
mutate(spreadObject.child);
const arraySpread = [{ value: "TOKEN" }];
const spreadArray = [{}, ...arraySpread];
mutate(spreadArray[0]);
return {
kind: "copy-boundary",
objectRest: objectRest.only.value,
arrayRest: arrayRest[0].value,
objectSpread: objectSpread.child.value,
arraySpread: arraySpread[0].value,
};
}`,
`export default function make() {
return {
kind: "copy-boundary",
objectRest: "UPDATED", arrayRest: "UPDATED",
objectSpread: "UPDATED", arraySpread: "UPDATED",
};
}`,
];
const [left, right] = await analyzeCliSources(root, sources);
const inputPath = join(root, "comparison.json");
await writeFile(
inputPath,
JSON.stringify({
left,
right,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
}),
);
const compared = await runCli([
"compare-javascript-export-shapes",
inputPath,
"--json",
]);
expect(compared).toMatchObject({
normalized_result: {
summary: { added: 0, removed: 0, changed: 4, unknown: 0 },
coverage: { status: "complete-within-inputs" },
changes: expect.arrayContaining(
["/arrayRest", "/arraySpread", "/objectRest", "/objectSpread"].map(
(path) =>
expect.objectContaining({
status: "changed",
path,
left: { availability: "literal", value: "TOKEN" },
right: { availability: "literal", value: "UPDATED" },
}),
),
),
},
});
}, 20_000);
});
describe("application workflow CLI and MCP capture lifetimes", () => {
it("compares captured primitives and source values after aliases are replaced", async () => {
const root = await createTestTempDirectory("rea-capture-lifetime-cli-");
temporary.push(root);
const fields = [
"rebound",
"rest",
"snapshot",
"destructured",
"objectSnapshot",
"arraySnapshot",
];
const sources = [
`export default function make() {
function mutate(value) { value.value = "MUTATED"; }
const original = {value: "TOKEN"};
let alias = original;
alias = {};
mutate(alias);
const child = {value: "TOKEN"};
let {...rest} = {child};
rest = {child: {}};
rest.child.value = "MUTATED";
const source = {value: "TOKEN"};
const snapshot = source.value;
const {value: destructured} = source;
const objectSnapshot = {value: source.value};
const arraySnapshot = [source.value];
mutate(source);
return {
kind: "capture-boundary",
rebound: original.value, rest: child.value,
snapshot, destructured,
objectSnapshot: objectSnapshot.value, arraySnapshot: arraySnapshot[0],
};
}`,
`export default function make() { return ${JSON.stringify({
kind: "capture-boundary",
...Object.fromEntries(fields.map((field) => [field, "UPDATED"])),
})}; }`,
];
const [left, right] = await analyzeCliSources(root, sources);
// Execute the authored fixtures independently of static analysis.
for (const [index, value] of ["TOKEN", "UPDATED"].entries()) {
const { stdout } = await execute(process.execPath, [
"--input-type=module",
"--eval",
"const module = await import(process.argv[1]); console.log(JSON.stringify(module.default()));",
join(root, String(index), "parser.mjs"),
]);
expect(JSON.parse(stdout)).toEqual({
kind: "capture-boundary",
...Object.fromEntries(fields.map((field) => [field, value])),
});
}
const input = {
left,
right,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
};
const inputPath = join(root, "comparison.json");
await writeFile(inputPath, JSON.stringify(input));
const expected = {
normalized_result: {
summary: { added: 0, removed: 0, changed: 6, unknown: 0 },
coverage: { status: "complete-within-inputs" },
changes: expect.arrayContaining(
fields.map((field) =>
expect.objectContaining({
path: `/${field}`,
status: "changed",
left: { availability: "literal", value: "TOKEN" },
right: { availability: "literal", value: "UPDATED" },
}),
),
),
},
};
expect(
await runCli(["compare-javascript-export-shapes", inputPath, "--json"]),
).toMatchObject(expected);
expect(await compareThroughStdioMcp(input)).toMatchObject(expected);
}, 20_000);
});
describe("application workflow CLI export Evidence", () => {
it("preserves uncertainty after a helper can mutate an awaited return object", async () => {
const root = await createTestTempDirectory("rea-awaited-export-shape-cli-");
temporary.push(root);
const sources = [
`export default async function make() {
const result = { kind: "record" };
function mutate(value) { value.extra = 1; }
mutate(await result);
return result;
}`,
'export default async function make() { return { kind: "record", extra: 1 }; }',
];
const [left, right] = await analyzeCliSources(root, sources);
const compared = await runCli([
"compare-javascript-export-shapes",
JSON.stringify({
left,
right,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
}),
"--json",
]);
expect(compared).toMatchObject({
operation: "compare_javascript_export_shapes",
normalized_result: {
summary: { added: 0, removed: 0, changed: 0 },
coverage: { status: "partial" },
changes: expect.arrayContaining([
expect.objectContaining({ status: "unknown" }),
]),
},
});
}, 20_000);
it("compares exact export shapes from file-backed Evidence", async () => {
const root = await createTestTempDirectory("rea-export-shape-cli-");
temporary.push(root);
@@ -647,6 +845,54 @@ describe("application workflow CLI validation", () => {
}, 20_000);
});
const compareThroughStdioMcp = async (
input: Record<string, unknown>,
): Promise<unknown> => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
const client = new Client({
name: "javascript-capture-parity",
version: "1",
});
try {
await client.connect(transport);
const response = await client.callTool({
name: "compare_javascript_export_shapes",
arguments: input,
});
expect(response.isError).not.toBe(true);
return response.structuredContent;
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
};
const analyzeCliSources = (
root: string,
sources: readonly string[],
): Promise<unknown[]> =>
Promise.all(
sources.map(async (source, index) => {
const applicationRoot = join(root, String(index));
await mkdir(applicationRoot);
await writeFile(join(applicationRoot, "parser.mjs"), source);
return runCli([
"analyze-javascript-application",
applicationRoot,
"--json",
]);
}),
);
const runCli = async (
arguments_: readonly string[],
environment: Readonly<Record<string, string>> = {},
@@ -348,6 +348,64 @@ describe("JavaScript export return-shape uncertain presence", () => {
});
describe("JavaScript export matching uncertain projections", () => {
it.each([
["Object.assign", "Object.assign(result, { extra: 1 });"],
["local helper", "mutate(result);"],
["alias", "const alias = result; mutate(alias);"],
["destructuring", "const { value } = { value: result }; mutate(value);"],
["shared wrapper", "mutate({ value: result });"],
["spread arguments", "mutate(...[result]);"],
["optional call", "mutate?.(result);"],
["constructor", "new Mutator(result);"],
["tagged template", "tag`${result}`;"],
])(
"does not infer an addition after %s can mutate the return value",
async (_description, invocation) => {
const graphs = await analyzeSources({
left: `
function mutate(value) { (value.value ?? value).extra = 1; }
function Mutator(value) { value.extra = 1; }
function tag(_strings, value) { value.extra = 1; }
export default function make() {
const result = { kind: "record" };
${invocation}
return result;
}
`,
right: 'export default () => ({ kind: "record", extra: 1 });',
});
const result = compare(...graphs);
expect(result.summary).toMatchObject({
added: 0,
removed: 0,
changed: 0,
});
expect(result.coverage.status).toBe("partial");
expect(result.changes).toEqual(
expect.arrayContaining([
expect.objectContaining({ status: "unknown" }),
]),
);
},
);
it("keeps sibling properties known when a method can mutate its receiver", async () => {
const graphs = await analyzeSources({
left: `export default function make() {
const result = { kind: "record", tokens: [] };
result.tokens.push({ extra: 1 });
return result;
}`,
right:
'export default () => ({ kind: "record", tokens: [{ extra: 1 }] });',
});
const result = compare(...graphs);
expect(result.summary).toMatchObject({ added: 0, removed: 0, changed: 0 });
expect(result.coverage.status).toBe("partial");
for (const inventory of result.property_inventories)
expect(inventory.properties).toContain("/kind");
});
it.each(["delete result.count;", "result.count = query();"])(
"omits matching uncertain projections after %s",
async (mutation) => {
@@ -12,6 +12,7 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../../src/contracts/applicationToolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "../../../src/contracts/javascript/javascriptExportShapeComparisonExample.js";
it("executes the advertised export presence example with matching analyzed Evidence", async () => {
@@ -253,7 +254,161 @@ describe("application workflow MCP parity", () => {
});
});
describe("repeated partial export comparisons", () => {
it.each(["inline", "retained"] as const)(
"retains distinct partial comparisons and idempotent concurrent repeats with %s Evidence",
async (mode) => {
const pairs = await Promise.all(
Array.from({ length: 4 }, async (_, index) => {
const source = `export default function make() {
const result = { kind: "record-${index}", count: 1 };
delete result.count;
return result;
}
export { make as named };`;
const [left, right] = await Promise.all([
analyzeSourceEvidence(source),
analyzeSourceEvidence(source),
]);
return { left, right };
}),
);
const { client, session, close } = await createApplicationMcpHarness();
onTestFinished(close);
if (mode === "retained")
for (const { left, right } of pairs)
for (const evidence of [left, right])
expect(session.recordEvidence(evidence).ok).toBe(true);
const compare = async (
pair: (typeof pairs)[number],
exportName = "default",
) => {
const response = await client.callTool({
name: "compare_javascript_export_shapes",
arguments: {
left:
mode === "inline"
? pair.left
: {
kind: "retained-evidence",
evidence_id: pair.left.evidence_id,
},
right:
mode === "inline"
? pair.right
: {
kind: "retained-evidence",
evidence_id: pair.right.evidence_id,
},
left_module_path: "parser.mjs",
left_export_name: exportName,
right_module_path: "parser.mjs",
right_export_name: exportName,
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = parseEvidence(response.structuredContent);
expect(evidence.normalized_result).toMatchObject({
changes: [],
coverage: { status: "partial" },
});
return evidence.evidence_id;
};
const [firstPair, secondPair, ...remaining] = pairs;
if (firstPair === undefined || secondPair === undefined)
throw new Error("Expected distinct comparison fixtures");
const firstId = await compare(firstPair);
const firstUnknowns = session.listUnknowns({
domain: "javascript-export-shape",
});
expect(firstUnknowns).toHaveLength(1);
const secondId = await compare(secondPair);
expect(secondId).not.toBe(firstId);
const selectedId = await compare(firstPair, "named");
expect(selectedId).not.toBe(firstId);
const concurrentIds = await Promise.all(
[firstPair, secondPair, ...remaining, ...remaining].map((pair) =>
compare(pair),
),
);
expect(concurrentIds.slice(0, 2)).toEqual([firstId, secondId]);
const evidenceIds = new Set([
firstId,
secondId,
selectedId,
...concurrentIds,
]);
expect(evidenceIds.size).toBe(pairs.length + 1);
const unknowns = session.listUnknowns({
domain: "javascript-export-shape",
});
expect(unknowns).toHaveLength(pairs.length + 1);
expect(unknowns).toEqual(expect.arrayContaining(firstUnknowns));
expect(
new Set(
unknowns.flatMap(
({ supporting_evidence_ids }) => supporting_evidence_ids,
),
),
).toEqual(evidenceIds);
expect(unknowns.every(({ revision }) => revision === 1)).toBe(true);
const records = session.exportEvidenceBundle().records;
for (const id of evidenceIds)
expect(records.some(({ evidence_id }) => evidence_id === id)).toBe(
true,
);
const retained = session.exportEvidenceBundle();
await Promise.all(pairs.map((pair) => compare(pair)));
expect(session.exportEvidenceBundle()).toEqual(retained);
},
);
});
describe("source-produced export comparison inventories", () => {
it("records partial comparison coverage even when matching unknown projections produce no changes", async () => {
const source = `export default function make() {
const result = { kind: "record", count: 1 };
delete result.count;
return result;
}`;
const [left, right] = await Promise.all([
analyzeSourceEvidence(source),
analyzeSourceEvidence(source),
]);
const { client, session, close } = await createApplicationMcpHarness();
onTestFinished(close);
const response = await client.callTool({
name: "compare_javascript_export_shapes",
arguments: {
left,
right,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
},
});
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
normalized_result: {
changes: [],
summary: { added: 0, removed: 0, changed: 0, unknown: 0 },
coverage: { status: "partial" },
},
});
const { evidence_id: evidenceId } = z
.object({ evidence_id: z.string() })
.parse(response.structuredContent);
expect(session.exportEvidenceBundle().unknowns).toEqual(
expect.arrayContaining([
expect.objectContaining({
domain: "javascript-export-shape",
supporting_evidence_ids: [evidenceId],
}),
]),
);
});
it("retains large source-produced export inventories through comparison schemas", async () => {
const fields = Array.from(
{ length: 64 },