From 28283bdc26ee048103d13363d5eb4c722fd86340 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:02:28 +0100 Subject: [PATCH] fix(oracles): own object-literal functions reached via dynamic lookup or whole-value reference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an owned function accesses a module-level object literal dynamically (e.g. handlers[message.method]) or passes it as a whole value (e.g. Object.values(handlers), dispatch(handlers)), which member is called is unknown statically, so ownership now brings every function defined inside the declaration's value into the caller's tree — matching the existing rule for classes passed as values. Static property reads (handlers.openProject(), handlers['openProject']()) and direct owns entries naming the data variable (src/x.ts#handlers) still leave unreferenced sibling methods and function properties unowned. This also fixes two related reference-resolution issues in owners.mjs: - skip PropertyAssignment declaration names when walking module-level data so arrow/function property assignments behave consistently with methods - resolve ShorthandPropertyAssignment value symbols ({ fnA, fnB }) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/oracles/oracle-gaps/owners.mjs | 118 +++++++- .../oracles/skills/oracles-design/SKILL.md | 14 +- .../oracle-gaps-owns-through-calls.test.ts | 257 ++++++++++++++++-- 3 files changed, 354 insertions(+), 35 deletions(-) diff --git a/packages/oracles/oracle-gaps/owners.mjs b/packages/oracles/oracle-gaps/owners.mjs index 490f94ab..09de659f 100644 --- a/packages/oracles/oracle-gaps/owners.mjs +++ b/packages/oracles/oracle-gaps/owners.mjs @@ -56,8 +56,16 @@ // top-level variable statement. A function that reads it brings it into its // tree, with what its initializer refers to outside the functions it holds, // and an owns entry may name it. A function its initializer holds, such as an -// object literal's method, is a unit of its own, owned where something -// refers to it, not because the declaration's text holds it. A mutant belongs to +// object literal's method or function property, is a unit of its own, owned +// where something refers to it, not because the declaration's text holds it: +// a static property read (`obj.a` or `obj['a']`) brings only that property +// and leaves sibling functions unowned, and naming the declaration in an +// `owns` entry (`src/x.ts#TABLE`) leaves its functions to their callers. +// When an owned body indexes a data declaration dynamically (`handlers[key]`) +// or uses it as a whole value (`dispatch(handlers)`, `Object.values(handlers)`), +// which member is called is unknown statically, so it brings every function +// defined inside the declaration's initializer, just as a class passed as a +// value brings all its methods. A mutant belongs to // the innermost unit whose lines hold it. Two functions may share a name, as a getter and // its setter do, or two nested helpers; each is still its own function, and // owns entry that names them owns them all. A function's owners are the @@ -318,8 +326,12 @@ export function ownership(ts, program, pkg, oracles) { } // The package functions a declaration names: itself, or, for a class used // as a value, all its members. `new C()` names only C's constructor; C's - // members are owned where the tree refers to them. - const targetsOf = (declaration, constructed) => { + // members are owned where the tree refers to them. For a data declaration + // used dynamically (`obj[key]`) or as a whole value (`fn(obj)`), which + // member is called is unknown statically, so it brings every function + // defined inside its value; a static property read (`obj.a`, `obj['a']`) + // brings only the data unit itself. + const targetsOf = (declaration, constructed, wholeValue) => { const file = declaration.getSourceFile() if (!inPackage(file.fileName)) return [] const functions = functionsOf(posix(relative(pkg, file.fileName))) @@ -340,22 +352,106 @@ export function ownership(ts, program, pkg, oracles) { ? declaration.parent : declaration, ) + const span = + wholeValue && + !constructed && + value !== undefined && + !ts.isParameter(declaration) + ? [value.getStart(file), value.end] + : undefined return functions.filter( - (fn) => fn.node === declaration || fn.node === value, + (fn) => + fn.node === declaration || + fn.node === value || + (span !== undefined && fn.start >= span[0] && fn.end <= span[1]), ) } + // The expression that evaluates a reference identifier: `a.b` for the + // property name `b`, unwrapped through parentheses, type assertions, and + // non-null assertions. + const referenceExpression = (child) => { + let ref = + ts.isPropertyAccessExpression(child.parent) && child.parent.name === child + ? child.parent + : child + while ( + ref.parent && + (ts.isParenthesizedExpression(ref.parent) || + ts.isAsExpression(ref.parent) || + ts.isSatisfiesExpression(ref.parent) || + ts.isNonNullExpression(ref.parent) || + ts.isTypeAssertionExpression(ref.parent)) + ) + ref = ref.parent + return ref + } + // Static string-literal element access (`obj['a']`) when the type checker + // resolves that property on `ref`. + const staticPropertySymbol = (ref) => { + if ( + ref.parent && + ts.isElementAccessExpression(ref.parent) && + ref.parent.expression === ref && + ts.isStringLiteralLike(ref.parent.argumentExpression) + ) + return checker + .getTypeAtLocation(ref) + .getNonNullableType() + .getProperty(ref.parent.argumentExpression.text) + return undefined + } + // A static property access (`obj.a` or a resolved `obj['a']`), a type-only + // query (`typeof obj`), or a runtime `typeof obj` does not pass the whole + // object as a value; any other use (such as `obj[key]` or `fn(obj)`) does. + const isWholeValue = (ref, staticProp) => + !ts.isPartOfTypeNode(ref) && + !(ref.parent && ts.isTypeOfExpression(ref.parent)) && + !( + ref.parent && + ts.isPropertyAccessExpression(ref.parent) && + ref.parent.expression === ref + ) && + staticProp === undefined + const resolveUsage = (symbol, ref) => { + const constructed = + ref.parent !== undefined && + ts.isNewExpression(ref.parent) && + ref.parent.expression === ref + const staticProp = staticPropertySymbol(ref) + const wholeValue = !constructed && isWholeValue(ref, staticProp) + const resolved = [] + for (const declaration of symbol?.declarations ?? []) + resolved.push(...targetsOf(declaration, constructed, wholeValue)) + if (staticProp) + resolved.push( + ...resolveUsage(staticProp, referenceExpression(ref.parent)), + ) + return resolved + } // Every package function, method, or class an owned body refers to. const referencesOf = (node) => { const found = [] const visit = (child) => { - if (ts.isIdentifier(child) || ts.isPrivateIdentifier(child)) { - let symbol = checker.getSymbolAtLocation(child) + // A property name in an object literal (`{ a: expr }`) declares the + // property rather than referring to it; a shorthand property (`{ a }`) + // also refers to the binding `a`. + const isPropertyName = + child.parent !== undefined && + ts.isPropertyAssignment(child.parent) && + child.parent.name === child + if ( + (ts.isIdentifier(child) || ts.isPrivateIdentifier(child)) && + !isPropertyName + ) { + let symbol = + child.parent !== undefined && + ts.isShorthandPropertyAssignment(child.parent) && + child.parent.name === child + ? checker.getShorthandAssignmentValueSymbol(child.parent) + : checker.getSymbolAtLocation(child) if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol) - const constructed = - ts.isNewExpression(child.parent) && child.parent.expression === child - for (const declaration of symbol?.declarations ?? []) - found.push(...targetsOf(declaration, constructed)) + found.push(...resolveUsage(symbol, referenceExpression(child))) } // A function in module data's initializer is a unit of its own, // reached only when something refers to it. diff --git a/packages/oracles/skills/oracles-design/SKILL.md b/packages/oracles/skills/oracles-design/SKILL.md index 63708fd1..5ea7a04b 100644 --- a/packages/oracles/skills/oracles-design/SKILL.md +++ b/packages/oracles/skills/oracles-design/SKILL.md @@ -437,8 +437,18 @@ pLimit` is `index.js#pLimit`. `exports.name = fn` is named `name`. - Module-level data (`const UNIT_MS = {...}`) is its own unit, named by its variable. An owned function that reads it owns it, and what its initializer refers to. An entry can also name it: `src/index.ts#UNIT_MS`. - A destructured declaration (`const { a, b } = ...`) is not a unit: if a law - depends on one, own the whole file. + Methods and function properties defined inside an object literal + (`const handlers = { a() {}, b: () => ... }`) are units of their own: a + static property read (`handlers.a()`, `handlers['a']()`) owns only `a` + and leaves sibling functions unowned, and naming the variable directly in + `owns` (`src/index.ts#handlers`) owns only the variable's own non-function + sites. Indexing the object dynamically (`handlers[method]()`) or passing + it as a whole value (`dispatch(handlers)`, `Object.values(handlers)`) + brings every function defined inside its initializer into the caller's + tree, so owning the dispatch entry point (`src/index.ts#handleInputChunk`) + owns the whole dispatch table. A destructured declaration + (`const { a, b } = ...`) is not a unit: if a law depends on one, own the + whole file. - When an entry pulls in another contract (a batching API in the same file, or a helper in a default export's call tree that serves another promise), write that contract's own oracle, or report its gaps as diff --git a/packages/oracles/tests/oracle-gaps-owns-through-calls.test.ts b/packages/oracles/tests/oracle-gaps-owns-through-calls.test.ts index 99b41dc3..51a171f0 100644 --- a/packages/oracles/tests/oracle-gaps-owns-through-calls.test.ts +++ b/packages/oracles/tests/oracle-gaps-owns-through-calls.test.ts @@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, realpathSync, + rmSync, writeFileSync, } from 'node:fs' import { tmpdir } from 'node:os' @@ -11,6 +12,32 @@ import { describe, expect, test } from 'vitest' import ts from 'typescript-for-tanstack-oracles' import { analyze } from '../oracle-gaps/analysis.mjs' +function makePackage(files: Record) { + // The native real path, as the CLI takes it: JavaScript's keeps an 8.3 name. + const pkg = realpathSync.native( + mkdtempSync(join(tmpdir(), `owns-through-calls-`)), + ) + mkdirSync(join(pkg, `src`), { recursive: true }) + mkdirSync(join(pkg, `tests`), { recursive: true }) + for (const [rel, content] of Object.entries(files)) + writeFileSync(join(pkg, rel), content) + return pkg +} + +function ownersAt( + pkg: string, + sources: Array, + testFile: string, + source: string, + snippet: string, +) { + const { owned } = analyze(ts, pkg, sources, [testFile]) + const text = readFileSync(join(pkg, source), `utf8`) + const position = text.indexOf(snippet) + expect(position).toBeGreaterThanOrEqual(0) + return owned.at(source, position).owners +} + // The gap report's refusal of a run whose selected sources no oracle owns. A // source is owned when one of its functions is in an owned call tree, even // when the entry that reaches it lives in another file. A fixed regression, @@ -18,27 +45,213 @@ import { analyze } from '../oracle-gaps/analysis.mjs' // generate a history where the owning entry is in another file. describe(`gap report ownership through the call trees`, () => { test(`a selected source owned only through another file's call tree is not refused`, () => { - // The native real path, as the CLI takes it: JavaScript's keeps an 8.3 name. - const pkg = realpathSync.native( - mkdtempSync(join(tmpdir(), `owns-through-calls-`)), - ) - mkdirSync(join(pkg, `src`)) - mkdirSync(join(pkg, `tests`)) - writeFileSync( - join(pkg, `src`, `a.ts`), - `import { helper } from './b'\nexport function run(): number {\n return helper()\n}\n`, - ) - writeFileSync( - join(pkg, `src`, `b.ts`), - `export function helper(): number {\n return 1\n}\n`, - ) - const testFile = join(pkg, `tests`, `a.test.ts`) - writeFileSync(testFile, `oracleProperty({ owns: ['src/a.ts#run'] })\n`) - - const { owned } = analyze(ts, pkg, [`src/b.ts`], [testFile]) - const position = readFileSync(join(pkg, `src`, `b.ts`), `utf8`).indexOf( - `return 1`, - ) - expect(owned.at(`src/b.ts`, position).owners).toEqual(new Set([testFile])) + const pkg = makePackage({ + 'src/a.ts': `import { helper } from './b'\nexport function run(): number {\n return helper()\n}\n`, + 'src/b.ts': `export function helper(): number {\n return 1\n}\n`, + 'tests/a.test.ts': `oracleProperty({ owns: ['src/a.ts#run'] })\n`, + }) + try { + const testFile = join(pkg, `tests`, `a.test.ts`) + expect( + ownersAt(pkg, [`src/b.ts`], testFile, `src/b.ts`, `return 1`), + ).toEqual(new Set([testFile])) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`dynamic lookup on an object-literal dispatch table owns all its functions and their callees`, () => { + const pkg = makePackage({ + 'src/content-mapper.mjs': [ + `function helper(x) { return x + 1 }`, + `const handlers = {`, + ` initialize: (params) => ({ ok: helper(params) }),`, + ` openProject(params) { return params + 2 },`, + ` transform: function (params) { return params + 3 },`, + ` closeProject(params) { return params + 4 },`, + `}`, + `export function handleInputChunk(message) {`, + ` const handler = handlers[message.method]`, + ` return handler(message.params)`, + `}`, + ``, + ].join(`\n`), + 'tests/a.test.ts': `oracleProperty({ owns: ['src/content-mapper.mjs#handleInputChunk'] })\n`, + }) + try { + const testFile = join(pkg, `tests`, `a.test.ts`) + const expected = new Set([testFile]) + for (const snippet of [ + `return x + 1`, + `ok: helper(params)`, + `return params + 2`, + `return params + 3`, + `return params + 4`, + ]) + expect( + ownersAt( + pkg, + [`src/content-mapper.mjs`], + testFile, + `src/content-mapper.mjs`, + snippet, + ), + ).toEqual(expected) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`static property reads and direct data entries leave sibling object-literal methods and arrows unowned`, () => { + const source = [ + `const handlers = {`, + ` initialize: (params: number) => params + 1,`, + ` openProject(params: number) { return params + 2 },`, + ` transform: function (params: number) { return params + 3 },`, + ` closeProject(params: number) { return params + 4 },`, + `}`, + `export function byDot(k: keyof typeof handlers, p: number) {`, + ` void k`, + ` return handlers.openProject(p)`, + `}`, + `export function byLiteralKey(p: number) {`, + ` return handlers['openProject'](p)`, + `}`, + ``, + ].join(`\n`) + + for (const entry of [`byDot`, `byLiteralKey`]) { + const pkg = makePackage({ + 'src/dispatch.ts': source, + 'tests/a.test.ts': `oracleProperty({ owns: ['src/dispatch.ts#${entry}'] })\n`, + }) + try { + const testFile = join(pkg, `tests`, `a.test.ts`) + expect( + ownersAt( + pkg, + [`src/dispatch.ts`], + testFile, + `src/dispatch.ts`, + `return params + 2`, + ), + ).toEqual(new Set([testFile])) + for (const unowned of [ + `params + 1`, + `return params + 3`, + `return params + 4`, + ]) + expect( + ownersAt( + pkg, + [`src/dispatch.ts`], + testFile, + `src/dispatch.ts`, + unowned, + ), + ).toEqual(new Set()) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + } + + // Naming the data declaration directly leaves both method declarations + // and arrow/function property assignments to their callers. + const pkg = makePackage({ + 'src/dispatch.ts': source, + 'tests/a.test.ts': `oracleProperty({ owns: ['src/dispatch.ts#handlers'] })\n`, + }) + try { + const testFile = join(pkg, `tests`, `a.test.ts`) + for (const unowned of [ + `params + 1`, + `return params + 2`, + `return params + 3`, + `return params + 4`, + ]) + expect( + ownersAt( + pkg, + [`src/dispatch.ts`], + testFile, + `src/dispatch.ts`, + unowned, + ), + ).toEqual(new Set()) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`whole-value references, wrapped/nested dispatch tables, shorthand properties, and cross-file imports`, () => { + const pkg = makePackage({ + 'src/table.mjs': [ + `function shA() { return 10 }`, + `function shB() { return 20 }`, + `export const shorthand = { shA, shB }`, + `export const frozen = Object.freeze({`, + ` first() { return 30 },`, + ` second: () => 40,`, + `})`, + `export const nested = {`, + ` v1: {`, + ` run() { return 50 },`, + ` stop() { return 60 },`, + ` },`, + ` v2: {`, + ` other() { return 70 },`, + ` },`, + `}`, + `export default {`, + ` defA() { return 80 },`, + ` defB: () => 90,`, + `}`, + ``, + ].join(`\n`), + 'src/entry.mjs': [ + `import defTable, { shorthand, frozen, nested } from './table.mjs'`, + `import * as tables from './table.mjs'`, + `function invokeAll(obj) { return Object.values(obj).map((fn) => fn()) }`, + `export function run(k) {`, + ` return [`, + ` shorthand[k](),`, + ` invokeAll(frozen),`, + ` tables.nested.v1[k](),`, + ` defTable[k](),`, + ` ]`, + `}`, + ``, + ].join(`\n`), + 'tests/a.test.ts': `oracleProperty({ owns: ['src/entry.mjs#run'] })\n`, + }) + try { + const testFile = join(pkg, `tests`, `a.test.ts`) + const expected = new Set([testFile]) + for (const snippet of [ + `return 10`, + `return 20`, + `return 30`, + `40`, + `return 50`, + `return 60`, + `return 80`, + `90`, + ]) + expect( + ownersAt(pkg, [`src/table.mjs`], testFile, `src/table.mjs`, snippet), + ).toEqual(expected) + // Only `nested.v1` was indexed dynamically; sibling `nested.v2.other` stays unowned. + expect( + ownersAt( + pkg, + [`src/table.mjs`], + testFile, + `src/table.mjs`, + `return 70`, + ), + ).toEqual(new Set()) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } }) })