Files
rea/src/domain/javascript/javascriptSemanticPromises.ts
T
morluto b138f52e12 refactor: prune internal seams and preserve configuration ownership (#10430)
* refactor: prune internal seams and preserve configuration ownership

* fix(setup): keep YAML aliases and inherited registration settings on refresh

- Reuse an unchanged YAML collection only while every alias in it still
  resolves after the edit; otherwise rebuild it so the alias becomes its
  value. A sibling anchor replaced or moved in the same refresh no longer
  leaves an unresolved alias in Hermes or Goose output.
- Keep a connection selector whose existing value already chooses stdio
  (for example an inherited Hermes transport: stdio) instead of superseding
  it; remote selectors are still replaced. Explicit stdio selectors are
  therefore no longer rewritten (Kimi expectation updated).
- When the whole Hermes registration is inherited through a merge,
  override it with that merge and write only the changed fields.

* fix(setup): edit registration fields whose YAML key is an alias

A key written as an alias to a string scalar (for example *field with
field: &field env) was treated as a source-only key, so any change to
its value was refused in Hermes and Goose. Resolve such keys to their
string, keep the aliased spelling while its anchor survives the edit,
and write the plain key when the same edit rebuilds the anchor.

* test(process): bound cleanup-boundary waits and always release gates

Both cancellation tests awaited a bare started promise and released
their gates only on success, so a missed boundary waited for the outer
deadline and could leave cleanup parked. Use awaitAcknowledgement and
release and join the cleanup in finally.

* fix(setup): repair only aliases an edit leaves unresolved

Replace the pre-edit alias survival guess, which expanded aliases to
sibling anchors that survive unchanged, with an exact repair: record
what each alias in the replaced value resolves to, write the edit, then
replace only aliases left without a preceding anchor by that value.

- Keep an aliased key's source position, so its anchor stays ahead of
  later aliases.
- Treat an aliased key as its string only when no other key in the map
  resolves to the same string; an ambiguous one stays guarded.
- Override an inherited Hermes registration only when the requested
  entry keeps every inherited field, so an explicit replacement can drop
  remote selectors.

* fix(setup): repair aliases whose binding an edit changes, keeping comments

An alias whose own anchor was removed could resolve to an earlier anchor
with the same name and silently change value. Record the node each alias
resolved to and repair any alias that no longer resolves to that node.
Carry the alias's comments and spacing onto the repaired value.

* test(setup): split the Hermes anchor and merge refresh cases

* fix(setup): refuse removing an overridden key its merge would restore

The merge-retention check skipped keys the mapping also overrides, so
dropping such a key (for example a remote url during an explicit stdio
replacement) let the retained merge restore it. Check removal before
skipping overridden keys, so the edit is refused with the existing
message instead of producing a registration that cannot be applied.
2026-11-14 04:08:37 -05:00

548 lines
18 KiB
TypeScript

import { javascriptSourceRangeKey } from "./javascriptSourceCoordinates.js";
import * as t from "@babel/types";
import type {
JavaScriptSemanticCallable,
JavaScriptSemanticPromiseOperation,
} from "./javascriptSemanticIr.js";
import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js";
import { createSemanticCallableIdStack } from "./javascriptSemanticCallableStack.js";
import {
readExactJavaScriptLiteral,
semanticStaticPropertyName,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js";
import { semanticBindingAtRead } from "./javascriptSemanticMutationInitializers.js";
import { isUnmodifiedGlobalReference } from "./javascriptSemanticGlobalReference.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import {
assignedSemanticResultBindings,
dataEffectMemberCallee,
scalarAssignedResultBinding,
} from "./javascriptSemanticDataEffectHelpers.js";
type PromiseMethod = JavaScriptSemanticPromiseOperation["method"];
type PromiseKind = JavaScriptSemanticPromiseOperation["kind"];
interface PromiseCandidate {
readonly node: t.Node;
readonly kind: PromiseKind;
readonly method: PromiseMethod;
readonly promiseId: string;
readonly ownerCallableId: string | null;
readonly ancestors: readonly t.Node[];
}
interface PromiseResolution {
readonly promiseIds: readonly string[];
readonly status: JavaScriptSemanticPromiseOperation["sourceResolution"];
}
interface PromiseOwnership {
readonly ownership: JavaScriptSemanticPromiseOperation["ownership"];
readonly ownerBindingId: string | null;
readonly returnSiteId: string | null;
}
interface PromiseExpressionResolutionContext {
readonly current: PromiseCandidate;
readonly candidateByNode: WeakMap<t.Node, PromiseCandidate>;
readonly state: JavaScriptSemanticAnalysisState;
readonly seenBindings: ReadonlySet<string>;
}
interface PromiseOwnershipContext {
readonly candidate: PromiseCandidate;
readonly candidateByNode: WeakMap<t.Node, PromiseCandidate>;
readonly state: JavaScriptSemanticAnalysisState;
readonly returnSiteIdFor: (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
) => string | null;
}
/** Recover explicit Promise construction, chaining, aggregation, and ownership. */
export const collectJavaScriptSemanticPromises = (
program: t.Program,
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
): JavaScriptSemanticPromiseOperation[] => {
const candidates = collectCandidates(program, state, callables);
const returnSiteIdFor = createReturnSiteLookup(callables);
const candidateByNode = new WeakMap<t.Node, PromiseCandidate>();
for (const candidate of candidates)
candidateByNode.set(candidate.node, candidate);
return candidates.map((candidate) => {
const ownership = promiseOwnership(
candidate,
candidateByNode,
state,
returnSiteIdFor,
);
const sources = promiseSources(candidate, candidateByNode, state);
return {
promiseId: candidate.promiseId,
kind: candidate.kind,
method: candidate.method,
location: range(candidate.node),
ownerCallableId: candidate.ownerCallableId,
...ownership,
sourcePromiseIds: [...new Set(sources.promiseIds)].sort(
compareUnicodeCodePoints,
),
sourceResolution: sources.status,
};
});
};
/**
* Node's `Promise` constructor calls the executor synchronously and throws a
* `TypeError` when it is not callable, before any promise object exists. An
* exactly readable literal that cannot be a function — or a missing argument —
* is therefore not a promise construction, while an identifier, a call result or
* a spread may still supply a function and keeps its operation.
*
* A class expression is callable enough to pass Node's own check, so it is kept.
*/
const rejectsPromiseExecutor = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): boolean => {
if (!t.isNewExpression(node)) return false;
const executor = node.arguments[0];
if (executor === undefined) return true;
if (t.isSpreadElement(executor)) return false;
const value = unwrapJavaScriptExpression(executor).node;
if (t.isFunctionExpression(value) || t.isArrowFunctionExpression(value))
return false;
if (t.isClassExpression(value)) return false;
// `NaN` and `Infinity` are unshadowed globals rather than literals, and neither
// is callable.
if (
t.isIdentifier(value) &&
(value.name === "NaN" || value.name === "Infinity") &&
isUnmodifiedGlobalReference(value, state, value.name)
)
return true;
// Every unary operator yields a primitive, and a primitive is never callable.
// A numeric literal is read directly rather than through the exact-value
// reader, which refuses to price a non-finite literal such as `1e309`.
return (
t.isUnaryExpression(value) ||
t.isNumericLiteral(value) ||
readExactJavaScriptLiteral(value).found ||
t.isTemplateLiteral(value) ||
t.isBigIntLiteral(value) ||
t.isRegExpLiteral(value) ||
t.isArrayExpression(value) ||
t.isObjectExpression(value)
);
};
const collectCandidates = (
program: t.Program,
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
): PromiseCandidate[] => {
const output: PromiseCandidate[] = [];
const admittedCallables = new Set(
callables.map(({ callableId }) => callableId),
);
const callableStack = createSemanticCallableIdStack(admittedCallables);
const ancestors: t.Node[] = [];
traverseJavaScriptValueAst(program, state.erasedSyntaxNodes, {
enter: (node, parent) => {
callableStack.enter(node, parent);
const details = promiseCandidateDetails(node, state);
if (details !== null && !rejectsPromiseExecutor(node, state)) {
output.push({
node,
...details,
promiseId: semanticPromiseId(details.kind, node),
ownerCallableId: callableStack.callables.at(-1) ?? null,
ancestors: [...ancestors],
});
}
ancestors.push(node);
},
exit: (node) => {
ancestors.pop();
callableStack.exit(node);
},
});
return output;
};
const promiseCandidateDetails = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): Pick<PromiseCandidate, "kind" | "method"> | null => {
if (
t.isNewExpression(node) &&
t.isIdentifier(node.callee, { name: "Promise" }) &&
isUnmodifiedGlobalReference(node.callee, state, "Promise")
)
return { kind: "constructor", method: "new" };
if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) {
const member = dataEffectMemberCallee(node);
if (member === null) return null;
const method = semanticStaticPropertyName(member.property, member.computed);
if (
t.isIdentifier(member.object, { name: "Promise" }) &&
isUnmodifiedGlobalReference(node.callee, state, ["Promise", method ?? ""])
) {
if (method === "all" || method === "allSettled")
return { kind: "aggregate", method };
if (method === "resolve" || method === "reject")
return { kind: "static", method };
}
if (method === "then" || method === "catch" || method === "finally")
return { kind: "chain", method };
}
if (t.isAwaitExpression(node) && !isPromiseProducer(node.argument, state))
return { kind: "awaited-expression", method: "await" };
return null;
};
const isPromiseProducer = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): boolean =>
promiseCandidateDetails(unwrapJavaScriptExpression(node).node, state) !==
null;
const semanticPromiseId = (kind: PromiseKind, node: t.Node): string =>
`promise:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
const promiseOwnership = (
candidate: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
state: JavaScriptSemanticAnalysisState,
returnSiteIdFor: PromiseOwnershipContext["returnSiteIdFor"],
): PromiseOwnership => {
if (candidate.kind === "awaited-expression") return emptyOwnership("awaited");
const context: PromiseOwnershipContext = {
candidate,
candidateByNode,
state,
returnSiteIdFor,
};
for (let index = candidate.ancestors.length - 1; index >= 0; index -= 1) {
const ancestor = candidate.ancestors[index];
if (ancestor === undefined) continue;
const ownership = ownershipAtAncestor(ancestor, context);
if (ownership === "boundary") break;
if (ownership !== null) return ownership;
}
return emptyOwnership("unknown");
};
const ownershipAtAncestor = (
ancestor: t.Node,
context: PromiseOwnershipContext,
): PromiseOwnership | "boundary" | null => {
const { candidate, candidateByNode, state, returnSiteIdFor } = context;
if (t.isAwaitExpression(ancestor))
return unwrapJavaScriptExpression(ancestor.argument).node === candidate.node
? emptyOwnership("awaited")
: "boundary";
const outer = candidateByNode.get(ancestor);
if (
outer !== undefined &&
outer.ownerCallableId === candidate.ownerCallableId &&
outerConsumesCandidate(outer, candidate)
)
return outer.kind === "chain"
? emptyOwnership("chained")
: emptyOwnership("aggregated");
if (isUnmodeledCall(ancestor, outer)) return "boundary";
const assigned = assignedPromiseBinding(ancestor, candidate.node, state);
if (assigned !== undefined)
return {
ownership: "assigned",
ownerBindingId: assigned,
returnSiteId: null,
};
if (t.isReturnStatement(ancestor)) {
if (
ancestor.argument == null ||
unwrapJavaScriptExpression(ancestor.argument).node !== candidate.node
)
return "boundary";
return returnedPromiseOwnership(
candidate.ownerCallableId,
range(ancestor),
returnSiteIdFor,
);
}
if (t.isExpressionStatement(ancestor))
return unwrapJavaScriptExpression(ancestor.expression).node ===
candidate.node
? emptyOwnership("detached")
: "boundary";
const callableId = semanticCallableIdForNode(ancestor);
if (callableId === null || callableId !== candidate.ownerCallableId)
return null;
return t.isArrowFunctionExpression(ancestor) &&
unwrapJavaScriptExpression(ancestor.body).node === candidate.node
? returnedPromiseOwnership(
candidate.ownerCallableId,
range(ancestor.body),
returnSiteIdFor,
)
: "boundary";
};
const isUnmodeledCall = (
node: t.Node,
candidate: PromiseCandidate | undefined,
): boolean =>
candidate === undefined &&
(t.isCallExpression(node) ||
t.isOptionalCallExpression(node) ||
t.isNewExpression(node));
const assignedPromiseBinding = (
ancestor: t.Node,
candidate: t.Node,
state: JavaScriptSemanticAnalysisState,
): string | null | undefined => {
if (!t.isVariableDeclarator(ancestor) && !t.isAssignmentExpression(ancestor))
return undefined;
const source = t.isVariableDeclarator(ancestor)
? ancestor.init
: ancestor.right;
if (source == null) return undefined;
if (unwrapJavaScriptExpression(source).node !== candidate) return undefined;
return scalarAssignedResultBinding(
assignedSemanticResultBindings(source, [ancestor], state),
);
};
const returnedPromiseOwnership = (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
returnSiteIdFor: PromiseOwnershipContext["returnSiteIdFor"],
): PromiseOwnership => ({
ownership: "returned",
ownerBindingId: null,
returnSiteId: returnSiteIdFor(callableId, location),
});
const outerConsumesCandidate = (
outer: PromiseCandidate,
candidate: PromiseCandidate,
): boolean => {
if (
outer.kind === "chain" &&
(t.isCallExpression(outer.node) || t.isOptionalCallExpression(outer.node))
) {
const member = dataEffectMemberCallee(outer.node);
return (
member !== null &&
unwrapJavaScriptExpression(member.object).node === candidate.node
);
}
if (
outer.kind === "aggregate" &&
(t.isCallExpression(outer.node) || t.isOptionalCallExpression(outer.node))
) {
const input = outer.node.arguments[0];
return (
t.isArrayExpression(input) &&
input.elements.some(
(element) =>
element !== null &&
!t.isSpreadElement(element) &&
unwrapJavaScriptExpression(element).node === candidate.node,
)
);
}
return false;
};
const emptyOwnership = (
ownership: JavaScriptSemanticPromiseOperation["ownership"],
): PromiseOwnership => ({
ownership,
ownerBindingId: null,
returnSiteId: null,
});
const indexReturnSites = (
callable: JavaScriptSemanticCallable,
): ReadonlyMap<string, string> => {
const output = new Map<string, string>();
for (const site of callable.returnSites) {
const key = javascriptSourceRangeKey(site.location);
if (!output.has(key)) output.set(key, site.returnSiteId);
}
return output;
};
const createReturnSiteLookup = (
callables: readonly JavaScriptSemanticCallable[],
): PromiseOwnershipContext["returnSiteIdFor"] => {
let callablesById:
| ReadonlyMap<string, JavaScriptSemanticCallable>
| undefined;
let returnSiteIdsByCallable:
| Map<string, ReadonlyMap<string, string>>
| undefined;
return (callableId, location) => {
if (callableId === null) return null;
callablesById ??= indexCallablesById(callables);
const callable = callablesById.get(callableId);
if (callable === undefined) return null;
returnSiteIdsByCallable ??= new Map();
let returnSiteIds = returnSiteIdsByCallable.get(callableId);
if (returnSiteIds === undefined) {
returnSiteIds = indexReturnSites(callable);
returnSiteIdsByCallable.set(callableId, returnSiteIds);
}
return returnSiteIds.get(javascriptSourceRangeKey(location)) ?? null;
};
};
const indexCallablesById = (
callables: readonly JavaScriptSemanticCallable[],
): ReadonlyMap<string, JavaScriptSemanticCallable> => {
const output = new Map<string, JavaScriptSemanticCallable>();
for (const callable of callables) {
if (output.has(callable.callableId)) continue;
output.set(callable.callableId, callable);
}
return output;
};
const promiseSources = (
candidate: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
state: JavaScriptSemanticAnalysisState,
): PromiseResolution => {
if (candidate.kind === "chain") {
const member =
t.isCallExpression(candidate.node) ||
t.isOptionalCallExpression(candidate.node)
? dataEffectMemberCallee(candidate.node)
: null;
return member === null
? unresolvedPromise()
: resolvePromiseExpression(
member.object,
promiseResolutionContext(candidate, candidateByNode, state),
);
}
if (candidate.kind === "aggregate")
return aggregateSources(candidate, candidateByNode, state);
if (candidate.kind === "awaited-expression")
return t.isAwaitExpression(candidate.node)
? resolvePromiseExpression(
candidate.node.argument,
promiseResolutionContext(candidate, candidateByNode, state),
)
: unresolvedPromise();
return { promiseIds: [], status: "complete" };
};
const aggregateSources = (
candidate: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
state: JavaScriptSemanticAnalysisState,
): PromiseResolution => {
if (
!t.isCallExpression(candidate.node) &&
!t.isOptionalCallExpression(candidate.node)
)
return unresolvedPromise();
const input = candidate.node.arguments[0];
if (!t.isArrayExpression(input)) return unresolvedPromise();
const resolutions = input.elements.map((element) => {
if (element === null) return completePromise();
if (t.isSpreadElement(element)) return unresolvedPromise();
if (isObviouslyNonPromise(element)) return completePromise();
return resolvePromiseExpression(
element,
promiseResolutionContext(candidate, candidateByNode, state),
);
});
return combinePromiseResolutions(resolutions);
};
const resolvePromiseExpression = (
rawNode: t.Node,
context: PromiseExpressionResolutionContext,
): PromiseResolution => {
const { current, candidateByNode, state, seenBindings } = context;
const node = unwrapJavaScriptExpression(rawNode).node;
const direct = candidateByNode.get(node);
if (direct !== undefined && direct.promiseId !== current.promiseId)
return { promiseIds: [direct.promiseId], status: "complete" };
if (!t.isIdentifier(node)) return unresolvedPromise();
const binding = resolveSemanticBindingState(state, node, node.name);
if (binding === undefined || seenBindings.has(binding.bindingId))
return unresolvedPromise();
const read = semanticBindingAtRead(binding, node, state);
if (
read.status !== "ordered" ||
!read.hasDefiniteInitializer ||
read.binding.initializers.length !== 1
)
return unresolvedPromise();
const initializer = read.binding.initializers[0];
if (initializer === undefined || initializer.projection.length > 0)
return unresolvedPromise();
const nestedSeen = new Set(seenBindings);
nestedSeen.add(binding.bindingId);
return resolvePromiseExpression(initializer.node, {
...context,
seenBindings: nestedSeen,
});
};
const promiseResolutionContext = (
current: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
state: JavaScriptSemanticAnalysisState,
): PromiseExpressionResolutionContext => ({
current,
candidateByNode,
state,
seenBindings: new Set(),
});
const combinePromiseResolutions = (
resolutions: readonly PromiseResolution[],
): PromiseResolution => ({
promiseIds: resolutions.flatMap(({ promiseIds }) => promiseIds),
status: resolutions.some(({ status }) => status === "unresolved")
? resolutions.some(({ status }) => status === "complete")
? "partial"
: "unresolved"
: resolutions.some(({ status }) => status === "partial")
? "partial"
: "complete",
});
const completePromise = (): PromiseResolution => ({
promiseIds: [],
status: "complete",
});
const unresolvedPromise = (): PromiseResolution => ({
promiseIds: [],
status: "unresolved",
});
const isObviouslyNonPromise = (node: t.Node): boolean =>
t.isLiteral(node) ||
t.isObjectExpression(node) ||
t.isFunction(node) ||
t.isClassExpression(node);