Commit graph

731 commits

Author SHA1 Message Date
henry201605
2f15c1ece1
feat(group): add Kotlin Spring WebClient long-form HTTP consumer extraction (#1884)
* feat(group): add Kotlin Spring WebClient long-form HTTP consumer extraction

Follow-up to #1855. Extends `kotlin.ts` with the long-form WebClient
fluent chain that #1855 explicitly deferred:

  webClient.method(HttpMethod.GET).uri("/x").retrieve().awaitBody<T>()

This pattern remains common in Kotlin Spring 4 → 5 migrations and in
codebases that prefer the fluent verb-as-enum style. The short form
(`webClient.get().uri("/x")`) was already supported in #1855.

Approach:
  - Single deeper tree-sitter query (`WEB_CLIENT_LONG_PATTERNS`) that
    matches the full chain structurally — both `.method(HttpMethod.X)`
    and `.uri("...")` in one pattern. Verb is captured as the
    `simple_identifier` of the `HttpMethod.X` field access.
  - Verb is whitelisted to GET/POST/PUT/DELETE/PATCH (consistent with
    the short-form's `WEB_CLIENT_SHORT_TO_HTTP` map).
  - Receiver constraint `(#eq? @obj "webClient")` mirrors the short
    form and Java plugin heuristic.

Out of scope (intentional):
  - Variable-bound verbs: `val verb = HttpMethod.PATCH; webClient.method(verb)...`
    Source-scan can't follow the binding without graph context.
    Pinned by an anti-overreach test.
  - HEAD/OPTIONS/TRACE: not in `WEB_CLIENT_SHORT_TO_HTTP` either —
    keeps polyglot symmetry with java.ts and the short form.

Tests: 4 new cases under `consumer extraction — fetch patterns`,
gated by tree-sitter-kotlin grammar availability.

  positive (3)
   - long form GET
   - long form POST / PUT / DELETE / PATCH (4 verbs in 1 fixture)
   - no double-emit pin (long-form chain produces exactly one
     consumer, not one from each query)
  anti-regression (1)
   - variable-bound verb does NOT match (graph-aware concern)

The previous `'does NOT match Kotlin WebClient long form (deferred
to follow-up)'` test from #1855 is replaced by these — the deferred
state is now resolved.

Reverse-validated: temporarily disabling the long-form emit makes
exactly the 3 positive tests fail; the variable-bound-verb anti-
regression test continues to pass (it pins behavior independent
of the emit being on or off).

Local validation:
  - test/unit/group/http-route-extractor.test.ts: 66/66 
  - test/unit/group: 546/546 
  - npx prettier --check (changed files): clean 

* test(group): address Claude review findings F1 and F2 on PR #1884

Two minor follow-ups from the production-readiness review:

F1 — Stale block comment at the top of the Kotlin consumer suite
(was: "Three consumer flavors covered here ... long-form deferred
to a follow-up"). Updated to "Four consumer flavors" and removed
the deferred sentence — the deferral is resolved by this PR. The
kotlin.ts file header was already updated; this brings the test
file comment in sync. Per DoD §2.3 (no stale comments).

F2 — Replaced `expect(wcConsumers.length).toBeGreaterThanOrEqual(4)`
with `expect(wcConsumers).toHaveLength(4)` in the multi-verb test.
The fixture is fully deterministic — exactly 4 long-form calls,
no other consumer types — so an exact count assertion is the right
shape per DoD §2.7 ("use toBe / toEqual for exact expectations").
Added a comment explaining what the assertion catches that the
existing per-verb toBeDefined() checks would miss (accidental 5th
consumer from a duplicate query firing or a regressed receiver
constraint).

F3 (HEAD/OPTIONS/TRACE negative test) is intentionally not added
in this PR — same precedent as #1855 where HEAD/OPTIONS/TRACE on
the short form are also implicitly excluded without a pinning
test. Happy to add one in a separate PR if maintainers want
explicit pinning across both forms.

F4 (CI on pre-merge SHA) is the maintainer's call — the merge from
main is theirs to re-trigger CI on. The merge brings only Java
consumer changes (PR #1872) and Go provider changes (PR #1886),
both in entirely separate files from this PR's Kotlin work.

Local validation:
  - test/unit/group/http-route-extractor.test.ts: 73/73 
    (66 from this PR pre-merge + 7 from PR #1872 merged via main)
  - npx prettier --check (changed files): clean 

* refactor(group): hoist Kotlin WebClient long-form verb regex to module scope

Address @magyargergo's review request on PR #1884:

  > Can you please extract the regexp from the for loop? 🙏
    (kotlin.ts:510)

Compiles the verb whitelist `^(GET|POST|PUT|DELETE|PATCH)$` once at
module load instead of every iteration of the long-form scan loop.
Mirrors the placement and JSDoc style of the sibling
`WEB_CLIENT_SHORT_TO_HTTP` constant.

Behavior is unchanged — same verb whitelist, same exclusion of
HEAD/OPTIONS/TRACE for symmetry with the short form. The 4
itKotlinConsumer long-form tests added in this PR continue to
pass, and the variable-bound-verb anti-overreach test continues
to pin the deliberate non-match.

Local validation:
  - test/unit/group/http-route-extractor.test.ts: 77/77 
  - test/unit/group: 557/557 
  - npx prettier --check (changed file): clean 

---------

Co-authored-by: henry <zhangwei2017@unipus.cn>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-29 09:27:54 +01:00
JaysonAlbert
7dae4fcc41
fix(group): attribute Spring interface routes to controllers (#1743)
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
* fix(group): attribute Spring interface routes to controllers

* test(group): normalize Spring route fixture paths

---------

Co-authored-by: gfwangjie <gfwangjie@gf.com.cn>
2026-05-29 07:35:01 +01:00
evolution
d71fd1688b
feat(go): add builtInNames set to Go language provider (#1886)
* feat(go): add builtInNames set to Go language provider

Add GO_BUILT_INS (15 functions, 18 types, 3 values) to the Go
LanguageProvider for parity with the other 13 language providers.
The set is converted to an isBuiltInName predicate by defineLanguage()
and consumed by the type-env return-type lookup to short-circuit
lookups for Go built-in symbols.

* feat(go): add Go 1.18+ and 1.21 predeclared identifiers to builtInNames

Add `clear`, `min`, `max` (Go 1.21 builtins), `any`, `comparable`
(Go 1.18 type aliases), and `iota` (predeclared constant) to
GO_BUILT_INS for complete coverage of the Go specification.

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-29 06:46:02 +01:00
MyShining
7b38b8aae2
feat(java): add HTTP consumer contract extraction (#1872) 2026-05-29 06:05:40 +01:00
henry201605
b565c7c990
feat(ingestion): resolve FastAPI include_router(prefix=...) cross-file routes (#1877)
* feat(ingestion): resolve FastAPI include_router(prefix=...) cross-file routes

FastAPI sub-route files declare paths via @router.<verb> while the entry
file mounts the router with app.include_router(<router>, prefix='/x').
Previously both the ingestion-layer Route graph nodes and the group-layer
ExtractedContract URLs lost the cross-file prefix, breaking provider <->
consumer matching.

Ingestion layer:
  - parse-worker emits routerIncludes / routerImports + decoratorReceiver
  - parsing-processor / parse-impl thread the new fields and aggregate
    prefixesByModule across chunks; decorator routes whose receiver is
    'router' are duplicated once per matching prefix
  - routes.ts joins prefix via normalizeExtractedRoutePath

Group layer:
  - HttpLanguagePlugin gains an optional prepareRepo() pre-pass and a
    repoContext arg to scan(); python.ts builds prefixesByModule and
    falls back to the bare path when no entry matches
  - http-route-extractor caches one repoContext per plugin

Tests:
  - 3 new http-route-extractor cases (attr / named-import / no-prefix)
  - ParseWorkerResult literals in 3 test files updated to the new shape

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(ingestion,group): address PR #1877 review — relative imports, cross-package collisions, host names, ingestion tests

Follow-ups to the FastAPI `include_router(prefix=...)` cross-file fix
based on PR #1877's automated production-readiness review. Three
correctness gaps and one test coverage gap addressed:

1. Relative-import support in the worker regex (FINDING 2)
   `FROM_IMPORT_ROUTER_RE` now accepts module paths starting with a
   `.` (e.g. `from .calls import router as calls_router`). The
   previous `[A-Za-z_][\w.]*` rejected leading dots and silently
   dropped every relative-import Shape-B include — a real pattern
   from the PR description's own motivating example. The matching
   helpers now strip leading dots before keying so absolute and
   relative imports collapse to the same module key.

2. Cross-package same-name module collisions (FINDING 3)
   Two-tier module keying replaces the previous basename-only key:
     • short key — `users`            (file basename without `.py`)
     • long  key — `api/users`        (parent dir + stem)
   `prefixesByLongKey` is consulted first and only falls back to
   `prefixesByShortKey` when no long-key match is available. Both
   the ingestion pipeline (parse-impl.ts) and the group extractor
   (http-patterns/python.ts) carry the same scheme so the graph
   nodes and HTTP contracts agree on which prefix applies.

   New protocol field `ExtractedRouterModuleAlias` (parse-worker →
   parsing-processor → parse-impl) lets Shape-A
   `<host>.include_router(<mod>.router, prefix='/x')` calls promote
   to a long key when the same file imports `<mod>` via
   `from <pkg> import <mod>`. Without this, `api/users.py` and
   `admin/users.py` collided on the basename `users` and the admin
   file's routes inherited the `/users` prefix that was only meant
   for `api/users.py`.

3. Non-`app` host variable names (FINDING 4)
   The group-layer `INCLUDE_ROUTER_*_PATTERNS` queries pinned the
   host identifier to the literal `"app"` and dropped every
   `application = FastAPI()` / `api = FastAPI()` pattern — the
   constraint was redundant given that the call shape
   (`include_router` invoked with a router argument and a
   `prefix=` keyword) is already specific enough. The pin is
   removed; the ingestion regex was already unrestricted.

4. Ingestion-layer regression tests (FINDING 1)
   The previous PR added group-layer tests
   (`http-route-extractor.test.ts`) but zero in-tree tests for the
   ingestion path. Two new suites pin the
   worker → parse-impl → routes flow:

   - `test/unit/fastapi-router-bindings.test.ts` (23 cases):
     `extractFastAPIRouterBindings()` is split into a stand-alone
     module so it can be unit-tested without booting a worker
     thread, then pinned for regex shape, two-tier key emission,
     relative-import support, and negative cases.
   - `test/integration/fastapi-prefix-pipeline.test.ts` (5 cases)
     plus `test/fixtures/fastapi-prefix-app/` — runs the full
     `runPipelineFromRepo()` against a realistic multi-package
     fixture (containing both `api/users.py` and `admin/users.py`)
     and inspects the resulting `Route` graph nodes for cross-file
     prefix joining and absence of cross-package bleed.

Verification

  - `npx tsc --noEmit`: pass
  - PR-touched test suites (6 files / 117 cases): all green
  - `npx prettier --check`: pass on touched files
  - `npx eslint`: 0 errors on touched files

Cache / compatibility

  The new `routerModuleAliases?` field on `ParseWorkerResult` and
  `routerModuleAliases` on `WorkerExtractedData` are optional /
  guarded with `?? []`, so historical parse-cache entries continue
  to load without forced re-scan.

Refs PR #1877.

* refactor(ingestion): move fastapi-router-bindings out of workers/ — pure module, not a worker

Addresses @magyargergo's `CHANGES_REQUESTED` review on PR #1877:

> Sorry I just found that we are introducing a new worker in the PR.

`gitnexus/src/core/ingestion/workers/fastapi-router-bindings.ts` was a
**pure-function module** — it never imported `worker_threads` or
`parentPort`, never spawned a worker, and was never registered as a
worker entry. It was placed in `workers/` purely because it was split
out of `workers/parse-worker.ts` to make its functions unit-testable
without booting a worker thread (parse-worker is itself the worker
entry and cannot be loaded from the main thread).

To remove the misleading directory placement:

  • The implementation moves to
    `gitnexus/src/core/ingestion/route-extractors/fastapi-router-bindings.ts`,
    alongside the other framework-specific route extractors (`expo`,
    `nextjs`, `php`, `laravel`, `middleware`, `response-shapes`).
  • `workers/parse-worker.ts` keeps a thin re-export so the worker
    entry can keep using `extractFastAPIRouterBindings` directly. The
    re-export now carries an explicit comment stating that the imported
    file is **not** a worker and that the `workers/` directory
    deliberately hosts only true worker entries (`parse-worker.ts`,
    `worker-pool.ts`, `quarantine.ts`).
  • The new file's leading docstring opens with "NOT A WORKER" and
    explains why it exists where it does.
  • The unit test (`test/unit/fastapi-router-bindings.test.ts`) is
    updated to import from the new path.

No behaviour change. The function body, signatures, and exported types
are identical.

Verification

  • `npx tsc --noEmit`: pass
  • `npx tsc` (dist rebuild): pass
  • `test/unit/fastapi-router-bindings.test.ts` (23 cases): all green
  • `test/integration/fastapi-prefix-pipeline.test.ts` (5 cases): all green
  • `test/unit/group/http-route-extractor.test.ts` (63 cases): all green
  • `npx prettier --check` on touched files: pass
  • `npx eslint` on touched files: 0 errors

Refs PR #1877.

* refactor(ingestion): drop parse-worker re-exports; consumers import router types directly from route-extractors

Addresses @magyargergo's two remaining review comments on PR #1877:

1. **`gitnexus/src/core/ingestion/workers/parse-worker.ts:247`** —
   "Can you please remove them and update the call sites?"

   The `export type { ExtractedRouterInclude, ExtractedRouterImport,
   ExtractedRouterModuleAlias } from '../route-extractors/...'` block
   in parse-worker.ts is gone. The remaining `import type {…}` is
   purely local — used only to type the corresponding fields on
   `ParseWorkerResult` below — and the leading comment now says so
   explicitly ("this file does NOT re-export them"). The
   `extractFastAPIRouterBindings` symbol is also no longer re-exported
   from parse-worker.ts; it's still imported here so the worker entry
   can call it per file, but downstream consumers must reach it via
   `route-extractors/fastapi-router-bindings` directly.

   Call sites updated:
     - `gitnexus/src/core/ingestion/parsing-processor.ts`
     - `gitnexus/src/core/ingestion/pipeline-phases/parse-impl.ts`

   Both files now `import type { ExtractedRouterInclude,
   ExtractedRouterImport, ExtractedRouterModuleAlias }` directly from
   `route-extractors/fastapi-router-bindings.js`. The worker types
   they still need (`ParseWorkerResult`, `ExtractedToolDef`, etc.)
   keep coming from `workers/parse-worker.js`.

   The unit + integration tests already imported from the new path,
   so no test changes were required.

2. **`gitnexus/src/core/ingestion/parsing-processor.ts:168`** —
   suggested simplification:

       for (const item of result.routerIncludes ?? []) allRouterIncludes.push(item);
       for (const item of result.routerImports ?? []) allRouterImports.push(item);
       for (const item of result.routerModuleAliases ?? []) allRouterModuleAliases.push(item);

   Applied verbatim. Replaces the previous `if (result.…) for …`
   guards. The cache-compat semantics are unchanged — historical
   parse-cache entries that lack these fields still load cleanly,
   the new form just spells the fallback inline.

No behavior change, no tests touched, no public API change.

Verification

  • `npx tsc --noEmit`: pass
  • `npx tsc` (dist rebuild): pass
  • PR-touched test suites (6 files / 117 cases): all green
  • `npx prettier --check` on touched files: pass
  • `npx eslint` on touched files: 0 errors

Refs PR #1877.

* refactor(ingestion): hoist fastapi-router-bindings type imports to top of parse-worker.ts

Move the `import type { ExtractedRouterInclude, ExtractedRouterImport,
ExtractedRouterModuleAlias }` block to the top of the file with the
other type imports, and drop the comment that previously sat next to
ExtractedDecoratorRoute.

---------

Co-authored-by: henry <zhangwei2017@unipus.cn>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-28 19:04:19 +01:00
azizur100389
97c1f85e87
refactor(cpp): Use function-type ADL entities (#1822)
* fix(cpp): use function-type ADL entities

* test(hooks): stabilize concurrency burst reporting

* Fix C++ return type capture subtag handling

* Harden C++ function-type ADL extraction

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-28 17:18:19 +01:00
jelsco
11fc43b425
feat(impact): per-symbol processes field on byDepth items (#1867)
* feat(impact): per-symbol processes field on byDepth items

Today `impact` returns aggregated `affected_processes` at the top level
but the per-symbol `byDepth` items don't say which processes each caller
participates in. Consumers planning a deploy want to know if a given
caller is hit by a daily cron, a webhook, or a user-facing route - each
is a different deploy-risk profile - and that information requires a
follow-up cypher query per symbol today.

This change attaches `processes: [...]` to every `byDepth[depth][i]`
item, listing the processes that symbol participates in:

  byDepth: {
    "1": [
      {
        depth: 1,
        id: "Function:src/foo.ts:doStuff",
        name: "doStuff",
        ...
        processes: [
          { id: "proc:cron_daily", label: "Daily cron",
            processType: "cron", step: 12 }
        ]
      }
    ]
  }

The list is empty for symbols not in any process. Additive change, no
breaking modifications to existing fields.

Implementation:
- A second chunked Cypher pass runs after the existing per-process
  aggregation pass, returning per-(symbol, process) rows. Same chunk
  size and MAX_CHUNKS as the aggregation pass, so worst-case adds 10
  extra round-trips bounded by the same env var.
- The enrichment pass is skipped entirely when `affectedProcesses.length
  === 0` (nothing to enrich) or `summaryOnly === true` (byDepth not
  returned anyway).
- The aggregation query is unchanged - the new query has a distinct
  RETURN shape (`RETURN s.id AS sid, ...`) so an existing unit test that
  counts STEP_IN_PROCESS chunks was narrowed to match only the
  aggregation pattern.

Tests:
- New: byDepth items always have a `processes` field (default empty
  when no STEP_IN_PROCESS edges exist).
- New: when STEP_IN_PROCESS rows exist, the matching byDepth item
  carries the right `{id, label, processType, step}` entry.
- Updated: impact-batching-grouping test mock narrowed to count only
  aggregation chunks (the new per-symbol pass is covered separately).

* style: apply prettier to gitnexus/src/mcp/local/local-backend.ts

Pure line-wrap fix flagged by quality / format CI on PR #1867. Zero
semantic change: prettier broke a chained .slice().map() across three
lines instead of one. No test changes, no logic changes.

* fix(impact): address PR review findings on per-symbol process enrichment

- byDepth.processes doc now states each item carries processes (Finding 1)
- move per-symbol STEP_IN_PROCESS enrichment post-pagination so symbols
  beyond the pre-pagination cap no longer get false-empty processes:[]
  (Finding 2); hoist CHUNK_SIZE/MAX_CHUNKS to function scope so the
  post-pagination pass can reference them
- dedup per-symbol query with DISTINCT + MIN(r.step) per (symbol,process)
  pair (Finding 3)
- suppress the per-symbol pass under summaryOnly, incl. impactByUid group
  fan-out, plus a test asserting the query never fires (Findings 4, 6)

* fix(impact): address second-round review findings A-E

Finding A (blocker): impactByUid passed summaryOnly:true, which drops the
entire byDepth field. cross-impact.ts reads fan.byDepth to build the group
by_depth output, so cross-repo by_depth was always {}. Replace with a new
skipPerSymbolEnrichment option on _runImpactBFS that suppresses only the
per-symbol STEP_IN_PROCESS pass while preserving byDepth.

Finding B+D (blocker): rewrite the byDepth.processes tool description. Drop
the stale "enrichment cap" wording (no longer true post-pagination), document
the {id,label,processType,step} entry shape, and tell agents to cross-check
affected_processes when partial:true.

Finding C: bound the post-pagination per-symbol enrichment loop to
MAX_CHUNKS*CHUNK_SIZE page IDs and surface partial:true when capped, so a
large page cannot trigger unbounded DB round-trips (DoD 2.6).

Finding E: add a test exercising the real impactByUid -> _runImpactBFS path
asserting byDepth survives and the per-symbol query never fires.

---------

Co-authored-by: scotjelinski <58397194+scotjelinski@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-28 16:15:37 +01:00
Gergő Magyar
99168be773
feat(ingestion): trace indirect call patterns — FastAPI Depends() and frontend HTTP consumers (#1852) 2026-05-28 05:33:30 +01:00
henry201605
d9d6318b64
feat(group): add Kotlin Spring HTTP consumer extraction (#1855)
* feat(group): add Kotlin Spring HTTP consumer extraction

Follow-up to #1849 (Kotlin providers). Extends `http-patterns/kotlin.ts`
with three call-site patterns common in Kotlin Spring projects:

  - RestTemplate: `restTemplate.getForObject("/x", ...)` and the
    full verb family (getForObject/getForEntity → GET,
    postForObject/postForEntity → POST, put → PUT, delete → DELETE,
    patchForObject → PATCH). Mirrors the Java plugin's
    `REST_TEMPLATE_TO_HTTP` map so polyglot repos coalesce on a
    single contract id.

  - WebClient short form: `webClient.get().uri("/x")` and the
    `.post()` / `.put()` / `.delete()` / `.patch()` siblings. The
    chain parses as two nested `call_expression` nodes; the query
    anchors on the outer `.uri(...)` and walks one level inward
    to constrain the verb.

  - OkHttp: `Request.Builder().url("/x")`. Kotlin parses
    `Request.Builder()` as a `call_expression` whose callee is a
    `navigation_expression` (not Java's `object_creation_expression`),
    so the query shape differs from `java.ts` but the receiver/method
    constraints (`Request` / `Builder` / `url`) and emitted
    contract format match.

Out of scope: `webClient.method(HttpMethod.X).uri("/y")` long form.
The verb sits on a sibling `call_expression` two hops away, so it
needs a walk-up helper rather than a flat tree-sitter query. A
dedicated anti-overreach test pins the current behavior so a future
short-form change can't accidentally start matching the long form.

Receiver name constraints (`#eq? @obj "restTemplate"`,
`#eq? @cls "Request"`) match the Java plugin's heuristic — a project
that aliases the receiver under a different name won't be picked up.
This trade-off keeps false-positive rates low and is documented in
the file header.

Tests: 5 new cases under `consumer extraction — fetch patterns`,
gated by tree-sitter-kotlin grammar availability.

  positive (3)
   - RestTemplate verbs (5 calls × 5 verbs)
   - WebClient short-form verbs (5 calls × 5 verbs)
   - OkHttp Request.Builder().url("/x")
  anti-regression (2)
   - WebClient long form `.method(HttpMethod.X)` produces no
     consumer (deferred-feature pin)
   - non-restTemplate receiver does not match (receiver-name pin)

Reverse-validated: removing the `(#eq? @obj "restTemplate")`
constraint causes the receiver-name anti-regression test to fail.

Local validation:
  - test/unit/group/http-route-extractor.test.ts: 59/59 
  - test/unit/group: 539/539 
  - npm run format:check: clean 

* test(group): pin Kotlin OkHttp POST-chain heuristic-default GET behavior

Address Claude review on PR #1855 (Finding 1).

The OkHttp query in `kotlin.ts:OK_HTTP_PATTERNS` matches the
`.url("/x")` sub-expression of a builder chain, but the verb is
encoded on a separate sibling call (`.post(body)` / `.delete()` /
...). The query intentionally does not walk the chain to recover
the verb — it emits `method: 'GET'` for every match, mirroring the
Java plugin's `OK_HTTP_PATTERNS` (java.ts).

Concretely: `Request.Builder().url("/x").post(body).build()` becomes
`http::GET::/x`, not `http::POST::/x`. This is an already-accepted
Java parity heuristic, but it was untested on the Kotlin side.

This commit:
  - Adds an anti-overreach test pinning the current behavior:
      * exactly one consumer is emitted with method=GET
      * no second http::POST::/x consumer appears
  - Documents the limitation in kotlin.ts as a "Known limitation"
    block tied to the test, so a future verb-walk implementation
    has to update the comment in lockstep with the assertion.

Rationale for not implementing verb-walk in this PR:
  - Verb-walk requires walking sibling call_expression nodes (the
    `.post(body)` chain), which is the same shape as the
    deferred WebClient long-form work
  - Java has the same limitation in production today; fixing only
    Kotlin would create polyglot drift
  - A coordinated future PR can add verb-walk to both plugins at
    once and update both comments + the pin tests together

Finding 2 (silent test-skip when tree-sitter-kotlin grammar is
unavailable) is intentionally NOT addressed here — same gating
pattern was accepted in #1849 for Provider tests, and a coordinated
follow-up should add a CI sentinel covering both Provider and
Consumer suites in one place.

Local validation:
  - test/unit/group/http-route-extractor.test.ts: 60/60 
  - test/unit/group: 540/540 
  - npm run format:check: clean 

---------

Co-authored-by: henry <zhangwei2017@unipus.cn>
2026-05-27 21:32:24 +01:00
henry201605
46eb0ebf56
feat(group): add Kotlin Spring HTTP route extraction (named + positional) (#1849)
* feat(group): add Kotlin Spring HTTP route extraction (named + positional)

Mirror the Java Spring named-argument fix for Kotlin Spring Boot
controllers. Adds a new `http-patterns/kotlin.ts` plugin behind the
optional `tree-sitter-kotlin` grammar, registered for `.kt`/`.kts`.

Both annotation forms produce providers:
  @RequestMapping("/api")          / @GetMapping("/users")
  @RequestMapping(path = "/api")   / @GetMapping(value = "/users")
  @RequestMapping(value = "/api")  / @GetMapping(path = "/users")

The Kotlin AST (fwcd/tree-sitter-kotlin) shares one node type
(`value_argument`) for positional and named forms, so the queries
are split:
  - positional: anchors `string_literal` as the first named child
    of `value_argument` via the immediate-child anchor `.`
  - named: explicitly captures `simple_identifier` and constrains
    it to `^(path|value)$` via `#match?`, mirroring the same
    safety bar enforced by `http-patterns/java.ts` and
    `topic-patterns/java.ts`. Without this constraint the query
    would also capture non-route attributes like `produces`,
    `consumes`, `headers`, `name`, `params`.

`tree-sitter-kotlin` is an optionalDependency (parser-loader.ts,
parse-worker.ts pattern). When the native binding is unavailable
the plugin exports `null` and `index.ts` skips registering
`.kt`/`.kts` so the orchestrator stays healthy.

Scope: providers only. Consumer detection (RestTemplate, WebClient,
OkHttp) on Kotlin call-site ASTs differs enough from Java's
`method_invocation` shape to warrant a separate, focused PR.

Tests: 11 new cases under `provider extraction — source-scan
fallback (Strategy B)`, gated by the kotlin grammar availability.

  positive (8)
   - class @RequestMapping("/api/v1") (positional)
   - class @RequestMapping(path = "/api/v2")
   - class @RequestMapping(value = "/orders")
   - method @GetMapping(value = "/users")
   - method @GetMapping(path = "/users")
   - method @PostMapping(path = "/users")
   - mixed: class named-arg + method positional
   - mixed: class positional + method named-arg
  anti-regression (3)
   - @GetMapping(produces = "application/json") emits no provider
   - @GetMapping(name = "x", value = "/users") emits exactly one provider
   - @RequestMapping(path = "/api", name = "myApi") prefix stays /api

Reverse-validated: removing the `(#match? @key "^(path|value)$")`
constraint causes precisely the 3 anti-regression tests to fail.

Local validation:
  - test/unit/group/http-route-extractor.test.ts: 54/54
  - test/unit/group: 534/534
  - npx tsc --noEmit: clean (modulo the pre-existing TS2339 in
    user-defined-conversions.ts merged from main, unrelated)

* style(test): apply prettier line wrapping to long itKotlin titles

---------

Co-authored-by: henry <zhangwei2017@unipus.cn>
2026-05-27 09:33:52 +01:00
henry201605
eeea46466b
fix(group): handle named annotation args in Java Spring route extraction (#1834)
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
* fix(group): handle named annotation args in Java Spring route extraction

The Java HTTP plugin only matched positional `@RequestMapping("/path")`
syntax for class-level prefixes and method-level routes. Named argument
forms (`path = "/path"` and `value = "/path"`) produce an
`element_value_pair` AST node that the tree-sitter queries did not cover,
causing the class prefix to be lost and named-arg method routes to be
missed entirely during cross-repo contract extraction.

Add a second pattern to both SPRING_CLASS_PREFIX_PATTERNS and
SPRING_METHOD_ROUTE_PATTERNS matching the element_value_pair structure.

* fix(group): constrain Spring named-arg query to path/value keys + add regression tests

Address Claude review on PR #1834. The named-argument patterns added
in 8b6fa6e used `value: (string_literal)` (a tree-sitter field
selector for the right-hand side of element_value_pair), which matched
ANY annotation member with a string value — not just `path`/`value`.

Concrete fallout (without this fix):
  @GetMapping(produces = "application/json") → bogus http::GET::/application/json
  @GetMapping(name = "listUsers", value = "/users") → extra http::GET::/listUsers
  @RequestMapping(headers = "X-Foo=bar", path = "/api") → class prefix
    could be set to "X-Foo=bar" because prefixByClassId.set runs per
    match in document order, so the LAST element_value_pair wins.

The sibling topic-patterns/java.ts already demonstrates the correct
shape: constrain the `key:` field to the route member names.

This commit:
  - Adds `key: (identifier) @key (#match? @key "^(path|value)$")` to
    both SPRING_CLASS_PREFIX_PATTERNS and SPRING_METHOD_ROUTE_PATTERNS
    named-arg queries.
  - Adds 9 regression tests under
    `provider extraction — source-scan fallback (Strategy B)`:
      * @RequestMapping(path = "/api/v3") class prefix
      * @RequestMapping(value = "/orders") class prefix
      * @GetMapping(value = "/users") method route
      * @PostMapping(path = "/users") method route
      * mixed: class named-arg + method positional
      * mixed: class positional + method named-arg
      * @GetMapping(produces = "application/json") → no provider emitted
      * @GetMapping(name = "listUsers", value = "/users") → exactly one
        provider with path "/users", no /listUsers route
      * @RequestMapping(path = "/api", name = "myApi") → prefix is /api,
        not myApi (verifies the class-prefix overwrite scenario)

Tests: 42/42 pass in http-route-extractor.test.ts;
       522/522 pass under test/unit/group;
       npx tsc --noEmit clean.

* test(group): add @GetMapping(path = ...) case to match review checklist verbatim

Claude review on PR #1834 explicitly asked for the method-level
`@GetMapping(path = "/users")` case. The previous commit covered it
indirectly by exercising path= on @PostMapping (the Spring method
annotations share the same query, so any verb proves the path= field
is matched). Add a dedicated GET+path= test so the reviewer's
checklist is satisfied 1:1, and keep the POST+path= case as a bonus
verb-coverage test.

Tests: 43/43 pass in http-route-extractor.test.ts.

---------

Co-authored-by: henry <zhangwei2017@unipus.cn>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-27 07:35:46 +01:00
dependabot[bot]
ca3e1755c2
chore(deps)(deps): bump lru-cache from 11.4.0 to 11.5.0 in /gitnexus (#1844)
Bumps [lru-cache](https://github.com/isaacs/node-lru-cache) from 11.4.0 to 11.5.0.
- [Changelog](https://github.com/isaacs/node-lru-cache/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-lru-cache/compare/v11.4.0...v11.5.0)

---
updated-dependencies:
- dependency-name: lru-cache
  dependency-version: 11.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-27 06:45:18 +01:00
dependabot[bot]
6acdc49f06
chore(deps)(deps-dev): bump @types/node in /gitnexus (#1845)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 25.9.0 to 25.9.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.9.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-27 06:44:41 +01:00
azizur100389
b1445daf04
feat(cpp): rank user-defined conversions (#1829) 2026-05-27 06:36:23 +01:00
dale
d903152eba
fix(typescript): reuse suffix index in scope resolver (#1840)
* fix(typescript): reuse suffix index in scope resolver

Build a suffix index once per TypeScript scope-resolution pass and pass it into standard import resolution so package-style imports avoid repeated linear file-list scans.\n\nFixes #1839

* test(typescript): add wiring-level test for scope-resolver suffix index

- Test typescriptScopeResolver.resolveImportTarget directly (the real
  production entry point) with package-style, unresolvable, and relative
  imports
- Use vi.spyOn on buildSuffixIndex to verify the index is built inside
  the makeTsResolveImportTarget closure — fails if index wiring is removed
- Fix existing test to pass real file lists instead of empty arrays
  alongside the prebuilt index, matching production wiring

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Test <test@example.com>
2026-05-26 20:23:13 +01:00
Sparsh
7556a8e73a
feat(cobol): migrate COBOL to scope-based resolution (regex provider) (#941) (#1835)
* feat(cobol): migrate COBOL to scope-based resolution (regex provider)

Migrate COBOL to scope-based registry resolution, validating the
parse-source-agnostic contract — COBOL uses regex, not tree-sitter,
but implements the same LanguageProvider interface via emitScopeCaptures.

Phase 1-5 complete per #941 DoD.

New files:
  languages/cobol/captures.ts       — emitScopeCaptures wrapping regex tagger
  languages/cobol/interpret.ts      — import/type-binding/receiver hooks
  languages/cobol/index.ts          — barrel export
  languages/cobol/scope-resolver.ts — ScopeResolver wiring (9 fields, 3 toggles)

Modified files:
  languages/cobol.ts                — wire 4 scope-resolution hooks
  registry.ts                       — register cobolScopeResolver
  registry-primary-flag.ts          — document REGISTRY_PRIMARY_COBOL

Fixtures:
  17 fixture files, 30 test cases across 11 required classes
  test/integration/resolvers/cobol-scope.test.ts

Tests: 24/24 pass (default + REGISTRY_PRIMARY_COBOL=0)
tsc: zero cobol-specific errors
Shadow mode (GITNEXUS_SHADOW_MODE=1): zero crashes
Regex perf: 10K-line file in 408ms (threshold: 2000ms)

NOT added to MIGRATED_LANGUAGES — REGISTRY_PRIMARY_COBOL env var only.

* chore(cobol): add COBOL to MIGRATED_LANGUAGES

* Revert "chore(cobol): add COBOL to MIGRATED_LANGUAGES"

This reverts commit f234330e9f.

* fix(cobol): revert MIGRATED_LANGUAGES flip, fix JSDoc dup, fix arityCompatibility

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-26 18:37:39 +01:00
ChamHerry
681a352006
fix(worker): analyze native worker aborts (#1833)
* fix(analyze): avoid native aborts on generated worker bundles

Retire timed-out parse workers instead of force-terminating native parser state, and skip Monaco generated worker bundles by default while preserving explicit .gitnexusignore negation overrides.

Constraint: Node native tree-sitter bindings can abort the process when a timed-out worker is terminated while inside parser state.

Rejected: Falling back to sequential parsing for native stalls | it can move the same native crash onto the main thread.

Confidence: high

Scope-risk: moderate

Directive: Keep timeout recovery from force-terminating workers until they return to JS or exit naturally.

Tested: npm test; npx tsc --noEmit; npm run build; targeted analyze on /Users/wangxc/Code/keep; gitnexus detect_changes --scope staged

Not-tested: Node 22 LTS runtime and non-macOS platforms

* fix(worker): bound retired parser worker lifetimes

Keep timeout recovery from immediately terminating workers that may still be inside native parser state, while making terminal pool shutdown own retired worker cleanup so long-lived processes do not accumulate retired threads.

Constraint: Claude review on PR #1833 required retiredWorkers cleanup in pool.terminate() and tripBreaker() without regressing no-immediate-terminate timeout safety.

Rejected: clearing the retiredWorkers set without terminating | would remove JS bookkeeping while leaking the underlying worker thread.

Confidence: high

Scope-risk: moderate

Directive: Preserve the distinction between recoverable timeout retirement and terminal pool shutdown; do not reintroduce immediate terminate in removeWorkerFromSlot(..., 'retire').

Tested: npx vitest run test/unit/worker-pool-timeout-retire.test.ts; npx vitest run test/unit/worker-pool-timeout-retire.test.ts test/unit/worker-pool-resilience.test.ts test/unit/worker-pool-cumulative-timeout.test.ts test/unit/worker-pool-slot-generation.test.ts; npx tsc --noEmit; npm run build; npx prettier --check src/core/ingestion/workers/worker-pool.ts test/unit/worker-pool-timeout-retire.test.ts ../docs/todo/pr-1833-retired-worker-cleanup-plan.md; npx eslint src/core/ingestion/workers/worker-pool.ts test/unit/worker-pool-timeout-retire.test.ts; gitnexus detect_changes --scope staged.

Not-tested: npm test full suite did not complete green in this environment; two runs each had one unrelated test/unit/hooks.test.ts parseHookOutput null failure, and each failed hook test passed when rerun in isolation.

* ci: retrigger checks

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: wangxc <wangxc_a_bj@si-tech.com.cn>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Test <test@example.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-26 17:28:39 +01:00
Gergő Magyar
5e012c373b
fix(cli): detect missing LadybugDB native binary at startup with actionable guidance (#835) (#1837)
* fix(cli): detect missing LadybugDB native binary at startup with actionable guidance (#835)

Add checkLbugNative() pre-flight that verifies lbugjs.node exists before
any command transitively imports @ladybugdb/core. When missing (bun default
install, --ignore-scripts), prints repair instructions instead of crashing
with ERR_DLOPEN_FAILED. Also enhances `gitnexus doctor` to probe the
native binary status.

* fix(review): guard eval-server, un-guard status command

eval-server transitively loads @ladybugdb/core and needs the native
binary check. status only reads filesystem metadata and should remain
accessible when the binary is missing.

* fix(lint): use console.log instead of console.error in native check gate

The project eslint config only allows console.log.

* fix(cli): route native-check to stderr and validate binary loadability

Fixes two Codex adversarial review findings:

1. Native-check failure message now goes to process.stderr.write instead
   of console.log, preventing MCP stdout protocol contamination.

2. checkLbugNative now attempts a controlled require() probe after the
   existence check. Truncated, ABI-mismatched, or wrong-platform binaries
   produce actionable guidance instead of passing through to crash at
   process.dlopen.

---------

Co-authored-by: Test <test@example.com>
2026-05-26 17:10:08 +01:00
Gergő Magyar
05d269ec28
feat(ruby): migrate Ruby to scope-based resolution (RFC #909 Ring 3) (#1831)
* feat(ruby): migrate Ruby to scope-based resolution (RFC #909 Ring 3)

Implement the full scope-resolution pipeline for Ruby following the
PR #1639 (Rust migration) standard, targeting registration in
MIGRATED_LANGUAGES with 100% scope parity.

Scope resolver hooks (languages/ruby/):
- query.ts: RUBY_SCOPE_QUERY covering scopes, declarations, imports,
  type-bindings (constructor inference via .new), and references
- captures.ts: emitRubyScopeCaptures orchestrator with import
  decomposition, receiver-binding synthesis, method reclassification,
  and arity metadata for both declarations and calls
- receiver-binding.ts: self type-binding synthesis for instance methods,
  singleton methods, and class << self blocks
- interpret.ts: interpretRubyImport (wildcard semantics) and
  interpretRubyTypeBinding (YARD, constructor, alias sources)
- import-target.ts: resolveRubyImportTarget adapting the existing
  suffix resolver for require/require_relative/load
- merge-bindings.ts: tier-based shadowing (local > namespace > import)
- arity.ts: Ruby arity check with *args/**kwargs/&block support
- scope-resolver.ts: rubyScopeResolver with custom buildRubyMro
  (kind-aware IMPLEMENTS partitioning: prepend > direct > include;
  extend excluded from instance MRO per legacy semantics)
- simple-hooks.ts: bindingScopeFor, importOwningScope, receiverBinding

Wiring:
- ruby.ts provider gains 7 scope-resolution hooks
- Registered in SCOPE_RESOLVERS map and MIGRATED_LANGUAGES
- 127 legacy tests wired with createResolverParityIt('ruby')
- 27 new scope-specific tests in ruby-scope.test.ts

Parity: 89/127 legacy tests pass under registry-primary; 38 are
heritage/property/YARD gaps expected in V1. All 127 pass under legacy.

Closes #931

* feat(ruby): add emitHeritageEdges hook, YARD parsing, bare calls, property emission

Extend the scope-resolution pipeline with a new optional `emitHeritageEdges`
hook (ScopeResolver contract + run.ts wiring) that runs between
`preEmitInheritanceEdges` and `buildMro`. This lets languages whose heritage
declarations are syntactic method calls (Ruby include/extend/prepend) emit
IMPLEMENTS edges from the scope-resolver without touching the legacy pipeline.

Ruby scope-resolution improvements:
- Heritage: intercept include/extend/prepend in captures.ts, encode as
  special imports, emit IMPLEMENTS edges via emitHeritageEdges hook
- Properties: intercept attr_accessor/attr_reader/attr_writer, emit
  Property nodes + HAS_PROPERTY edges via the same hook
- Bare calls: add (body_statement (identifier)) capture to scope query,
  matching the legacy query pattern for zero-arity method calls
- YARD parsing: second-pass comment scanner for @param/@return/@type
  annotations with findFollowingMethod that handles body_statement nesting
- Query fixes: @declaration.trait for modules (was @declaration.module
  which normalizeNodeLabel didn't recognize), constant constructor
  bindings (SERVICE = UserService.new), call-return inference

Parity: 114/127 legacy tests pass under registry-primary (up from 89).
Remaining 13 are advanced type-inference chain resolution (compound
receiver, cross-file return-type propagation, for-in element types).

* feat(ruby): achieve 100% scope-resolution parity (127/127)

Fix all 13 remaining type-inference failures:

- Add expandsWildcardTo hook (expandRubyWildcardNames) so finalize can
  materialize individual bindings from require/require_relative wildcard
  imports, unblocking cross-file return-type propagation
- Add member-call-return type binding synthesis in captures.ts for
  assignments like `x = obj.method()` — enables compound receiver
  chaining through member call return types
- Add YARD @return support for attr_accessor/attr_reader/attr_writer
  calls, creating field-type bindings for chain resolution
- Add @declaration.property captures alongside __property__ imports so
  properties register in localDefs → model.fields → write-access
- Add constructor-return inference for methods ending with Foo.new()
- Add for-loop variable type aliasing in scope query
- Rebuild nodeLookup after emitHeritageEdges in run.ts so Property
  nodes created by the heritage hook are visible to downstream passes
- Extend compound-receiver resolver to handle compound member-call
  rawNames with () and increase max depth from 4 to 8
- Extend receiver-bound-calls Case 3b for compound rawNames

All 127 legacy Ruby tests pass under both REGISTRY_PRIMARY_RUBY=0
(legacy) and =1 (registry-primary). Ruby is now fully registered
in MIGRATED_LANGUAGES with 100% scope parity.

* test(ruby): add pipeline benchmark exercising heritage emission

Synthetic Ruby codebases at 100/250/500 files with include + extend +
prepend mixins, diamond mixin patterns (shared BaseMixin modules),
attr_accessor properties, YARD annotations, and cross-file imports.

Strict equality assertions verify exact IMPLEMENTS and HAS_PROPERTY
edge counts: 4 IMPLEMENTS per class (include x2, extend, prepend)
plus 1 per non-base mixin module, 3 HAS_PROPERTY per class.

Dedup in emitRubyMixinEdges prevents double-counting when the worker
path (repos >= 15 files) already created Property/IMPLEMENTS edges
before scope-resolution runs.

Scaling: 0.76x and 1.40x (both linear, well under 3x threshold).

* ci: retrigger build

* fix(ci): resolve format, registry-primary-flag, and sequential-mixin test failures

- Run prettier on all changed files (captures.ts, run.ts, ruby-scope.test.ts,
  ruby.test.ts, ruby-pipeline-benchmark.test.ts)
- Update registry-primary-flag.test.ts: use Swift (not in MIGRATED_LANGUAGES)
  instead of Ruby for the isolation and env-var mutation tests
- Pin ruby-sequential-mixin.test.ts to REGISTRY_PRIMARY_RUBY=0 (legacy mode)
  since it tests inferImplicitReceiver + selectDispatch hooks that live in the
  legacy call-processor (gated off under registry-primary)

---------

Co-authored-by: Test <test@example.com>
2026-05-26 16:16:49 +01:00
Gergő Magyar
d5b2edddc4
fix(test): use retry cleanup in antigravity e2e to prevent ENOTEMPTY flake (#1838)
* fix(test): use retry cleanup in antigravity e2e to prevent ENOTEMPTY flake

Replace bare `fsp.rm` / `fs.rmSync` in antigravity-hook-e2e.test.ts
afterAll with `cleanupTempDir` / `cleanupTempDirSync` from test-db.ts
which retry with backoff on transient filesystem errors.

Also make `shouldSwallowCleanupError` swallow ENOTEMPTY on all
platforms (was Windows-only). The CI failure on macOS was ENOTEMPTY
on a deeply nested node-gyp cache directory inside the temp HOME —
a cleanup-time race that retries usually resolve, but the final
attempt must not crash the test suite if the race persists.

* fix: restore fsp import needed for mkdtemp/mkdir

---------

Co-authored-by: Test <test@example.com>
2026-05-26 15:40:08 +01:00
Gergő Magyar
4870879b21
fix(wiki): add budget-aware grouping to prevent context overflow on large repos (#627) (#1832)
* fix(wiki): add budget-aware grouping to prevent context overflow on large repos (#627)

When the grouping prompt exceeds 100k tokens (e.g. Apache TVM with ~2,378
files and ~306k estimated tokens), batch files by top-level directory and
issue one LLM call per batch. Partial results are deterministically merged;
any batch failure falls back to directory-based grouping.

* fix(wiki): address review findings — exact assertions, progress fix, error logging

- Replace bounds-only .toBeGreaterThan assertions with exact .toBe values
- Add per-batch budget compliance assertion for sub-batch case
- Add assertion that partial LLM results don't leak through nuclear fallback
- Pass fixedPercent/percentRange to streamOpts in batched LLM calls
- Log batch failure in onProgress before falling back to directory grouping
- Strengthen mergeGroupings dedup test from .toContain to exact .toEqual

* chore(autofix): apply prettier + eslint fixes via /autofix command

* fix(wiki): prevent slug collisions and handle single-file oversize in batched grouping

mergeGroupings now normalizes module keys by slug so case/punctuation
variants ("API Routes" vs "API routes") merge into one module instead
of producing colliding .md files.

batchFilesForGrouping now truncates per-file symbol lists via binary
search when a single file exceeds GROUPING_TOKEN_BUDGET, so every
LLM request stays within the context window.

* style(wiki): apply prettier formatting to generator.ts

---------

Co-authored-by: Test <test@example.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-26 12:32:07 +01:00
Gergő Magyar
c916c88361
feat(mcp): add limit/offset/summaryOnly pagination to impact tool (#1818)
* feat(mcp): add limit/offset/summaryOnly pagination to impact tool (#414)

The impact tool returns unbounded byDepth arrays for hub symbols (base
error classes, shared utilities), producing 140KB+ responses that get
truncated by MCP clients. maxDepth alone does not help when most
dependents are at depth 1.

Add three new parameters:
- summaryOnly: returns counts/risk/processes/modules without byDepth
- limit: caps symbols per depth level (default 100)
- offset: skips symbols for pagination

Also adds byDepthCounts to all responses so agents can see total counts
even when the symbol list is paginated or omitted.

Closes #414

* fix(mcp): prevent pagination from silently truncating cross-repo impact

Address review findings on #1818:

- F1 (blocker): _runImpactBFS no longer defaults to limit 100 when
  limit is not set — only _impactImpl (MCP entry) applies the default.
  Internal callers (impactByUid, group impact) get complete results.
  GroupToolPort.impact interface gains optional limit param, and
  cross-impact.ts passes limit: 10000 for local UID collection.

- F2 (blocker): tool description updated — byDepth is now documented
  as paginated, not 'all affected symbols'.

- F3: impactByUid calls _runImpactBFS without limit, so Phase-2
  neighbor results are no longer capped at 100.

- F4: pagination metadata now appears when offset > 0 (head truncation),
  not just tail truncation. Pagination.limit is null when uncapped.

- F5: limit/offset schema types changed from number to integer;
  Math.trunc applied in implementation as defense-in-depth.

- F6: 7 new tests — multi-depth pagination, offset-only truncation,
  offset past end, float inputs, _runImpactBFS internal uncapped path,
  collectImpactSymbolUids with paginated vs complete data.

* fix(mcp): NaN guard on pagination params, complete GroupToolPort interface

- Add Number.isFinite guard to limit/offset in _runImpactBFS so NaN
  inputs fall through to uncapped/zero defaults instead of producing
  silent empty byDepth with no truncation signal.

- Add offset and summaryOnly to GroupToolPort.impact interface to
  match the implementation and prevent silent param loss at the
  port boundary.

- Replace bounds-only toBeLessThan assertion with exact byDepthCounts
  and pagination assertions per DoD §2.7.

* fix(mcp): address remaining review findings for impact pagination

- #3: Forward limit/offset/summaryOnly through callToolAtGroupRepo
  so group-mode MCP callers can use the new pagination params.

- #4: Extract GROUP_LOCAL_PHASE_LIMIT constant from magic 10000 in
  cross-impact.ts with a comment explaining the intent.

- #7: eval-server formatImpactResult uses byDepthCounts[depth] for
  the 'and N more' suffix instead of paginated slice length.

- #8: Extract ImpactParams interface from duplicate inline type
  definitions in impact() and _impactImpl().

- #9: Add --limit, --offset, --summary-only CLI flags to the impact
  command with i18n help strings (en + zh-CN).

- #10: Clarify in tool description that limit/offset apply per depth
  level, not per total result set.

* chore(autofix): apply prettier + eslint fixes via /autofix command

* @
fix(mcp): address Copilot review feedback on impact pagination

- Sanitize limit/offset with Number.isFinite in _impactImpl to prevent
  NaN passthrough from bypassing the default limit of 100
- Omit pagination.limit field instead of emitting null when paginationLimit
  is Infinity, keeping the response schema consistent
- Move GROUP_LOCAL_PHASE_LIMIT after all imports in cross-impact.ts
- Stop forwarding limit/offset/summaryOnly to group-mode impact since
  runGroupImpact overrides limit with GROUP_LOCAL_PHASE_LIMIT for UID
  collection and does not re-paginate
- Validate CLI parseInt results with Number.isFinite before passing to
  the backend, falling back to undefined so defaults apply
- Use byDepthCounts to decide whether to render depth sections in
  formatImpactResult, handling empty pages from offset past end
@

* @
fix(mcp): address code review findings on impact pagination

- Fix formatImpactResult "N more" count: use Math.min(items.length, 12)
  instead of hardcoded 12, so paginated pages with <12 items show the
  correct remaining count
- Detect summaryOnly responses (byDepth absent, byDepthCounts present)
  and show a summary-mode message instead of misleading "(0 items on
  this page — adjust offset)" per depth level
- Document that limit/offset/summaryOnly are single-repo only and
  ignored in group mode (@groupName) in MCP tool schema descriptions
- List byDepthCounts in summaryOnly description and note byDepth
  absence when summaryOnly is true
- Remove unused limit/offset/summaryOnly from GroupToolPort.impact
  interface since they are never forwarded to group impact
- Deduplicate parseInt calls in CLI tool.ts: extract to local variables
  with consistent optional-chain usage
@

* chore(autofix): apply prettier + eslint fixes via /autofix command

* @
fix(group): restore limit in GroupToolPort.impact interface

cross-impact.ts passes limit: GROUP_LOCAL_PHASE_LIMIT through the
GroupToolPort.impact interface for UID collection. Only offset and
summaryOnly were truly unused — limit must stay.
@

* @
docs: add limit/offset/summaryOnly to impact tool options in README
@

---------

Co-authored-by: Test <test@example.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-26 08:48:24 +01:00
Sparsh
966ddb981e
feat(cpp): thread base-specifier qualifier through dependent-base lookup (#1815) (#1819)
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
* feat(cpp): thread base-specifier qualifier through dependent-base lookup (#1815)

captures.ts: add extractBaseLookupQualifier, fix isBaseDependent
for qualified_identifier bases. two-phase-lookup.ts: qualifier
storage, markCppDependentBase accepts qualifier, dedup index
by nodeId (last-wins), V3 qualifier targeting (dormant).

Infrastructure delivered: qualifier extraction, storage, dedup,
isBaseDependent fix. V3 targeting dormant until qualifiedName
computation fix reaches localDefs.

Part of #1564. Infrastructure for #1815.

* fix(cpp): three conservatism fixes for dependent-base lookup

Fix 1 — Map collision in markCppDependentBase (line 83):
Change innermost storage from Map<baseName, qualifier> to
Map<baseName, Set<qualifier>> so multiple captures of the same
dependent base name with different qualifiers don't collide.

Fix 2 — Single-candidate bypass (lines 197-206):
For qualified bases with only one candidate, verify namespace match
before accepting. Unqualified bases still accept the unique candidate.
Previously accepted regardless, creating false edges.

Fix 3 — V3→V2 fallthrough (line 221):
When a syntactic qualifier is present but no exact match is found,
suppress rather than falling through to V2 prefix-heuristic. V2 only
runs for truly unqualified bases, which is what it was designed for.

All three are conservative bug fixes — turn false positives into
suppression, not behavior changes. 250/250 tests pass both modes.

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-26 08:01:55 +01:00
dependabot[bot]
05151b1079
chore(deps)(deps): bump lru-cache from 11.3.6 to 11.4.0 in /gitnexus (#1826) 2026-05-26 07:28:32 +01:00
dependabot[bot]
5458ddce77
chore(deps)(deps-dev): bump @types/node in /gitnexus (#1825) 2026-05-26 05:59:15 +01:00
dependabot[bot]
3161938730
chore(deps)(deps-dev): bump vitest from 4.1.6 to 4.1.7 in /gitnexus (#1824) 2026-05-26 05:27:57 +01:00
Gergő Magyar
d4449b4ec8
fix(lbug): resolve non-ASCII paths for KuzuDB on Windows (#1811) (#1817)
* fix(lbug): resolve non-ASCII paths to 8.3 short form on Windows (#1811)

KuzuDB's native C++ layer uses ANSI file APIs (fopen) on Windows.
When the repo path contains CJK or other non-ASCII characters, the
UTF-8 bytes from Node.js are misinterpreted as the system's Active
Code Page (e.g. GBK), producing a garbled path — "Error 3: The
system cannot find the path specified."

Add `toNativeSafePath()` which converts non-ASCII paths to their
Windows 8.3 short-name form (all-ASCII) before passing them to the
native layer. Applied to both the database open path and the COPY
CSV paths. No-ops on non-Windows and on all-ASCII paths.

Closes #1811

* test(lbug): add unit + integration tests for non-ASCII path handling (#1811)

- Unit tests for toNativeSafePath: ASCII passthrough, non-Windows
  no-op, Windows short-path conversion, nonexistent-path fallback
- Integration test: full initLbug + loadGraphToLbug round-trip with
  CJK characters in the storage path — runs on all platforms
- Fix toNativeSafePath to reject cmd.exe output containing '?' chars
  (replacement for unrepresentable Unicode in the console code page)
- Register integration test in vitest lbug-db project and
  cross-platform-tests.ts matrix

* chore(autofix): apply prettier + eslint fixes via /autofix command

* feat(lbug): junction fallback, tmpdir CSV staging, pool-adapter coverage (#1811)

U1+U4: toNativeSafePath now tries 8.3 short path → NTFS junction
fallback → diagnostic warning. Junctions target path.dirname(p) and
reconstruct the leaf. Handles EEXIST races. Registers cleanup on
exit/SIGTERM/SIGINT. Orphan scan on first call removes stale
junctions from prior crashes.

U2: loadGraphToLbug redirects csvDir to os.tmpdir() when
storagePath contains non-ASCII on Windows, avoiding non-ASCII
characters in COPY FROM paths entirely.

U3: All 4 createLbugDatabase call sites in pool-adapter.ts now
wrap dbPath with toNativeSafePath.

* fix(test): fix CI failures from toNativeSafePath addition (#1811)

- Fix lbug-non-ascii-path integration test: use CodeRelation (actual
  relationship table name) instead of CALLS
- Add toNativeSafePath to lbug-config.js mocks in pool-wal-recovery
  and lbug-pool-win-fts-probe tests — pool-adapter now imports it

* fix(lbug): sanitize path before cmd.exe shell expansion (CodeQL)

Reject paths containing cmd.exe metacharacters (" % | & < > ^)
before interpolating into the `for %I` short-path command.
Prevents command injection via crafted path names.

* fix(lbug): address code review findings in non-ASCII path implementation

- U1: Use process.exit(0) on Windows instead of process.kill re-raise
  (SIGTERM forcefully kills on Windows, handlers never fire)
- U2: Pass safePath to openWithLockRetry so sidecar sweep targets the
  path KuzuDB actually opened, not the original non-ASCII path
- U3: Skip junction creation in worker threads (isMainThread guard) to
  prevent junction leaks from pool-adapter workers
- U4: Replace existsSync with lstatSync in orphan scan to avoid 30s
  blocking on unreachable UNC network targets

* chore(autofix): apply prettier + eslint fixes via /autofix command

* fix(lbug): correct SIGTERM exit code and run Prettier (#1811)

- Use exit code 143 (SIGTERM) / 130 (SIGINT) on Windows instead of 0
  so termination is not masked as success
- Run Prettier to fix formatting (CI Gate blocker)

* fix(lbug): eliminate CodeQL command-injection taint in tryShortPath

Pass the path via GITNEXUS_SP environment variable instead of
interpolating it into the cmd.exe command string. The FOR loop
reads %GITNEXUS_SP% from the environment, so the command text is
entirely static — no user-controlled data in the shell command.

Also removes CMD_UNSAFE_RE since the env var approach makes
character-level sanitization unnecessary.

---------

Co-authored-by: Test <test@example.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-25 21:28:12 +01:00
Gergő Magyar
a229e8e77b
fix(build): skip build.js when running outside the monorepo (#1795) (#1816)
`scripts/build.js` assumes the monorepo sibling `gitnexus-shared`
exists. When a user runs `npm install` from within a global install
directory, the `prepare` lifecycle fires `build.js`, which calls
`execSync(tsc, { cwd: nonExistentPath })` — Node reports this as
the misleading `spawnSync /bin/sh ENOENT`.

Add an early guard: if `gitnexus-shared` is absent and `dist/`
already exists (published package context), exit cleanly. If neither
exists, print a helpful error pointing to the monorepo checkout.

Co-authored-by: Test <test@example.com>
2026-05-25 15:31:11 +01:00
Nilotpal Kashyap
50c6acb108
feat(setup): implement antigravity integration setup and hook adapter… (#1730)
* feat(setup): implement antigravity integration setup and hook adapter for gitnexus

* docs(readme): list Antigravity in supported editors

* test(setup-antigravity): pin platform per-test to fix Windows CI failure

The MCP entry assertion expected `npx` directly, but on Windows
`getMcpEntry()` wraps it as `cmd /c npx ...`, which broke the Windows
runner. Pin platform to darwin in beforeEach so the existing assertion
is deterministic, restore the descriptor in afterEach, and add a
parity test for the win32 cmd-wrapper shape.

* fix(antigravity): align hook adapter to Gemini CLI schema + fix Windows CI

Rebase the Antigravity integration on the canonical Gemini CLI hooks
contract (https://geminicli.com/docs/hooks/reference/), which is the
documented schema Antigravity 2.0 inherits:

- Hook adapter: replace PreToolUse/PostToolUse with the single AfterTool
  event. BeforeTool has no documented context-injection channel in the
  Gemini contract, so augmentation runs in AfterTool where
  hookSpecificOutput.additionalContext is the documented way to append
  text to the tool result the agent reads. Stale-index hints land in the
  same channel (so the agent sees them) and are mirrored to stderr for
  terminal users. Tool-name matcher updated to Gemini CLI snake_case
  (search_file_content|glob|run_shell_command).
- Setup: write hooks to ~/.gemini/settings.json under canonical
  hooks.AfterTool[] (replaces the ad-hoc hooks.json top-level group).
  Polite-neighbor merge preserves existing user hooks. Also copy
  win-rm-list-json.ps1 alongside hook-db-lock-probe.cjs so the Windows
  MCP server ownership probe doesn't silently fail open.
- Tests: 17 regression tests covering MCP write, win32 shape, hook
  schema, polite-neighbor merge, idempotency, adapter context emission,
  stale-index hint, and skill layout.
- README: footnote documenting the AfterTool design choice and a link
  to the Gemini CLI hooks reference.

Windows CI fix: installSkillsTo previously used glob('*.md') +
glob('*/SKILL.md'), which returned zero matches under the Windows
runner's temp paths (8.3 short-name like RUNNER~1). Replace with
fs.readdir + dirent type checks — same behavior, no path quirks. This
fixes the only failing Windows job on the PR.

* fix(antigravity): address PR review — windowsHide, stale docs, dead code

Addresses the production-readiness review findings on PR #1730:

- F1 (blocker): add windowsHide:true to all four spawnSync sites in the
  Antigravity hook adapter (findCanonicalRepoRoot, runGitNexusCli's two
  branches, buildStaleIndexHint) so they don't flash console windows on
  Windows. Matches the fix #1794 already on main for the Claude hook.
- F2 (blocker): update gitnexus/README.md editor table to say AfterTool
  and link the Gemini CLI hooks reference. The published README had
  drifted to the pre-c1872b4 PreToolUse + PostToolUse schema.
- F3: rewrite the stale ~/.gemini block comment in setup.ts. It still
  described the old hooks.json + gitnexus group + grep_search design.
- F4: remove grep_search dead code from extractPattern and its doc
  comment. The registered matcher is search_file_content|glob|run_shell_command,
  so grep_search would never be invoked.
- F5: annotate timeout:10000 with a ms-unit comment noting Gemini CLI
  uses milliseconds (Claude Code uses seconds).
- F6: add the GITNEXUS_DEBUG branch to extractAugmentContext for parity
  with the Claude adapter, so suppressed augment stderr is recoverable.
- F7: stageAdapter test helper now copies win-rm-list-json.ps1 alongside
  the .cjs helpers, so the adapter's Windows lock-probe path isn't a
  silent fail-open in child-process smoke tests.

* test(antigravity): add integration tests and register in cross-platform matrix

Adds end-to-end coverage on top of the unit-level tests, per maintainer
request:

- test/integration/setup-antigravity.test.ts (10 tests): exercises the
  real setupCommand() against a temp HOME with ~/.gemini/antigravity/
  present. Verifies mcp_config.json shape, ~/.gemini/settings.json
  AfterTool entry, adapter + helpers + win-rm-list-json.ps1 copy,
  baked-in cliPath rewrite (issue #108 regression class), skill layout,
  polite-neighbor merge against existing user hooks, idempotency,
  skip-when-absent, corrupt-file safety, and key preservation.
- test/integration/antigravity-hook-e2e.test.ts (19 tests): runs the
  full install-then-execute flow — invokes setupCommand to lay down
  the adapter + helpers, then spawns the INSTALLED adapter as a real
  child process against a temp git repo + .gitnexus/. The source
  adapter cannot be spawned directly (it requires sibling .cjs helpers
  that only live in hooks/claude/); install-then-spawn mirrors the
  production codepath. Covers staleness detection across all five git
  mutation types, --embeddings propagation, polite skip on
  toolResponse.error / exit_code !== 0, augment crash-free behavior,
  cwd validation, corrupted/missing meta.json, unknown event names,
  empty stdin, and the no-.gitnexus deep-nested case.
- scripts/cross-platform-tests.ts: registers all three antigravity
  test files (unit in PLATFORM_LOGIC, two integration files in
  SPAWN_CLI) so Windows and macOS CI exercise them on every run.

* fix(antigravity): review fixes — dedup, silent-failure guard, type coercion, glob filter

- Delete mergeGeminiSettingsHooks (verbatim copy of mergeHooksJsonc),
  replace call site with the original
- Unify geminiHasGitnexusHook into hasGitnexusHook with commandFragment
  parameter; delete the duplicate
- Guard against silent adapter-copy failure: verify the adapter file
  exists before registering the AfterTool hook entry in settings.json;
  surface helper copy errors instead of swallowing
- Fix toolSucceeded type coercion: use Number() so string exit_code
  values from Gemini CLI are handled correctly
- Align glob tool extractPattern with Claude adapter's restrictive
  regex filter (/[*\/]([a-zA-Z][a-zA-Z0-9_-]{2,})/)
- Remove bounds-only toBeGreaterThan(0) assertion (DoD §2.7)
- Add antigravity adapter to HOOK_FILES windowsHide regression list

* chore(autofix): apply prettier + eslint fixes via /autofix command

* chore: trigger CI

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Test <test@example.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-25 14:46:17 +01:00
Copilot
baf57bec88
feat(rust): Migrate Rust to scope-based resolution (RFC #909 Ring 3) (#1639)
* Initial plan

* feat: add Rust scope-resolution hooks (RFC #909 Ring 3)

Implement the scope-based resolution pipeline for Rust, following the
established pattern from Go and other migrated languages.

New files in gitnexus/src/core/ingestion/languages/rust/:
- query.ts: tree-sitter scope query covering scopes, declarations,
  imports, type bindings, and references
- cache-stats.ts: parse cache hit/miss counters
- import-decomposer.ts: decomposes use declarations into individual
  import captures (handles grouped, wildcard, renamed, re-exported)
- receiver-binding.ts: synthesizes self type bindings for impl methods
- interpret.ts: interprets captures into ParsedImport/ParsedTypeBinding
- arity.ts: arity compatibility checker (no overloading in Rust)
- merge-bindings.ts: local-shadows-import binding merge strategy
- simple-hooks.ts: binding scope, import owning scope, receiver binding
- import-target.ts: resolves Rust module paths (crate/super/self)
- method-owners.ts: bridges impl block methods to struct defs
- captures.ts: main emit function with import decomposition and
  self-binding synthesis
- scope-resolver.ts: ScopeResolver implementation
- index.ts: barrel re-exports

Wiring changes:
- rust.ts: add scope hook imports and properties to defineLanguage
- registry.ts: register rustScopeResolver in SCOPE_RESOLVERS
- registry-primary-flag.ts: add Rust to MIGRATED_LANGUAGES

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Co-authored-by: magyargergo <11230420+magyargergo@users.noreply.github.com>

* feat(LANG-rust): add scope-resolution hooks and register Rust ScopeResolver

Implements RFC #909 Ring 3 deliverables:
- query.ts: tree-sitter scope query for Rust
- captures.ts: emitRustScopeCaptures with method reclassification
- import-decomposer.ts: use statement decomposition (groups, renames, globs)
- interpret.ts: interpretRustImport + interpretRustTypeBinding
- import-target.ts: crate/module/super/self path resolution
- receiver-binding.ts: self/&self/&mut self receiver synthesis
- method-owners.ts: impl block → struct ownership bridging
- arity.ts: no-overloading arity check
- merge-bindings.ts: local > import > wildcard binding precedence
- simple-hooks.ts: binding/import scope, receiver binding
- scope-resolver.ts: ScopeResolver contract implementation
- Wired into rustProvider (rust.ts) with scope hooks
- Registered in SCOPE_RESOLVERS (pipeline/registry.ts)
- NOT yet added to MIGRATED_LANGUAGES (29 advanced pattern tests pending)

Agent-Logs-Url: https://github.com/abhigyanpatwari/GitNexus/sessions/8f14b730-79d4-4356-9505-325750d71f84

Co-authored-by: magyargergo <11230420+magyargergo@users.noreply.github.com>

* Add Rust scope-resolution integration tests (RFC #909 Ring 3)

Tests cover the core deliverables for the Rust scope-resolution pipeline:
- impl blocks and trait implementations
- Module resolution (crate::, super::, self::)
- Struct fields and type bindings
- Self/&self/&mut self receiver binding
- Generic functions (V1 ignores generic args)
- Grouped imports (use foo::{A, B})
- Renamed imports (use foo::Bar as Baz)
- Arity checking (no overloading)
- Struct literal constructor inference
- Return type inference
- Scoped/qualified calls (Foo::new())
- Enum declarations
- Multiple impl blocks
- Free function calls
- Typed let bindings

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Co-authored-by: magyargergo <11230420+magyargergo@users.noreply.github.com>

* test(LANG-rust): add 28 scope-resolution integration tests

Covers 15 test suites validating: impl blocks, trait impls, grouped
imports, renamed imports, module resolution, receiver binding,
arity filtering, struct literal inference, return type inference,
qualified calls, struct fields, enums, multiple impl blocks, free
calls, and typed let bindings.

Agent-Logs-Url: https://github.com/abhigyanpatwari/GitNexus/sessions/8f14b730-79d4-4356-9505-325750d71f84

Co-authored-by: magyargergo <11230420+magyargergo@users.noreply.github.com>

* feat(LANG-rust): add implicit crate path fallback, 35 scope tests

- Import resolver now falls back to crate-relative for unqualified
  module paths (Rust 2015 edition compat)
- Added 7 more test cases: re-exports, shadowing, closures, default
  trait methods (35 total, exceeding ≥30 requirement)

Agent-Logs-Url: https://github.com/abhigyanpatwari/GitNexus/sessions/8f14b730-79d4-4356-9505-325750d71f84

Co-authored-by: magyargergo <11230420+magyargergo@users.noreply.github.com>

* feat(rust): add Rust to MIGRATED_LANGUAGES with 100% scope-resolution parity

35/35 integration tests pass under both REGISTRY_PRIMARY_RUST=0 (legacy)
and =1 (scope-resolution). Rust scope-resolution is now the default
production call-resolution path.

* test(rust): add pipeline benchmark matching PHP benchmark pattern

Generates synthetic Rust codebases at 100/250/500 files with structs,
impl blocks, traits, cross-module use declarations, and method calls.
Measures wall-clock time, peak heap, and scaling ratios.

Results: sub-linear scaling (0.79x ratio), 500 files in 3.8s with
workers, 110MB peak heap. Gated by GITNEXUS_BENCH=1.

* chore(autofix): apply prettier + eslint fixes via /autofix command

* perf(rust): optimize captures, type normalization, and method-owner linking

- Cache findEnclosingImpl result to avoid duplicate tree walk per function
- Avoid double namedChild accessor call in struct field arity counting
- Extract regex constants (REF_PREFIX_RE, PTR_PREFIX_RE) from hot normalization loops
- Replace O(s) suffix-match scan with O(1) Map lookup in method-owner linking

Benchmark: 500 files 3806ms → 2970ms (-22%), 250 files 2432ms → 1752ms (-28%)

* fix(rust): resolve CodeQL alerts — file-system race and dead code

- Remove existsSync+appendFileSync/writeFileSync TOCTOU in benchmark
  fixture generator; appendFileSync creates if missing
- Remove always-true guard on computeRustCallArity return; narrow
  return type from number|undefined to number
- Remove no-op .filter() in fixture generator

* feat(rust): hoist impl return-type bindings to struct scope for chain resolution

Synthesize a module-level duplicate of @type-binding.return captures for
methods inside impl blocks. The scope-extractor's auto-hoist places these
on the struct's Class scope, making them visible to the compound receiver
chain resolver via classScopeByDefId. Without this, method return types
are only on the impl block scope (which has no class-like def and is not
indexed by classScopeByDefId), so chains like svc.get_user().save()
cannot follow the intermediate return type.

This is the structural prerequisite for chain resolution, pattern binding,
and for-loop element-type parity (28 remaining tests). The cross-file
return-type propagation step still needs wiring for full parity.

* fix(rust): use implNode anchor for return-type hoisting — fixes chain resolution

Use the enclosing impl_item node (not tree.rootNode) as the synthetic
capture anchor. The scope-extractor's auto-hoist places bindings whose
anchor matches the innermost scope on the parent scope. With implNode,
the binding lands on the Module scope (parent of impl's Class scope),
giving declaredAtScope the correct context for findClassBindingInScope
to resolve the return type across the scope chain.

Unlocks: chain calls (svc.get_user().save()), return-type inference,
assignment chains, cross-file binding propagation, call-result binding,
deep field chains — 28→27 failing tests.

* feat(rust): add populateRangeBindings hook + .await query capture

Implement populateRustRangeBindings (Phase 2 hook, same pattern as Go's
populateGoRangeBindings) to populate type bindings that need runtime type
lookup — for-loop element types, if-let/while-let captured patterns,
match arm patterns, and struct destructuring field types.

Also add tree-sitter query capture for let x = fn().await — unwraps
await_expression to find the inner call_expression.

28→19 failing tests: fixes for-loop Tier 1c, .iter()/.into_iter(),
async .await, if-let captured_pattern.

* fix(rust): fix tuple_struct_pattern variable extraction + Result<T,E> raw type lookup

- Skip wrapper type identifier when finding bound variable in
  tuple_struct_pattern (Some(user) was binding 'Some' not 'user')
- Add lookupRawParameterType to read unstripped generic type from AST
  for Ok/Err pattern resolution (normalizeRustTypeName strips generics)

28→15 failing tests: fixes if-let Some, if-let Ok/Err, match arm patterns.

* fix(rust): fix match_arm parent traversal + raw return type for for-loop calls

- Walk up from match_arm through match_block to find match_expression
  for source variable extraction
- Add lookupRawFunctionReturnType to find unstripped return type from
  AST for same-file for-loop call expression iterables

28→14 failing tests.

* feat(rust): inject field type bindings on struct scopes for chain resolution

Walk struct_item AST nodes and inject field types (e.g., address -> Address)
as typeBindings on the struct's Class scope. The compound receiver chain
resolver uses these to follow field chains like user.address.save().

Also fixes: match_arm parent traversal to match_expression, lookupFieldType
to check typeBindings first.

28→11 failing tests: fixes field type chains, deep chains, struct destructuring.

* feat(rust): cross-file return type lookup for for-loop call iterables

Build allReturnTypes map across all parsedFiles in Phase 2 first pass,
then use it to resolve for-loop iterables like `for x in get_fn()` when
get_fn is defined in another file.

28→9 failing tests.

* feat(rust): cross-file field type map for struct destructuring

Build allFieldTypes map across parsedFiles in Phase 2 first pass. Used
by processStructDestructuring to resolve `let Point { x, y } = p` when
Point is defined in another file.

28→7 failing tests.

* fix(rust): compound assignment write capture + pending assignment fixpoint

- Add compound_assignment_expr query for +=, -=, etc. field writes
- Add processPendingAssignments with 3-pass fixpoint for field access
  and method call result variable bindings (let addr = user.address,
  let city = addr.get_city())

28→5 failing tests.

* fix(rust): identity method return-type bindings for unwrap/expect chains

Inject unwrap/expect/clone/as_ref/as_mut as return-type bindings on
struct scopes that return the struct's own type. Since normalizeRustTypeName
already unwraps Option<T> → T, calling .unwrap() on a value typed as T
is semantically an identity — the return type equals the receiver type.

28→3 failing tests: fixes user.unwrap().save() and repo.unwrap().save() chains.

* fix(rust): skip enum variant call-return bindings + cross-file pending assignments + identity alias

- Skip Some/None/Ok/Err in @type-binding.call-return — these are enum
  variant constructors, not type names; let the annotation capture win
- Add identifier alias handler in processPendingAssignments for
  `let alias = opt` chains
- Cross-file field type and method return type lookup in pending
  assignment fixpoint via findFieldTypeAcrossFiles/findMethodReturnTypeAcrossFiles
- Identity method bindings (unwrap/expect/clone) on struct scopes

155/156 tests pass (99.4%). Remaining: trait default method dispatch
via MRO (repo.count() where count has default impl on Repository trait).

* feat(rust): 100% scope-resolution parity — MRO with same-file IMPLEMENTS + trait default method reclassification

- Add buildRustMro that includes same-file IMPLEMENTS edges in the MRO
  chain, so trait default methods (e.g., repo.count()) resolve through
  the struct → trait ancestry walk
- Only add IMPLEMENTS to MRO when struct and trait are in the same file;
  cross-file trait calls require the trait to be imported (Rust semantics)
- Reclassify function_item inside trait_item as @declaration.method so
  default trait methods register in the model's methods lookup

156/156 legacy parity tests pass. 35/35 scope tests pass. 0 regressions.

* fix(rust): address code review findings — null guard, name collision, scope order

- Fix Array.find() null guard: check === undefined not === null in
  processCapturedPattern (find() never returns null)
- Fix allReturnTypes/allFieldTypes name collision: delete entry on
  second occurrence so colliding names (new, default, Config) produce
  no result rather than a wrong result
- Fix lookupTypeInScopes: search function scope then module scope only,
  skip unrelated Class scopes that could shadow names from other functions

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: magyargergo <11230420+magyargergo@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Test <test@example.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-25 13:20:08 +01:00
eddie.pan
5ce448a93a
feat(wiki): support local Claude and Codex providers (#1769)
* feat(wiki): support local Claude and Codex providers

* chore(autofix): apply prettier + eslint fixes via /autofix command

* fix(wiki): address local CLI provider review findings

- Add subprocess timeout: LocalCLIConfig gains requestTimeoutMs,
  runLocalCLI sets a kill timer that rejects with an actionable error
  matching the HTTP timeout message format. --timeout is no longer
  silently ignored for claude/codex providers.
- Add windowsHide: true to spawn() to prevent console window flash on
  Windows, matching cursor-client.ts behavior.
- Skip GITNEXUS_MODEL env var for local providers so a user's OpenAI
  model name doesn't cross-contaminate claude/codex CLI invocations.
  Precedence for local providers: --model → savedLocalModel → ''.
- Guard against empty stdout: reject with actionable error when CLI
  exits 0 but produces no output, preventing silent empty wiki pages.

* fix(wiki): address deep-review findings in local CLI providers

- Move empty-output guard from runLocalCLI to per-provider callers so
  Codex can read --output-last-message file even when stdout is empty
- Merge existing config in interactive setup (local + Azure paths) to
  prevent saveCLIConfig from erasing previously saved API keys
- Use StringDecoder for stdout/stderr to handle multi-byte UTF-8 chars
  split across pipe chunk boundaries
- Distinguish ENOENT from non-zero exit in detectLocalCLI so users see
  auth guidance instead of misleading "CLI not found" when the binary
  exists but is not authenticated

* test(wiki): add subprocess contract tests for local CLI providers

Add 21 integration-level tests covering the Claude and Codex subprocess
contracts that wiki-flags.test.ts mocks out:

- Claude argv: -p, --output-format text, --no-session-persistence,
  --model conditional, stdin prompt content, CI=1, windowsHide:true
- Codex argv: exec subcommand, --sandbox read-only, -c approval_policy,
  --output-last-message temp path, --cd, stdin marker, --model
- Timeout: kill timer fires and rejects, no timer when unset
- Codex file fallback: stdout used when file missing, error when both empty
- detectLocalCLI: warn on non-ENOENT, silent on ENOENT
- onChunk: cumulative byte count forwarded

Also register the test in cross-platform-tests.ts SPAWN_CLI section and
fix detectLocalCLI ENOENT detection logic (invert the check so non-ENOENT
errors produce a warning).

* fix(wiki): platform-aware process tree kill and Codex contract snapshot

- Add killChildTree helper that uses taskkill /T /F /PID on Windows to
  terminate the entire process tree (including cmd.exe grandchildren),
  with fallback to child.kill() if taskkill fails or on non-Windows
- Add Codex CLI flag contract snapshot test that locks the exact spawn
  args — any flag rename, reorder, or removal is caught immediately
- Add Windows taskkill tests: success path asserts taskkill called with
  correct PID and /T /F flags, failure path verifies child.kill() fallback

---------

Co-authored-by: eddie.pan2 <eddie.pan2@jtexpress.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Test <test@example.com>
2026-05-25 12:59:48 +01:00
Sparsh
1bbc876336
fix(cpp): dependent-base resolution across nested/inline namespaces (#1634) (#1814)
* fix(cpp): dependent-base resolution across nested/inline namespaces (#1634)

Replace exact namespace-prefix match with prefix-contains filter capped
at one level deeper, then accept only if exactly one candidate survives.

Behavior change:
- Derived<T> in ns::outer can now find Inner<T> in ns::outer::inner
  (nested namespace) or ns::v1 (inline namespace) via prefix walking
- Global-scope deriving classes match any single-segment namespace
- Sibling namespace collisions (e.g. detail::Inner vs public_api::Inner)
  correctly suppress when multiple candidates share the same simple name
- Deep nesting (ns → ns.a.b) still suppresses (one-level cap)

Fixtures added:
  pos:  nested ns, this->f() -> 1 edge to inner::Inner::f
  neg:  no Inner exists -> 0 edges
  inline:  inline namespace variant -> 1 edge
  sibling-suppress:  sibling collision -> 0 edges (ambiguity suppressed)

Part of #1564.
64.

* test: add deep-nesting suppression fixture, link #1815 in comment, unqualify inline fixture

- Update code comment to reference follow-up issue #1815 instead of
  'deferred to follow-up'
- Inline fixture: drop explicit v1:: qualifier (exercise inline-expansion
  path more idiomatically as DoD intended)
- Add deep-nesting suppression fixture (ns.a.b -> 0 edges) that pins the
  one-level cap as a documented invariant
- Add legacy parity entry for deep-nesting fixture

Part of #1564, #1634.

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-25 12:36:06 +01:00
Gergő Magyar
5e8690f992
feat(progress): add per-language progress reporting to scope-resolution phase (#1813)
* feat(progress): add per-language progress reporting to scope-resolution phase (#1741)

The scope-resolution phase (which can run 74+ minutes on large Java/Kotlin
repos) previously emitted zero progress updates, causing the CLI progress bar
to freeze at ~49% with a stale "Parsing code" label — making users think
the tool was stuck.

- Add `scopeResolution` to PipelinePhase type and PHASE_LABELS
- Add `onProgress` callback to `runScopeResolution` with per-file updates
  during the extract loop and sub-phase boundary markers (building scope
  model, resolving references, emitting edges)
- Wire progress through `scopeResolutionPhase` with pre-counted file totals,
  per-language labels, and pipeline-wide percent mapping (90-95 internal)
- Bump mro/communities/processes percent ranges to 95-100 to maintain
  monotonic progress after scope resolution
- Add `scopeResolution` to mro's deps (latent ordering fix: mro reads
  EXTENDS edges that scope resolution writes via preEmitInheritanceEdges)

* fix(progress): clamp overallRatio, fire final extract event, fix mro @deps JSDoc

- Clamp overallRatio to [0,1] so percent never exceeds 95 when
  readFileContents drops files (langFileCount < totalScopeFiles)
- Fire onProgress for the last file in the extract loop even when
  files.length is not divisible by progressInterval
- Update mro @deps JSDoc to include scopeResolution

* fix(progress): ensure bar redraws at every state transition

- Fire initial 'extracting' event at file 0 so the sub-phase label
  appears immediately, not after progressInterval files
- Emit a completion event at percent 95 when scope resolution finishes
  so the bar definitively reaches the phase ceiling before mro starts

* feat(progress): improve UX with human-readable elapsed, language counter, cleaner labels

- Format elapsed time as "5m 12s" / "1h 20m" instead of raw "(312s)"
  for all pipeline phases (CLI-wide improvement)
- Add language counter "[1/3]" to scope-resolution detail so users
  know how many languages remain and which is active
- Rename sub-phases for clarity: "building scope model" → "analyzing
  types", "emitting edges" → "linking symbols"
- Remove nested parentheses from detail strings for cleaner display
- Expand scope-resolution percent range from 5 to 8 points (90-98
  internal → 54-59% display) for more visible bar motion
- Re-allocate mro (98), communities (98-99), processes (99-100)

* feat(progress): typed sub-phases, i18n locales, and test coverage

- Extract ScopeResolutionSubPhase union type with exhaustive switch
  guard so adding a sub-phase without updating phase.ts is a compile
  error
- Add scopeResolution key to en and zh-CN locale files so the web UI
  shows translated labels instead of raw message fallback
- Extract formatElapsed to its own module with 7 boundary-value tests
  (0s, 59s, 60s, 3599s, 3600s, 3661s, 7323s)
- Add runScopeResolution onProgress integration test proving sub-phase
  order (extracting → analyzing types → resolving references → linking
  symbols) and the 0-file early-return path

---------

Co-authored-by: Test <test@example.com>
2026-05-25 11:53:54 +01:00
Sparsh
73a6a5376e
fix(cpp): thread call-site types into qualified member lookup (#1632) (#1810)
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
* fix(cpp): thread call-site types into qualified member lookup (#1632)

Widen Callsite (arity optional, add argumentTypes) and add optional
callsite?: Callsite to ScopeResolver.resolveQualifiedReceiverMember.
receiver-bound-calls.ts passes the ReferenceSite through structurally;
resolveCppQualifiedNamespaceMember forwards it to narrowOverloadCandidates
along with cppConversionRank, enabling exact-type and conversion-rank
disambiguation across inline-namespace children.

Behavior change:
- outer::foo(42) where v1 declares foo(int) and v2 declares foo(double)
  now resolves to v1::foo (was: 0 edges, conservatively suppressed).
- Same-name same-normalized-signature (e.g. foo(int) vs foo(long)) still
  suppresses at 0 edges via isOverloadAmbiguousAfterNormalization.
- ADL using-import path (resolveAdlCandidates) unchanged — passes no
  callsite, narrowing degrades to existing pass-through behavior.

Closes #1632. Part of #1564.

* fix(cpp): update legacy parity expected-failure list for #1632

- Remove stale expected-failure entry for old diff-sigs test name
  (test now expects 1 edge; legacy DAG also emits 1 edge)
- Add entry for normalized-signature ambiguity (int vs long) test
- Rename describe block from 'conservative suppress' to
  'distinct signatures resolved via call-site types'

Verified both modes:
  REGISTRY_PRIMARY_CPP=1: 241/241 passed
  REGISTRY_PRIMARY_CPP=0: 194 passed, 47 skipped, 0 failed
2026-05-25 07:11:47 +01:00
Lucas van Staden
1c4993251c
fix(php): synthesize module scope for namespace-less PHP files (.phtml) (#1801)
* fix(php): phtml scope synthesis with full-file range + O(1) Step 4 lookup (#1801, #1803)

Address PR #1801 review findings and complete #1803 fix:

scope-extractor.ts:
- Synthetic Module scope uses full-file range (computed from existing
  drafts) so positionIndex containment works for top-level references
  in ERROR-root .phtml files
- Orphan scope re-parenting done on drafts in extract() by replacing
  with new drafts — no mutation of readonly fields, no PHP-specific
  logic in shared buildScopeTree
- Dead matchCount parameter removed from ensureModuleScope

namespace-siblings.ts:
- Step 4 parsedFiles.find() replaced with pre-built Map for O(1) lookup
  (was O(n²) with 16K files = ~256M comparisons)

* test(php): add pipeline benchmark for scaling regression detection

Synthetic PHP fixture generator (N files × M namespaces × K classes)
with cross-namespace imports and calls. Measures wall-clock, peak heap,
node/edge counts at 100/250/500 file scales with worker pool enabled.

Results on current branch:
- 100 files: 982ms, 65MB (9.8ms/file)
- 250 files: 1310ms, 70MB (5.2ms/file)
- 500 files: 2006ms, 92MB (4.0ms/file)
- Scaling: sublinear (0.53x-0.77x ratio)

Gated behind GITNEXUS_BENCH=1 so it does not run in normal CI.

* chore: trigger CI

* fix: prettier formatting + update scope-extractor test for synthesis behavior

* fix: extend synthetic Module range to all captures + update integration test

Address CI failure and review findings:
- ensureModuleScope now computes range from ALL captures (scope,
  declaration, reference, type-binding) not just scope drafts. This
  ensures top-level references after the last inner scope are covered.
- Update parse-worker-scope-integration test for synthesis behavior.
- Update extract() docstring to document synthesis contract.

---------

Co-authored-by: Test <test@example.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-24 20:37:17 +01:00
Gergő Magyar
06c3fb360d
fix(group): move manifest/workspace extraction before closeLbug (#1802) (#1807) 2026-05-24 19:53:07 +01:00
Lucas van Staden
2006a3e5ac
fix(php): reduce memory during deferred-call accumulation and scope-resolution (#1800) 2026-05-24 15:53:20 +01:00
Gergő Magyar
66f9ec8eff
feat(java): add Java to MIGRATED_LANGUAGES with 100% scope-resolution parity (#1805)
* feat(java): add Java to MIGRATED_LANGUAGES with 100% scope-resolution parity

Route Java through the scope-resolution pipeline instead of the legacy
single-threaded call processor, fixing the analyze hang on large Java
codebases (issue #1741).

Changes:
- Add Java to MIGRATED_LANGUAGES (registry-primary-flag.ts)
- Add tree-sitter queries for var type inference (call-result, alias,
  field-access, enhanced-for), instanceof/switch pattern bindings,
  and method references (User::getName, this::save, User::new)
- Fix importedName to use simple class name instead of FQN so
  finalize binding materialization matches correctly
- Implement buildJavaMro with IMPLEMENTS edge transitive closure
  for interface default method resolution
- Implement populateJavaPackageSiblings for same-package implicit
  class visibility across files
- Implement cross-file return-type mirroring from imported class
  files via populateRangeBindings hook
- Add var type binding post-processing in captures.ts to resolve
  call-result and alias chains from same-file return types
- Add variable-aware argument type inference for overload resolution
- Fix pickConstructorOrClass to walk child scopes for Constructor
  defs (scope-resolution places them in Function scopes)
- Remove over-aggressive field_access suppression in shouldEmitReadMember
  so ACCESSES edges emit for field steps in method chains
- Enable collapseMemberCallsByCallerTarget for legacy parity
- Update unit tests to use Ruby as unmigrated language example

Parity: 178/178 integration tests pass in both registry-primary
and legacy modes.

* fix(java): address code review findings for scope-resolution migration

- pickConstructorOrClass: skip inner Class scopes when walking
  children for Constructor defs (prevents resolving to wrong
  constructor in nested-class scenarios)
- populateJavaCrossFileReturnTypes: filter out parameter-annotation
  bindings from class-scope mirroring to prevent foreign parameter
  types from shadowing local variables
- resolveVarTypeBindings: detect ambiguous names (overloaded methods
  with different return types, same-named variables across scopes)
  and skip resolution rather than last-write-wins
- sharedPrefixLength renamed to sharedSegmentCount: segment-based
  directory proximity for deterministic sort ordering
- Add MAX_PACKAGE_FILES cap (500) to skip O(N^2) package-siblings
  injection for pathologically large packages

* perf(java): optimize hot paths in scope-resolution migration

- Replace O(D^2) list.some() dedup with O(1) Set lookup in
  populateJavaPackageSiblings binding injection
- Replace queue.shift() O(N) with index-based O(1) iteration
  in closeInterfaces BFS traversal
- Cache sharedSegmentCount results per file in sort comparator
  to avoid redundant path splitting

* perf(ingestion): skip deferred accumulation for registry-primary languages

The legacy call/import/heritage processing path accumulates extracted
data from ALL files during the parse phase, then skips registry-primary
files one-by-one during processing.  For a 25K-file Java codebase this
wastes ~150 MB holding calls that are never consumed.

Gate the accumulation with a per-chunk file-path cache: calls, imports,
heritage, constructor bindings, and assignments for registry-primary
languages (Java, Python, TypeScript, Go, C#, C, C++, PHP, JavaScript,
Kotlin) are no longer pushed into the deferred arrays.  The scope-
resolution pipeline handles these languages independently.

Verified: 2258/2258 resolver integration tests pass across all languages.

* fix(java): address Codex adversarial review findings

- Cross-file return binding: detect ambiguous method names across
  imported classes (two classes with same-named methods but different
  return types) and delete the binding rather than first-wins
- Package-siblings: only inject top-level classes (parent is Module
  scope) to prevent nested/inner classes from leaking to package scope
- Add diagnostic log when MAX_PACKAGE_FILES cap fires so operators
  know same-package visibility was disabled for a large package

* fix(test): force REGISTRY_PRIMARY_JAVA=false in legacy call-processor unit tests

Three call-processor test suites use .java file paths to exercise
legacy DAG features (MRO fast path, interface dispatch, class lookup
fallback).  Now that Java is in MIGRATED_LANGUAGES, the call-processor
skips Java files.  Force the flag off in beforeEach/afterEach so the
legacy path runs, matching the existing Python pattern in the same file.

---------

Co-authored-by: Test <test@example.com>
2026-05-24 14:29:26 +01:00
Gergő Magyar
ac9a2ee12f
chore(ci): consolidate parity shards and narrow cross-platform matrix (#1798)
* chore(ci): reduce CI runner-minutes by consolidating parity and narrowing cross-platform

Scope-resolution parity previously spawned 9 separate GitHub Actions jobs
(one per migrated language), each doing full checkout + npm ci + build for
a single test file. Consolidate into one job running scripts/run-parity.ts
which loops through all migrated languages sequentially — same coverage,
~45 fewer runner-minutes of redundant setup per PR.

Cross-platform (Windows/macOS) previously ran the full 373-file test suite.
Narrow to 45 platform-sensitive files (native LadybugDB, process spawning,
path separators, worker threads, filesystem behavior). Full suite still runs
on Ubuntu with coverage.

Also adds 2 missing lbug integration tests (lbug-orphan-sidecar-recovery,
lbug-readonly-init) to the sequential lbug-db vitest project where they
belong, and rewrites TESTING.md to document all test lanes.

* fix: address code review findings on parity and cross-platform scripts

- Capture stderr in run-parity.ts (vitest writes diagnostics to stderr)
- Lower per-invocation timeout from 5min to 60s to stay within CI job limit
- Add --language flag validation (error on missing value)
- Add timeout diagnostic to run-cross-platform.ts catch block
- Add analyze-wal-checkpoint-failure.test.ts to lbug-db sequential project
- Expand cross-platform list: parser-loader, pipeline, pipeline-graph-golden,
  setup-skills, cli/tool-no-index-stderr (51 files, was 45)

* fix: add shell:true for Windows npx resolution and simplify fs import

execFileSync('npx', ...) fails with ENOENT on Windows because npx is
npx.cmd — shell:true resolves this. Also replaces dynamic await
import('fs') with static import, and fixes timeout detection to use
err.killed instead of err.code.

* fix(ci): raise parity per-invocation timeout to 120s and job timeout to 30min

TypeScript and C++ resolver tests take 60-90s on CI runners, exceeding
the 60s per-invocation timeout. Raise to 120s. Also bump the job-level
timeout from 25 to 30 minutes for margin (realistic total is ~11 min).

* fix(ci): raise parity per-invocation timeout to 180s for C++ resolver

C++ resolver tests take 130-150s on CI runners due to template
metaprogramming, ADL, and SFINAE fixture volume. 120s was still too
tight. Realistic total across all 9 languages is ~12 min, well under
the 30-min job timeout.

* fix(ci): use stdio inherit for parity — no per-invocation timeout

Switch from piped stdio with per-invocation timeouts to stdio: 'inherit'.
Vitest output streams to CI console in real time, making failures
immediately visible. The CI job-level timeout (30 min) is the only
guard — no more artificial per-invocation timeouts that cut off slow
resolver tests like C++ (which genuinely takes 3+ minutes).

---------

Co-authored-by: Test <test@example.com>
2026-05-24 12:10:10 +01:00
ManniX-ITA
39e9b40136
fix(windows): pass windowsHide:true to every child_process spawn-family call (#1794)
* fix(hooks): pass windowsHide:true to every spawnSync to suppress flashing console windows on Windows

On Windows, every PostToolUse and Stop event from Claude Code (and
the Cursor integration variant) cold-spawns ``node`` / ``npx.cmd`` /
``git`` / ``lsof`` through ``child_process.spawnSync``. Without
``windowsHide: true`` in the options, Node's child_process module
asks ``CreateProcess`` to use ``STARTF_USESHOWWINDOW`` with
``SW_SHOWDEFAULT``, and a black console window flashes onto the
user's desktop for the duration of the call. Under active
editor / agent use this means a near-continuous stream of pop-up
windows — unusable in practice (reported live on a Windows 11
workstation running the gitnexus Claude plugin against an active
project; the flashes stack on the taskbar and steal focus from the
editor).

The Node fix is one option flag per spawnSync:

    spawnSync(cmd, args, {
        encoding: 'utf-8',
        timeout,
        cwd,
        stdio: ['pipe', 'pipe', 'pipe'],
        windowsHide: true,            // <-- new
    });

``windowsHide`` is a no-op on macOS/Linux (Node docs: "Hide the
subprocess console window that would normally be created on Windows
systems"), so the patch is platform-neutral and zero-risk on the
other two majors.

This commit touches every ``spawnSync`` call in the three sources
that ship the hook layer:

* gitnexus/hooks/claude/gitnexus-hook.cjs            (4 sites)
* gitnexus/hooks/claude/hook-db-lock-probe.cjs       (3 sites)
* gitnexus-claude-plugin/hooks/gitnexus-hook.js      (6 sites)
* gitnexus-claude-plugin/hooks/hook-db-lock-probe.cjs (3 sites)
* gitnexus-cursor-integration/hooks/gitnexus-hook.cjs (3 sites)

Total: 19 spawn sites guarded. ``hook-lock.cjs`` / ``hook-lock.js``
don't spawn subprocesses; nothing else in the hooks/ dirs touches
``child_process``.

Verified on Windows 10 22H2 / Node 22.21 / gitnexus 1.6.5 by
installing the locally-built tarball and running an active Claude
Code session against a large mixed-language repo — no console
window appears for any hook fire (pre-fix: ~2-3 visible flashes per
edit). No behavioural change on Linux/macOS hosts.

* test(hooks): regression — every hook spawnSync paired with windowsHide:true

Source-level assertion that every ``spawnSync`` invocation in the
hook layer has a matching ``windowsHide: true`` in its options
object. Without the flag, Node's child_process module asks
CreateProcess to use STARTF_USESHOWWINDOW with SW_SHOWDEFAULT and
a black console window flashes onto the user's desktop for the
duration of each call — see the parent fix commit.

The check is source-level rather than behavioural because:

* the flag's effect is observable only on Windows;
* GitHub Actions runs vitest on Linux for the hook tests;
* regressing this is easy (every new spawnSync site has to remember
  to add the flag), and a runtime check on a Windows-only CI leg
  would still let a PR land on the main branch first.

Counts spawnSync occurrences and windowsHide:true occurrences per
file (in code, ignoring comments) and asserts equality. Five files
covered:

* gitnexus/hooks/claude/gitnexus-hook.cjs
* gitnexus/hooks/claude/hook-db-lock-probe.cjs
* gitnexus-claude-plugin/hooks/gitnexus-hook.js
* gitnexus-claude-plugin/hooks/hook-db-lock-probe.cjs
* gitnexus-cursor-integration/hooks/gitnexus-hook.cjs

Adding a new hook file requires updating the HOOK_FILES tuple. A
sanity assertion ``spawnCount > 0`` catches accidental deletion of
all spawn calls in a future refactor (would otherwise silently make
the count-equality assertion trivially true).

Sits next to the existing "no shell: true" and ".cmd extension"
regression tests in test/unit/hooks.test.ts — same shape, same
spirit.

* fix(src): extend windowsHide:true to every spawn-family call in cli/core/mcp/server

Companion to the hook-layer fix in this branch's first commit. The
same Windows console-window flash bug applies to every
``spawn`` / ``spawnSync`` / ``execFile`` / ``execFileSync`` /
``execFileAsync`` / ``execSync`` call in the source tree — not just
the hooks. The MCP local backend
(``src/mcp/local/local-backend.ts``) and the ``gitnexus serve`` git
helpers (``src/server/git-clone.ts``) are particularly bad because
they run from daemonized processes that have no parent console; the
spawned child auto-allocates one and it pops onto the user's
desktop. The CLI sites are less visible (the user is at a terminal
with an existing console; ``stdio: 'inherit'`` shares it) but the
flag is harmless there — windowsHide only suppresses NEW console
allocation, an inherited parent console is untouched. The visible
output of ``gitnexus analyze`` and friends is preserved verbatim.

The pre-existing fix at ``src/core/lbug/extension-loader.ts:96``
established the convention in this codebase. This commit applies it
uniformly.

Sites covered (21 new):

| File | Sites |
|---|---|
| src/cli/analyze.ts           | 1 |
| src/cli/setup.ts             | 2 |
| src/cli/wiki.ts              | 3 |
| src/core/embeddings/embedder.ts | 1 |
| src/core/git-staleness.ts    | 3 |
| src/core/run-analyze.ts      | 1 |
| src/core/wiki/cursor-client.ts | 2 |
| src/core/wiki/generator.ts   | 3 |
| src/mcp/local/local-backend.ts | 2 |
| src/server/git-clone.ts      | 2 |
| src/core/lbug/extension-loader.ts | (already had it, untouched) |

Combined with the 19 hook sites from the first commit + the 1
pre-existing extension-loader site, the codebase now has uniform
``windowsHide: true`` on every spawn-family call.

Behavioural notes:

* ``windowsHide`` is documented by Node as a no-op on POSIX —
  Linux/macOS hosts see byte-identical behaviour.
* ``stdio: 'inherit'`` callers (e.g. ``cli/wiki.ts:522`` opens the
  editor in the user's terminal) keep their interactive UX. The
  child inherits the parent's stdio handles; no new console is
  allocated; the flag has nothing to hide.
* Piped callers (``stdio: ['pipe',…]``) continue to deliver every
  byte of stdout/stderr back to the parent for the parent to log
  / process / re-print. No output is swallowed.
* ``execSync`` / ``execFileSync`` callers that previously had no
  ``stdio`` option (e.g. ``generator.ts:887`` ``execSync('git
  rev-parse HEAD', { cwd })``) keep their default pipe semantics
  (``.toString()`` still works) — windowsHide is added alongside
  the existing ``cwd`` option.

Verified on Windows 10 22H2 / Node 22.21 by installing the locally
built tarball and exercising:

* MCP detect_changes via the local backend → no flash.
* gitnexus serve → no flash on git clone/clone-pull.
* gitnexus analyze interactively → output appears in terminal as
  before, no extra window.

* test(windowsHide): extend regression to every spawn-family call in src/

Companion to the src/ patch. The hooks.test.ts regression now
covers 16 files (5 hooks + 11 source files), and asserts the
invariant for every spawn-family function — not just spawnSync.

Changes:

* Generalise countSpawnCalls() to also count spawn, execFile,
  execFileSync, execFileAsync, execSync (the entire spawn-family
  surface of child_process). Skip method calls (e.g. RegExp.exec)
  via a negative-lookbehind on ``.``.
* Add SRC_FILES table with all 11 source-tree files that import
  spawn-family functions from child_process.
* Loop over [...HOOK_FILES, ...SRC_FILES] so a regression in any
  file fails the same test name.
* Tighten the assertion to ``hideCount >= spawnCount`` rather
  than strict equality, because some sites (e.g. setup.ts:534
  using execFileAsync via shell:true on Windows) may legitimately
  add windowsHide to nested option objects in future refactors.
* Sanity gate ``spawnCount > 0`` per file catches a refactor
  that deletes all spawn calls (would otherwise make the
  assertion trivially true).

Manually exercised against the patched repo:
  16 files, 28 total spawn-family calls, 28 windowsHide:true.
  All pass.

The convention to keep this list in sync: every new file in
gitnexus/src/ that imports from 'child_process' must be added to
the SRC_FILES tuple. The cost is one line per file; the benefit
is the next contributor never has to think about windowsHide
again — the test will catch a miss before merge.

* style: prettier --write on storage/git.ts + hooks.test.ts

CI quality / format job flagged two formatting issues in the
merge-resolution commit: a long single-line options object in
storage/git.ts and similar in hooks.test.ts. prettier --write
fixes both with the project's standard wrap-and-trailing-comma
style. No semantic change.

* test(git): include windowsHide in toHaveBeenCalledWith assertion

The merge-resolution commit added windowsHide:true to the
'git rev-parse --is-inside-work-tree' execSync call in
src/storage/git.ts, but the matching strict-shape assertion in
git.test.ts:31-34 still expected the pre-patch two-key options
object {cwd, stdio}. vitest's toHaveBeenCalledWith does a deep
structural match, so the extra third key flipped the assertion
to fail.

Add windowsHide: true to the expected shape. Only this one
assertion is strict; the two siblings ('passes the correct cwd'
and the no-cwd-arg case) use expect.objectContaining and
expect.any(String) and remain green without modification.

* test(setup-codex): include windowsHide in execFile shape assertions

Same root cause as the git.test.ts fix on this branch: the windowsHide
patch added windowsHide:true to the execFile() options in
src/cli/setup.ts, but three strict-shape toHaveBeenCalledWith
assertions in setup-codex.test.ts still expected the pre-patch
{shell:true} / {shell:false} two-key options. vitest does a deep
structural match, so the extra key flipped the assertions to fail
on every CI matrix leg (ubuntu coverage + macos + windows).

Adding windowsHide:true alongside the existing 'shell' key in
all three sites.

* ci: retrigger checks

go-parity failed on a flaky onnxruntime-node postinstall network timeout
(AggregateError [ETIMEDOUT] in node ./script/install), which cascaded into
the CI Gate. No code change — empty commit to re-run the pipeline.

* fix(test): strengthen windowsHide regression assertions (PR #1794 review)

- Replace toBeGreaterThanOrEqual with exact toBe per DoD §2.7
- Remove unused `m` variable in countSpawnCalls (CodeQL finding)
- Add windowsHide: true to runGit test helper for consistency

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: ManniX-ITA <35522085+ManniX-ITA@users.noreply.github.com>
Co-authored-by: Test <test@example.com>
2026-05-24 09:51:21 +01:00
Léon Simmons
a8a8a3710d
fix(lbug): skip init lock and filesystem mutations for read-only opens (#1783) (#1784)
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
`doInitLbug` unconditionally called `acquireInitLock`, which creates
`${dbPath}.init.lock` inside the workspace. On a Docker `:ro` bind
mount this fails with EROFS.

The init lock prevents a TOCTOU race during DB creation — read-only
opens never create databases and don't need it. Split the init path:

- Read-only: skip path cleanup, init lock, orphan sidecar removal,
  and mkdir. Go straight to preflightLbugSidecars (allowQuarantine:
  false) then openLbugConnection with readOnly: true.
- Writable: unchanged behavior (lock, cleanup, open).
- Shadow-replay recovery: catch EROFS/EACCES/EPERM from the writable
  fallback in ensureReadOnlyConnectionUsable and surface an actionable
  error instead of a raw filesystem exception.

Includes integration test verifying read-only open never creates
lbug.init.lock on disk.

Fixes #1783

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-24 08:05:27 +01:00
azizur100389
eb69f667ab
feat(cpp): Add structured resolver suppression outcomes (#1785) 2026-05-24 07:34:40 +01:00
Minidoracat
2b6e7ffbd9
fix(php): avoid Blade templates entering PHP analysis (#1790) 2026-05-23 23:37:40 +01:00
Hugo Gu
2c066d46a1
test(cli): stabilize eval-server host checks (#1786) 2026-05-23 16:45:35 +01:00
dependabot[bot]
fb94dba484
chore(deps)(deps-dev): bump tsx from 4.22.0 to 4.22.3 in /gitnexus (#1789) 2026-05-23 08:49:15 +01:00
Gergő Magyar
51e667808a
feat(lang-kotlin): flip Kotlin to MIGRATED_LANGUAGES + close #1756 / #1757 (refs #1746) (#1782) 2026-05-23 07:24:35 +01:00
dependabot[bot]
84ac88a741
chore(deps)(deps): bump qs from 6.14.2 to 6.15.2 in /gitnexus (#1791) 2026-05-23 06:39:05 +01:00
ChamHerry
fc6007e70b
feat(i18n): make web and CLI language-aware (#1748) 2026-05-23 06:14:24 +01:00
Copilot
87b91c821e
fix(lbug): add WAL checkpoint-threshold control (#1772)
* Initial plan

* fix(analyze): add WAL auto-checkpoint CLI control and default-off behavior

* test(analyze): share lbug auto-checkpoint parsing and align validation

* fix(analyze): always enable lbug auto-checkpoint and expose threshold control

* refactor(lbug): inline always-on auto-checkpoint constructor arg

* fix(analyze): guide checkpoint-threshold on Ladybug WAL checkpoint IO failures

* test(analyze): cover checkpoint IO guidance and add integration guard

* fix(analyze): tighten checkpoint IO detection and remove test hook

* fix(analyze): remove checkpoint test hook and tighten error matching

* fix(analyze): rename to wal-checkpoint-threshold, raise default, add manual checkpoint driver with retry

Address review feedback on PR #1772:

- Rename CLI flag, env var, AnalyzeOptions field, recovery-hint tag, and
  parser/constants from lbug-* to engine-neutral wal-* (matches the existing
  WAL_RECOVERY_SUGGESTION / isWalCorruptionError convention).
- Raise default threshold from -1 (Ladybug stock ~16 MiB) to 64 MiB so users
  on the default config no longer hit the original rename/remove race.
- Align both READMEs to publish 67108864 (64 MiB) instead of 65536 (which
  would have made the crash more frequent).
- Add wal-checkpoint-driver.ts: a periodic manual CHECKPOINT driver wrapped
  in a 3-attempt jittered retry (50/200/500 ms), driven from runFullAnalysis.
  Opt-out via GITNEXUS_WAL_MANUAL_CHECKPOINT=0. Moves the race window into a
  JS-controllable retry surface while keeping native auto-checkpoint on.
- Move LBUG_CHECKPOINT_RENAME_RE / REMOVE_RE plus the predicate (renamed to
  isLbugCheckpointIoError) into lbug-config.ts alongside isWalCorruptionError.
  Predicate is now exported. Add a permissive fallback matcher and pin the
  matched Ladybug version in comments.
- Warn instead of silently defaulting when GITNEXUS_WAL_CHECKPOINT_THRESHOLD
  is set to a non-empty unparseable value (closes the CLI-vs-env asymmetry).
- Add a typed RecoveryHint string-literal union in cli-message.ts so future
  hint tags can't drift.
- Add a real integration test under test/integration/ that triggers a
  Ladybug checkpoint IO failure via a pre-existing directory at the rename
  target (portable across platforms; no test-only injection hook).
- Add small-disk / CI caveat (32 MiB secondary suggestion) to the recovery
  hint and README env-var rows.
- Document CLI/env precedence in the analyze --help block.
- Help placeholder: <value> -> <bytes>.
- Rename analyze-lbug-auto-checkpoint.test.ts to use the new wal-* token.

* chore(lbug): remove dead jitteredDelay helper and apply prettier

- Drop unused `jitteredDelay` function flagged by CodeQL in PR #1772; the
  retry loop already inlines the same calculation with the injectable
  `randomImpl` so the helper was dead. Move the non-cryptographic-by-design
  comment next to the actual jitter site.
- Apply `prettier --write` to wal-checkpoint-driver.ts and the new
  integration test to absorb the PR autofix bot's formatting findings.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Test <test@example.com>
2026-05-22 14:46:49 +01:00
azizur100389
952ada70c5
feat(cpp): Resolve overloaded operator calls (#1754)
* feat(cpp): resolve overloaded operator calls

* fix(cpp): tighten overloaded operator resolution

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-05-22 13:31:06 +01:00