fix(markdown): a bare free function name needs its file cited (#4804)

`resolve_markdown_mentions` linked bare code spans like `token` or `raw`
to unrelated free functions carrying the same label across languages.

Require section-scoped evidence for bare prose-like free function names:
- Keep a bare free-function mention only if the section cites the defining
  file (via a code span, file link, or path qualification) or cites another
  symbol from that file (#4804).
- Exempt distinct code identifiers (snake_case, camelCase, or PascalCase
  in export-by-convention languages).
- Extract source-file links as file citations, scoped to enclosing headings
  as evidence owners, minting doc->file references only for scanned files.
- Resolve inline Markdown links strictly against document-relative targets,
  and reject mixed-form citations escaping the scan root.
- Reconcile doc->file citations in watch rebuilds and bump AST cache schema.
This commit is contained in:
Lalit Madan committed 2026-11-09 18:52:41 +05:30
1 parent 6c8002eca4
commit 638ab3ec18
7 files changed
+850 -76

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@ except Exception:
_EXTRACTOR_VERSION = "unknown"
# Bump when AST cache-key semantics change independently of the package version.
_AST_CACHE_SCHEMA = 40 # Solidity members, free functions and types whose names differ only by a leading `_` (or by case) in one scope (`_grantRole(bytes32,address)` / `grantRole(bytes32,address)`) get separate node ids: the one public name keeps its id and the others are salted, as in Python and C# (#3302, #4415), so the `_` function no longer vanishes and its calls stop landing on its twin (#5027); a Solidity call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own member instead of producing no edge, gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060); a Solidity call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call (the receiver), fail-closed when the type is unknown or two functions fit (#5062); a C# constructor (instance, static or primary) is its own node owned by its type through a `method` edge, its body and `: base(...)`/`: this(...)` calls credited to it, and `new X(...)`/`: base`/`: this` additively link the arity-correct overload (#5054); and a C# call inside a property/indexer accessor, expression body, operator or conversion is credited to that member (an indexer is a `this[]` node, an operator a `.operator +()` node) instead of being lost (#5056), so cached Solidity and C# extractions re-run; prior (39): A Markdown code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and emits a `ns_qualified` raw_call (#4610, #4695), so cached Markdown extractions re-run; prior (38): C# preprocessor directives and `#if` branches that would derail tree-sitter-c-sharp are blanked before parsing (byte-length preserving, so lines and columns do not move), so a directive no longer closes the enclosing class early and drops later members or calls (#5003); a Solidity library call (`Lib.f()`, including an aliased import), and an `emit`/`revert`/`require` naming a declared event or error, link to the member they name instead of producing no edge, resolved only when a single visible type and a unique name/arity member match (#5001, #5005); and a YAML `<<` merge sequence gives the earlier anchor precedence for a duplicated key, matching the merge spec and PyYAML, so the winning key carries its correct source line (#4995); so cached C#, Solidity and YAML extractions re-run; prior (37): Solidity `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling stub that kept the importer's own folder (#4985); a Python module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard (#4972); Kotlin resolves a call to an overloaded method and attributes calls inside an `init {}` block to the class, and a bare call no longer binds to a class the caller cannot reach (#4935, #4956); a Go same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method (#4962, #4966); a Go member call on a receiver typed from another package (`pkg.T`) binds only to the `T` declared at the path the file imports `pkg` from (#3368, #4853); and a Go interface method call additively dispatches to the interface's implicit implementers (#4934), so cached Solidity, Python, Kotlin and Go extractions re-run; prior (36): C++ extraction changes: a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling so it no longer loses to a same-normalized function, and a salted alias keeps its own `contains` edge (#4951); a member call `x.m()` binds by the receiver's type, now typed from parameters and class fields and not just locals, with untyped receivers kept bound in-file (#3215, #4946); an out-of-line/split-header definition attaches to the unique owner whose class file is in its include set via a `_cpp_qualified` identity marker, instead of file-containing or cross-binding to an unrelated same-named function (#4916, #4920); and a local callable value (a lambda or `std::function` local) is kept out of global call resolution by byte-range binding lifetimes so it no longer mints a spurious INFERRED call to a same-named global (#4917, #4921), so cached C++ extractions re-run; prior (35): A Rust module-qualified call like `crate::b::helper()` resolves to the function it names via qualifier-verified cross-file resolution, kept inside the caller's crate and out of local names (#2135, #4944); a Rust call written inside an expression macro's arguments (`println!`, `vec!`, ...) is linked, with a parsed call winning the dedupe (#4945); and cache keys keep their written case (file I/O through os_long_path, cache identity via normpath not normcase, anLine truncated
_AST_CACHE_SCHEMA = 41 # Markdown file spans and links to source files are extracted as `path`-only raw calls (file citations; a link to a scanned source file also gains a doc->file `references` edge, #4804); prior (40): Solidity members, free functions and types whose names differ only by a leading `_` (or by case) in one scope (`_grantRole(bytes32,address)` / `grantRole(bytes32,address)`) get separate node ids: the one public name keeps its id and the others are salted, as in Python and C# (#3302, #4415), so the `_` function no longer vanishes and its calls stop landing on its twin (#5027); a Solidity call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own member instead of producing no edge, gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060); a Solidity call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call (the receiver), fail-closed when the type is unknown or two functions fit (#5062); a C# constructor (instance, static or primary) is its own node owned by its type through a `method` edge, its body and `: base(...)`/`: this(...)` calls credited to it, and `new X(...)`/`: base`/`: this` additively link the arity-correct overload (#5054); and a C# call inside a property/indexer accessor, expression body, operator or conversion is credited to that member (an indexer is a `this[]` node, an operator a `.operator +()` node) instead of being lost (#5056), so cached Solidity and C# extractions re-run; prior (39): A Markdown code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and emits a `ns_qualified` raw_call (#4610, #4695), so cached Markdown extractions re-run; prior (38): C# preprocessor directives and `#if` branches that would derail tree-sitter-c-sharp are blanked before parsing (byte-length preserving, so lines and columns do not move), so a directive no longer closes the enclosing class early and drops later members or calls (#5003); a Solidity library call (`Lib.f()`, including an aliased import), and an `emit`/`revert`/`require` naming a declared event or error, link to the member they name instead of producing no edge, resolved only when a single visible type and a unique name/arity member match (#5001, #5005); and a YAML `<<` merge sequence gives the earlier anchor precedence for a duplicated key, matching the merge spec and PyYAML, so the winning key carries its correct source line (#4995); so cached C#, Solidity and YAML extractions re-run; prior (37): Solidity `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling stub that kept the importer's own folder (#4985); a Python module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard (#4972); Kotlin resolves a call to an overloaded method and attributes calls inside an `init {}` block to the class, and a bare call no longer binds to a class the caller cannot reach (#4935, #4956); a Go same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method (#4962, #4966); a Go member call on a receiver typed from another package (`pkg.T`) binds only to the `T` declared at the path the file imports `pkg` from (#3368, #4853); and a Go interface method call additively dispatches to the interface's implicit implementers (#4934), so cached Solidity, Python, Kotlin and Go extractions re-run; prior (36): C++ extraction changes: a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling so it no longer loses to a same-normalized function, and a salted alias keeps its own `contains` edge (#4951); a member call `x.m()` binds by the receiver's type, now typed from parameters and class fields and not just locals, with untyped receivers kept bound in-file (#3215, #4946); an out-of-line/split-header definition attaches to the unique owner whose class file is in its include set via a `_cpp_qualified` identity marker, instead of file-containing or cross-binding to an unrelated same-named function (#4916, #4920); and a local callable value (a lambda or `std::function` local) is kept out of global call resolution by byte-range binding lifetimes so it no longer mints a spurious INFERRED call to a same-named global (#4917, #4921), so cached C++ extractions re-run; prior (35): A Rust module-qualified call like `crate::b::helper()` resolves to the function it names via qualifier-verified cross-file resolution, kept inside the caller's crate and out of local names (#2135, #4944); a Rust call written inside an expression macro's arguments (`pLine truncated
# Per-process memo: distributions() scans site-packages metadata, which is
+10
View File
@@ -5030,6 +5030,9 @@ def _merge_csharp_partial_class_nodes(
cn = rc.get("caller_nid")
if cn in remap:
rc["caller_nid"] = remap[cn]
eo = rc.get("evidence_owner")
if eo in remap:
rc["evidence_owner"] = remap[eo]
def _drop_shadowed_csharp_partial_bases(all_nodes: list[dict], all_edges: list[dict]) -> None:
@@ -11283,6 +11286,10 @@ def extract(
_new = _remapped(rc.get("caller_nid"), rc.get("source_file"))
if _new is not None:
rc["caller_nid"] = _new
if rc.get("evidence_owner"):
_new_eo = _remapped(rc.get("evidence_owner"), rc.get("source_file"))
if _new_eo is not None:
rc["evidence_owner"] = _new_eo
# swift_extensions[].nid is the same kind of id carrier as caller_nid
# above (cache.py remaps both), consumed by _merge_swift_extensions far
# below. Left stale it matches no node, so whether the extension merge
@@ -11364,6 +11371,9 @@ def extract(
cn = rc.get("caller_nid")
if cn in sym_remap:
rc["caller_nid"] = sym_remap[cn]
eo = rc.get("evidence_owner")
if eo in sym_remap:
rc["evidence_owner"] = sym_remap[eo]
# Same for swift_extensions[].nid (see the id_remap pass above).
for result in per_file:
for ext in result.get("swift_extensions", []) or []:
+109 -42
View File
@@ -30,12 +30,20 @@ _MD_REF_DEF_RE = re.compile(
_MD_WIKILINK_RE = re.compile(r'(?<!\!)\[\[([^\]|#]+?)(?:\\?\|[^\]]*|#[^\]]*)?\]\]')
# Document extensions a Markdown link may point at for a `references` edge, and
# the extensions the Obsidian wikilink index covers.
_MD_LINKABLE_EXTS = {".md", ".mdx", ".qmd", ".markdown", ".rst", ".txt"}
# Source files can be linked as citations and resolved to references edges (#4804).
_MD_CITEABLE_EXTS = _MD_LINKABLE_EXTS | CODE_EXTENSIONS
# Inline code spans, single or double backtick delimited. Fenced blocks are
# skipped before this runs, so a span here is prose citing a symbol by name.
_MD_CODE_SPAN_RE = re.compile(r'(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)')
# A code span naming a file path (e.g. `graphify/build.py`, `setup.py`).
_MD_FILE_SPAN_RE = re.compile(r'^([A-Za-z0-9_./\-]+\.([A-Za-z0-9]+))$')
# The two mention grammars a code span can carry. A path-qualified mention
# (``src/pkg/mod.py::Widget::render``) names the defining file and a
# ``::``-separated symbol chain, exactly as pytest node ids and cite-lint
@@ -309,14 +317,20 @@ def _is_external_link(target: str) -> bool:
def _resolve_markdown_link(raw: str, source_dir: Path,
wikilink: bool = False) -> "Path | None":
"""Resolve a markdown link target to the absolute path of a sibling document.
wikilink: bool = False,
exts: "set[str] | None" = None) -> "Path | None":
"""Resolve a markdown link target to the absolute path it names.
Returns the resolved (normalized, not necessarily existing) path when the
target is a *local* relative/absolute file-path link to a document, or None
when it should be skipped: external URLs (http/https/mailto/protocol-
relative/data), pure in-page anchors (``#section``), and links to non-doc
file types (code/assets are handled by their own extractors).
target is a *local* relative/absolute file-path link to a linkable file, or
None when it should be skipped: external URLs (http/https/mailto/protocol-
relative/data), pure in-page anchors (``#section``), and links to
unlinkable file types (assets, unknown extensions).
``exts`` is the set of linkable extensions; the default is document
extensions only. ``_MD_CITEABLE_EXTS`` additionally accepts source files,
which ``add_link`` turns into file citations (resolved to doc->file edges
at corpus time) rather than document edges.
The anchor fragment (``#section``) and query (``?x=1``) are stripped before
resolution so ``./repo.md#setup`` resolves to the same node as ``./repo.md``.
@@ -353,7 +367,8 @@ def _resolve_markdown_link(raw: str, source_dir: Path,
if suffix == "":
target = target + ".md"
suffix = ".md"
if suffix not in _MD_LINKABLE_EXTS:
linkable = _MD_LINKABLE_EXTS if exts is None else exts
if suffix not in linkable:
if not wikilink:
return None
# The suffix may be part of the note name ([[v1.2 release]]): try
@@ -386,16 +401,18 @@ def _resolve_markdown_link(raw: str, source_dir: Path,
return resolved
def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
"""Classify one inline code span as a symbol mention, or None.
"""Classify one inline code span as a symbol mention, file citation, or None.
Returns ``(path, names)``: ``path`` is the cited file for the
``path::Name`` form and None for a bare or dotted mention; ``names`` is the
symbol chain, outermost first, so ``pkg.sub.Widget`` yields
``["pkg", "sub", "Widget"]`` and the resolver can hold the match to that
evidence. A trailing ``()`` is dropped from the last name so ``render()``
and ``render`` cite the same symbol. Spans that read as a file
(``setup.py``, ``README.md``), a shell command, an expression or prose are
not mentions and yield None.
Returns ``(path, names)``:
- for a path-qualified mention (``src/mod.py::Widget::render``), ``path`` is
the cited file and ``names`` is the symbol chain;
- for a bare or dotted mention (``Widget``, ``pkg.Widget``), ``path`` is None
and ``names`` is the symbol chain;
- for a source-file span (``graphify/build.py``, ``setup.py``), ``path`` is
the file path and ``names`` is empty, so resolution can record it as file
evidence (#4804).
Spans that read as a shell command, an expression, a document name
(``README.md``) or prose yield None.
"""
text = span.strip()
if not text or " " in text:
@@ -403,15 +420,22 @@ def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
m = _MD_PATH_MENTION_RE.match(text)
if m:
return m.group(1), m.group(2).split("::")
if not text.endswith("()"):
fm = _MD_FILE_SPAN_RE.match(text)
if fm and "." + fm.group(2).lower() in CODE_EXTENSIONS:
return text, []
m = _MD_BARE_MENTION_RE.match(text)
if m:
if "." in text:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` and ``README.md``
# are files. A dotted span whose last segment is a code or document
# extension is the latter. Other file-like spans (``pyproject.toml``)
# classify as a mention and are rejected at resolution, where the
# qualifier ``pyproject`` matches no callable's file or owner.
if "." + m.group(1) in CODE_EXTENSIONS or "." + m.group(1) in DOC_EXTENSIONS:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` is a source-file
# citation handled by _MD_FILE_SPAN_RE above (and re-caught here for a
# non-ASCII path). A document name (``README.md``) is not a mention:
# only code files are evidence for a bare mention. Other file-like
# spans (``pyproject.toml``) classify as a mention and are rejected at
# resolution, where the qualifier ``pyproject`` matches no callable.
if "." + m.group(1) in CODE_EXTENSIONS:
return text, []
if "." + m.group(1) in DOC_EXTENSIONS:
return None
return None, text.rstrip("()").split(".")
return None, [m.group(1)]
@@ -452,7 +476,9 @@ def extract_markdown(path: Path) -> dict:
instead of an under-connected orphan (#1376). The target node ID is built
from the resolved target path with the same recipe as the target file's
own node, so the edge merges into that node (no ghost node). External
URLs, in-page anchors, images and non-document targets are skipped.
URLs, in-page anchors, images and non-document targets are skipped; a
link that names a source file is not a document edge either, it is
recorded as a file citation (below).
Inline code spans on heading and body lines (backtick-quoted ``Widget``,
``render()``, ``pkg.Widget`` or ``src/mod.py::Widget::render``) are
@@ -465,9 +491,12 @@ def extract_markdown(path: Path) -> dict:
file path. That pass emits
heading --references--> code symbol (page --references--> symbol for a
mention above the first heading): EXTRACTED for the path-qualified form,
INFERRED for a bare name that matches exactly one code symbol. The shared
cross-file call pass skips these raw_calls, so a mention never becomes a
``calls`` edge.
INFERRED for a bare name that matches exactly one code symbol. A bare
free-function name whose label reads as prose (``token``, ``raw``) requires
evidence from its defining file in the citing section (#4804).
Source-file links are recorded as file citations and resolved at corpus time.
The shared cross-file call pass skips these raw_calls, so a mention never
becomes a ``calls`` edge.
Fenced code blocks (``` ... ``` or ~~~ ... ~~~, closed by a run of the
same character at least as long, per CommonMark) are skipped during
@@ -506,7 +535,7 @@ def extract_markdown(path: Path) -> dict:
seen_mentions.add(key)
raw_call = {
"caller_nid": caller_nid,
"callee": names[-1],
"callee": names[-1] if names else "",
"is_member_call": False,
"language": "markdown",
"context": span.strip(),
@@ -558,11 +587,41 @@ def extract_markdown(path: Path) -> dict:
# Dedup link edges by resolved target node so a hub doc that links to the
# same sibling many times yields one edge, not N (keeps weights meaningful).
linked_targets: set[str] = set()
seeded_citations: set[tuple[str, str]] = set()
def add_link(raw: str, line: int, wikilink: bool = False) -> None:
resolved = _resolve_markdown_link(raw, source_dir, wikilink=wikilink)
def add_link(raw: str, line: int, owner: str = file_nid,
wikilink: bool = False) -> None:
resolved = _resolve_markdown_link(raw, source_dir, wikilink=wikilink,
exts=_MD_CITEABLE_EXTS)
if resolved is None:
return
suffix = resolved.suffix.lower()
if suffix in CODE_EXTENSIONS and suffix not in _MD_LINKABLE_EXTS:
# Record source file link as citation; resolver mints edge if scanned (#4804).
try:
cited = os.path.relpath(
str(resolved), str(source_dir)
).replace("\\", "/")
except ValueError: # different drives on Windows
cited = str(resolved).replace("\\", "/")
key = (owner, cited)
if key in seeded_citations:
return
seeded_citations.add(key)
raw_calls.append({
"caller_nid": file_nid,
"evidence_owner": owner,
"callee": "",
"is_member_call": False,
"language": "markdown",
"context": cited,
"source_file": str_path,
"source_location": f"L{line}",
"path": cited,
"file_link": True,
"wikilink": wikilink,
})
return
# Build the target ID with the SAME recipe as the target file's own
# node (_make_id(str(path)) at extract time, canonicalized to
# _file_node_id(rel) by the extract() post-pass). Using the absolute
@@ -606,22 +665,18 @@ def extract_markdown(path: Path) -> dict:
fence = opened
continue
# Markdown links -> document references (#1376). Scanned on every
# non-fenced line (including heading lines, which the heading branch
# below `continue`s past) so links anywhere in the doc are captured.
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
add_link(ref_def.group(1) or ref_def.group(2), line_num)
# Inside the frontmatter block a leading `#` is a YAML comment, not an
# H1. Links above are still scanned there on purpose: review workflows
# put wikilinks in frontmatter (e.g. a `consulted:` list), and those are
# real references. Only heading detection is suppressed.
if line_num_0 < body_start:
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num, owner=file_nid)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, owner=file_nid, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
add_link(ref_def.group(1) or ref_def.group(2), line_num, owner=file_nid)
continue
# Detect headings: # Heading, ## Heading, etc.
@@ -644,14 +699,26 @@ def extract_markdown(path: Path) -> dict:
add_edge(parent, h_nid, "contains", line_num)
heading_stack.append((level, h_nid))
# Links in the heading itself belong to this heading.
for m in _MD_INLINE_LINK_RE.finditer(title):
add_link(m.group(1) or m.group(2), line_num, owner=h_nid)
for m in _MD_WIKILINK_RE.finditer(title):
add_link(m.group(1), line_num, owner=h_nid, wikilink=True)
# A code span in the heading itself is that heading's mention.
for m in _MD_CODE_SPAN_RE.finditer(title):
add_mention(h_nid, m.group(2), line_num)
continue
# Body prose: a code span cites a symbol on behalf of the enclosing
# heading (the page when the text precedes the first heading).
# Body prose: links and code spans belong to the enclosing heading
# (the page when the text precedes the first heading).
owner = heading_stack[-1][1] if heading_stack else file_nid
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num, owner=owner)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, owner=owner, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
add_link(ref_def.group(1) or ref_def.group(2), line_num, owner=owner)
for m in _MD_CODE_SPAN_RE.finditer(line_text):
add_mention(owner, m.group(2), line_num)
+6
View File
@@ -1213,6 +1213,12 @@ def _disambiguate_colliding_node_ids(
raw_call["caller_nid"] = remap[caller_key]
elif raw_call.get("caller_nid") in unambiguous_remaps:
raw_call["caller_nid"] = unambiguous_remaps[str(raw_call["caller_nid"])]
if raw_call.get("evidence_owner"):
eo_key = (raw_call.get("evidence_owner", ""), call_source_key)
if eo_key in remap:
raw_call["evidence_owner"] = remap[eo_key]
elif raw_call.get("evidence_owner") in unambiguous_remaps:
raw_call["evidence_owner"] = unambiguous_remaps[str(raw_call["evidence_owner"])]
def _is_type_like_definition(node: dict) -> bool:
if node.get("type") == "namespace":
+260 -26
View File
@@ -33,9 +33,13 @@ to the code node that defines it:
tie-breaking: an ambiguous name is a guess, and a guess is not an edge.
A bare, parenthesis-less method name is held to one more test: a word like
``redis`` is prose as often as it is a reference, so a method match survives
only when the citing document also names the class that owns it (#4609).
The trailing ``()``, a dotted form, or a class/function label carries enough
evidence on its own.
only when the citing section also names the class that owns it (#4609).
A bare free function name is held to the same test with its defining file in
place of the owner class: prose-like words (``token``, ``raw``) require the
citing section to cite that file or a symbol from it (#4804). Evidence is
section-scoped. Classes, snake_case, camelCase, trailing ``()``, or PascalCase
in export languages carry sufficient evidence on their own. Links to scanned
source files also mint doc->file references edges.
The match is INFERRED (0.95, a named cross-file reference).
An explicit relative cite (``./`` or ``../``) resolves against the document's
@@ -49,9 +53,13 @@ from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS
from graphify.extractors.base import (
_LANGUAGE_BUILTIN_GLOBALS,
active_scan_root as _active_scan_root,
)
MARKDOWN_MENTION_SUFFIXES = frozenset({".md", ".mdx", ".qmd", ".skill"})
@@ -67,6 +75,33 @@ def _symbol_label(node: dict[str, Any]) -> str:
return str(node.get("label", "")).strip("()").lstrip(".")
_CAMEL_CASE_RE = re.compile(r'[a-z][A-Z]')
# Languages where exported identifiers are PascalCase by convention (#4804).
_PASCAL_EXPORT_SUFFIXES = frozenset({
".go", ".cs", ".vb", ".swift", ".scala", ".pas", ".dpr", ".lpr",
".ps1", ".psm1",
})
def _is_prose_like_label(label: str) -> bool:
"""Whether a bare label looks like ordinary prose rather than a distinct code identifier.
Distinct code identifiers — snake_case (containing ``_``) or camelCase (a
lowercase letter followed by uppercase) — are exempt from the bare
free-function evidence test (#4804), while plain single-word lowercase
names (``token``, ``raw``, ``fail``, ``config``) require evidence. A
PascalCase label is exempt only in a PascalCase-export language, checked
by the caller against the target's source file.
"""
return "_" not in label and not _CAMEL_CASE_RE.search(label)
def _is_pascal_case_export_language(source_file: str) -> bool:
"""Whether *source_file*'s language exports identifiers as PascalCase."""
return os.path.splitext(_posix(source_file))[1].lower() in _PASCAL_EXPORT_SUFFIXES
def _is_file_node(node: dict[str, Any]) -> bool:
label = str(node.get("label", ""))
source_file = str(node.get("source_file", ""))
@@ -96,12 +131,101 @@ def _match_cited_file(cited: str, doc_file: str, source_files: set[str]) -> str
return None
if cited_posix in source_files:
return cited_posix
return _cited_file_suffix(cited_posix, source_files)
def _cited_file_suffix(cited_posix: str, source_files: set[str]) -> str | None:
"""The scanned file a normalized cite names by unique segment-aligned suffix."""
stripped = _RELATIVE_PREFIX_RE.sub("", cited_posix)
matches = [sf for sf in source_files
if sf == stripped or sf.endswith("/" + stripped)]
return matches[0] if len(matches) == 1 else None
def _match_cited_file_any_form(cited: str, doc_file: str,
source_files: set[str], *,
form_mismatch: bool,
scan_root: "Path | str | None" = None) -> str | None:
"""Resolve a cited file even when a partial rebuild mixes path forms.
Preserved nodes carry project-relative ``source_file`` values while a
freshly re-extracted document may carry an absolute one, so the
document-relative join in :func:`_match_cited_file` can miss a file that is
in the corpus. The suffix fallback fires only when that mixing is detected
(an absolute citing document against a corpus with relative paths) — with
uniform path forms the explicit-relative discipline above holds unchanged.
The result licenses evidence and doc->file citations, both anchored to
corpus files, so a unique corpus path that is a suffix of the joined path
is the file the document's own directory tree names.
"""
matched = _match_cited_file(cited, doc_file, source_files)
if matched is not None or not form_mismatch:
return matched
root = _posix(str(scan_root)) if scan_root is not None else None
if root is None:
active = _active_scan_root()
if active is not None:
root = _posix(str(active))
joined = _posix(os.path.normpath(
os.path.join(os.path.dirname(_posix(doc_file)), _posix(cited))))
if root is not None:
try:
rel = _posix(os.path.relpath(joined, root))
except ValueError:
return None
if rel.startswith("..") or os.path.isabs(rel):
return None
matches = [sf for sf in source_files if rel == sf or rel.endswith("/" + sf)]
return matches[0] if len(matches) == 1 else None
matches = []
doc_posix = _posix(doc_file)
for sf in source_files:
if joined == sf:
matches.append(sf)
elif joined.endswith("/" + sf):
prefix = joined[:-len(sf)]
if prefix.endswith("/") and doc_posix.startswith(prefix):
matches.append(sf)
return matches[0] if len(matches) == 1 else None
def _match_file_link(cited: str, doc_file: str,
source_files: set[str], *,
form_mismatch: bool,
scan_root: "Path | str | None" = None) -> str | None:
"""Resolve an authored Markdown link to a source file strictly against its target."""
doc_dir = os.path.dirname(_posix(doc_file))
relative = _posix(os.path.normpath(os.path.join(doc_dir, _posix(cited))))
if relative in source_files:
return relative
if not form_mismatch:
return None
root = _posix(str(scan_root)) if scan_root is not None else None
if root is None:
active = _active_scan_root()
if active is not None:
root = _posix(str(active))
if root is not None:
try:
rel = _posix(os.path.relpath(relative, root))
except ValueError:
return None
if not rel.startswith("..") and not os.path.isabs(rel) and rel in source_files:
return rel
return None
matches = []
doc_posix = _posix(doc_file)
for sf in source_files:
if relative == sf:
matches.append(sf)
elif relative.endswith("/" + sf):
prefix = relative[:-len(sf)]
if prefix.endswith("/") and doc_posix.startswith(prefix):
matches.append(sf)
return matches[0] if len(matches) == 1 else None
def _evidence(node_id: str, nodes_by_id: dict[str, dict[str, Any]],
parents: dict[str, set[str]]) -> set[str]:
"""Labels a dotted mention may qualify ``node_id`` with.
@@ -147,12 +271,16 @@ def resolve_markdown_mentions(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
*,
scan_root: "Path | str | None" = None,
) -> None:
"""Turn ``language: "markdown"`` raw calls into ``references`` edges in place."""
mentions = _markdown_raw_calls(per_file)
if not mentions:
return
root = scan_root or _active_scan_root()
code_nodes = [
n for n in all_nodes
if n.get("id") and n.get("file_type") == "code" and not _is_file_node(n)
@@ -244,19 +372,105 @@ def resolve_markdown_mentions(
return parent
return None
#: Targets already cited by each document, used as evidence in pass 2b.
def _section_chain(caller: str) -> set[str]:
"""*caller* (a heading or page) plus every heading enclosing it.
A citation recorded under a heading licenses bare mentions in that
heading's own section and every section nested inside it; a sibling
section is not covered (#4804).
"""
chain = {caller}
frontier = [caller]
while frontier:
nid = frontier.pop()
for p in parents.get(nid, ()):
if p not in chain:
chain.add(p)
frontier.append(p)
return chain
#: Targets already cited by each caller (heading or page), used as
#: section-scoped evidence in passes 2b and 2c.
cited_targets: dict[str, set[str]] = {}
# Files cited via file spans, path-qualified mentions, or links (#4804).
code_file_nodes = {
_posix(str(n.get("source_file"))): n["id"]
for n in all_nodes
if n.get("id") and n.get("file_type") == "code"
and n.get("source_file") and _is_file_node(n)
}
citable_files = set(code_file_nodes)
# Detect path mixing in partial rebuilds (absolute doc vs relative corpus).
corpus_has_relative_paths = any(not os.path.isabs(sf) for sf in citable_files)
cited_files: dict[str, set[str]] = {}
for rc in mentions:
cited = rc.get("path")
if not cited:
continue
caller = str(rc.get("evidence_owner") or rc.get("caller_nid", ""))
if not caller:
continue
doc = _posix(str(rc.get("source_file", "")))
if rc.get("file_link") and not rc.get("wikilink"):
source_file = _match_file_link(
str(cited), doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
else:
source_file = _match_cited_file_any_form(
str(cited), doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
if source_file is not None:
cited_files.setdefault(caller, set()).add(source_file)
# Mint page --references--> file edges for links to scanned files (#4804).
for rc in mentions:
if not rc.get("file_link"):
continue
caller = str(rc.get("caller_nid", ""))
cited = str(rc.get("path") or "")
if not caller or caller not in node_ids or not cited:
continue
doc = _posix(str(rc.get("source_file", "")))
if rc.get("wikilink"):
target_file = _match_cited_file_any_form(
cited, doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
else:
target_file = _match_file_link(
cited, doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
target = code_file_nodes.get(target_file) if target_file else None
if target is None or target == caller or (caller, target) in existing:
continue
existing.add((caller, target))
all_edges.append({
"source": caller,
"target": target,
"relation": "references",
"context": rc.get("context", ""),
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
def _add(rc: dict, target: str | None, confidence: str, score: float) -> None:
caller = str(rc.get("caller_nid", ""))
if target is None or target == caller:
return
doc = _posix(str(rc.get("source_file", "")))
if (caller, target) in existing:
# The edge is already in the graph, but this document still CITES that
# target, so it stays on record as owner evidence for a later method
# mention in the same document (#4609 review finding).
cited_targets.setdefault(doc, set()).add(target)
# Retain target as section-scoped citation evidence (#4609, #4804).
cited_targets.setdefault(caller, set()).add(target)
return
existing.add((caller, target))
all_edges.append({
@@ -270,12 +484,9 @@ def resolve_markdown_mentions(
"source_location": rc.get("source_location"),
"weight": 1.0,
})
cited_targets.setdefault(doc, set()).add(target)
cited_targets.setdefault(caller, set()).add(target)
# Pass 1: explicit evidence resolves on its own — a cited path, a dotted
# qualifier chain, or a trailing (). Record those targets per document.
# Pass 2 handles the bare, parenthesis-less, single-name spans, where the
# word alone (`redis`, `data`, `message`) is indistinguishable from prose.
# Pass 1: explicit evidence resolves directly (path, dotted chain, or trailing ()).
bare: list[dict] = []
for rc in mentions:
caller = str(rc.get("caller_nid", ""))
@@ -289,22 +500,45 @@ def resolve_markdown_mentions(
else:
bare.append(rc)
# Pass 2a: bare mentions that do not name a method. A class or free function
# label is specific enough to keep matching, and the class a later method
# mention needs must be on record before pass 2b runs.
# Pass 2a: classes and distinct identifiers (snake_case, camelCase, export PascalCase).
method_mentions: list[tuple[dict, str, str, float]] = []
function_mentions: list[tuple[dict, str, str, float]] = []
for rc in bare:
target, confidence, score = _target(rc)
if target is not None and _method_owner(target) is not None:
if target is None:
continue
if nodes_by_id.get(target, {}).get("_callable_class"):
_add(rc, target, confidence, score)
elif _method_owner(target) is not None:
method_mentions.append((rc, target, confidence, score))
else:
label = _symbol_label(nodes_by_id[target])
if label[:1].isupper():
prose_like = not _is_pascal_case_export_language(
nodes_by_id[target].get("source_file", ""))
else:
prose_like = _is_prose_like_label(label)
if prose_like:
function_mentions.append((rc, target, confidence, score))
else:
_add(rc, target, confidence, score)
# Pass 2b: bare method mentions require the owner class to be cited (#4609).
for rc, target, confidence, score in method_mentions:
chain = _section_chain(str(rc.get("caller_nid", "")))
cited = {t for c in chain for t in cited_targets.get(c, ())}
if _method_owner(target) in cited:
_add(rc, target, confidence, score)
# Pass 2b: a bare method name (#4609) is only evidence when the same
# document already cites the class that owns it. `redis` the server does not
# link to `Cache.redis` unless the document names `Cache`;
# `successWithWarnings` survives because `HandlerResult` is cited next to it.
for rc, target, confidence, score in method_mentions:
doc = _posix(str(rc.get("source_file", "")))
if _method_owner(target) in cited_targets.get(doc, ()):
# Pass 2c: bare prose-like free function names require defining file or symbol evidence (#4804).
for rc, target, confidence, score in function_mentions:
target_file = _posix(str(nodes_by_id.get(target, {}).get("source_file") or ""))
if not target_file:
continue
chain = _section_chain(str(rc.get("caller_nid", "")))
cited = {t for c in chain for t in cited_targets.get(c, ())}
if target_file in {f for c in chain for f in cited_files.get(c, ())} or any(
_posix(str(nodes_by_id.get(t, {}).get("source_file") or "")) == target_file
for t in cited
):
_add(rc, target, confidence, score)
+15 -1
View File
@@ -931,10 +931,24 @@ def _reconcile_markdown_links(
and not _is_file_node(target)
)
def _is_code_file_citation(edge: dict) -> bool:
"""A page -> source-file link citation minted by markdown resolution (#4804)."""
if edge.get("relation") != "references" or edge.get("target_file"):
return False
target = nodes_by_id.get(edge.get("target"))
source = nodes_by_id.get(edge.get("source"))
return (
target is not None
and target.get("file_type") == "code"
and _is_file_node(target)
and source is not None
and source.get("file_type") == "document"
)
def _keep_edge(edge: dict) -> bool:
if not (_is_ast_tier(edge) and edge.get("relation") == "references"):
return True
if _is_code_span_mention(edge):
if _is_code_span_mention(edge) or _is_code_file_citation(edge):
return True
owner = source_paths.normalize(edge.get("source_file"))
if owner not in parsed_sources:
+449 -6
View File
@@ -101,9 +101,16 @@ def test_code_span_mentions_are_classified():
# namespace root (`App\`) names no symbol at all.
for span in ("Foo::CONST", "Foo::class", "App\\", "C:\\Users\\me"):
assert _code_span_mention(span) is None, span
# Files, commands, expressions and prose are not symbol mentions.
for span in ("setup.py", "README.md", "notes.txt", "git revert", "x = 1", "a-b",
"--flag", "", "src/widget.py"):
# A source-file span classifies with an empty symbol chain, so resolution
# can record it as file evidence (#4804).
assert _code_span_mention("setup.py") == ("setup.py", [])
assert _code_span_mention("src/widget.py") == ("src/widget.py", [])
# A *document* span is not evidence (only code files are), so it is not a
# mention at all.
assert _code_span_mention("README.md") is None
assert _code_span_mention("docs/notes.mdx") is None
# Commands, expressions and prose are not symbol mentions.
for span in ("git revert", "x = 1", "a-b", "--flag", ""):
assert _code_span_mention(span) is None, span
@@ -358,11 +365,39 @@ def test_bare_method_with_parentheses_still_resolves(tmp_path):
assert (notes["id"], method["id"]) in _references(r)
def test_bare_function_mention_still_resolves_without_its_owner(tmp_path):
"""The extra owner test is scoped to methods; a free function label stays evidence (#4609)."""
def test_bare_lowercase_word_does_not_link_to_an_unrelated_function(tmp_path):
"""`token` the query parameter is prose, not a reference to token() in an unrelated JS file (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) {\n return name;\n}\n",
"docs/feed.md": "# Quote feed\n\nThe client sends the API key as the `token` query parameter.\n",
})
feed = _node(r, "Quote feed")
assert {t for (s, t) in _references(r) if s == feed["id"]} == set()
def test_bare_function_mention_survives_when_the_document_cites_another_symbol_from_its_file(tmp_path):
"""`token` next to `palette()` from the same file is a real reference (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"docs/feed.md": "# Quote feed\n\nWalks through charts, mentions `palette()` and then `token`.\n",
})
feed = _node(r, "Quote feed")
token = _node(r, "token()", "charts.js")
palette = _node(r, "palette()", "charts.js")
assert (feed["id"], token["id"]) in _references(r)
assert (feed["id"], palette["id"]) in _references(r)
def test_bare_function_with_parentheses_still_resolves(tmp_path):
"""A trailing () is explicit evidence, so defining file does not need another symbol cited (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "def deploy():\n pass\n",
"notes.md": "# Notes\n\nRun `deploy` after the tests.\n",
"notes.md": "# Notes\n\nRun `deploy()` after the tests.\n",
})
notes = _node(r, "Notes")
@@ -370,6 +405,33 @@ def test_bare_function_mention_still_resolves_without_its_owner(tmp_path):
assert (notes["id"], deploy["id"]) in _references(r)
def test_bare_function_survives_when_a_class_in_its_file_is_cited(tmp_path):
"""`deploy` next to `Deployer` in the same file is a real reference (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "class Deployer:\n pass\n\ndef deploy():\n pass\n",
"notes.md": "# Notes\n\nUse `Deployer` then run `deploy`.\n",
})
notes = _node(r, "Notes")
deploy = _node(r, "deploy()", "deploy.py")
assert (notes["id"], deploy["id"]) in _references(r)
def test_function_evidence_cited_in_another_document_does_not_count(tmp_path):
"""The file-symbol evidence is per document: one doc's mention cannot license another's (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"a.md": "# A\n\nUses `palette()`.\n",
"b.md": "# B\n\nSends `token`.\n",
})
b = _node(r, "B")
assert {t for (s, t) in _references(r) if s == b["id"]} == set()
def test_owner_cited_in_another_document_does_not_count(tmp_path):
"""The owner evidence is per document: one doc's mention cannot license another's (#4609)."""
r = _extract(tmp_path, {
@@ -442,3 +504,384 @@ def test_dotted_mention_resolves_when_method_name_is_a_builtin(tmp_path):
# The builtin-named `.open()` must resolve just like `.connect()`.
assert repo_open["id"] in cited
assert repo_connect["id"] in cited
def test_bare_function_survives_when_file_is_cited(tmp_path):
"""Naming the defining file (span or link) licenses a bare function (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/span.md": "# Span\n\n- `web/charts.js` — uses `token` to read styles.\n",
"docs/link.md": "# Link\n\nSee [charts](../web/charts.js). Uses `token`.\n",
})
token = _node(r, "token()", "charts.js")
span_node = _node(r, "Span")
link_node = _node(r, "Link")
refs = _references(r)
assert (span_node["id"], token["id"]) in refs
assert (link_node["id"], token["id"]) in refs
def test_two_bare_functions_from_one_file_with_no_other_citation_yield_no_edge(tmp_path):
"""Two bare prose-like names cannot circularly license each other without evidence (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"notes.md": "# Notes\n\nCalls `palette` then `token`.\n",
})
notes = _node(r, "Notes")
assert {t for (s, t) in _references(r) if s == notes["id"]} == set()
def test_bare_function_resolves_when_class_is_cited_after_it_in_document(tmp_path):
"""Pass 2a/2c ordering ensures license is document-scoped, not reading-order dependent (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "class Deployer:\n pass\n\ndef deploy():\n pass\n",
"notes.md": "# Notes\n\nRun `deploy` first. Then use `Deployer`.\n",
})
notes = _node(r, "Notes")
deploy = _node(r, "deploy()", "deploy.py")
deployer = _node(r, "Deployer", "deploy.py")
refs = _references(r)
assert (notes["id"], deploy["id"]) in refs
assert (notes["id"], deployer["id"]) in refs
def test_bare_function_survives_with_path_qualified_evidence(tmp_path):
"""A path-qualified class citation licenses a bare function from that file (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "class Deployer:\n pass\n\ndef deploy():\n pass\n",
"notes.md": "# Notes\n\nSee `deploy.py::Deployer`. Then run `deploy`.\n",
})
notes = _node(r, "Notes")
deploy = _node(r, "deploy()", "deploy.py")
assert (notes["id"], deploy["id"]) in _references(r)
def test_target_with_no_source_file_is_safely_skipped():
"""A callable target without a source_file sentinel is skipped without error (#4804)."""
from graphify.markdown_resolution import resolve_markdown_mentions
per_file = [{"raw_calls": [
{"caller_nid": "doc_notes", "callee": "sourceless", "language": "markdown",
"context": "sourceless", "source_file": "notes.md", "source_location": "L1"},
]}]
nodes = [
{"id": "doc_notes", "label": "Notes", "file_type": "document", "source_file": "notes.md"},
{"id": "code_sourceless", "label": "sourceless()", "file_type": "code",
"_callable": True, "source_file": ""},
]
edges: list[dict] = []
resolve_markdown_mentions(per_file, nodes, edges)
assert not [e for e in edges if e.get("relation") == "references"]
def test_nested_class_resolves_standalone(tmp_path):
"""A nested class is a class, not a method; it resolves without outer class cited (#4804)."""
r = _extract(tmp_path, {
"tree.py": "class Outer:\n class Inner:\n pass\n",
"notes.md": "# Notes\n\nUse `Inner`.\n",
})
notes = _node(r, "Notes")
inner = _node(r, "Inner", "tree.py")
assert (notes["id"], inner["id"]) in _references(r)
def test_bare_function_with_snake_case_or_camel_case_resolves_without_file_citation(tmp_path):
"""Distinct code identifiers (snake_case or camelCase) resolve standalone (#4804)."""
r = _extract(tmp_path, {
"build.py": (
"def deduplicate_by_label():\n pass\n\n"
"def buildFromJson():\n pass\n"
),
"notes.md": (
"# Notes\n\n"
"Calls `deduplicate_by_label` and `buildFromJson`.\n"
),
})
notes = _node(r, "Notes")
dedup = _node(r, "deduplicate_by_label()", "build.py")
build_json = _node(r, "buildFromJson()", "build.py")
refs = _references(r)
assert (notes["id"], dedup["id"]) in refs
assert (notes["id"], build_json["id"]) in refs
def test_bare_function_mention_survives_when_symbol_itself_cited_with_parentheses(tmp_path):
"""An explicit () mention under h1 licenses a bare mention under h2 (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function palette() { return 'dark'; }\n",
"docs/guide.md": (
"# Overview\n\n"
"Call `palette()` to configure theme.\n\n"
"## Details\n\n"
"Reads `palette` for current colors.\n"
),
})
overview = _node(r, "Overview")
details = _node(r, "Details")
palette = _node(r, "palette()", "charts.js")
refs = _references(r)
assert (overview["id"], palette["id"]) in refs
assert (details["id"], palette["id"]) in refs
def test_link_to_scanned_source_file_is_a_reference_and_licenses_bare_mentions(tmp_path):
"""A link to a scanned source file is a doc->file edge AND licenses a bare mention (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": "# Guide\n\nSee [charts](../web/charts.js). Sends `token`.\n",
})
guide = _node(r, "Guide")
token = _node(r, "token()", "charts.js")
charts_file = _node(r, "charts.js", "charts.js")
page = _node(r, "guide.md")
refs = _references(r)
assert (guide["id"], token["id"]) in refs
# The link itself is a real reference from the page to the scanned file
# node — EXTRACTED, since the document names the file verbatim.
assert refs[(page["id"], charts_file["id"])]["confidence"] == "EXTRACTED"
def test_extract_markdown_records_a_source_file_link_as_a_citation(tmp_path):
"""The citation rides the markdown raw-call channel with only `path`, so the
corpus-aware resolver can decide edge vs evidence-only (#4804)."""
doc = tmp_path / "docs" / "guide.md"
doc.parent.mkdir()
doc.write_text("# Guide\n\nSee [charts](../web/charts.js) and `token`.\n")
r = extract_markdown(doc)
assert all(e["relation"] == "contains" for e in r["edges"])
page = next(n for n in r["nodes"] if n.get("node_kind") == "page")
citations = [rc for rc in r["raw_calls"] if rc["callee"] == "" and rc.get("path")]
assert [(rc["caller_nid"], rc["path"]) for rc in citations] == [
(page["id"], "../web/charts.js")]
assert all(rc.get("file_link") for rc in citations)
# The symbol mention still travels as a normal markdown raw call.
assert [rc["callee"] for rc in r["raw_calls"] if rc.get("path") is None] == ["token"]
def test_link_to_unscanned_source_file_yields_no_edge_or_phantom(tmp_path):
"""A link to a source file outside the corpus is evidence only, never a dangling edge."""
outside = tmp_path / "outside" / "script.py"
outside.parent.mkdir()
outside.write_text("def run():\n pass\n")
r = _extract(tmp_path, {"docs/guide.md": "# Guide\n\nSee [script](../outside/script.py).\n"})
assert r["edges"] == [e for e in r["edges"] if e["relation"] == "contains"]
def test_wikilink_to_scanned_source_file_yields_only_a_file_edge(tmp_path):
"""An Obsidian wikilink naming a scanned source file is a page->file reference."""
r = _extract(tmp_path, {
"setup.py": "def setup():\n pass\n",
"docs/guide.md": "# Guide\n\nSee [[setup.py]].\n",
})
page = _node(r, "guide.md")
setup_file = _node(r, "setup.py", "setup.py")
assert set(_references(r)) == {(page["id"], setup_file["id"])}
def test_single_word_pascal_case_function_resolves_standalone(tmp_path):
"""An exported Go/C#/Swift entry point (`Serve`) is a distinct identifier, not prose (#4804)."""
r = _extract(tmp_path, {
"worker.go": "package worker\n\nfunc Serve() {}\n",
"docs/guide.md": "# Guide\n\n`Serve` starts the server.\n",
})
guide = _node(r, "Guide")
serve = _node(r, "Serve()", "worker.go")
assert (guide["id"], serve["id"]) in _references(r)
def test_single_word_lowercase_function_still_needs_evidence(tmp_path):
"""The PascalCase exemption does not loosen the prose-like test (`serve`)."""
r = _extract(tmp_path, {
"worker.go": "package worker\n\nfunc serve() {}\n",
"docs/guide.md": "# Guide\n\n`serve` starts the server.\n",
})
guide = _node(r, "Guide")
assert {t for (s, t) in _references(r) if s == guide["id"]} == set()
def test_file_citation_evidence_survives_a_rebuild(tmp_path):
"""A source-file link's citation comes from the cached fragment, so a rebuild keeps the edge."""
from graphify.watch import _rebuild_code
corpus = tmp_path / "corpus"
(corpus / "docs").mkdir(parents=True)
(corpus / "web").mkdir()
(corpus / "web" / "charts.js").write_text(
"export function token(name) { return name; }\n")
doc = corpus / "docs" / "guide.md"
doc.write_text("# Guide\n\nSee [charts](../web/charts.js). Sends `token`.\n")
graph_path = corpus / "graphify-out" / "graph.json"
def reference_edges():
links = json.loads(graph_path.read_text(encoding="utf-8"))["links"]
return {(e["source"], e["target"]) for e in links
if e.get("relation") == "references"}
assert _rebuild_code(corpus, no_cluster=True, acquire_lock=False) is True
expected = reference_edges()
# Two edges: the doc->file link reference and the licensed mention edge.
assert len(expected) == 2
doc.write_text(doc.read_text() + "\nStill `token`.\n")
assert _rebuild_code(corpus, changed_paths=[doc], no_cluster=True,
acquire_lock=False) is True
assert reference_edges() == expected, "document re-extracted"
# The citation now comes from the document's cached fragment, so a code-side
# rebuild must still resolve the mention.
(corpus / "web" / "charts.js").write_text(
"export function token(name) { return name; }\n"
"export function palette() { return 'dark'; }\n")
assert _rebuild_code(corpus, changed_paths=[corpus / "web" / "charts.js"],
no_cluster=True, acquire_lock=False) is True
assert reference_edges() == expected, "code re-extracted"
def test_bare_function_mention_in_a_sibling_section_needs_its_own_evidence(tmp_path):
"""Evidence is section-scoped: a citation in one h1 does not license a sibling h1 (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"docs/guide.md": (
"# Charts\n\n"
"`palette()` configures the theme.\n\n"
"# Token notes\n\n"
"The API key travels as the `token` query parameter.\n"
),
})
token_notes = _node(r, "Token notes")
charts = _node(r, "Charts")
token = _node(r, "token()", "charts.js")
palette = _node(r, "palette()", "charts.js")
refs = _references(r)
# The explicit () citation resolves on its own.
assert (charts["id"], palette["id"]) in refs
# The sibling section's prose word gets no license from it...
assert {t for (s, t) in refs if s == token_notes["id"]} == set()
# ...but a nested section would: evidence at h1 licenses its h2 children.
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"docs/guide.md": (
"# Charts\n\n"
"`palette()` configures the theme.\n\n"
"## Colors\n\n"
"Reads `palette` for the current scheme.\n"
),
})
colors = _node(r, "Colors")
assert (colors["id"], palette["id"]) in _references(r)
def test_pascal_case_in_a_lowercase_convention_language_needs_evidence(tmp_path):
"""`Token` in Python is prose as often as not; only PascalCase-export languages skip the test (#4804)."""
r = _extract(tmp_path, {
"build.py": "def Token():\n pass\n",
"notes.md": "# Notes\n\n`Token` builds the response.\n",
})
notes = _node(r, "Notes")
assert {t for (s, t) in _references(r) if s == notes["id"]} == set()
# With the defining file cited, the same mention resolves.
r = _extract(tmp_path, {
"build.py": "def Token():\n pass\n",
"notes.md": "# Notes\n\nSee `build.py`. `Token` builds the response.\n",
})
notes = _node(r, "Notes")
token = _node(r, "Token()", "build.py")
assert (notes["id"], token["id"]) in _references(r)
def test_file_span_is_evidence_but_not_a_doc_file_edge(tmp_path):
"""A source-file code span licenses bare mentions; only a link is a doc->file reference (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/span.md": "# Span\n\n- `web/charts.js` — uses `token` to read styles.\n",
})
span_node = _node(r, "Span")
token = _node(r, "token()", "charts.js")
refs = _references(r)
assert (span_node["id"], token["id"]) in refs
assert len(refs) == 1, "a span is evidence, not a link: no doc->file edge"
def test_cited_file_fallback_respects_explicit_relative_discipline():
"""The suffix fallback fires only under detected path-form mixing (#4804)."""
from graphify.markdown_resolution import _match_cited_file_any_form
sources = {"web/charts.js"}
# Uniform path forms: an explicit ../ cite resolves against the citing
# document's directory only — even when the doc sits outside the corpus
# root and a corpus file shares the tail (#4804's discipline).
assert _match_cited_file_any_form(
"../web/charts.js", "/other/docs/guide.md", sources,
form_mismatch=False) is None
# An absolute citing document against a relative corpus is exactly the
# partial-rebuild mixing the fallback exists for.
assert _match_cited_file_any_form(
"../web/charts.js", "/repo/docs/guide.md", sources,
form_mismatch=True) == "web/charts.js"
def test_escaping_citation_does_not_match_in_corpus_file():
"""An explicit cite escaping the scan root does not match an in-corpus file."""
from graphify.markdown_resolution import _match_cited_file_any_form
sources = {"web/charts.js"}
assert _match_cited_file_any_form(
"../../outside/web/charts.js", "/repo/docs/guide.md", sources,
form_mismatch=True, scan_root="/repo",
) is None
def test_source_file_link_in_heading_does_not_license_sibling_heading(tmp_path):
"""A source-file link licenses mentions in its own section, not sibling sections."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": (
"# Charts\n\n"
"See [charts](../web/charts.js).\n\n"
"# Authentication\n\n"
"Sends `token` for auth.\n"
),
})
auth = _node(r, "Authentication")
token = _node(r, "token()", "charts.js")
assert (auth["id"], token["id"]) not in _references(r)
def test_missing_source_link_does_not_reference_other_files(tmp_path):
"""An inline Markdown link to a missing path does not fall back to unrelated files."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": "# Guide\n\nSee [charts](web/charts.js).\n",
})
page = _node(r, "guide.md")
charts_file = _node(r, "charts.js", "charts.js")
assert (page["id"], charts_file["id"]) not in _references(r)