GitNexus/.github/scripts
Mick Cooney 62115ab04f
feat(r): add R language support (#3513)
* docs(r): document that namespace-qualified S4 constructors are not recognised

Review finding: `methods::setClass(...)` is ignored by the S4 field detector.
Confirmed by test, and wider than fields: every S4/RefClass pattern
(setClass, setRefClass, setGeneric, setMethod in R_QUERIES, plus the field and
method extractors) requires a bare identifier callee, so a namespace_operator
callee creates no class, slot, generic or method. R6::R6Class is supported.

Widening touches nine files (queries, naming-argument, captures, owner hooks,
post-parse, scope resolver, both extractors) and the qualifier-veto logic, so
it is not a trivial change. Documented as a known limit in
docs/languages/r-provider.md and pinned by characterisation tests in
r-definition-anchors.test.ts (each paired with its unqualified control).

* fix(r): charge the start-state filter to the matcher work budget

LinearRegex.seed() filtered the closure's character states against the start
character before charging only 1 + (accepting states), so the range scans of
the failed state tests were free. A pattern of a few large character classes
could be probed with distinct start characters (each a filter miss, memoised
only up to 4096 keys) at almost no recorded cost.

Reproduction: for 20 alternated classes of 200 ranges, one miss on a
non-matching name recorded work 1 (expected >= 4000 range checks); a loop of
600 distinct start characters never exhausted a 1,000,000 budget. The filter
now charges 1 + ranges.length per examined state on a cache miss; hits stay
cheap. New tests in r-export-pattern-shared-budget.test.ts.

* fix(r): skip the body of an `else if` in NAMESPACE as conditional

skipConditionalBody returned just after the `if` of `else if (cond) body`, so
the main scan then read `(cond)` as stray text and emitted the body's
importFrom, S3method, export, exportClasses, exportMethods and exportPattern
directives as unconditional (the same for `if (a) if (b) body`).

Reproduction: 12 new cases in r-namespace-parser.test.ts failed on the
unfixed scanner (e.g. `if (a) {} else if (b) importFrom(x, y)` returned x::y;
`else if (b) export(hidden)` exported `hidden`). The nested `if (cond)` is now
stepped over iteratively (no recursion, tested with 50,000 nested ifs) and the
body that follows it is skipped.

* fix(r): decode string literals in the rename dynamic-lookup guard

The R rename guard compared the raw text of each `string_content` node with the
old and new name. An escaped spelling (`"f\u006fo"`, `'f\x6fo'`, octal) keeps
its escape inside string_content, and a raw string (`r"(foo)"`) has no
string_content node at all, so renaming `foo` proceeded while a get() or
do.call() on the escaped or raw spelling still resolved the old name.

Reproduction: 10 cases in the new test/unit/r-rename-string-guard.test.ts
returned 'ok' instead of unsupported_occurrence on the unfixed provider, and the
two new fixtures string-lookup-escaped and string-lookup-raw (rename-provider-r)
renamed successfully on the unfixed build. The guard now decodes each `string`
node (escapes, octal, raw strings) and compares the value.

docs/languages/r-provider.md said "spelled as a string literal"; it now states
the whole-value rule and what is still not detected (substring, paste0(),
non-indexed files).

* fix(r): limit library() wildcard expansion to top-level definitions

expandRWildcardNames walked the flat localDefs of the target file and filtered
only dotted names, so a function nested inside another function
(`outer <- function() { helper <- function() 1 }`) was offered as a
package-level name to every file that calls library()/require() on the package.

Reproduction: two new cases in r-dotted-s3-hooks.test.ts failed on the
unfixed code (['outer', 'helper', 'top'] instead of ['outer', 'top'];
['a', 'b', 'c', 'd'] instead of ['a']). The expansion now keeps only names bound
at module scope (rFileTopLevel().names, which already feeds the dotted-tail
guard); top-level functions and bare-call S4/R6 classes are still listed
(controls added; test/integration/resolvers/r.test.ts unchanged and green).

* fix(r): bind roxygen @param types for dotted formal names

parseRoxygenParams read the parameter name with `\w+`, which stops at the first
dot, so `#' @param na.rm Data` documented nothing and the formal got no type
(the old unit test pinned that as "does not bind a dotted parameter name").

Reproduction: four new cases in type-env-r.test.ts (na.rm, .data,
max_n.rows, braced form with a continuation line) returned undefined instead of
'Data' on the unfixed pattern. The name pattern is now `[\w.]*\w[\w.]*`, so a
dotted identifier matches while `...` and `x,y` stay unbound; the former
"does not bind" case is replaced by positive cases plus a not-a-formal control.

* docs: count the audited tree-sitter peers as nine

AUDITED_PEERS in scripts/prepare-tree-sitter-bundle.cjs lists nine manifests
since @eagleoutice/tree-sitter-r was added (r, c, cpp, java, php, ruby, rust,
javascript, typescript); CONTRIBUTING still said eight.

* docs(r): mention CFG and rename in the README R paragraphs

Both R paragraphs now say that --pdg builds a control-flow graph for R and that
rename is conservative. The shared Control flow paragraph no longer implies
reaching definitions for R, which has control flow only.

* chore(deps): record the audited 0.25.1 tree-sitter peer for the R grammar

CONTRIBUTING.md (Native tree-sitter npm packages) requires the lockfile to pin
the audited grammars' tree-sitter peer to exactly 0.25.1, as it already does for
c, cpp, java, php, ruby, rust and typescript. The R grammar entry still carried
upstream's ^0.21.0. Only the peer range changes; the upstream peerDependenciesMeta
(including its tree_sitter key typo) is untouched.

Checked: npm ci --dry-run --ignore-scripts passes in the repository root and in
gitnexus/, npm ls --depth=0 reports nothing invalid, and a fresh npm pack
(including prepack) installed into an isolated prefix passes
scripts/assert-native-parsers.mjs (20 grammars, R included) with the R
manifest's peer at 0.25.1.

* test(r): raise the worker readiness timeout in R worker-backed tests

A reviewer's focused R run hit two worker-startup timeouts and had to rerun
with a 30-second readiness setting. The worker pool waits only 5 seconds by
default (GITNEXUS_WORKER_READY_TIMEOUT_MS), and every R test that parses
through the real worker pool started cold against that budget, unlike
csharp-razor-view-components and structural-pair-coverage, which already
raise it.

Apply the same idiom to the R tests that spawn the pool: stub the variable to
60000 in beforeAll and restore it with vi.unstubAllEnvs() in afterAll. Covers
r-worker-owner-absence, cfg/r-cfg-join, r-post-parse-gating, and the
resolvers/r*.test.ts files. rename-provider-r goes through
rename-integration-cases.ts, which already passes a 15-second budget to its
child process, so it is unchanged.

Tests only; no production code, schema or parse-cache change.

* perf(r): binary-search character classes in the linear regex matcher

inSet() scanned a class's ranges from the front on every state visit, but the
search loop charged one unit per visit regardless of class size, so a wide
class multiplied real work the budget never counted. Ranges are sorted,
merged and disjoint for every CharSet (normalise() for written classes,
constants and complement() for escapes), so a binary search is equivalent.
Charged work is unchanged.

Tests pin the reads per visit, the edges of a large class and the charged
work counters.

* fix(r): make the roxygen @param name and package qualifier parsing linear

The @param name pattern [\w.]*\w[\w.]* backtracks quadratically on a long
name followed by anything but a blank (32,000 characters took about half a
second per line), and parseRQualifier's lazy [\s\S]*? does the same on a
long run of blanks. Match [\w.]+ and require a word character separately,
and take the text before the first '::' directly. Accepted inputs and
results are unchanged (checked against the old patterns on two million
generated strings).

Tests cover large adversarial inputs and the dotted formal names.

* docs(r): correct stale wildcard-expansion and escape-digit comments

Three comments named rProvider.expandsWildcardTo, which does not exist for R:
the pipeline consumes the hook from the ScopeResolver, so point them at
rScopeResolver.expandsWildcardTo. State the \x, \u and \U digit limits in
unescapeRString's comment, which are those of R's own parser.

Comments only.

* docs(r): correct the R provider guide and the type-resolution matrix

r-provider.md: state that an empty or missing if arm is the header's seq
edge (control dependence labels it as the complement of the other arm);
extend the bare-callee limit to library(), require() and source(); say that
NAMESPACE raw strings and strings spanning lines are dropped without a
warning, which the logged-warning sentence did not cover; name the language
registrations that do mention R; give the devtools::load_all() rationale for
the unfiltered library() wildcard.

type-resolution-system.md: R binds no declaration, call-result or
method-call-result types (extractDeclaration is empty and there is no
extractPendingAssignment), and its cross-file propagation is partial, with a
test cited. Drop R from the footnote about synthesizeWildcardImportBindings(),
which does not exist.

* fix(r): qualify R6, RefClass and S4 member ids with their class

Member ids carried no owner, so a second class in one file that shared a
member name with an earlier one (push, items, a setMethod generic, a slot)
minted the same id as the first and lost the member, along with its
HAS_METHOD or HAS_PROPERTY edge.

Register resolveDetachedOwnerName for R. It names the class declared by an
ancestor R6Class assignment, setClass or setRefClass call, or the signature
class of a setMethod call, so ids become Method:<file>:Stack.push#n and
Property:<file>:Stack.items. The owner edge is still attached by postParse
through ownerNameHint. The change is R-only: the hook is optional and
undefined for every other language.

The r-packages characterisation counts now include Child.greet, the member
the id collision used to drop.

* fix(r): read the formals of R6 and RefClass methods

extractRParameters tested for identifier and argument nodes, but the grammar
emits one parameter node per formal, so it always returned an empty list.
Every R6 and RefClass method therefore had parameterCount 0 and a #0 id, and
a variadic method was not marked variadic.

Read the parameter nodes: the name field gives the formal, a default makes it
optional, and a dots name makes it variadic (such a method has no count and
no arity tag in its id).

* fix(r): attach R members only to classes defined in R

attachDeferredROwners resolved the owner hint through the class registry,
which every language shares. A Python class Circle next to an R Circle made
the name ambiguous, so the R methods and slots lost their HAS_METHOD and
HAS_PROPERTY edges; and with no R Circle, an R setMethod attached to the
Python class.

Keep only candidates whose graph node is an R class before the uniqueness
test. The change is inside R's postParse hook, so shared code is untouched.

* fix(r): read slots and fields given as c(...) vectors

The slot pattern matched only list(...) and representation(...), although
the field extractor accepts any call, so setClass("A", slots = c(a =
"numeric")) and setRefClass("R", fields = c(...)) created no Property nodes.

Accept c(...) for both. An unnamed string in slots = c("a", "b") or
fields = c("a", "b") names an untyped member, as in R; an unnamed string in
representation(...) or list(...) is still not a member. The new pattern
captures its callee as @_vecOwner, so the class-naming capture filter does
not mistake these strings for the class name.

* fix(r): match backtick-quoted definitions against NAMESPACE export entries

export(`%+%`) names the symbol %+%, while the definition node keeps its
spelling `%+%`, so the export check never matched and the function was
flagged as not exported (the same for exportPattern()). Compare the symbol
through one shared helper, rBareName.

* fix(r): bind roxygen @param tags to formals written in backticks

A formal written `data` in backticks never matched the tag @param data, so
its documented type was dropped. Look the tag up by the symbol.

* fix(r): rename functions through their backtick-quoted spellings

A backticked name is an identifier whose text keeps its backticks, so the
rename provider never matched `helper`(x) with helper. The call was left
behind, and a local `helper` <- function(...) was not seen as a shadow, so
a call to the local function was silently renamed. Match occurrences,
claims and bindings on the symbol, and compare the symbol in the safety
checks.

* fix(r): strip backticks from NAMESPACE export entries in linear time

The pattern /^`+|`+$/g is quadratic on an entry such as x, a long run of
backticks, then y; the entry is repository-controlled text read on every
importFrom lookup of a name the package does not export. Trim with two scans.

* perf(r): scan NAMESPACE conditional blocks in linear time

An unterminated `{` after an `if` scanned to the end of the file, and the
resynchronisation then landed inside the region just scanned, so a file of
`if (a) {` lines with no `}` was quadratic (300 KB took 8.8 s, and the file is
parsed several times per analysis). Index where every block ends in one pass
and answer each block from the index. Parsing results are unchanged.

* fix(r): reject POSIX class names that Object.prototype also has

[[:constructor:]], [[:toString:]] and [[:__proto__:]] resolved on the
prototype chain and spliced function source text into the pattern, so the
pattern compiled to garbage instead of being rejected as an unknown class
and reported as dropped. Look classes up as own properties.

* fix(r): read the DESCRIPTION Package field past a byte-order mark

A UTF-8 byte-order mark before `Package:` hid the package, so its qualified
calls were dropped as external. And `\s*` crossed a newline, so an empty
`Package:` field captured the next line's `Version:` as the package name.
Strip the mark and keep the value on the field's own line.

* fix(r): type R6 field defaults that are typed NA constants

The grammar parses NA, NA_integer_, NA_real_, NA_character_ and NA_complex_
as `na` nodes, not identifiers, so the identifier branch never ran and no
type was inferred. Type them as integer, numeric, character and complex, and
plain NA as logical.

* perf(r): look up a wildcard import's target file in a per-pass index

expandRWildcardNames scanned every parsed file with find() for each
library() edge (450,000 edges over 3,000 files took 5.9 s). Build the
module-scope lookup once per pass, as the C, C++ and Python providers do.

* docs(r): list exportClassPattern() as not read

The directive is not tokenised, so a class exported only through it reads as
not exported. Say so under the NAMESPACE limits.

* fix(r): order merged bindings by code unit, not by locale

rMergeBindings sorted same-tier bindings with localeCompare, whose order
follows the machine's locale. Compare node ids by code unit, as the package
discovery does.

* fix(r): read RefClass methods of an unassigned setRefClass call

The method patterns required `A <- setRefClass(...)`, so a bare
`setRefClass("A", methods = list(...))` produced the Class and its fields
but no Method. The method extractor and the class owner lookup never needed
the assignment; match the call itself in both queries.

* docs(r): state how backtick-quoted names resolve

A call and its definition must spell a backticked name alike to be linked,
and importFrom() of a backtick-defined function does not bind. NAMESPACE
exports and rename match the symbol either way.

* fix(r): bind importFrom() of a backtick-quoted definition

A function written in backticks keeps them in its binding key and on its
node, while NAMESPACE entries and importFrom() carry the bare symbol, so
importFrom(pkg, `%||%`) found no defining file and the call degraded to
the name-based guess, which cannot tell two packages' `%||%` apart.

rFileTopLevel now keys the top-level names by symbol (rBareName) and
records the spellings it saw. resolveRNamedImport looks files up by
symbol, populateRNamespaceImports synthesises the import with the
definition's own spelling (one per spelling the provider uses) and lets
a backtick-defined function of the caller package mask its import. The
global-name-fallback veto and the pkg::name() lookups compare symbols.
The dotted-tail guard still compares the name as written, which is how
finalize indexes it. Names without backticks answer exactly as before,
pinned by a characterisation snapshot recorded before the change.

* fix(r): refuse a rename target name that registers an S3 method at any dot

The guard looked only at the text before the first dot, so
to.json.foo (a method of the dotted generic to.json) passed, and base
generics such as print, format, summary and plot were never checked
unless the sources defined them. Every dot-separated prefix of the new
name is now tested against the functions the indexed sources define and
a small list of base generics.

* fix(r): refuse renaming a function that is also assigned with <<-

A <<- inside a function is a global re-definition that the scope graph
keeps as a second declaration of the same name. A rename dropped the
selected function and its calls but left the superassignment, so after
the rename the function wrote a new global of the old name instead of
replacing the renamed one. The top-level form was already refused by
the engine; checkSafety now refuses any <<- or ->> to the name, in or
out of a function, with the same ambiguous_reference code.

* fix(r): rename a call that a non-function parameter of the same name does not shadow

R skips a binding that is not a function when it looks up the callee of
f(x), but the rename provider claimed every parameter, so a call under
function(x, helper = 2) was left unrenamed and failed after the rename.

A parameter whose default is a constant and which the body never assigns
is no longer claimed, so the call is renamed with the function it
reaches. A parameter that may hold a function (a function or computed
default, or an assignment to it in the body) is claimed as before, and
a call of the name under it is refused as ambiguous_reference, since it
may reach either. A parameter without a default that is called stays a
function-valued parameter and its call is left alone.

* fix: name the published grammar package in the parser-unavailable hint

The warning for a language whose grammar could not be loaded told the
user to run npm rebuild tree-sitter-<language>. R's grammar is published
as @eagleoutice/tree-sitter-r, so the hint named a package that does not
exist. The grammar loader now keeps a small map of grammars published
under another name, and every other language gets the same hint as
before.

* docs: count 19 providers in the local import scoping guide

The guide said 18-provider registry. The providers table in
languages/index.ts has 19 entries with R, one per SupportedLanguages
value (counted from the built registry: Object.keys(providers).length).

* docs: link the R provider guide from ARCHITECTURE.md related docs

The Objective-C provider guide is listed there; the R guide, which
AGENTS.md and both READMEs already link, was not.

* test(r): state the real CI behaviour of the worker owner-absence guard

The header said the suite hard-fails on CI like the other worker-backed
suites. Only object-literal-owner-resolution shares that tripwire; the
others skip silently when dist/ is missing. The header now says so, and
that the integration tier builds dist/ first.

* test(r): count 23 hinted members in r-packages

Member ids carry their class since fc32e539, so the two greet methods of
Parent and Child in s4_and_r6.R are two nodes instead of one. The
owner-absence test sits outside the R test set script and kept the old
count of 22.

* test(r): pin the cross-file and R6 method rename refusals

The guide documents ambiguous_reference for an unqualified call into
another file and a refusal for R6 methods, but no fixture covered
either. Add both. The R6 method is refused by the provider as a class
member (unsupported_occurrence); the guide wrongly listed it among the
shared engine's stale_graph refusals, which now name only dotted
functions and S4 classes.

* test(r): size the argument-scaling guard so the small run is measurable

The ratio guard divided by a 15 ms floor on the small run, so shapes whose
small run took 1 to 2 ms (comments before the naming argument) could hide
a quadratic regression that cost less than 150 ms at 8,000 arguments. The
small size now doubles from 2,000 until its fastest run lasts 20 ms, and
the large run stays four times that size, so the ratio is taken between
runs long enough to measure. The largest shape runs for about 2.4 s.

* test: count the bundled R grammar in the ARM64 bundle repair test

* test(cache): allow scoped grammar packages in the packageName audit

* docs(r): point parser-change guidance at the automatic cache identity

* fix(r): treat only <-, <<- and = as assignments when reading definitions

The R grammar gives every infix operator one binary_operator node. The
definition and scope queries, the R6 owner checks and the type-binding
scanners matched it on shape alone, so x + R6Class(...), x == function() 1
and obj == Foo$new() declared a class, a function and a type binding.

Constrain every binary_operator query pattern to operator
["<-" "<<-" "="] and check the same operator in the field and method
extractors' R6 owner test, the constructor scanner, the roxygen formal
binder and the local class-name collector.

* fix(r): decode octal escapes in NAMESPACE strings and unify the decoder

unescapeRString handled the single-character, hex and unicode escapes but
not R's \nnn octal escape, so exportPattern("^\101") reached the matcher as
^\101 (refused as a legacy octal escape) instead of ^A, and the pattern was
dropped. The rename string guard carried its own copy of the decoder that
did handle octal.

Decode one to three octal digits in unescapeRString (the low byte, with the
NUL escape kept verbatim as R rejects it), make the rename guard use it, and
apply it to quoted names in export() and S3method() as well so a NAMESPACE
string means what R reads. Backticked names keep an escaped backtick as
written, as before.

* test(r): pin that $ ends at the name and \8 stays a back-reference

The matcher refuses \1 to \9 because TRE reads them as back-references
whether or not the group exists, and $ matches only at the end of the name
as it does in JavaScript and TRE. Both are deliberate, so say so in the
header and the escape reader and pin them with tests, including the
RegExp oracle for $ before a final line terminator.

* docs(r): say that NAMESPACE refines graph nodes, not scope definitions

refineRExportStatus flips isExported on graph nodes only. The scope
definitions that finalization reads carry no export verdict for R
(undefined means unknown), which is deliberate: library() attaches every
top-level name, as devtools::load_all() does. State that in the provider
guide and pin it with a test, so a later change that stamps a verdict
onto scope definitions is a conscious one.

* fix(r): treat only functions as S3 generics in the rename guard

checkSafety collected every local definition into the set of possible
generics, so renaming a function to Widget.foo was refused when Widget was
an R6 or S4 class, or area.circle when area was only an R6 method. The
final NAMESPACE-export check likewise matched a member of the same name in
the same file. A class, method or property is not an S3 generic and has no
NAMESPACE export entry of its own; match functions only.

* fix(r): limit the VIRTUAL placeholder edge to S4 classes

emitRVirtualHeritageEdges treated every inherits reference named VIRTUAL
as the S4 sentinel contains = "VIRTUAL", so an R6 class with
inherit = VIRTUAL, an ordinary base class, also got an EXTENDS edge to the
synthetic placeholder node. Only a class declared by a naming call
(setClass, setRefClass) can carry the sentinel; require that of the
deriving class.

* fix(ci): encode the slash of a scoped package in the registry URL

npm_view_json interpolated the package name into the registry path, so
@eagleoutice/tree-sitter-r was requested as /@eagleoutice/tree-sitter-r/latest.
The registry serves that spelling today, but a scoped package is one path
segment with the slash encoded (@scope%2Fname). Quote the name, keeping the
leading @, and pin both the scoped and unscoped URLs in the tests.

* fix(r): accept only a syntactic name as a bare NAMESPACE argument

normaliseArg rejected whitespace, quotes, parentheses and = in a bare
directive argument, so foo+bar, x[1] or a$b was returned as a symbol name.
R reads a bare argument as a symbol; an operator or indexing expression is
not one, and only a quoted or backticked argument can spell such a name.
Accept a letter or dot followed by letters, digits, dots and underscores.

* docs(r): name the one other backtick normaliser in the bare-name header

The header said every comparison of a definition spelling with a symbol
goes through rBareName. The NAMESPACE export check in import-resolvers/r.ts
compares through its own stripBackticks, which removes every leading and
trailing backtick, not one pair. Say so. Comment only.

* fix(r): refuse a rename on the indexed NAMESPACE verdict, not on a flag the planner never saw

The rename planner built its graph from rows that carried no isExported, so the
provider's NAMESPACE check saw undefined for every node and refused every function
under R/, private ones included. The rows now carry the indexed isExported flag
when the column holds a boolean (no key otherwise), and the provider refuses only
a function the index did not prove private.

Positive fixtures rename a private package function (also under exportPattern);
negative fixtures cover exportPattern and an S3method third-argument registration.
A unit test runs the real refinement pass on a real graph, and a characterisation
test pins the row shape the planner receives.

* fix(r): refuse to rename an infix function or operator

An a %+% b use is an operator token, not an identifier, so renaming the
definition of a %op% function edited only the definition and left every infix
use calling a function that no longer exists. The old or the new name being an
infix function or an operator (`%+%`, `[[`) is now refused.

Fixtures cover an infix function used at top level and inside a function; a unit
test covers the operator spellings and a backticked name that stays renamable.

* fix(r): refuse a rename that would strand a replacement function

helper(z) <- 5 calls the replacement function helper<-, not helper, so renaming
the getter renamed the call in the assignment target and left the setter
unreachable under the new name, and renaming helper<- itself left every
helper(z) <- v calling a function that no longer exists.

Refused now: a call of the name anywhere in an assignment target (plain, nested
in $, [[, names(), attr(), or the -> forms), an old or new name ending in <-, and
a string-defined setter of either name. Four fixtures and a unit test cover each
form beside calls that are only read.

* fix(r): refuse a new name that is already a global

assertDeclarationCollisions is per file and function-only, so a rename onto a name
that a top-level variable already held (or assigned later) overwrote or was
overwritten by it, and a function of that name in another file became a second
global whose survivor depended on load order.

The provider now refuses a new name that is assigned at top level (<-, =, ->, a
for variable), assigned with <<- or ->> anywhere, or defined as a function in
another file. Local assignments, parameters and members of that name are still
allowed. Five fixtures and a positive control cover each form.

* fix(r): refuse a new name that the sources already read as a value

The engine protects the call form of a new name, but R's reference sites are calls,
so a plain read was invisible: sapply(x, paste), Reduce(max, x), x <- letters or a
default f = assist all kept compiling and silently started to mean the renamed
global.

The provider now refuses any identifier read of the new name that is not bound
locally: a parameter of an enclosing function covers a read, and covers a call only
when it has no default. Bound names, argument names, members ($, @) and qualified
names are not reads. Four fixtures and unit tests cover values, callees, formulas
and the allowed spellings.

* fix(r): refuse a new name that registers a method of a group or common generic

BASE_GENERICS missed the S3 group generics and many dispatching base functions, so
sum.items, Ops.money, Math.money, abs.diff, is.numeric.foo, as.complex.foo and
unlist.foo were accepted and silently registered as methods.

The list now has the Ops, Math, Summary, Complex and matrixOps groups with each
member, the is.* and as.* generics, and the common base, stats, graphics and utils
generics. Unit tests walk the documented group members, and two fixtures cover
Ops.money and sum.items.

* test(r): run the rename guard unit tests on a real knowledge graph

Four unit files handed checkSafety a graph whose forEachNode did nothing, so the
NAMESPACE branch could never be reached from them. They now build a real graph
(empty, or with one node of a chosen label for the member-versus-function case).

* docs(r): list the final rename refusals and the PDG answers R cannot give

The rename section now names each refusal the provider makes (NAMESPACE export
read from the indexed flag, infix functions and operators, replacement functions,
new-name collisions and value reads, group and common generics). The control-flow
section records that pdg_query flows, explain and impact --mode pdg return empty
answers for R without saying that R has no def/use harvest; the shared tools carry
no per-language capability signal, so this is documented rather than patched.

* fix(r): attach members to a class whose name is shared or defined twice

attachDeferredROwners left every member of a class unowned when more than one
class of that name was registered, including a class defined twice in one file
(one graph node registered twice) and the same helper class in R/ and tests/.

Candidates are now de-duplicated by node id. When several distinct classes
share the name, the member attaches to the one defined in its own file; if its
file defines none or several of them the member stays unowned, as before, and
one warning per call names the class names affected.

* fix(r): own a setMethod() written with signature() or c() by its first class

setMethod("show", signature("A"), ...) and c("A", "B") signatures named no
owner, so the methods of one generic on different classes collapsed into one
node and none had a HAS_METHOD edge.

The owner is the string in the first argument of a signature() or c() value,
named or not. A multi-class signature therefore belongs to its first class; a
first argument that is not a string still names no owner.

* fix(r): make the export-pattern nesting limit independent of JIT warm-up

MAX_NESTING was 2048, beyond what a cold process can recurse: a deeply nested
pattern failed with a stack overflow in a fresh process and compiled after a
warm-up, so whether a NAMESPACE pattern was in effect depended on the machine
and on what ran before it, and the reason given was misleading.

The limit is now 256, which still compiles on a quarter of the default stack,
so the verdict is the same cold or warm and carries the right reason.

* fix(r): charge a remembered export-pattern verdict to the work budget

A matcher answered a name it had already decided from its memo without any
charge, so asking thousands of matchers about the same few names (initialize,
print, show across many classes) cost time that no budget counted: 5,000
repeat calls over 12,000 matchers took 612 ms and charged nothing.

A memo hit now costs one visit, so the repeat is bounded by the shared budget
like every other cost, and the verdict itself is unchanged.

* fix(r): charge export patterns that are refused after their NFA was built

A pattern that expanded past the state cap was refused only after building up
to 16,384 states, yet it reserved no states, charged no work and did not close
the allowance, so the next such pattern started from scratch: 98 KB of
exportPattern("(a|b){8000}...") lines took 4.2 s while the budget counted
nothing, against the documented bound of about a second.

A refusal is now charged for what was built (eight visits per state or build
step), and a spent work budget refuses later patterns before they are parsed.
The guide also says that budget exhaustion while resolving importFrom() names
is not reported, because the scope resolver loads its own configuration.

* fix(r): name an S3method() of another package's generic after the generic

S3method(pkg::generic, class), the delayed-registration form roxygen2 writes
for @exportS3Method pkg::generic, registered no method at all when written
bare and the nonexistent "pkg::generic.class" when quoted, so the function
generic.class read as not exported and an importFrom() of it did not bind.

The generic is the text after the last :: or ::: outside quotes and
backticks, so the method is generic.class as R registers it.

* fix(r): keep installed libraries and ignored trees out of package discovery

Discovery read the disk on its own and skipped only renv, packrat, revdep and
.Rcheck, so an installed library under lib/, library/, .Rlibs/, vendor/ or
build/ registered its packages as repository packages (their qualified calls
then fell to the name-based guess instead of reading as external), and a tree
of ignored directories spent the 5,000-directory hidden-package budget and
made discovery read as incomplete.

Discovery now skips dot-directories and the directories the indexer itself
ignores (isHardcodedIgnoredDirectory), and a DESCRIPTION with a Built: field,
which only an installed package has, registers nothing and hides nothing. The
depth-3 and 200-directory bounds are pinned with their boundary values.

* fix(r): look up backticked NAMESPACE exports from a set built once

Resolving an importFrom() name that the provider's NAMESPACE does not export
walked every export entry before giving up, so a provider with 20,000 exports
and a caller importing 20,000 names took about two seconds, and NAMESPACE text
is the only bound.

The walk only looked for entries that start or end with a backtick (a quoted
"`%+%`" entry keeps them). Those are now collected in one pass per export set,
and a lookup is a set membership test; the answers are unchanged.

* fix(r): refuse a closure-local function as the unique-name fallback target

A function bound inside another function lives in that call's frame, so no
other function in its file or another can call it by its bare name. The
unique-name fallback ignored that: when the name was unique in the repository,
a bare call elsewhere bound to the closure-local function at 0.5.

The R fallback veto now refuses a function or class that the file's scope
model holds below the top level. A candidate the scope model does not hold, and
every top-level definition, are judged as before.

* fix(r): let the package attached last mask a name two library() calls define

Two library() calls that attach packages defining the same name bound the call
to whichever package file sorted first by id, so a script that attached lp2
after lp reached lp's function while R reaches lp2's.

rMergeBindings now keeps, within the wildcard tier, only the bindings of the
library() call that comes last in the file. A package of several files that
defines the name twice stays ambiguous, and a binding with no call position
leaves the tier as it was.

* fix(r): stop a call through a formal or loop variable at that name

A formal or a for variable bound no name in the scope model, so
function(data, transform) transform(data) was credited with a call of a
top-level transform() at 0.85, and the unique-name fallback made the same guess
across files.

Each function scope now publishes the names its formals and for loops bind as
lexical names, the shadowing barrier the scope model already has for a
parameter. A formal with a constant default that the body never assigns is left
out, because R skips a value that is not a function when it looks up a callee
(the rename provider reads it the same way).

* perf(r): answer package locality from an index of unowned package directories

rQualifierLocality scanned every parsed file path once per distinct pkg::
qualifier, so a run's work was qualifiers x files (4,000 x 5,000 took 0.84 s).

populateRQualifiedCalls now builds the set of <name>/R/ directory names that no
discovered package owns once, and each qualifier is a set lookup. The answers
are unchanged, and a call without the index still scans.

* docs: say that a new extension point is the one reason to touch shared code

The scope-resolution section says adding a language needs no changes to shared
code. R added two optional LanguageProvider hooks (postParse and
resolveMemberOwnerNode) that no other language implements, so the sentence now
names that case and points at the hook table.

* chore(deps): group the scoped tree-sitter-r grammar with the other grammars

The tree-sitter-grammars group matched tree-sitter-* only, so
@eagleoutice/tree-sitter-r would have been bumped in a pull request of its own
instead of with the other grammars.

* chore(r): drop an eslint-disable directive that suppresses nothing

ESLint reports it as unused with --report-unused-disable-directives; no other
file carries it above an ES import.

* docs(r): correct comments that contradict the code

The R provider header said library() and source() bring everything into scope
with no named imports and that imports are standard import nodes: source()
binds no name, NAMESPACE importFrom() produces named imports, and the import
captures come from the R scope query. The scope resolver said a bare member
call never reaches an R5 method and that R has no super, but RefClass methods
call siblings by bare name (unresolved today) and R6 has super$method().

* perf(r): read the roxygen block of a function once, not once per formal

extractParameter runs for each formal and re-collected and re-parsed the whole
comment block above the function every time, so work grew as formals x block
lines (2,000 formals under 2,000 @param lines took 11.9 s).

The parsed block is now kept per assignment node in the tree, as the file's
class names already are.

* refactor(r): state the R export default in the provider, not in shared code

rExportChecker was a shared export that only the R provider used, and it made
export-detection.ts differ from upstream for a function that returns true.
ObjectiveC already writes the same checker inline.

The provider now carries it as () => true with the reason beside it, and
export-detection.ts is byte-identical to upstream again.

* docs(r): list the call-resolution and class-handling gaps that are left as is

Each statement was reproduced against the code before it was written: self$m()
without a type binding, RefClass sibling calls, calls to generics and
generators, source() suffix matching, the library() edge fan-out, same-named
helpers in two packages, METHOD_OVERRIDES on parameter counts, calls inside
setMethod bodies, inherit = pkg::Base, string-named R6 members, nested function
ids, the TRE differences in export patterns and conditional NAMESPACE bodies.
Also says how a class name shared by several classes is owned and reported.

* docs(r): say which class owns a setMethod() written with a multi-class signature

* test(r): pin the documented export-pattern and discovery caps by literal

The caps in r-provider.md were asserted through the constants themselves, so changing a
cap, or the number the document gives, failed nothing. Pin each cap, check that the
document states the same number, and test the state cap, the pattern length cap, the
hidden-package scan budget and a spent matcher at their exact boundaries. Also pin the
backslash-u fallback to the letter u when fewer than four hex digits follow.

* fix(r): read contains= case-sensitively, and pin the VIRTUAL heritage edge

R matches argument names case-sensitively, so setClass("A", CONTAINS = "B") names no
base; the scope query linked it anyway. Drop the CONTAINS spelling from both predicates.

Pin the VIRTUAL placeholder: a class naming both a real base and VIRTUAL gets both edges
(the dedup set must be seeded only from edges that target the placeholder), the edge keeps
its confidence and reason, and running the heritage hook twice mints one node and one edge.

* test(r): pin the arity hook, the missing-config paths and the rebuild hint

rArityCompatibility had no test at all. populateRQualifiedCalls and
rFileBelongsToDiscoveredPackage are reached with no package config, and a run must not see
the previous run's answers; neither was asserted. The npm rebuild hint for the R grammar
names the scoped package; nothing checked it.

* test(r): compare a warm durable-cache run with a cold one

The deferred-owner pass and the NAMESPACE export refinement only ever ran cold in the R
tests. Analyse r-packages and r-package-layout twice, the second time from the saved parse
cache with no worker pool, and require the same definitions (isExported, ownerId) and the
same CALLS, EXTENDS, IMPORTS and member edges.

* test(r): pin the whole CALLS edge set of r-package-layout and r-packages

The layout fixture already holds callers in tests/, scripts/, vignettes/ and inst/, but only
their export status was asserted. Pin every CALLS edge, with reason and confidence, for both
projects, so a misdirected edge that keeps the count fails.

* test(r): pin the documented no-edge call shapes and the R6 dispatch limits end to end

Add the r-call-shapes fixture, a package that contains each shape r-provider.md says creates
no edge or node: lapply/Map/do.call/match.fun/get/registry/pkg::f as values, infix operators,
obj@slot, UseMethod/NextMethod, super$ and private$, inherit = pkg::Base, an inherited
self$ call, setClassUnion/setValidity/setReplaceMethod/Class$methods, roxygen @export,
exportClassPattern, renv parsing and the unread import forms. Positive controls sit beside
them, and the whole CALLS set is pinned.

* test(r): pin a cross-file rename, the paste0 gap and the number of R rename cases

The documented claim that a rename succeeds across files had only same-file successes behind
it, and the undetected paste0() lookup was unpinned. Add a qualified pkg::name() cross-file
rename and a run-time-built lookup name, and count the R cases so that an emptied fixture
directory cannot leave the suite green with no test.

* test(r): pin the control flow the CFG visitor documents as not modelled

Control flow inside an expression (y <- if, switch, &&, ||, ifelse, return() or break inside
tryCatch/local), stop(), on.exit() and tryCatch handlers stay one block, and a break or next
outside a loop falls back to EXIT. Nothing exercised these forms.

* test(r): record that a NAMESPACE-only edit leaves isExported stale until --force

r-provider.md documents this as a limitation of the shared incremental write path. Pin the
current behaviour (stale after an incremental analyse, correct after a forced one) so a fix
there shows up and the document is updated with it.

* test(r): narrow the regex and rename-safety results so typecheck:tests passes

* fix(ci): weight the R rename suite by its measured Windows cost

rename-provider-r.test.ts was charged 100 s in WINDOWS_WEIGHTS_SEC but
takes 600-750 s on the Windows runner (49 persisted fixtures, each a
native analyze). The shard packer therefore placed it on shard 5/10 with
the go and dml-gate suites, which exhausted the 20-minute watchdog on
two consecutive attempts.

Charge it 620 s, add a regression test that keeps it off the go and
dml-gate shards, and raise the recorded-workload ceiling from 17 to 18
minutes: the table total grew by about 520 s, so a perfect ten-way
split now averages about 1047 s per shard.

* fix(r): let the later library() call win when one package is bound twice

rMergeBindings kept the first binding of a node, so a batched call with a
package named by several library() calls was order-sensitive. Keep the
binding whose call starts later, add a unit case and pin the ABA and BAB
shapes through the pipeline.

* test(r): let the rename verdict helper read <<- and = function definitions

The helper listed only 'name <- function', while the indexer also lists
<<- and = definitions, so a generic defined with = never reached the S3
guard. Add cases that go through the helper with each operator.

* test(r): name the wrapped namespace directive test by its shape

* test(r): tell the R6 owner walk from a non-class with a discriminating assertion

getRTopLevelMethodOwnerName is the setMethod helper and returns null for any
argument node, so the negative assertion could not fail. Use the owner lookup
the R6 path uses, in the positive and the negative case.

* test(r): assert the pattern length cap accepts a pattern of exactly that length

Build the pattern from empty groups so only the length rule is in play, and
check that it compiles, matches 'aa' and not 'a', and that one more
character is refused.

* fix(r): keep the whitespace inside a quoted NAMESPACE name

normaliseArg trimmed the text inside quotes and backticks, so export(" a ")
named the symbol a instead of the symbol ' a ', which is what R reads. Trim
only around the argument, and pin it with a parser test and a pipeline case
where a package defines both a and ` a `.

* fix(r): keep a matched export-pattern answer after the work budget is spent

rExportPatternMatches answered false for every name once the budget was
spent, so a duplicate definition of a name that had been exported earlier
flipped to private. Remember the names matched while the budget lasted and
answer them from that set; undecided names still read as unexported, which
the documentation now says.

* fix(r): read a NULL default as a formal that may hold a function

A formal defaulting to NULL is the usual placeholder of an optional
callback, so classing it as constant let a rename edit the call of the
parameter and drew a false edge to a same-named top-level function. Treat it
as 'maybe': the rename refuses the call and the scope publishes the formal
as a lexical name. Update the provider guide and pin both paths.

* fix(r): say what is wrong with a rejected rename name

validateName let ... and ..N through to a misleading name_collision. Reject
them as reserved, say in the message that new names are ASCII-only by design,
and report an old name made only of non-ASCII characters as an unsupported
identifier rather than an infix function or operator.

* fix(r): keep a repeated library() package at its first attachment

R leaves an already attached package where it is, so library(a);
library(b); library(a) still lets b mask a. The merger counted the last
call as a fresh attachment, and because the pipeline folds the bindings of
a name in one at a time, a package masked at one step was forgotten at the
next. Remember each package's first attachment, masked ones included, on
the surviving bindings, and flip the expectations that pinned the other
direction (A/B/A -> B, B/A/B -> A) in the unit and pipeline tests.

* fix(r): make rename re-read NAMESPACE and fail closed on a stale export flag

After an edit of NAMESPACE alone, the unchanged R/ files are not
re-processed, so the persisted isExported of a newly exported function
stays false and rename read that as proof of privacy. The rename guard now
also uses the NAMESPACE the planner has just loaded from disk (recorded by
the R workspace hook against each parsed file): it refuses when NAMESPACE
exports the name by export(), exportPattern() or S3method(), and fails
closed (incomplete_semantics) when NAMESPACE is gone or unreadable, when
an exportPattern() was dropped or ran out of budget, or when no config was
recorded. The persisted flag remains a second, additive check. The
incremental test now asserts the refusal on the stale index and after
--force; unit cases cover each way NAMESPACE can change. Docs updated.

* fix(r): record the rename NAMESPACE config before the populate passes replace parsed files

populateRNamespaceImports and populateRQualifiedCalls replace entries of the
ParsedFile array (import synthesis; any dropped external pkg::fn site), but the
rename guard looks the recorded config up by the original ParsedFile object. A
package file that called stats::sd(), or whose package importFrom()ed a name from
another repository package, therefore read as 'NAMESPACE was not read' and every
rename in it was refused with incomplete_semantics.

Record the config against the objects as received and again against the final
array. Adds rename fixtures for a private and an exported function in a file
with an external qualified call, a private function in a package with a local
importFrom(), and extends the incremental NAMESPACE test with an external call
and an incremental run that reuses the parse cache.

* fix(r): make rename refuse when the NAMESPACE reader may have hidden an export

The NAMESPACE scanner skipped conditional (if/else) bodies, dropped raw-string and
multi-line arguments, and discarded a malformed directive together with everything up
to the next column-0 directive, all silently. Rename treated 'not in the export lists'
as proof of privacy, so it could rename a function whose export() entry the reader had
never seen and leave NAMESPACE naming a missing function.

The scanner now reports when a skipped or discarded region names an export-family
directive, and parseRNamespaceExports also flags an argument of one that it cannot
read. loadRPackageConfig stores that as RNamespaceInfo.exportsUnreadable and rename
refuses with incomplete_semantics. An ordinary NAMESPACE, including conditional
imports, does not set it. The indexed isExported is unchanged. r-provider.md updated.

* fix(r): load the R grammar lazily so a native load failure disables only R

parse-worker.ts and languages/r/query.ts imported @eagleoutice/tree-sitter-r
statically. A binding that cannot load (no prebuild, ABI mismatch) therefore
crashed every worker and every module importing the R provider, failing analyze
for all languages. The worker now loads it behind the same guard as the vendored
grammars, through the shared grammar loader, and the query module resolves it on
first use as the Kotlin one does. With the binding removed, analyze indexes the
other languages and skips R files with one logged error.

* fix(r): refuse a rename of a function that a roxygen2 @export tag exports

roxygen2 rebuilds NAMESPACE from @export* tags, so renaming a tagged function
changes the package's public API on the next document() even when the NAMESPACE on
disk and the persisted isExported say it is private. checkSafety now refuses a
top-level function whose directly preceding #' block has an @export* tag. Documents
that a successful rename leaves .Rmd/.qmd/.Rd/pkgdown/roxygen cross-reference
consumers unchanged; the rename result has no provider-owned note field.

* fix(r): rename functions with a leading dot and refuse R's hook functions

The rename engine reads a definition's simple name as the text after the last '.'
of its qualified name, so the graph symbol .helper never matched the definition
'helper' and every leading-dot rename failed with a misleading stale_graph. The R
provider's canonicalName now keeps a one-word leading-dot name whole (names with a
dot inside, such as area.circle, keep the engine's reading and stay refused).

That would also have let .onLoad, .onAttach and the other functions R calls by
name through, so checkSafety refuses them explicitly.

* docs(r): document replacement-function calls, package-less R/ directories and unparseable files

Pins the rename behaviour with two fixtures (an R/ directory without a package is
refused; a syntax error in an unrelated indexed file refuses with parse_error) and
adds the replacement-function CALLS limitation to the Limits section.

* test(r): type the refusal in the leading-dot rename test for the strict:false typecheck

* test(r): make the wall-clock guards in the R tests robust to a loaded runner

The argument-scaling ratio gate now repeats a measurement whose ratio is over the
limit (a quadratic query is over it every time, a noisy runner is not). The
absolute bounds take the fastest of up to three attempts that each build their own
state, so a cache warmed by an earlier attempt cannot hide a regression. The
named-import lookup test counts walks of the export set instead of timing 20,000
lookups, as its sibling tests already do.

* docs(r): count R among the retained import providers in local-import-scoping.md

The registry count was raised to 19 but the retained-provider table stopped at Dart
and the text still said eleven, so the two tables summed to 18.

* fix(r): read NAMESPACE only as a regular file and cap DESCRIPTION and NAMESPACE size

NAMESPACE was opened by name, so a symlink in the analysed repository was followed,
unlike DESCRIPTION which is read only when the directory read lists a regular file.
Neither manifest had a size cap (the walker's cap covers source files only). Both
now go through one reader that rejects anything over 4 MiB: a DESCRIPTION that
cannot be read leaves discovery marked incomplete, a NAMESPACE that cannot be read
is treated as absent (rename then refuses).

* test(r): revert the unrelated cleanup helper swap in the tree-sitter bundle test

The R rows the test needs are unchanged; the rmSync to cleanupTempDirSync change was
not required by R and widened the diff against upstream.

* test(r): pin that a UTF-8 BOM at the start of an R file indexes and renames

The grammar skips the mark, so the first-line definition, its CALLS edge and the
rename all work and the mark is kept. Added as a rename fixture; no code change.

* docs(r): correct the shared-code registration list and say why the persisted export flag stays

R registers its export checker on its own provider, not in a shared table, so the
provider guide no longer lists one. The Rename section now states that the persisted
isExported is kept as a second, fail-closed check beside the plan-time NAMESPACE read.

* test(r): drop non-null assertions from the new timing helpers

* test(r): keep the Windows rename suite small by testing guard logic in unit tests

The hook, roxygen, conditional-export and package-less R/ cases exercise checkSafety
only, which the unit tests already drive with a real NAMESPACE load. Each rename
fixture runs a native analyse (about 12 s on Windows), so only the cases that need
the engine stay as fixtures (external-call and local-import NAMESPACE reads,
leading-dot identity, unparseable file, BOM). Adds the package-less R/ unit case.

* ci(r): raise the Windows shard weight of the R rename suite for the six fixtures added

* fix(r): read DESCRIPTION and NAMESPACE through one opened handle

readManifestFile checked the size with fs.stat(path) and then read with
fs.readFile(path), which CodeQL reports as a file system race (js/file-system-race).
The file is now opened once (O_NOFOLLOW and O_NONBLOCK where the platform has them),
and the regular-file check, the size cap and the read all use that handle; one byte
past the checked size is read so a file that grows is refused. The DESCRIPTION read
for hidden packages in skipped subtrees now goes through the same reader, so it has
the same cap and fails closed (cannot rule a package out). Tests that spied on
readFile now spy on open; new cases cover the cap boundary, empty file, directory,
symlink and FIFO.

* fix(r): cache the R parser only after its language is set

getRParser assigned the module-level parser before setLanguage ran, so a
failed grammar load left a language-less parser that the next call returned.
Build it locally and cache it once setLanguage has succeeded, as the C#
provider does.

* fix(r): match a backticked R6 class name against its roxygen type

declaredClassName kept the backticks of an R6 class name, so a class written
with backticks never matched the roxygen type naming it, unlike a backticked
formal. Compare the bare name.

* fix(r): reject an empty quoted source in interpretRImport

The capture keeps its quotes, so source("") arrived as two characters and
passed the empty-source guard. Test emptiness after stripping the quotes;
targetRaw is unchanged.

* docs(r): document that a same-name parameter suppresses a pkg::f() edge

A function parameter or for variable named like the target of pkg::f() makes
the shared free-call fallback refuse the call before the qualified lookup
runs, so the call gets no CALLS edge. Record it under the known limits and
soften the qualified-call header, which claimed the qualifier outranks every
lexical tier. No shared code is changed.

* docs(r): state the exportPattern remembered-name cap and fastestWithin's minimum

rExportPatternMatches remembers at most 100,000 matched names per package, so
past that a name reads as not exported once the budget is spent; say so in the
function comment and the provider guide. fastestWithin always runs one attempt,
even when tries is below 1; word the comment to match.

* refactor(r): move R import target into languages/r

Move import-resolvers/r.ts to languages/r/import-target.ts (pure rename plus
import repoints, comments and docs) so the file already sits where upstream
#3670 expects per-language import targets, ahead of merging upstream/main.
No behaviour change.

* fix(r): strip backticks from R6 class name when typing $new() receivers

The R grammar yields an identifier whose text keeps its backticks, so
`Foo`$new() produced calleeName "`Foo`" while the class-name set holds the
bare name. Apply rBareName, as declaredClassName already does. Found in bot
review round 5 (PR #3513, comment 4348423277).

* docs(r): correct isExported comment in local-backend

The indexed isExported verdict is read by R rename's second privacy check, so
"never consulted by the engine" was wrong. Found in bot review round 5
(PR #3513, comment 4348423305).

* fix(ci): read package.json as utf-8 in tree-sitter readiness test

* docs(ci): describe cross-platform shard measurement without a run link

* fix(r): never treat a parameter default as proof of function-ness

A default says nothing about the argument a caller passes, so
`function(x, helper = 2) helper(x)` reaches the parameter when the caller
passes a function and the outer function when it does not, and
`function(x, helper) helper(x)` may reach either too. The rename provider and
the scope captures read the default as proof; every named formal is now treated
alike ("maybe").

Claim A (constant default): `role()` no longer marks a constant-default formal
'unrelated', so the call under it is not renamed with the function, and
checkSafety refuses it with ambiguous_reference.
Claim B (no default): the same call under a default-less formal is refused the
same way (it used to be left behind silently).
New-name side: a call of the NEW name under a same-named formal is a read of
the new name (name_collision) for every formal, not only those with a default;
a plain read of the formal is still not a read.
Call-side twin: rFunctionLexicalNames no longer skips constant-default formals,
so a call through any named formal gets no CALLS edge to an outer function of
that name (the rename planner and the resolver now agree).

The parameter lattice (RParameterKind, kindOfParameter, parameterNamed,
rParameterKind, innermostParameterKind) collapses into the boolean
isRParameterName and a private hasEnclosingParameter. isRConstantValue,
rBoundName and rOwnAssignedNames move to R/assignment.ts (kept, not deleted:
the assignment work needs them); captures.ts no longer imports from rename.ts.

Verdict changes (rename fixtures, helper -> assist unless noted):
- parameter-constant-default-call: success (2 edits) -> error ambiguous_reference
- parameter-constant-default-call-and-read: incomplete_semantics -> ambiguous_reference
- function-unrelated-parameter (compute -> calculate): success -> error ambiguous_reference
- new parameter-no-default-call: error ambiguous_reference
- new collision-new-name-parameter-call: error name_collision
- new parameter-read-only (control): success, 1 edit
- unchanged: parameter-assigned-call, parameter-function-default-call,
  collision-unrelated-uses, value-reference-*
CALLS edges: r-formal-shadows `constant_default` no longer reaches `transform`;
`plain` still does.

Tests: r-rename-parameter-shadow (rewritten for isRParameterName and the
collapsed verdicts), r-lexical-names, r-rename-collisions (a call under a
default-less formal named like the new name now collides), r-formal-shadows,
rename-provider-r (58 fixtures). docs/languages/r-provider.md lines on formals,
the rename guard and the new-name collision updated.

* fix(r): refuse exportPattern constructs that TRE reads differently from JavaScript

Fail closed on word boundaries (\< \>), \a \e \Q \E, \x{, \u, letter class
escapes inside brackets, collating and equivalence elements, {,n} and a leading
] in a bracket expression. A refused pattern is dropped, so rename reports
incomplete_semantics instead of guessing.

* fix(r): keep qualified calls and library() inside the package namespace

pkg::name() whose package does not define name no longer falls back to a
same-file or other-package definition: a re-export (export plus importFrom of
a local origin that defines the name once) binds the origin, anything else is
dropped, and so is every qualified site of unknown locality. pkg::name() to a
private name from outside the package tree gets no edge; pkg:::name still
binds. library()/require() attach only the exported names of a package that
has a NAMESPACE (unreadable or cut-short NAMESPACEs are not proven exports),
and the unique-name guess skips a candidate its package's readable, complete
NAMESPACE does not export unless the caller is inside that package's tree
(tests/ and inst/ included; a root-level package covers every file outside
nested packages).

Visibility (public/private/unknown) is decided once per pass in sorted order
with completeness read after the batch, so an exportPattern work-budget
cutoff gives the same verdicts whatever the file or site order.

Reverses the load_all() reading of library() and the "Permanent" re-export
pin. Verdict changes: r-qualified-calls reexport_user (global-name-fallback
0.5 -> import-resolved 0.85 to the origin), truncated-discovery qualifier
sites (kept -> no edge), r.test.ts run_all -> hidden_helper (0.5 -> no edge),
r-dotted-s3-collision use_odd via library (0.85 -> no edge). No rename
verdict changes.

* fix(r): bind R6 self to its enclosing class

`self$m()` inside an R6 method resolved by the shared lexical walk, because `self` had no type
binding. An inherited method got no edge, and a top-level function of the same name was bound
instead (0.49), as was one for a method that no class in the chain defines.

emitRScopeCaptures now types `self` in each R6 method (a function in the public, private or
active list of an R6Class call assigned to a name, bare or R6::) as that class, through a
synthetic @type-binding.self capture that interpretRTypeBinding reads with the shared `self`
source. The shared receiver pass then resolves the call through the class and its MRO at the
receiver-call confidence (0.85). Where self is no R6 instance (a free function, a parameter
named self, an R6Class call that is assigned to nothing, a RefClass method) the module and the
outermost function frames own `self` untyped (scopeOwnsReceivers), so the call is suppressed as
receiver-owned-but-unbound instead of reaching a free function. A file that binds `self` at top
level is exempt, so a global `self <- Foo$new()` still types its free functions' calls. For a
typed self whose class and parents lack the method, resolveReceiverMember answers an empty
ambiguous lookup, which stops the lexical fallback (outcome member-lookup-ambiguous; no shared
code is touched).

A class name containing a dot keeps the generic route: the shared pass reads it as qualified.
Documented in docs/languages/r-provider.md.

Tests: new r-self-binding fixture and test (c1-c13), r-call-shapes pins re-measured, two rename
fixtures (a free function sharing a name with an R6 method called through self).

* fix(r): treat ordinary assignments as lexical bindings and refuse renames they could shadow

`f <- function(x) { helper <- identity; helper(x) }` called the top-level
`helper()`: an ordinary assignment bound nothing in the function's frame. The
function scope now publishes the names its own body assigns a value that may be
a function (an identifier, a call, anything computed, NULL) as lexical names, so
a call of the name stops there (also `=`, `->`, a closure reading the local, and
the base of a complex target such as `names(x) <- v` or `x$a <- v`, never the
called name). A function literal stays a real definition and a constant is
skipped by R at a call, so neither is lexical; `<<-` and `->>` assign outward.
The rule is flow-insensitive: a call before the assignment, or under an `if`,
becomes unresolved.

That alone would let a rename of the outer `helper` succeed and strand
`helper(x)` (the lexical-name claim is a distinct-declaration basis), so the
rename guard refuses with ambiguous_reference when any function body assigns the
renamed name such a value, whether or not a call exists. Both sides read one
walker, `rLexicalAssignedNames` in R/assignment.ts, so they cannot drift.

Verdict changes (rename fixtures, helper -> assist):
- call before the assignment, conditional assignment: incomplete_semantics ->
  ambiguous_reference
- new: assign-local-identifier-call, assign-local-no-call (ambiguous_reference),
  constant RHS with and without a call (incomplete_semantics, as before),
  function literal with and without a call (success, 1 edit), plain call
  (success, 2 edits), nested function literal (success, 2 edits)

Known loss until the qualified-call reorder that follows: `pkga::helper(x)`
inside a function that assigns a local `helper` loses its edge.

* refactor(scope-resolution): let a qualified hit outrank a lexical name claim

emitFreeCallFallback applied the lexical name-claim block before it asked the
language's resolveQualifiedFreeCall hook, so a call written with an explicit
path (`pkg::fn()`) lost its edge whenever a parameter, `for` variable or local
binding of the same bare name was in scope, although the path names the module
and a local binding of the tail cannot be what it means. The hook is now
evaluated before the block and a defined hit for a site with rawQualifiedName
bypasses it; the same result is reused at the old call site. An undefined hit,
a site without a written path and a language without the hook keep the block.

This is the declared shared-pass exception of the R review fixes: the edit is
in scope-resolution/passes/free-call-fallback.ts, language-neutral, and names
no language. The resolveQualifiedFreeCall docstring in
scope-resolution/contract/scope-resolver.ts is clarified to say the hook
outranks the name-claim block (the contract left that order open).

Besides R, only PHP and Rust implement the hook; no existing pin in any
language moved. New pins: a unit test with a fake hook for the ordering,
Rust and PHP fixtures for the shape, and the R cells (`pkga::helper(x)` beside
a local `helper`, and beside a same-named parameter or `for` variable) that
the R provider documented as a known loss.

* fix(r): record a replacement call as a call of the setter

* fix(r): report chained receivers as unresolved instead of dropping them

A member call whose receiver is itself a $ access or a call (a$b$m(),
Cls$new()$m(), self$f$m()) had no call site, so it was invisible to the
unresolved-receiver count. R6 fields and method results carry no declared
type, so the chain is never followed: the site is minted with the shared
codec's truncated receiver chain, which the shared fold refuses, and the
call ends with a receiver-unresolved outcome and no edge.

A chain whose first link is not a variable (get_user()$save(),
pkg::Cls$new()$m(), x[[1]]$f$m()) mints no site at all and stays
invisible. No shared code changes; unit and integration tests pin the
reliance on the truncated marker.

* docs(r): add the ingestion gaps guide and a receiver corpus

* fix(r): keep self typed through field writes and off private members

An R6 method that wrote through self (`self$count <- 1`, `self$x[[i]] <- v`,
`self[["x"]] <- v`, `names(self$x) <- v`) made `self` a lexical name of the
method, so later `self$m()` calls lost the receiver type: an own method fell
to 0.51 and an inherited or missing one bound a free function of that name at
0.49. A write through self no longer binds the name; only a plain
`self <- v` (or a formal or loop variable called `self`) does, and a function
that rebinds self that way now owns it, so `self$m()` there is unresolved
unless the new binding is typed.

`self$m()` also reached methods of the `private` list. self is the public
interface, so private members are now skipped: a private-only name is
unresolved and a parent's public method wins over a private one of the
class. The definitions carry no section, so the capture pass records the
private members per file and hands them to the main thread through the
capture side channel (worker and parse-cache safe).

exportPattern() now refuses any backslash inside a bracket expression, which
TRE reads as a literal member (`[a\-z]` is a range from `\` to `z`), instead
of reading it as a JavaScript escape. The common `^[^\\.]` is dropped too.

Also removes the dead rOwnAssignedNames helper and restores prettier 3.8.1
formatting (the lockfile version) on files reformatted by a newer local
prettier, including the unrelated union in the shared scope-resolver.ts.

* docs(r): track the ingestion gaps guide

The file was created under an ignored docs/ path and never committed, although
AGENTS.md and the R provider guide link to it.

* perf(r): find replacement calls in one linear pass

emitRScopeCaptures asked, for every free call, whether it lay in an
assignment target by walking up the tree. tree-sitter's .parent
re-descends from the root and the first-argument check materialised the
whole argument list, so the walk was cubic in first-argument nesting and
quadratic in the number of call-valued arguments: a 1,500-deep nn(...)
or a c() of 10,000 calls stalled the parse worker until the file was
dropped from the index.

rReplacementCallIds now marks the replacement calls top-down, once per
file and only when the file has a free call: from each assignment target
it follows a call's first argument and the base of $, @, [ and [[, the
reverse of the old upward walk, with an explicit stack. The capture
output is identical (equivalence test over every R fixture);
isRReplacementCall stays as the single-call reference.

The trailing-colon trim of an S3method() generic used /:+$/, which is
quadratic in a run of colons; it is now a backwards loop.

The linear-regex cost comment now gives measured figures: a counted
visit costs up to about 70 ns for many short tests, so the package and
load caps are about 2 s and 7 s at worst. No per-test overhead is
charged: doing so moved a budget-exhaustion verdict in the
qualified-visibility determinism test.

* fix(r): type a receiver only when every binding agrees

A constructor binding (`x <- T$new()`) now types `x` only when every
binding of `x` in its frame (the file's top level or a function) is that
constructor; NULL, constants and field writes through `x` are neutral.
Another class, any other value, a formal, a `for` variable, `rm()`,
`assign()` with a literal name or a replacement call on `x` leaves the
receiver untyped, so the call is unresolved instead of reaching another
class's method. `<<-` and `->>` bind in the enclosing frames only, never
in their own.

Every typed receiver now reads the public interface as `self` does: a
private member gets no edge and records `member-lookup-ambiguous`, a
parent's public member wins over a child's private one, and a member the
owner lookup misses is no longer bound to a free function of that name.
Member calls match `$` only, so `u@save()` mints no site. A generator
object (`User$save()`) is never a receiver of an instance method, and a
dotted class name (`My.Class`) gets no receiver lookup (R-13), which also
gives up its own and inherited methods.

New fixtures r-receiver-agreement and r-typed-receiver-members pin the
rule, its kept idioms and its limits (with(), a rebinding in another
file, last-wins); the receiver corpus gains eleven rows.

* fix(r): scope blocks and follow declared package dependencies

Braces that R evaluates in an environment of their own (local(), with(),
within(), test_that(), describe() and it(), bare or pkg::-qualified) are
now block scopes. A definition inside is reached from those braces only:
calls from another block or file are refused rather than guessed, and a
constructor-typed local no longer types receivers in the next test_that
block. withr::with_*() and suppressWarnings() are unchanged.

S3method() registers a method for dispatch; it does not export it. The
NAMESPACE reader records registration-only names, and resolution
(library(), pkg::name, importFrom() and the visibility memo) treats them
as private, while pkg:::name still reaches them. The graph node stays
public and rename keeps refusing a registered method.

The unique-name guess now follows what package code may reach when it
passes R CMD check. From a package's R/ (with a NAMESPACE read in full),
a candidate in another package is refused unless the caller declares a
link (an importFrom() entry for the name, import(), the S4 import forms,
a transitive Depends: or a library() in the caller's file), and a
candidate in a loose script is refused unless an importFrom() entry
exists. A call from tests/ into the package's own data-raw/ or inst/ is
refused unless the file calls source(), system.file() or test_path().
These calls are unsupported for check-clean package code rather than
impossible; an unresolved call is preferred to an unsupported edge.

S4 generator calls are pinned as they are (no generator-specific rule).

* fix(r): refuse renames the graph cannot prove safe

Refuse a rename when the index cannot show it is safe: R6 member
shadowing (portable), a duplicate top-level definition in the load
unit, unindexed R files (via refreshResolutionConfig), a call before a
local or later top-level definition, a new name exported by NAMESPACE,
generated files, call-shaped strings, RefClass inherited members,
roxygen @rawNamespace/@export names, and the pretty and weighted.mean
generics. Adds 36 fixtures and a unit test for the unindexed-source
collector.

* test(r): split the R rename fixtures across two files and run eleven platform shards

The 110 R rename fixtures run as one file that projects to about 1665 s on
Windows at 15 s per test, past the 1200 s shard watchdog. Run them as two files
of 55 fixtures (about 825 s each) so each fits a shard.

The helper keeps defineRenameFixtureTests(language) unchanged for every
language, except that it skips fixtures listed in renameOverflowIds (R only).
defineRenameOverflowFixtureTests(language) registers just those, from the new
rename-provider-r-part2.test.ts. The matrix test is untouched. Each file pins its
partition count, and the first file proves no overflow id names a missing
fixture.

Shard weights, the cross-platform file list and the coverage hints now include
the second file. Charging the second half adds 695 s to the Windows table, which
no longer fits ten shards under the two-minute headroom the shard unit test
requires (busiest shard 1133 s against a 1080 s ceiling). TOTAL in ci-tests.yml
goes from 10 to 11, giving a busiest shard of 1029 s.

* docs(r): close the audit fixes with exact test targets and the final behaviour

Tests: the seven weak assertions in resolvers/r.test.ts now name exact node
ids (the cross-package case pins the pkgB::CleanData call, not the script's
bare call), and r-self-binding gains cell c16 (a parent's public field and a
child's private method share a name: no edge, a suppressed lookup). The
field branch of the self lookup is unreachable for R6 fields, so the
field-branch mutant is equivalent; the cell is red under the mutant that
removes the final ambiguous answer. The chained-receiver marker is not
load-bearing end to end, which the gaps inventory now says.

Docs: the R provider guide and the gaps inventory describe the receiver
agreement rule, block scopes, S3 registration, the dependency rules for the
name guess, the 0.35 qualified tier, the rename guards and their limits; the
inventory gains rows R-26 to R-42 and a corrected audit pin. AGENTS.md header
and changelog row carry the same date; gitnexus/CHANGELOG.md lists the R
language support. Two comment-only edits: the postParse hazard sentence in
language-provider.ts and ARCHITECTURE.md, and a corrected comment on the dotted
call filter in the R scope resolver.

* chore(bench): re-baseline receiver-resolution for the R receiver fixtures

The count arm moves from 138 to 159 call drops and from 168 to 189 across all
kinds. All 21 added drops are .R files (callDropsByExtension..R goes from absent
to 21) and no other extension moves; reads (30) and writes (0) are unchanged.
By shape: chain-field 56 to 63, no-chain 36 to 39, chain-call 32 to 35,
unclassified 13 to 21. By origin: in-program 57 to 64, unknown 49 to 55,
unclassified 2 to 10, external stays 30.

The bench counts only suppressed outcomes with the reason receiver-unresolved
(measure.mjs), so the movement is that reason alone: the R fixtures added since
the last baseline, where the receiver-agreement rule, typed private members,
dotted class names and with() limits end as unresolved receivers. At the
previous head the drift was 138 to 149 (R plus 11); the later receiver and
rename fixtures account for the other 10. No R arm is added to the shape
corpora. BASELINE.md records the movement, and the R gaps inventory notes that
the count arm now attributes drops to .R files.

* fix(r): refuse renames past block-local definitions and $methods() calls

The local-definition guard now also reads the braces of block scopes
(local, test_that, describe, it, with, within; bare or pkg::). A call of
the name before a block-local function literal, or a literal assigned only
under if, refuses the rename: R calls the outer function there, but the
index binds the call to the block-local literal, so the rename left that
call behind. A nested function or block is judged by its own body, so a
stub defined first inside it() under describe() is still accepted.

A x$methods(...) call whose arguments mention the name refuses the rename
too: methods added to a RefClass generator that way are not modelled, so a
bare call inside one was rewritten although R reaches the class method.

Also pin that a function-local rebinding shadows a module-level
constructor type in a file that no <<- rebinds (r-receiver-agreement m10).

Four rename fixtures (57 per test file); gaps rows R-43 and R-44.

* chore(bench): add R to the scope-resolution benchmark

The benchmark from #3711 requires a corpus generator and committed graph
baselines for every supported language, so its inventory check failed
once R was registered. The R arm sources the preceding file and calls
through an R6 instance (`value <- C0$new(); value$make0_0()$make0_1()`):
the first call resolves across files, the second stays unresolved
because R6 method results carry no type, as documented for the provider.

Baselines were recorded with --record; every other language's entry is
unchanged. R: 100 files 99 cross-file calls, 1,000 files 999.

* test(r): drop the Rcpp generator token from the generated-wrapper fixture

gitleaks reads the generator-token UUID that Rcpp writes on line 2 of
RcppExports.R as a generic API key. The rename guard keys only on the
"Generated by" / "do not edit by hand" header on line 1, so the token
line is replaced by a comment and the line numbers stay as they were.
The fixture commit that added the token stays in the branch history,
so its two findings are fingerprinted in .gitleaksignore, following the
existing entry for a synthetic fixture value.

* fix(r): keep the cross-platform command under the Windows length limit

run-cross-platform.ts passes every cross-platform test file to npx on one
command line, run through cmd.exe (shell: true). cmd.exe caps a command
line at 8191 characters, and npx.cmd adds about 131 characters of node
and npx-cli.js paths when it expands its arguments. With the five R
rename files listed, the longest Windows shard command was 8066
characters (about 8197 expanded), and every Windows shard failed with
"The syntax of the command is incorrect." Upstream's own list is 7827
characters without R.

Keep only rename-provider-r.test.ts (part 1, 23 of the 114 fixtures,
dealt round-robin from the sorted ids) on the Windows and macOS list.
Parts 2 to 5 now run on the Linux coverage shards only. The longest
shard command is now 7870 characters (about 8001 expanded). The
five-way split and the partition pins are unchanged; the test comments
and the R docs say which parts run where.

* fix(r): keep names public when NAMESPACE exports cannot be proven complete

refineRExportStatus marked every name absent from NAMESPACE as private
even when the NAMESPACE was unreadable (a conditional export such as
`if (...) export(cond)`) or an exportPattern() was dropped or cut short,
so such names may well be exported. Completeness is now read once per
package after every node has been tested, as rBuildSymbolVisibilityMemo
does.

The rename guard now prefers its incomplete_semantics verdict over the
generic exported refusal when a NAMESPACE was read but not fully applied,
which keeps the namespace-pattern-word-boundary golden unchanged.

Three assertions in r-export-pattern-shared-budget.test.ts encoded the old
behaviour (names of a package with dropped patterns read as unexported) and
now expect them to keep their default export status.

* fix(r): do not read a block-local assignment as a top-level collision

The rename collision scan used !insideFunction to decide whether an
assignment of the new name binds at top level, so `local({ assist <- 1 })`
and `test_that(...)` bodies caused a false name_collision. It now uses
bindsAtTopLevel, which accounts for block scopes and is already used for
the old-name check.

Adds the rename-integration case r/new-name-block-local (a real indexed
run, since the unit helper builds sources without scopes) and raises the
pinned R fixture count to 115 (parts 23/23/23/23/23).

* fix(r): recognise quoted and backticked methods and R6 section formals

The setRefClass extractor compared the raw text of an argument name with
`methods`, and the R6 extractor did the same for `public`, `private` and
`active`, so `` `methods` = `` and `"methods" =` produced the class but no
methods. Both now compare the name with its surrounding quotes or
backticks removed, as Class already is, through a new rArgumentName
wrapper (argumentNameText itself is untouched: 17 upstream dependants).

Partial-name matching (`meth =`) stays a documented limitation.

* docs(r): correct why only R rename part 1 is on the cross-platform list

The comment in cross-platform-tests.ts and the two R docs said parts 2-5
were left off because cmd.exe's 8191-character limit leaves no room. That
was true when run-cross-platform.ts went through a shell, but it now
calls execFileSync(process.execPath, ...) with no shell, so the limit no
longer applies. The wording now says so, and gives the remaining reason:
each part is a real indexing run per fixture and the Windows and macOS
shard time is bounded by keeping them on the Linux shards. The same
claim in a comment of rename-provider-r.test.ts is corrected too.

Comment and documentation only; the list itself is unchanged.

* test(r): make the via_lapply shadowing test non-vacuous

The assertion toEqual(['lapply'].filter(n => targets(...).includes(n)))
passed for any result without extra entries. The suggested
toEqual(['lapply']) would fail against the old fixture, because base
lapply is not defined there and via_lapply resolved to no target at all.

The fixture now defines lapply, so the test asserts both halves
explicitly: via_lapply resolves to exactly ['lapply'] (the call site is
resolved, and the anonymous function's `handler` formal shadows the
top-level handler, so there is no edge to it), and a new
via_lapply_unshadowed, with no shadowing formal, reaches handler as a
positive control. The receiver-resolution baseline check still matches.

* test(r): define the Data class in the same file as the documented function

The r-roxygen-param-prose fixture kept the R6 class Data in model.R and
the two callers in run.R, so Data was not a local class of run.R. The
class now sits in run.R, so a bad inference from the prose
"@param df Data frame of observations" is not stopped by the local-class
guard alone.

Verified by mutation: widening BARE_TYPE_RE to drop its end anchor makes
six type-env-r unit tests fail, but this integration test still passes,
because no graph edge consumes the roxygen type. The anchored-type rule is
therefore pinned by the type-env-r unit tests; this test remains an
end-to-end control. The receiver-resolution baseline check still matches.

* fix(r): refuse a block-local binding of the new name unless it is a constant

Switching the collision scan to bindsAtTopLevel let any binding of the new
name inside a local() or test_that() block through. That is safe only when
the value cannot be a function: R's function lookup skips a non-function,
but a function, or a value not shown to be a constant (a call result),
would capture the renamed calls in the block. The scan now still refuses a
block-local binding of the new name unless its right-hand side is a
literal. Function bodies keep their earlier behaviour.

Adds rename-integration cases r/new-name-block-function (already refused
by an existing path; kept as a regression pin) and r/new-name-block-unknown
(fails without this change), and raises the pinned R fixture count to 117
(parts 24/24/23/23/23). The collision unit test that passed with or without
the fix now says what it covers and points at the integration cases.

* fix(r): recognise quoted and backticked formals in the field extractor

The R6 public/private and setClass/setRefClass representation, slots and
fields formals were compared by raw text, so a class written with
`"public" =` or `` `fields` = `` had methods but no fields. They now use
rArgumentName, like the method extractor. Tests cover fields, slots,
representation, and R6 public and private; the method extractor test also
covers R6 private and active.

* docs(r): tighten comments after review

The refineRExportStatus docstring now states the completeness condition,
the two adjacent rename guard comments are merged, a long comment in
rename-provider-r.test.ts is wrapped, and the r-roxygen-param header says
plainly that the integration test is an end-to-end control that does not
fail when the anchored-type rule is loosened.

* test(r): give the parameterised section-formal cases unique titles

The R6 method cases of r-method-extractor-owner.test.ts hard-coded
'public' in a title shared by rows for public, private and active, so
the completeness audit found the same test identity more than once.
The title now carries both the spelling and the formal; the assertions
are unchanged.

* test(scenario-map): recognise R in the source-shape language tables

Name R in the identifier, file-extension and test-path tables so R tests
that feed inline source, or write .R fixtures, are parsed with the R
grammar when their inputs are shaped instead of being treated as plain
text.

* docs(r): state the grammar install policy and the unset provider hooks

R is a required bundled grammar, so GITNEXUS_SKIP_OPTIONAL_GRAMMARS does
not apply to it. Record also that the provider sets no entry-point
patterns, description extractor or MRO strategy, and which default it
takes.

* test(r): count only real drops in the receiver agreement and corpus tests

The shared receiver pass (DART-11) records an informational
receiver-type-unresolved outcome for an untyped function-local receiver.
It adds no edge and no drop count includes it, so the R tests now count a
suppressed outcome as a drop only when its reason is not informational.
The classification lives in one helper keyed on the reason alone.

The tests also assert the repository has no ACCESSES relationships and
that no informational note sits on the line of a resolving row.

* docs(r): describe the informational receiver note in the ingestion gaps

An untyped function-local receiver adds no edge and no counted drop; since
the shared receiver pass (DART-11) it also records an informational
receiver-type-unresolved note that no drop count and no impact bound
includes. Update the INVISIBLE-GAP definition, R-20 and its next step, and
the README taxonomy line to say so.

* docs(r): scope the informational receiver note claim to drop counts

* test(r): build the import visibility stub through the shared factory

The free-call qualified-over-name-claim test hand-built
ScopeResolutionIndexes.imports as a bare Map. Since the import visibility
interface landed (#3908) the name-claim lookup calls imports.edgesAt, so
the stub threw. Build it with createEagerImportVisibility, as the other
hand-made indexes in test/unit/scope-resolution do.

* fix(r): read unindexed R sources through one file handle

Resolves the CodeQL file-system race alerts (check on a path, then read of
the same path) in collectRUnindexedSources and gitnexusIgnore. Both now go
through readRegularFile: open once, stat the handle, read the handle, close in
finally.

Behaviour, before and after (pinned by r-rename-unindexed-sources.test.ts):
- .gitnexusignore as a symbolic link, directory or FIFO: before, lstat.isFile()
  was false so no rules applied; after, no rules apply and a FIFO does not
  block. POSIX: the open uses O_NOFOLLOW/O_NONBLOCK, so a final symbolic link
  fails with ELOOP (caught, undefined) and the handle stat rejects non-regular
  files. Windows has neither flag: the handle stat rejects directories and
  oversize files and an lstat after the open rejects a symbolic link, leaving
  a narrow open-to-lstat window (same as readNestedGitignore). No dev/ino
  comparison is made (Windows stat(path).dev differs from fstat(fd).dev).
- Regular .gitnexusignore: rules applied, unchanged.
- R file over MAX_UNINDEXED_R_SOURCE_BYTES: unreadable entry, unchanged; a file
  of exactly the cap is still read.
- R file that is a symbolic link or non-regular: the walk still skips it via
  Dirent.isFile(); a file swapped for a link after the walk is now refused
  (unreadable) instead of followed.
- Open or read failure: unreadable entry, unchanged.

* fix(scenario-map): anchor the structural node-type pattern

/body|list|specifier$/ read as if all three alternatives were suffixes, but
only specifier$ is anchored: body and list match anywhere in the node type
(class_body_declaration, field_declaration_list). That is the behaviour in
force, so it is kept; the pattern becomes isTypeDeclarationType with explicit
includes/includes/endsWith and no ambiguous regex. Verified identical to the
old expression over 41k generated node-type strings, and pinned by tests.

* fix(r): bound the unindexed-source read to the size cap

* perf(parse-worker): load the R grammar on first R file

* fix(r): give each file its own VIRTUAL placeholder class

The contains = "VIRTUAL" sentinel minted one graph-wide placeholder owned
by an arbitrary declaring file. The incremental writer follows only
file-owned edges, so editing or deleting that file made the next
incremental analyse fail. Mint one placeholder per declaring file, with an
id (Class:<file>:<virtual>) that cannot meet a real class named VIRTUAL, so
every EXTENDS edge stays within one file. Add an incremental regression
test.

* fix(scope-resolution): gate the qualified free-call reorder behind a provider opt-in

The free-call pass ran a provider's resolveQualifiedFreeCall before the lexical
name-claim block for every language. For Rust this added CALLS edges for
let, for, match, if let and file-level const callers of a module-qualified
call beside a same-named binding.

Add the optional ScopeResolver.qualifiedFreeCallOutranksNameClaim, set only
by R. Without it the pass keeps the original order, with the hook after the
block, so Rust and PHP graphs match upstream main again. Pin the Rust shapes
as unchanged and test the opt-out order and the unconditional assignment.

* fix(r): refuse rename when several dirs declare the same Package: name (T9)

A rename preview for a target in a package whose `Package:` name another
directory also declares returned an OK plan: `pk:::fn` was rewritten in one
copy or stranded in the other. The config loader now records the directories
whose name is declared more than once (`duplicatePackageDirs`), and the safety
check refuses with an ambiguity reason. Edge binding for duplicate names is out
of scope.

Impact (index at 44d693958, worktree method): checkSafety UNKNOWN (reached
through the RenameProvider hook, no resolved callers; confirmed by text search
that only the rename engine calls it; the change only adds a refusal),
loadRPackageConfig LOW (8 impacted). detect-changes --scope staged on the
source files: 2 files, 10 symbols, not partial, risk medium.

Refs #114

* fix(r): refuse rename when a call in a parameter default meets a local definition (T10)

A function that defines a local function of the renamed name in its body, and
calls the name in a parameter default, produced an OK plan with one edit and the
default left on the old name. The defaults are lazily evaluated in the function's
own environment, so such a call is as undecidable as a call before the local
definition; rCallsBeforeLocalDefinition now collects calls in `parameters` too,
and the existing ordering test refuses it.

Impact (index at 44d693958, worktree method): rCallsBeforeLocalDefinition LOW
(1 impacted). detect-changes --scope staged on the source file: 1 file,
1 symbol, not partial, risk low.

Refs #114

* fix(r): apply the string-call, unindexed-file and hook-name guards to the new name (T11)

Three rename guards tested only the old name, so `helper` -> `abs` (a string
evaluated as `abs(1)`), `helper` -> a name an unindexed R file uses, and
`helper` -> `.onLoad` all returned OK plans. Each check now also tests newName,
with its own refusal message.

Impact (index at 44d693958, worktree method): checkSafety UNKNOWN (RenameProvider
hook, no resolved callers; only the rename engine calls it; the change only adds
refusals). detect-changes --scope staged on the source file: 1 file, 2 symbols, not partial, risk medium.

Refs #114

* fix(r): refuse rename of a function defined twice at the top level of its own file (T15)

`helper <- function...` twice in one file produced an OK plan that renamed only
one of the definitions. The safety check now counts the top-level bindings of the
name in the target's own file and refuses when there is more than one; the
cross-file duplicate check already existed.

Impact (index at 44d693958, worktree method): definesAtTopLevel LOW (1 impacted,
now a wrapper over topLevelBindingCount); checkSafety UNKNOWN (RenameProvider hook,
only the rename engine calls it; the change only adds a refusal). detect-changes
--scope staged (worktree with the four fixes applied over 44d693958): 2 files,
15 symbols, not partial, risk medium.

Refs #114

* fix(r): refuse library()/importFrom() binding of a name that a closure-local function also carries (T3)

The shared finalize pass indexes the definitions of a file by simple name and
binds an imported name to the first it meets. A closure-local `validate` ahead
of an exported top-level `validate` therefore won the 0.85 edge.

expandRWildcardNames and resolveRNamedImport now refuse a name when another
undotted definition of the file carries it (RFileTopLevel.repeated); the call
falls to the lower tiers. Dotted members stay with namedImportsBindTopLevelOnly.
The r.test.ts "known limitation" test now asserts the refusal.

Impact (index of an earlier commit, storage-version workaround): expandRWildcardNames
LOW, 1 caller; resolveRNamedImport CRITICAL by graph depth (2 direct callers,
resolveRImportTarget and populateRNamespaceImports), the change only drops edges.
detect-changes --scope staged on the source files: low, 0 processes, not partial
(test files excluded: new files are not in the index).

Refs #115

* fix(r): refuse library()/importFrom() binding of a name defined as a function in two files of one package (T6)

Two files of one package that define the same function made library(pkg) and
importFrom(pkg, name) bind the first file at 0.85, against r-provider.md and
the unique-definition rule of the masking pass.

resolveRNamedImport returns null and expandRWildcardNames drops the name when
more than one R/ file of the package binds it to a function (a class of that
name next to one function is not a second callee, so the Bioconductor
generator idiom still binds). Both go through the same helper in
import-target.ts; the call falls to the lower tiers, where the name stays
ambiguous. r-provider.md now says so for importFrom() as well.

Impact (index of an earlier commit): rFileTopLevel LOW, 4 direct callers, 0
processes; resolveRNamedImport and expandRWildcardNames as in the previous
commit (edge-dropping only). detect-changes --scope staged: low, 0 processes,
not partial.

Refs #115

* fix(r): attach nothing for library() calls that spell exclude, include.only or character.only (T7)

The scope emitter took the first argument of every library()/require() as the
package and ignored exclude =, include.only = and character.only =, so a hidden
name, a name outside include.only, or a variable naming another package still
got a 0.85 import-resolved edge.

isRNonNamingScopeMatch now drops the import capture when the call's argument
list spells any of the three (one cached pass per list). Literal filtering is
not attempted. The names fall to the lower tiers (unique-name guess, 0.5).
r-provider.md documents the behaviour. The unit test that expected
library(character.only = TRUE, pkg) to import pkg now expects nothing.

Impact (index of an earlier commit): isRNonNamingScopeMatch CRITICAL by graph
depth (1 direct caller, emitRScopeCaptures; 2 processes at depth 3), the change
only drops import captures. detect-changes --scope staged on source and docs: low,
0 processes, not partial (test files excluded: new files are not indexed).

Refs #115

* test(r): update unit expectations for names defined as a function in two files (T6 follow-up)

The T6 commit made a name that two files of one package define as a function
bind nowhere through importFrom() and library(). Three unit expectations
pinned the old binding to the first file; they now pin the refusal (the
characterisation snapshot changes only for `corelib::shared`).

Refs #115

* fix(r): count exportPattern alternation scan work as build steps (T12)

The literal-alternation check in Nfa.build re-scanned every alternative of a group once
per copy of a repeated group, outside every budget: exportPattern("(" + 16374 x "|" +
"){16384}") fits the 16 KB pattern cap, builds almost no states, and took 10.9 s to
analyse against 3.0 s for a plain NAMESPACE. What the scan visits now counts as build
steps, so such a pattern is refused for the work cap (and charged as a refusal) after a
bounded number of copies. The trie walk of buildWords is no longer than that scan, so it
needs no separate charge. Successfully compiled patterns are not charged to the shared
budget: a successful build is already bounded by the build-step and state caps.

Pinned on the build-step counter in test/unit/r-export-pattern-compile-cost.test.ts, not
on elapsed time. Re-measured: analyse of the crafted NAMESPACE 4.0 s against 5.2 s for a
plain one on the same machine.

Impact (worktree index, approximate; literalWord, literalWords, buildWords,
compileLinearRegexDetailed): LOW, callers only inside languages/r/linear-regex.ts and
export-pattern.ts / package-config.ts. detect-changes staged: low, 4 symbols, 0 processes.

Refs #116

* fix(r): make the exportPattern warnings and the grammar rebuild hint say what happens (L8, L11)

L8: the dropped and cut-short exportPattern warnings said the names "are treated as not
exported", but refineRExportStatus keeps such nodes exported (no name is proven private).
The warnings now say "not proven private and stay exported"; the existing 200-pattern
test asserts both the kept status and the wording.

L11: the "parser not available" skip warning now ends "then analyze --force": after a
grammar is rebuilt, files skipped as unparsed are only picked up by a full re-index. The
text is shared and names no language; the R and Swift expectations are updated.

Impact (worktree index 1de5780b6, approximate): reportRExportPatternProblems and
runChunkedParseAndResolve, string changes only. detect-changes staged: 4 source files,
low risk; test files also mapped.

Refs #116

* docs(r): correct the receiver baseline numbers, the import-target scan reason; list the R NAMESPACE edit test as lbug-db; fix a test comment (L13, L15, L16, L18)

L13: test/integration/r-namespace-edit-incremental.test.ts opens LadybugDB; it is now in
the lbug-db project include list and the default project exclude list in vitest.config.ts
(TESTING.md describes the list generically and needs no edit).
L15: BASELINE.md R section now agrees with baseline.json: 161 call drops and 195 in
total (no-chain 41, unknown 69). The merged Dart awaited-call fix (#3876) removed one
drop after the paragraph was written.
L16: the stated reason for R's import-target ceilings named two O(files) legs; source()
is keyed (normToRaw exact join, suffix index on a miss), only library(localpkg) scans.
Corrected in bench/import-target/measure.mjs and baselines.json (notes only).
L18: the second position of the two-character string is the end context, not the middle.

detect-changes staged is PARTIAL here: vitest.config.ts and measure.mjs map to no
symbols (config/comment-only changes).

Refs #116

* docs(r): state known limits and fix contradictory sentences (T4, T5, T8, T14, T16, L1-L7, L10)

Docs only, plus one source comment (no behaviour change).
- r-provider.md: library() masking caveat beside an S3 method (T5, R-46);
  unreadable NAMESPACE file or package beyond the discovery bound is treated
  as absent, every name public, silently, and a directive the reader cannot
  read is a different case (T8, R-47; package-config.ts:660-700); dotted name
  binds the first definition by path, not a unique one (T4, R-45;
  scope-resolver.ts:224); URL and ~ source() paths (L10); exotic NAMESPACE
  forms (T16, R-48); bare-name export tagging (L7, R-49; post-parse.ts:221);
  bounded-work limits L1, L2, L4, L5, L6.
- r-ingestion-gaps.md: rows R-45 to R-49; R-02 gains the 0.85 local() form
  (T14; only function nodes mint @scope.lexical-names, captures.ts:101).
- linear-regex.ts: comment corrected; the 350 MB figure counts automata
  only, verdict memos are uncounted, reviewer measured 1.2 GB (L3).

Refs #117

* docs(r): state which export flag R-49 refers to and who reads it

Refs #117

* fix(r): keep the import edge of a function whose same-file class def follows it (F1)

repeatedSimpleNames counted every undotted localDef, class defs included, so
`Circle <- function(r)` followed by `setClass("Circle")` in one file was treated
as a repeated name and the 0.85 import edge was dropped, unlike the cross-file
case (cf44fa923). A class def that follows the function of the same name is no
longer a repeat: the shared finalize pass binds the first callable-or-type def,
which is the function. Two functions (T3) and a class def ahead of the function
stay refused, since finalize would bind the class there; that order keeps the
0.5 guess to the right function and is pinned as a limit.

Tests: r-s4-generator same-file-{library,importfrom} fail before, pass after;
classfirst variants pin the limit.

Impact: repeatedSimpleNames LOW, 10 upstream symbols (all R), the change only
adds edges. detect-changes --scope staged on the source file: low, 0 processes
(test and fixture files are new, so not in the index, and were excluded).

Refs #119
Refs #115

* test(r): run r-virtual-placeholder-incremental with the lbug-db tests (F4)

Listed in the lbug-db include and in the default exclude, as e72a4c7c9 did for
r-namespace-edit-incremental.

Refs #119

* test(r): assert the solo rename verdict explicitly and relabel the T10 characterisation (F2)

Refs #119

* test(r): document the dist requirement of the lazy-grammar test and warn when it skips (F3)

Refs #119

* docs(r): qualify the free-call ordering claim, the T3 and T7 limits, the R-47 variants and the duplicate Package: refusal (F5)

Refs #119

* docs(r): soften the claim that the <virtual> id segment cannot meet a real class id (F6)

A class named by a string or in backticks (setClass("<virtual>")) could. Comment
only; no code change. detect-changes --scope staged mapped no symbols (a comment
edit), so it reports PARTIAL and is not a clean check; the diff is one doc comment.

Refs #119

* fix(r): say what the exportPattern warnings mean for library() and pkg:: (F7)

The warnings said unproven names "stay exported". The graph flag does stay true,
but library() and pkg:: resolution do not treat such names as provably public.
The text now says both; the test asserts it.

Impact: reportRExportPatternProblems is a log-text change only. detect-changes
--scope staged: low, 0 processes.

Refs #119
Refs #115

* chore(r): keep the analyze --force rebuild hint for every language (F8, no code change)

Verified in code that a file skipped for a missing grammar binding is picked up
only by a full re-index, for every language: the skip in parse-impl.ts (skippedByLang)
is language-neutral and leaves the file node in the graph; run-analyze.ts hashes
every File node (newFileHashes) and diffs by hash (diffFileHashes), so an unchanged
skipped file is not re-parsed; the already-up-to-date fast path (lastCommit ===
currentCommit) has no grammar-availability input; and ANALYSIS_FEATURES, which
forces a re-index when it changes, holds no grammar-availability entry. Read from the
code, not run end to end. The hint in parse-impl.ts and its test stay as they are.

Refs #119

* test(parse-worker): pin one-time R grammar load and the missing-binding log (Refs #111)

Adds three integration tests to parse-worker-lazy-r-grammar.test.ts: the R grammar is
required once and reused across several sub-batches of one worker; a worker whose R
binding is unloadable logs no missing-binding error when only non-R files are parsed;
and with R files present it logs the failure once, caches it across sub-batches and
skips the R files without crashing. The preload gains a failR switch (workerData) and
an fd 2 write probe; the helper takes a list of sub-batches because availability is
resolved once per language per sub-batch.

Mutation check (dist temporarily edited, restored): disabling both the worker's
lazyLanguageCache and the shared loader's loadCache fails the reuse and the
failure-caching tests; loading R eagerly at module load fails the no-R-file tests.
Disabling only the worker cache does not fail them, because the shared loader cache
also dedups the require.

Impact check: tests only, no source symbol edited. detect-changes not applicable to a
test-only change. git diff --stat:  1 file changed, 88 insertions(+), 15 deletions(-)

* docs(scope-resolution): describe the qualified free-call opt-in without naming a language (Refs #113)

Comment-only rewording of lines this PR added to shared ingestion code so
they describe the mechanism generically: the qualifiedFreeCallOutranksNameClaim
doc, the resolveMemberOwnerNode doc, and two parse-worker comments. No code,
type or behaviour change.

Impact: comment-only, so no symbol's behaviour or callers change; impact
analysis not applicable.
detect-changes (staged): PARTIAL, as expected for a comment-only change
(parse-worker.ts maps no symbols; it holds only comment edits). Mapped:
LanguageProviderConfig, ScopeResolver; 0 affected processes; risk unknown.

* Resolve R callable shadowing in file and block scopes

* Exercise R import index reuse with literal source paths

* Verify exact R import edges and reachable source controls

* Use the shared grammar loader in workers and benchmark literal R sources

* Index R package sources once per import-resolution pass

* Respect refined R visibility when collecting exported types

* Size identity hash buffers to the files being read

* Decline positional R matches consumed by abbreviated arguments

* Preserve R package imports with abbreviated character.only set to FALSE

* perf(r): index package ownership once per discovery pass

* perf(r): classify nested function receivers without repeated parent searches

* perf(index): reuse the synchronous artifact hashing buffer

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-19 17:16:27 +00:00
..
triage redoing auto labeling using z score instead of clustering lowkey the method 2026-03-21 23:21:23 -05:00
check-tree-sitter-upgrade-readiness.py feat(r): add R language support (#3513) 2026-11-19 17:16:27 +00:00
check-workflow-concurrency.py fix(release): gate publication on accuracy and paired evaluation (#3503) 2026-10-10 08:26:08 +01:00
evolution-runner-ready.py fix(release): gate publication on accuracy and paired evaluation (#3503) 2026-10-10 08:26:08 +01:00
evolution-runner.py fix(release): gate publication on accuracy and paired evaluation (#3503) 2026-10-10 08:26:08 +01:00
fetch-lbug-fts-artifacts.mjs fix(lbug): ship FTS per-platform and recover in-place native aborts (#3274) 2026-09-14 08:52:24 +01:00
npm-ci-retry.sh fix(ci): stop the review agent rejecting its own graph-backed reviews (#2731) 2026-07-28 17:13:29 +01:00
review-citations.cjs fix(ci): stop the placeholder review, verify citations, repair once (#2733) 2026-07-28 18:51:01 +01:00
review-precheck.cjs fix(ci): stop the placeholder review, verify citations, repair once (#2733) 2026-07-28 18:51:01 +01:00
test_check_tree_sitter_upgrade_readiness.py feat(r): add R language support (#3513) 2026-11-19 17:16:27 +00:00
update-vendored-grammars.mjs fix(deps): upgrade native tree-sitter to 0.25.1 (#3531) 2026-10-10 13:07:59 +03:00
verify-workflow-run-pr-identity.cjs fix(ci): look up fork prebuild PRs by head owner and branch (#3236) 2026-09-09 09:46:24 +01:00