Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
fix(incremental): validate omissions with scoped source identities
Lum110402efdd8f2dea
diff --git a/docs/incremental/symbol-loss-validation.md b/docs/incremental/symbol-loss-validation.mdindex 9a0956ac..ae9558d6 100644--- a/docs/incremental/symbol-loss-validation.md+++ b/docs/incremental/symbol-loss-validation.md@@ -11,11 +11,11 @@ The source-evidence layer mixed structural declarations, runtime-installed names## Decision rules1. A preserved graph descriptor must keep its symbol kind/name and explicit class ownership. Unowned callables require source identity verification across commits.-2. Source identities are `(path, kind, owner, name)`. Locations disambiguate within a revision; they are not cross-revision identity. Duplicate source identities and competing graph mappings remain unknown.+2. Source identities are `(path, kind, owner, name)`. Ownership comes from extractor receiver metadata or AST scope; same-line containment is never used to guess a receiver. Locations disambiguate within a revision; they are not cross-revision identity. Duplicate source identities and competing graph mappings remain unknown.3. A unique current declaration plus a unique current graph binding preserves the old symbol. A declaration without a matching graph node reports `still-present`.4. Missing identities become `unknown` if parsing, baseline identity, evidence version, or current ID ownership cannot be verified. Empty extraction never proves deletion.-5. Supplemental evidence describes possible declarations using `kind`, `owner`, `name`, optional name suffix, location and reason. A null field is explicitly unknown, never an empty/free scope. Only evidence compatible with the missing identity prevents deletion. Ordinary reads, strings and parameter names are not declarations.-6. Static installers preserve exact names and owners (including Ruby readers versus writers). Dynamic keys have unknown names; unresolved receivers have unknown owners; arbitrary evaluation/installer aliases may require file-wide uncertainty. The gate does not execute code or restore old semantic data.+5. Supplemental evidence describes possible declarations using `kind`, `owner`, `name`, optional name suffix, location and reason. A null field is explicitly unknown, never an empty/free scope. Only evidence compatible with the missing identity prevents deletion. Ordinary reads, strings and parameter names are not declarations. Literal symbol names are not normalized as graph-ID delimiters (for example, #run differs from .run).+6. Verified standard installers preserve exact names and owners (including Ruby readers versus writers). Dynamic keys have unknown names; unresolved, shadowed or reassigned receivers have unknown owners; arbitrary evaluation/installer aliases or shadowed installer APIs may require file-wide uncertainty. The gate does not execute code or restore old semantic data.7. If the uniquely mapped old identity is absent and no compatible uncertainty remains, report `deleted`. A different class's same-name declaration is not that identity. Reusing the old graph ID for a different owner remains an identity conflict until the analyzer supplies distinct descriptors.8. Any unresolved entry blocks publication. One targeted repair may regenerate complete affected files. Failed repair leaves all three durable baseline files unchanged.@@ -28,10 +28,16 @@ Each source transition is checked independently from publication mechanics.| Result | preserved, still-present but omitted, genuinely deleted, unknown || Identity | stable ID; alternate ID; reused ID; same name across owners; free function versus method; duplicate/overloaded source identities; moved lines || Supplemental names | exact same/different name; unknown name; reader/writer suffix; quoted/symbol spelling; escapes/interpolation |-| Scope | same class; another class; free scope; unresolved receiver; bound installer alias; arbitrary evaluation |+| Scope | same class; another class; free scope; unresolved/shadowed/reassigned receiver; unrelated local/import aliases; bound installer alias; arbitrary evaluation || Syntax | JS/TS/JSX/TSX methods/properties/assignments/property APIs; Ruby accessors/method installers; Python attributes/installers; Go/Rust/C++ receiver extraction || Negative evidence | unrelated string, parameter, normal read/call; static installer for another symbol; another owner's accessor || Invalid evidence | unsupported parser, parse recovery/error, empty extraction, missing evidence version, ambiguous old mapping || Publication | 20-to-1 omission; equal counts; merge/direct-finalize refusal; retry success/failure; stable prepare baseline; stale shards; deleted/excluded files; both data directories; current edge endpoint reuse |Tests must assert positive and negative outcomes for each recognizer rather than only adding the latest reported failure. Existing publication tests continue to verify actual persisted bytes and fresh edge identities. Full Linux/Windows CI and one overall Codex review follow the integrated local matrix.++## Interpretation limits++The comparison uses identities represented by the same parser/extractor in both revisions, rather than compiler-wide type equivalence or arbitrary execution. Unextractable old identities, opaque names/owners, and unsupported receiver qualification remain unknown. Supplemental fields describe potential callability when the extractor only provides a property inventory. A changed source identity can be a confirmed deletion even if another owner now has the same name; reusing the old graph ID for that different identity is separately rejected.++The scoped matrix lives in `tests/skill/understand/test_symbol_evidence_matrix.test.mjs`; publication checks remain in `test_prepare_incremental.test.mjs`. Test fixtures simulate analyzer output, and do not measure live LLM omission frequency.diff --git a/tests/skill/understand/test_incremental_symbols.test.mjs b/tests/skill/understand/test_incremental_symbols.test.mjsindex c3d45810..4abb41de 100644--- a/tests/skill/understand/test_incremental_symbols.test.mjs+++ b/tests/skill/understand/test_incremental_symbols.test.mjs@@ -22,7 +22,7 @@ describe('incremental symbol matching', () => {'attr_writer :name', 'attr_accessor :name', 'obj.attr', 'attr_writer "run"', 'attr_writer :"run"'])('allows unrelated Ruby deletion beside %s', accessor => {const before = parser.analyzeFileStrict('a.rb', 'class A\n def run; end\nend');const after = parser.analyzeFileStrict('a.rb', `class A\n def keep; end\n ${accessor}\nend`);- expect(after.hasUnresolvedNames).toBe(false);+ expect(after.symbolEvidence?.version).toBe(1);expect(compareFileSymbols(graph([node('A.run')]), graph([]), before, after).missing[0].status).toBe('deleted');});@@ -34,7 +34,7 @@ describe('incremental symbol matching', () => {const before = parser.analyzeFileStrict('a.rb', `class A\n def ${name}${name.endsWith('=') ? '(value)' : ''}; end\nend`);const after = parser.analyzeFileStrict('a.rb', `class A\n def keep; end\n ${accessor}\nend`);expect(before.status).toBe('succeeded');- expect(after.hasUnresolvedNames).toBe(false);+ expect(after.symbolEvidence?.version).toBe(1);expect(compareFileSymbols(graph([node(`A.${name}`)]), graph([]), before, after).missing[0].status).toBe('unknown');});@@ -51,7 +51,7 @@ describe('incremental symbol matching', () => {const after = parser.analyzeFileStrict(filePath, newSource);expect(before.status).toBe('succeeded');expect(after.status).toBe('succeeded');- expect(after.hasUnresolvedNames).toBe(true);+ expect(after.symbolEvidence?.possible.length).toBeGreaterThan(0);const previous = graph([node('A.run', { filePath, id: `function:${filePath}:A.run` })]);expect(compareFileSymbols(previous, graph([]), before, after).missing[0].status).toBe('unknown');const ordinary = parser.analyzeFileStrict(filePath, extension === 'rb'@@ -202,7 +202,6 @@ describe('incremental symbol matching', () => {['escaped method assignment', String.raw`class A { keep() {} }; A.prototype.r\u0075n = function() {};`],['escaped identifier', String.raw`class A { r\u0075n() {} keep() {} }`],['escaped string method name', String.raw`class A { "r\u0075n"() {} keep() {} }`],- ['moved method', 'class B { run() {} }'],])('treats %s as unknown, never deletion', (_label, code) => {expect(compare([node('A.run')], [], 'class A { run() {} }', code).missing[0].status).toBe('unknown');});@@ -219,7 +218,7 @@ describe('incremental symbol matching', () => {expect(compare([node(escaped)], [], String.raw`class A { r\u0075n() {} }`, 'class A { run() {} keep() {} }').missing[0].status).toBe('unknown');const outdated = { ...parse('class A { keep() {} }') };- delete outdated.hasUnresolvedNames;+ delete outdated.symbolEvidence;const result = compareFileSymbols(graph([node('A.run')]), graph([]), parse('class A { run() {} }'), outdated);expect(result.missing[0].status).toBe('unknown');});diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjsindex 9d1063fe..fd54637b 100644--- a/tests/skill/understand/test_prepare_incremental.test.mjs+++ b/tests/skill/understand/test_prepare_incremental.test.mjs@@ -232,6 +232,28 @@ afterEach(async () => {});describe('incremental symbol publication gate', { timeout: 30_000 }, () => {+ it.each([+ ['rb', 'class A\n def run; end\nend\nclass B; end\n', 'class A\n def keep; end\nend\nclass B\n attr_reader :run\nend\n'],+ ['ts', 'class A { run() {} }\nclass B {}\n', 'class A { keep() {} }\nclass B {}\nObject.defineProperty(B.prototype, "run", { value() {} });\n'],+ ['py', 'class A:\n def run(self): pass\nclass B: pass\n', 'class A:\n def keep(self): pass\nclass B: pass\nsetattr(B, "run", lambda self: None)\n'],+ ])('publishes a genuine deletion while another %s owner installs the same name', (extension, oldSource, newSource) => {+ const path = `src/scopes.${extension}`;+ const f = symbolFixture(2, { [path]: oldSource });+ const previous = JSON.parse(f.persisted()[0]);+ const method = { ...f.methodNodes[0], id: `function:${path}:A.run`, name: 'A.run', filePath: path };+ previous.nodes.push(method);+ writeFileSync(join(f.dataDir, 'knowledge-graph.json'), JSON.stringify(previous));+ writeProjectFile(f.root, path, newSource);+ const head = commit(f.root, 'delete one owner method');+ prepare(f.root, f.baseCommit);+ f.write('batch-1.json', { nodes: [previous.nodes.find(node => node.id === `file:${path}`)], edges: [] });+ run(python, [mergeScript, f.root], f.root);+ run(process.execPath, [finalizeScript, f.root], f.root);+ const [graph, fingerprints, meta] = f.persisted().map(JSON.parse);+ expect(graph.nodes.some(node => node.id === method.id)).toBe(false);+ for (const baseline of [graph.project, fingerprints, meta]) expect(baseline.gitCommitHash).toBe(head);+ });+it.each(['attr :name', 'attr_writer "run"', 'attr_writer :"run"'])('publishes genuine Ruby reader deletion beside %s and an ordinary attr call', accessor => {const path = 'src/accessor.rb';const f = symbolFixture(2, { [path]: `class A\n def run; end\n ${accessor}\nend\nobj.attr\n` });diff --git a/tests/skill/understand/test_symbol_evidence_matrix.test.mjs b/tests/skill/understand/test_symbol_evidence_matrix.test.mjsnew file mode 100644index 00000000..03c8bddb--- /dev/null+++ b/tests/skill/understand/test_symbol_evidence_matrix.test.mjs@@ -0,0 +1,242 @@+import { beforeAll, describe, expect, it } from 'vitest';+import { TreeSitterPlugin, builtinLanguageConfigs } from '../../../understand-anything-plugin/packages/core/dist/index.js';+import { compareFileSymbols } from '../../../understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs';++let parser;+beforeAll(async () => {+ parser = new TreeSitterPlugin(builtinLanguageConfigs.filter(config => config.treeSitter));+ await parser.init();+});+const oldSource = {+ ts: 'class A { run() {} }\nclass B { keep() {} }',+ rb: 'class A\n def run; end\nend\nclass B\n def keep; end\nend',+ py: 'class A:\n def run(self): pass\nclass B:\n def keep(self): pass\n',+};+const shells = {+ ts: 'class A { keep() {} }\nclass B { keep() {} }\n',+ rb: 'class A\n def keep; end\nend\nclass B\n def keep; end\nend\n',+ py: 'class A:\n def keep(self): pass\nclass B:\n def keep(self): pass\n',+};+const installers = [+ { extension: 'ts', form: 'property assignment', source: (target, key) => `${target}.prototype[${key}] = function() {};` },+ { extension: 'tsx', form: 'property API', source: (target, key) => `Object.defineProperty(${target}.prototype, ${key}, { value() {} });` },+ { extension: 'js', form: 'reflection API', source: (target, key) => `Reflect.defineProperty(${target}.prototype, ${key}, { value() {} });` },+ { extension: 'rb', form: 'reader', source: (target, key) => `${target}.attr_reader(${key})` },+ { extension: 'rb', form: 'method installer', source: (target, key) => `${target}.define_method(${key}) { 1 }` },+ { extension: 'py', form: 'attribute installer', source: (target, key) => `setattr(${target}, ${key}, lambda self: None)` },+];+function classify(extension, currentSource, { beforeSource, name = 'A.run', newNodes = [], oldExtra = {} } = {}) {+ const family = ['ts', 'tsx', 'js', 'jsx'].includes(extension) ? 'ts' : extension;+ const path = `src/example.${extension}`;+ const node = { id: `function:${path}:${name}`, type: 'function', name, filePath: path, ...oldExtra };+ const previous = { filePath: path, nodes: [node], edges: [] };+ const current = { filePath: path, nodes: newNodes, edges: [] };+ const before = parser.analyzeFileStrict(path, beforeSource ?? oldSource[family]);+ const after = parser.analyzeFileStrict(path, currentSource);+ expect(before.status).toBe('succeeded');+ expect(after.status).toBe('succeeded');+ return { before, after, previous, current, result: compareFileSymbols(previous, current, before, after) };+}++const matrix = installers.flatMap(installer => ['A', 'B', 'target'].flatMap(owner => [+ { label: 'same name', key: '"run"', possibleMatch: true },+ { label: 'other name', key: '"other"', possibleMatch: false },+ { label: 'dynamic name', key: '("r" + "un")', possibleMatch: true },+].map(key => ({ ...installer, owner, ...key }))));++describe('scoped symbol evidence contract', () => {+ it.each(matrix)('$extension $form, owner=$owner, $label', ({ extension, owner, key, possibleMatch, source }) => {+ const family = ['ts', 'tsx', 'js'].includes(extension) ? 'ts' : extension;+ const outcome = classify(extension, shells[family] + source(owner, key));+ const status = possibleMatch && owner !== 'B' ? 'unknown' : 'deleted';+ expect(outcome.result.missing[0].status).toBe(status);+ if (status === 'unknown') {+ expect(outcome.result.missing[0].evidence).toContainEqual(expect.objectContaining({ owner: owner === 'target' ? null : owner }));+ }+ });++ it.each(['attr', 'attr_reader', 'attr_accessor', 'attr_writer'])('scopes lexical Ruby %s to B and keeps writer names distinct', accessor => {+ for (const spelling of [':run', '"run"', ':"run"', '("r" + "un").to_sym']) {+ const current = `class A\n def keep; end\nend\nclass B\n ${accessor} ${spelling}\nend`;+ expect(classify('rb', current).result.missing[0].status).toBe('deleted');+ const onA = current.replace(`class B\n ${accessor}`, `class A\n ${accessor}`);+ expect(classify('rb', onA).result.missing[0].status).toBe(accessor === 'attr_writer' ? 'deleted' : 'unknown');+ }+ });++ it.each([':run', '"run"', ':"run"', '("r" + "un").to_sym'])('protects a matching Ruby writer with %s', spelling => {+ const beforeSource = 'class A\n def run=(value); end\nend';+ expect(classify('rb', `class A\n def keep; end\n attr_writer ${spelling}\nend`,+ { beforeSource, name: 'A.run=' }).result.missing[0].status).toBe('unknown');+ });++ it.each([+ ['ts', 'console.log("run"); function log(run) { return run; } socket.send("data");'],+ ['rb', 'puts "run"\nobj.attr\nobj.run'],+ ['py', 'print("run")\ndef log(run): return run\nsocket.send("data")\ntype(A)\n'],+ ])('ordinary %s reads, strings and parameters do not declare an old method', (extension, code) => {+ expect(classify(extension, shells[extension] + code).result.missing[0].status).toBe('deleted');+ });++ it.each([+ ['ts', 'class A { keep() {} } class B { run() {} }'],+ ['rb', 'class A\n def keep; end\nend\nclass B\n def run; end\nend'],+ ['py', 'class A:\n def keep(self): pass\nclass B:\n def run(self): pass'],+ ])('a known different %s owner does not preserve A.run', (extension, code) => {+ expect(classify(extension, code).result.missing[0].status).toBe('deleted');+ });++ it.each([+ ['ts', 'const install = Object.defineProperty; install(A.prototype, "r" + "un", { value() {} });'],+ ['ts', 'const install = Object["define" + "Property"]; install(A.prototype, "r" + "un", { value() {} });'],+ ['rb', 'class A\n install = method(:attr)\n install.call(("r" + "un").to_sym)\nend'],+ ['py', 'install = setattr\ninstall(A, "r" + "un", lambda self: None)'],+ ])('unresolved %s installer aliases cannot authorize deletion', (extension, code) => {+ expect(classify(extension, shells[extension] + code).result.missing[0].status).toBe('unknown');+ });++ it.each(['ts', 'tsx', 'js', 'jsx'])('scopes computed declarations and unextracted fields in %s', extension => {+ for (const declaration of ['["r" + "un"]() {}', 'run = () => {}', '"run"() {}']) {+ expect(classify(extension, `class A { keep() {} } class B { ${declaration} }`).result.missing[0].status).toBe('deleted');+ expect(classify(extension, `class A { keep() {} ${declaration} }`).result.missing[0].status).toBe('unknown');+ }+ });++ it('does not let baseline-only supplemental declarations taint a confirmed current deletion', () => {+ expect(classify('ts', 'function keep() {}', { beforeSource: 'const run = () => {};', name: 'run' })+ .result.missing[0].status).toBe('deleted');+ });++ it.each([+ ['ts', 'function run() {} class A { run() {} }'],+ ['rb', 'class A; def run; end; end; class B; def run; end; end'],+ ])('uses AST ownership for same-line %s declarations', (extension, code) => {+ const state = classify(extension, code, { beforeSource: code });+ expect(state.result.missing[0].status).toBe('still-present');+ expect(compareFileSymbols(state.previous, state.previous, state.before, state.after).missing).toEqual([]);+ if (extension === 'ts') {+ const ambiguous = classify(extension, code, { beforeSource: code, name: 'run', oldExtra: { lineRange: [1, 1] } });+ expect(compareFileSymbols(ambiguous.previous, ambiguous.previous, ambiguous.before, ambiguous.after)+ .missing[0].status).toBe('unknown');+ }+ });++ it('does not turn a same-name class collision into a unique method identity', () => {+ const beforeSource = 'class A { run() {} }\nclass A { keep() {} }';+ expect(classify('ts', 'class A { keep() {} }', { beforeSource }).result.missing[0].status).toBe('unknown');+ });++ it('does not treat escaped class ownership as a confirmed method deletion', () => {+ expect(classify('ts', String.raw`class \u0041 { run() {} keep() {} }`).result.missing[0].status).toBe('unknown');+ expect(classify('ts', 'class A { run() {} keep() {} }', {+ beforeSource: String.raw`class \u0041 { run() {} }`, name: String.raw`\u0041.run`,+ }).result.missing[0].status).toBe('unknown');+ });++ it('rejects duplicate old source identities even when a line locates one declaration', () => {+ expect(classify('ts', 'function run() {} class Keep {}', {+ beforeSource: 'function run() {}\nfunction run() {}', name: 'run', oldExtra: { lineRange: [1, 1] },+ }).result.missing[0].status).toBe('unknown');+ });++ it('requires valid versioned scope evidence before authorizing a deletion', () => {+ const state = classify('ts', shells.ts);+ for (const symbolEvidence of [undefined, { version: 0, possible: [] }, { version: 1, possible: [{}] }]) {+ expect(compareFileSymbols(state.previous, state.current, state.before, { ...state.after, symbolEvidence })+ .missing[0].status).toBe('unknown');+ }+ });++ it.each([+ ['ts', 'function install(B) { Object.defineProperty(B.prototype, "run", {value() {}}); } install(A);'],+ ['ts', 'function install({B}) { Object.defineProperty(B.prototype, "run", {value() {}}); } install({B: A});'],+ ['ts', String.raw`function install(\u0042) { Object.defineProperty(B.prototype, "run", {value() {}}); } install(A);`],+ ['ts', 'B = A; Object.defineProperty(B.prototype, "run", {value() {}});'],+ ['py', 'def install(B): setattr(B, "run", lambda self: None)\ninstall(A)'],+ ['py', 'B = A\nsetattr(B, "run", lambda self: None)'],+ ])('a shadowed or reassigned %s class reference has unknown ownership', (extension, code) => {+ expect(classify(extension, shells[extension] + code).result.missing[0].status).toBe('unknown');+ });++ it.each([+ ['ts', 'function unrelated(B) {} Object.defineProperty(B.prototype, "run", {value() {}});'],+ ['ts', 'const unrelated = function B() {}; Object.defineProperty(B.prototype, "run", {value() {}});'],+ ['ts', 'import { B as unrelated } from "pkg"; Object.defineProperty(B.prototype, "run", {value() {}});'],+ ['py', 'def unrelated(B): pass\nsetattr(B, "run", lambda self: None)'],+ ['py', 'from pkg import B as unrelated\nsetattr(B, "run", lambda self: None)'],+ ])('an unrelated local %s binding does not erase known global ownership', (extension, code) => {+ expect(classify(extension, shells[extension] + code).result.missing[0].status).toBe('deleted');+ });++ it('class member names do not create JavaScript lexical bindings', () => {+ expect(classify('ts', 'class A { keep() {} } class B { B() {} install() { Object.defineProperty(B.prototype, "run", {value() {}}); } }')+ .result.missing[0].status).toBe('deleted');+ });++ it.each([+ ['ts', 'function install(Object) { Object.defineProperty(B.prototype, "other", {}); }'],+ ['ts', 'Object = custom; Object.defineProperty(B.prototype, "other", {});'],+ ['py', 'def install(setattr): setattr(B, "other", value)'],+ ])('unresolved %s installer identity cannot authorize deletion based on its arguments', (extension, code) => {+ expect(classify(extension, shells[extension] + code).result.missing[0].status).toBe('unknown');+ });++ it('standard reflection reads do not declare a method', () => {+ expect(classify('ts', shells.ts + 'Reflect.get(B.prototype, "run"); const get = Reflect.get;')+ .result.missing[0].status).toBe('deleted');+ });++ it('object-literal methods do not become methods of the lexically enclosing class', () => {+ expect(classify('ts', 'function run() {} class A { keep() { return { "run"() {}, ["r" + "un"]() {} }; } }')+ .result.missing[0].status).toBe('deleted');+ });++ it('a currently unresolved Rust receiver cannot prove an old inherent method disappeared', () => {+ expect(classify('rs', 'struct A; impl Trait for A { fn run(&self) {} }', {+ beforeSource: 'struct A; impl A { fn run(&self) {} }',+ }).result.missing[0].status).toBe('unknown');+ });++ it('receiver type formatting is not proof of deletion', () => {+ expect(classify('rs', 'struct A<T>{value:T} impl<T> A< T > { fn run(&self) {} }', {+ beforeSource: 'struct A<T>{value:T} impl<T> A<T> { fn run(&self) {} }', name: 'A<T>.run',+ }).result.missing[0].status).toBe('unknown');+ });++ it('private identifiers are concrete names and are distinct from runtime dot-prefixed keys', () => {+ expect(classify('ts', 'class A { #keep() {} }').result.missing[0].status).toBe('deleted');+ const state = classify('ts', 'class A { keep() {} }; Object.defineProperty(A.prototype, ".run", {value() {}});', {+ beforeSource: 'class A { #run() {} }', name: 'A.#run',+ });+ // The built-in extractor does not yet inventory private methods: that+ // missing baseline identity must remain unknown. The matcher contract also+ // supports extractor inventories that do include these literal names.+ expect(state.result.missing[0].status).toBe('unknown');+ state.before.structure.classes[0].methods.push('#run');+ expect(compareFileSymbols(state.previous, state.current, state.before, state.after).missing[0].status).toBe('deleted');+ });++ it('keeps Python file-level functions distinct from methods', () => {+ const state = classify('py', 'def keep(): pass\nclass A:\n def run(self): pass', {+ beforeSource: 'def run(): pass\nclass A:\n def run(self): pass', name: 'run', oldExtra: {lineRange: [1, 1]},+ });+ expect(state.result.missing[0].status).toBe('deleted');+ });++ it.each(['A', 'B'])('keeps C++ function-valued field uncertainty scoped to %s', owner => {+ const beforeSource = 'struct A { void run() {} }; struct B {};';+ const current = owner === 'A'+ ? 'struct A { void keep() {} std::function<void()> run; }; struct B {};'+ : 'struct A { void keep() {} }; struct B { std::function<void()> run; };';+ expect(classify('cpp', current, { beforeSource }).result.missing[0].status).toBe(owner === 'A' ? 'unknown' : 'deleted');+ });++ it.each(['N::A::run', '::N::A::run'])('cannot prove deletion when C++ qualification moves to %s', qualified => {+ expect(classify('cpp', `void ${qualified}() {} void keep() {}`, {+ beforeSource: 'namespace N { class A { void run() {} }; }',+ }).result.missing[0].status).toBe('unknown');+ expect(classify('cpp', 'void keep() {}', {+ beforeSource: `void ${qualified}() {}`, name: qualified.replace(/^::/, ''),+ }).result.missing[0].status).toBe('unknown');+ });+});diff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.mdindex e64aa27a..6d339eea 100644--- a/understand-anything-plugin/skills/understand/SKILL.md+++ b/understand-anything-plugin/skills/understand/SKILL.md@@ -416,13 +416,11 @@ Before dropping dangling endpoints, merge records normalized edge candidates froCandidate endpoints use the current analysis's node and ownership descriptors before any baseline alias is applied: an ID reused by a different current symbol must keep its current meaning. During repair, incoming edges are deferred outside the ordinary retained batch until those original HEAD descriptors can be matched against replacement nodes, so temporary ID reuse cannot create a false edge during merge.-A syntactically valid parse is insufficient to prove deletion when declaration names remain computed or escaped, including methods installed through computed prototype/object assignments. The strict parser marks this uncertainty, and missing symbols remain `unknown` rather than being treated as deleted merely because their literal spelling is absent.+The strict parser emits versioned, scoped symbol evidence. Each possible declaration records its kind, owner, name, source location, and reason. Unknown owners/names are explicit; a known declaration or installer on `B` cannot preserve a missing `A` symbol. Static keys retain their exact names, including the distinction between Ruby readers and writers. Dynamic keys, unresolved receiver bindings, installer aliases, and arbitrary evaluation only block identities compatible with that uncertainty. The report includes the matching evidence for investigation.-Runtime property-definition APIs (including `Object.defineProperty`, `Reflect`, and locally aliased property installers) and computed callees also make absence unconfirmed. The structural extractor does not evaluate runtime property creation; such evidence blocks automatic deletion confirmation even when the remaining declarations parse successfully.+Source identity is `(file path, symbol kind, owner, name)`. Same-line functions/methods use AST scope instead of inferred line containment. Shadowed/reassigned receiver names are unconfirmed; ordinary reads, strings, and parameters are not declarations. If an old ID is reused for a different current identity, repair must supply distinct descriptors. Unsupported parsing, empty extraction, ambiguous identities, and stale evidence formats remain blocking.-The same conservative rule applies to Ruby method installers/dynamic dispatch (such as `define_method`, `alias_method`, `send`, and class evaluation), Python attribute/class installers (such as `setattr`, `__dict__`, and `type`), and dynamic code evaluation. References to these APIs can establish uncertainty even through local aliases; ordinary source-confirmed Ruby/Python method deletions remain supported.--Ruby `attr`/`attr_*` calls with plain symbol or string arguments record the exact reader/writer names they install. They only make those names unconfirmed; unrelated genuine deletions and ordinary no-argument `obj.attr` calls do not taint the file. Dynamic, interpolated, or escaped accessor arguments remain unresolved.+The decision rules, limits, and cross-product test matrix are documented in `docs/incremental/symbol-loss-validation.md` in the repository. This validation uses structural source identities and recognized declaration/installer syntax; it does not execute programs or perform whole-program metaprogramming/type analysis.Go receiver methods, Rust inherent impl methods, and C++ out-of-class definitions retain explicit type ownership and their own source ranges. Their duplicate entries in `classes[].methods` are reconciled without assuming the method body is inside the type declaration. Free functions with the same name stay distinct; unresolved receivers and Rust trait impl identities remain `unknown`. Receiver changes also affect structural fingerprints when the type declaration is in another file.diff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjsindex 3f08c090..a6da2b6c 100644--- a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs@@ -55,22 +55,51 @@ function symbolKey(symbol) {return JSON.stringify([symbol.kind, symbol.owner, symbol.name]);}+function validSupplement(evidence) {+ const supplement = evidence?.symbolEvidence;+ return supplement?.version === 1 && Array.isArray(supplement.possible)+ && Array.isArray(supplement.functions)+ && supplement.functions.every(fn => fn && typeof fn.name === 'string' && (fn.owner === null || typeof fn.owner === 'string')+ && Array.isArray(fn.lineRange) && fn.lineRange.length === 2 && fn.lineRange.every(Number.isInteger))+ && supplement.possible.every(item => item && [null, 'callable', 'class'].includes(item.kind)+ && (item.owner === null || typeof item.owner === 'string')+ && (item.name === null || typeof item.name === 'string')+ && typeof item.reason === 'string' && Array.isArray(item.lineRange)+ && item.lineRange.length === 2 && item.lineRange.every(Number.isInteger)+ && (item.nameSuffix === undefined || typeof item.nameSuffix === 'string'));+}++function compatibleEvidence(evidence, symbol) {+ return evidence.symbolEvidence.possible.filter(item => {+ if (item.kind !== null && item.kind !== symbol.kind) return false;+ if (item.owner !== null && qualifiedName(item.owner) !== qualifiedName(symbol.owner)) return false;+ // These are actual parser/runtime names, not graph-ID spelling hints.+ // In particular, a private #run is distinct from the literal key .run.+ const names = [symbol.name];+ // An unresolved receiver may denote singleton/qualified method scopes.+ if (item.owner === null) names.push(names[0].split('.').at(-1));+ if (item.name !== null && !names.includes(item.name)) return false;+ return !item.nameSuffix || names.some(name => name.endsWith(item.nameSuffix));+ });+}+function sourceSymbols(evidence) {- if (evidence?.status !== 'succeeded' || !evidence.structure || !evidence.language) return [];+ if (evidence?.status !== 'succeeded' || !evidence.structure || !evidence.language || !validSupplement(evidence)) return [];const { functions, classes } = evidence.structure;const symbols = [];for (const fn of functions) {- let owner = fn.owner;- if (owner === undefined) {- const possibleOwners = classes.filter(cls => cls.methods.includes(fn.name));- const enclosing = possibleOwners.filter(cls => fn.lineRange[0] >= cls.lineRange[0]- && fn.lineRange[1] <= cls.lineRange[1]);- // These extractors emit out-of-type method definitions; only their- // explicit receiver metadata can distinguish those from free functions.- owner = ['go', 'rust', 'cpp', 'c'].includes(evidence.language) ? null- : enclosing.length === 1 ? enclosing[0].name : enclosing.length ? null : '';+ if (fn.owner !== undefined) symbols.push({ kind: 'callable', owner: fn.owner, name: fn.name, lineRange: fn.lineRange });+ }+ // Supplementary identities come from AST scope, never guessed by line-range+ // containment (which cannot distinguish same-line free functions/methods).+ for (const fn of evidence.symbolEvidence.functions) {+ symbols.push({ kind: 'callable', owner: fn.owner, name: fn.name, lineRange: fn.lineRange });+ }+ for (const fn of functions.filter(fn => fn.owner === undefined)) {+ if (!evidence.symbolEvidence.functions.some(candidate => candidate.name === fn.name+ && JSON.stringify(candidate.lineRange) === JSON.stringify(fn.lineRange))) {+ symbols.push({ kind: 'callable', owner: null, name: fn.name, lineRange: fn.lineRange });}- symbols.push({ kind: 'callable', owner, name: fn.name, lineRange: fn.lineRange });}for (const cls of classes) {symbols.push({ kind: 'class', owner: '', name: cls.name, lineRange: cls.lineRange });@@ -91,6 +120,10 @@ function sourceSymbols(evidence) {return symbols;}+function ambiguousOwner(symbol, source) {+ return symbol.owner && source.filter(item => item.kind === 'class' && item.name === symbol.owner).length > 1;+}+function nodeNames(node) {const path = normalizePath(node.filePath);const names = new Set([qualifiedName(node.name)]);@@ -136,8 +169,8 @@ function resolveSymbol(node, graph, symbols) {const qualified = candidates.filter(symbol => symbol.owner&& names.has(qualifiedName(`${symbol.owner}.${symbol.name}`)));if (qualified.length) candidates = qualified;- const owners = classOwners(node, graph).map(parent => parent.name);- if (owners.length) candidates = candidates.filter(symbol => owners.includes(symbol.owner));+ const owners = classOwners(node, graph).map(parent => qualifiedName(parent.name));+ if (owners.length) candidates = candidates.filter(symbol => symbol.owner !== null && owners.includes(qualifiedName(symbol.owner)));// Lines locate ownership within one revision only; they are never identity// across revisions. Do not use lines to guess among overloads/same-name classes.if (candidates.length > 1 && Array.isArray(node.lineRange)) {@@ -157,18 +190,32 @@ export function compareFileSymbols(previous, current, baseEvidence, headEvidenceconst newMappings = newSymbols.map(node => resolveSymbol(node, current, headSource));const missing = [];const replacements = [];+ const completeEvidence = validSupplement(baseEvidence) && validSupplement(headEvidence);for (let index = 0; index < oldSymbols.length; index++) {const node = oldSymbols[index];if (hasPreservedIdentity(node, previous, current, sameRevision)) continue;const entry = { id: node.id, name: node.name, type: node.type, status: 'unknown', reason: '' };const old = oldMappings[index];- if (!old || baseEvidence?.status !== 'succeeded' || headEvidence?.status !== 'succeeded') {+ if (baseEvidence?.status === 'succeeded' && headEvidence?.status === 'succeeded' && !completeEvidence) {+ entry.reason = 'Strict parser lacks valid scoped symbol evidence; rebuild the core package';+ } else if (!old || baseEvidence?.status !== 'succeeded' || headEvidence?.status !== 'succeeded') {entry.reason = 'Old symbol cannot be mapped uniquely, or source parsing is unavailable/failed';- } else if (oldMappings.filter(symbol => symbol && symbolKey(symbol) === symbolKey(old)).length !== 1) {- entry.reason = 'Multiple old graph nodes map to the same source symbol';+ } else if (baseEvidence.language === 'cpp' && old.name.includes('::')) {+ entry.reason = 'Compound C++ qualification does not establish a verified receiver identity';+ } else if ([old.name, old.owner].some(name => name.includes('\\') || name.includes('`') || name.startsWith('@')+ || name.startsWith('r#') || name.normalize('NFKC') !== name)) {+ entry.reason = 'Old source spelling does not establish a stable name or owner';+ } else if (oldMappings.filter(symbol => symbol && symbolKey(symbol) === symbolKey(old)).length !== 1+ || baseSource.filter(symbol => symbolKey(symbol) === symbolKey(old)).length !== 1) {+ entry.reason = 'Old source identity or graph binding is ambiguous';} else {const matches = headSource.filter(symbol => symbolKey(symbol) === symbolKey(old));const graphMatches = newMappings.filter(symbol => symbol && symbolKey(symbol) === symbolKey(old));+ if (ambiguousOwner(old, baseSource) || matches.some(symbol => ambiguousOwner(symbol, headSource))) {+ entry.reason = 'Source contains ambiguous same-name declaring classes';+ missing.push(entry);+ continue;+ }if (matches.length === 1 && graphMatches.length === 1) {const matchedIndex = newMappings.findIndex(symbol => symbol && symbolKey(symbol) === symbolKey(old));if (newSymbols[matchedIndex].id !== node.id) {@@ -183,16 +230,25 @@ export function compareFileSymbols(previous, current, baseEvidence, headEvidenceentry.reason = 'Current source has ambiguous same-name symbols';} else if (headSource.length === 0) {entry.reason = 'Empty structural extraction is not proof of deletion';- } else if (typeof baseEvidence.hasUnresolvedNames !== 'boolean' || typeof headEvidence.hasUnresolvedNames !== 'boolean') {- entry.reason = 'Strict parser lacks name-resolution evidence; rebuild the core package';- } else if (baseEvidence.hasUnresolvedNames || headEvidence.hasUnresolvedNames) {- entry.reason = 'Computed or escaped declaration names prevent confirming source deletion';- } else if (headSource.some(symbol => symbol.name === old.name)- || (headEvidence.leafTexts ?? []).some(text => qualifiedName(text.replace(/^['"`]|['"`]$/g, '')) === qualifiedName(old.name))) {- entry.reason = 'Name remains in source; moved or unsupported syntax cannot be ruled out';+ } else if (headSource.some(symbol => symbol.kind === old.kind && symbol.name === old.name && symbol.owner !== null+ && qualifiedName(symbol.owner).replace(/\s+/g, '') === qualifiedName(old.owner).replace(/\s+/g, ''))) {+ entry.reason = 'Receiver formatting may describe the old identity; type equivalence is not verified';+ } else if (!completeEvidence) {+ entry.reason = 'Strict parser lacks valid scoped symbol evidence; rebuild the core package';} else {- entry.status = 'deleted';- entry.reason = 'Both revisions parsed; uniquely mapped old symbol and its name are absent from current source';+ const uncertain = [...compatibleEvidence(baseEvidence, old).filter(item => item.reason === 'Unresolved declaration name'),+ ...compatibleEvidence(headEvidence, old)];+ const reusedIndex = newSymbols.findIndex(candidate => candidate.id === node.id);+ if (uncertain.length) {+ entry.reason = 'Compatible source evidence prevents confirming deletion';+ entry.evidence = uncertain;+ } else if (reusedIndex >= 0 && (!newMappings[reusedIndex]+ || symbolKey(newMappings[reusedIndex]) !== symbolKey(old))) {+ entry.reason = 'The old graph ID is reused by a different or unresolved source identity';+ } else {+ entry.status = 'deleted';+ entry.reason = 'Both revisions parsed; old identity is absent with no compatible declaration uncertainty';+ }}}missing.push(entry);