Compare commits
70
Commits
release/v1.5.0
...
v1.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b10d25bbca | ||
|
|
a94d6ef80b | ||
|
|
1ff324ca16 | ||
|
|
9364739fb4 | ||
|
|
75635638b1 | ||
|
|
5be0537ce4 | ||
|
|
6d9ec1009e | ||
|
|
4911201664 | ||
|
|
08541e2857 | ||
|
|
d9960c62bf | ||
|
|
7c983d798f | ||
|
|
d87744fffc | ||
|
|
100858f8c8 | ||
|
|
e5dafce9f2 | ||
|
|
ab956f113c | ||
|
|
6147579e54 | ||
|
|
4a1f912aee | ||
|
|
d09078925e | ||
|
|
338cb01ee0 | ||
|
|
4450a14b98 | ||
|
|
3f0b8c1a5b | ||
|
|
bb68cc1eb0 | ||
|
|
d6debf3324 | ||
|
|
9ab92a97d0 | ||
|
|
4fde5f241b | ||
|
|
9f9bbcd744 | ||
|
|
fd67cfd5a7 | ||
|
|
3f28f7ead5 | ||
|
|
d9ba9aa998 | ||
|
|
c19e76a4a3 | ||
|
|
b75e76d44a | ||
|
|
83b5bec293 | ||
|
|
3388ae16d7 | ||
|
|
d784f591b2 | ||
|
|
0f43190543 | ||
|
|
fe87ff8f74 | ||
|
|
be2401061e | ||
|
|
b73233d232 | ||
|
|
1c8ae5eb46 | ||
|
|
b73928f732 | ||
|
|
19faf3b326 | ||
|
|
cb772b9e29 | ||
|
|
10f8815639 | ||
|
|
6ead5e5986 | ||
|
|
14791ded4a | ||
|
|
9eeb20bb04 | ||
|
|
5a7c0fdbb1 | ||
|
|
0561d24efd | ||
|
|
153262304c | ||
|
|
16cf4c503e | ||
|
|
57951a197b | ||
|
|
63fc4c795f | ||
|
|
5c4fca21c3 | ||
|
|
dd0f5eed7d | ||
|
|
e3d73a7aed | ||
|
|
255e3e79eb | ||
|
|
be4458b650 | ||
|
|
4fed097abb | ||
|
|
4fa395f4b6 | ||
|
|
52277247fe | ||
|
|
ba5de0bde4 | ||
|
|
dc86ea96dc | ||
|
|
d1adc8331a | ||
|
|
80d363f145 | ||
|
|
12be2025f1 | ||
|
|
dcf40da3a8 | ||
|
|
c617350c58 | ||
|
|
71255a096c | ||
|
|
39322e37df | ||
|
|
0e6f8f1720 |
@@ -30,6 +30,10 @@ jobs:
|
||||
registry-url: https://registry.npmjs.org
|
||||
cache: npm
|
||||
cache-dependency-path: gitnexus/package-lock.json
|
||||
- name: Build gitnexus-shared
|
||||
run: npm install && npm run build
|
||||
working-directory: gitnexus-shared
|
||||
|
||||
- run: npm ci
|
||||
working-directory: gitnexus
|
||||
|
||||
@@ -63,7 +67,22 @@ jobs:
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Extract release notes from CHANGELOG
|
||||
id: changelog
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION="${GITHUB_REF#refs/tags/v}"
|
||||
NOTES=$(awk "/^## \\[$VERSION\\]/{found=1; next} /^## \\[/{if(found) exit} found" gitnexus/CHANGELOG.md)
|
||||
if [ -z "$NOTES" ]; then
|
||||
echo "::warning::No CHANGELOG entry found for v$VERSION, falling back to auto-generated notes"
|
||||
echo "fallback=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "$NOTES" > /tmp/release-notes.md
|
||||
echo "fallback=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2
|
||||
with:
|
||||
generate_release_notes: true
|
||||
body_path: ${{ steps.changelog.outputs.fallback == 'false' && '/tmp/release-notes.md' || '' }}
|
||||
generate_release_notes: ${{ steps.changelog.outputs.fallback == 'true' }}
|
||||
|
||||
@@ -63,7 +63,7 @@ Generic “core standards” playbooks are often long and stack-specific. For th
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **GitNexus**. Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. For current symbol stats, run `npx gitnexus analyze` and inspect `.gitnexus/meta.json`.
|
||||
This project is indexed by GitNexus as **GitNexus** (3975 symbols, 10043 relationships, 245 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
|
||||
|
||||
|
||||
@@ -58,8 +58,65 @@ This repository is a **monorepo** with two main products: the **CLI / MCP packag
|
||||
| Web UI behavior | `gitnexus-web/src/` (components, workers, graph client). |
|
||||
| CI | `.github/workflows/*.yml`, `.github/actions/setup-gitnexus/`. |
|
||||
|
||||
## Known limitations
|
||||
|
||||
### Overloaded method resolution
|
||||
|
||||
Method and Constructor node IDs include an arity suffix (`#<paramCount>`) to
|
||||
disambiguate overloaded methods. Two overloads with different parameter counts
|
||||
produce distinct graph nodes: `Method:file:Class.method#1` vs
|
||||
`Method:file:Class.method#2`.
|
||||
|
||||
**Same-arity overload disambiguation:** When two overloads share the same
|
||||
parameter count but differ in types (e.g. `save(int)` vs `save(String)`), a
|
||||
type-hash suffix `~type1,type2` is appended to produce distinct node IDs:
|
||||
`Method:file:Class.save#1~int` vs `Method:file:Class.save#1~String`. The suffix
|
||||
is only added when a same-arity collision is detected within a class and all
|
||||
parameters have non-null type annotations. Languages without type info (Python,
|
||||
Ruby, JS) fall back to arity-only IDs. TypeScript/JavaScript overload signatures
|
||||
are intentionally excluded from type-hashing because they are declaration-only
|
||||
contracts that should collapse to the implementation body's node ID. See issue
|
||||
\#651.
|
||||
|
||||
**C++ const-qualified overload disambiguation:** Methods overloaded by const
|
||||
qualification (e.g. `begin()` vs `begin() const`) are disambiguated via an
|
||||
`isConst` property and a `$const` ID suffix appended to the const-qualified
|
||||
variant when a non-const collision exists. The `$const` suffix appears after the
|
||||
type-hash suffix: e.g. `Method:file:Container.begin#0$const`.
|
||||
|
||||
**Generic/template type preservation in type-hash:** The type-hash suffix uses
|
||||
`rawType` (full AST text including generic/template args) rather than the
|
||||
simplified `type` from `extractSimpleTypeName`. This means C++ template overloads
|
||||
like `process(vector<int>)` vs `process(vector<string>)` produce distinct IDs:
|
||||
`~vector<int>` vs `~vector<std::string>`. Java generic overloads like
|
||||
`process(List<String>)` vs `process(List<Integer>)` are a compile error due to
|
||||
type erasure, so this gap is theoretical for Java.
|
||||
|
||||
**ID stability on first overload:** Type and const tags are collision-only. When
|
||||
a class has `save(int)` as its only `save` method, the ID is `save#1` (no tag).
|
||||
Adding `save(String)` changes the original to `save#1~int`. This is correct for
|
||||
fresh analysis but means IDs are not stable across overload additions. Future
|
||||
incremental re-analysis should account for this.
|
||||
|
||||
**Variadic method matching:** When one side is variadic (`parameterCount`
|
||||
undefined) and the other has a fixed count, `METHOD_IMPLEMENTS` edges are
|
||||
emitted with confidence 0.7 instead of 1.0. Variadic methods like
|
||||
`foo(String... args)` may superficially match `foo(String s)` by type but
|
||||
are not guaranteed to be interchangeable across all languages (Java/Kotlin
|
||||
accept this via varargs sugar; TypeScript, C#, Rust do not).
|
||||
|
||||
**Confidence tiering** for `METHOD_IMPLEMENTS` edges:
|
||||
|
||||
| Match quality | Confidence | When |
|
||||
|---|---|---|
|
||||
| Exact parameter types match | 1.0 | Both sides have `parameterTypes` arrays and they match |
|
||||
| Arity (count) matches | 1.0 | Both sides have `parameterCount`, types unavailable |
|
||||
| Variadic vs fixed | 0.7 | One side is variadic, other has fixed count |
|
||||
| Lenient (insufficient info) | 0.7 | One or both sides lack type and count data |
|
||||
|
||||
## Related docs
|
||||
|
||||
- [MIGRATION.md](MIGRATION.md) — breaking changes and migration guidance.
|
||||
- [RUNBOOK.md](RUNBOOK.md) — operational commands and recovery.
|
||||
- [GUARDRAILS.md](GUARDRAILS.md) — safety boundaries for humans and agents.
|
||||
- [TESTING.md](TESTING.md) — how to run tests.
|
||||
|
||||
@@ -10,6 +10,19 @@ All notable changes to GitNexus will be documented in this file.
|
||||
- Added automatic cleanup of stale KuzuDB index files
|
||||
- LadybugDB v0.15 requires explicit VECTOR extension loading for semantic search
|
||||
|
||||
## [1.5.3] - 2026-04-01
|
||||
|
||||
### Added
|
||||
|
||||
- **TypeScript/JavaScript MethodExtractor config** — shared extraction config covering abstract methods, visibility modifiers, async/override keywords, decorators, rest/optional/destructured parameters, and return types (#588) — @compound-ai
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Azure OpenAI compatibility** — use `max_completion_tokens` instead of deprecated `max_tokens` (newer models reject `max_tokens`); skip `temperature` for Azure provider (some models reject non-default values) (#618)
|
||||
- **Simplified Azure interactive setup** — 3 prompts (endpoint, deployment, key) instead of 7 (#618)
|
||||
- **Wiki HTML viewer script injection** — escape `</script>` in embedded JSON so LLM-generated markdown no longer breaks the viewer (#618)
|
||||
- Ensure import rewrites survive npm publish lifecycle
|
||||
|
||||
## [1.4.0] - 2026-03-13
|
||||
|
||||
### Added
|
||||
|
||||
@@ -49,4 +49,206 @@ If always-on instructions grow, load deep conventions via conditional reads (e.g
|
||||
|
||||
## GitNexus rules
|
||||
|
||||
GitNexus MCP rules are in the `<!-- gitnexus:start -->` … `<!-- gitnexus:end -->` block in **[AGENTS.md](AGENTS.md)** — load that section when working with MCP tools or the graph index.
|
||||
GitNexus MCP rules are in the `<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **GitNexus** (3975 symbols, 10043 relationships, 245 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`.
|
||||
|
||||
## When Debugging
|
||||
|
||||
1. `gitnexus_query({query: "<error or symptom>"})` — find execution flows related to the issue
|
||||
2. `gitnexus_context({name: "<suspect function>"})` — see all callers, callees, and process participation
|
||||
3. `READ gitnexus://repo/GitNexus/process/{processName}` — trace the full execution flow step by step
|
||||
4. For regressions: `gitnexus_detect_changes({scope: "compare", base_ref: "main"})` — see what your branch changed
|
||||
|
||||
## When Refactoring
|
||||
|
||||
- **Renaming**: MUST use `gitnexus_rename({symbol_name: "old", new_name: "new", dry_run: true})` first. Review the preview — graph edits are safe, text_search edits need manual review. Then run with `dry_run: false`.
|
||||
- **Extracting/Splitting**: MUST run `gitnexus_context({name: "target"})` to see all incoming/outgoing refs, then `gitnexus_impact({target: "target", direction: "upstream"})` to find all external callers before moving code.
|
||||
- After any refactor: run `gitnexus_detect_changes({scope: "all"})` to verify only expected files changed.
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `gitnexus_impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph.
|
||||
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope.
|
||||
|
||||
## Tools Quick Reference
|
||||
|
||||
| Tool | When to use | Command |
|
||||
|------|-------------|---------|
|
||||
| `query` | Find code by concept | `gitnexus_query({query: "auth validation"})` |
|
||||
| `context` | 360-degree view of one symbol | `gitnexus_context({name: "validateUser"})` |
|
||||
| `impact` | Blast radius before editing | `gitnexus_impact({target: "X", direction: "upstream"})` |
|
||||
| `detect_changes` | Pre-commit scope check | `gitnexus_detect_changes({scope: "staged"})` |
|
||||
| `rename` | Safe multi-file rename | `gitnexus_rename({symbol_name: "old", new_name: "new", dry_run: true})` |
|
||||
| `cypher` | Custom graph queries | `gitnexus_cypher({query: "MATCH ..."})` |
|
||||
|
||||
## Impact Risk Levels
|
||||
|
||||
| Depth | Meaning | Action |
|
||||
|-------|---------|--------|
|
||||
| d=1 | WILL BREAK — direct callers/importers | MUST update these |
|
||||
| d=2 | LIKELY AFFECTED — indirect deps | Should test |
|
||||
| d=3 | MAY NEED TESTING — transitive | Test if critical path |
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| `gitnexus://repo/GitNexus/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/GitNexus/clusters` | All functional areas |
|
||||
| `gitnexus://repo/GitNexus/processes` | All execution flows |
|
||||
| `gitnexus://repo/GitNexus/process/{name}` | Step-by-step execution trace |
|
||||
|
||||
## Self-Check Before Finishing
|
||||
|
||||
Before completing any code modification task, verify:
|
||||
1. `gitnexus_impact` was run for all modified symbols
|
||||
2. No HIGH/CRITICAL risk warnings were ignored
|
||||
3. `gitnexus_detect_changes()` confirms changes match expected scope
|
||||
4. All d=1 (WILL BREAK) dependents were updated
|
||||
|
||||
## Keeping the Index Fresh
|
||||
|
||||
After committing code changes, the GitNexus index becomes stale. Re-run analyze to update it:
|
||||
|
||||
```bash
|
||||
npx gitnexus analyze
|
||||
```
|
||||
|
||||
If the index previously included embeddings, preserve them by adding `--embeddings`:
|
||||
|
||||
```bash
|
||||
npx gitnexus analyze --embeddings
|
||||
```
|
||||
|
||||
To check whether embeddings exist, inspect `.gitnexus/meta.json` — the `stats.embeddings` field shows the count (0 means no embeddings). **Running analyze without `--embeddings` will delete any previously generated embeddings.**
|
||||
|
||||
> Claude Code users: A PostToolUse hook handles this automatically after `git commit` and `git merge`.
|
||||
|
||||
## CLI
|
||||
|
||||
| Task | Read this skill file |
|
||||
|------|---------------------|
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->` block in **[AGENTS.md](AGENTS.md)** — load that section when working with MCP tools or the graph index.
|
||||
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **GitNexus** (3298 symbols, 7954 relationships, 185 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`.
|
||||
|
||||
## When Debugging
|
||||
|
||||
1. `gitnexus_query({query: "<error or symptom>"})` — find execution flows related to the issue
|
||||
2. `gitnexus_context({name: "<suspect function>"})` — see all callers, callees, and process participation
|
||||
3. `READ gitnexus://repo/GitNexus/process/{processName}` — trace the full execution flow step by step
|
||||
4. For regressions: `gitnexus_detect_changes({scope: "compare", base_ref: "main"})` — see what your branch changed
|
||||
|
||||
## When Refactoring
|
||||
|
||||
- **Renaming**: MUST use `gitnexus_rename({symbol_name: "old", new_name: "new", dry_run: true})` first. Review the preview — graph edits are safe, text_search edits need manual review. Then run with `dry_run: false`.
|
||||
- **Extracting/Splitting**: MUST run `gitnexus_context({name: "target"})` to see all incoming/outgoing refs, then `gitnexus_impact({target: "target", direction: "upstream"})` to find all external callers before moving code.
|
||||
- After any refactor: run `gitnexus_detect_changes({scope: "all"})` to verify only expected files changed.
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `gitnexus_impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph.
|
||||
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope.
|
||||
|
||||
## Tools Quick Reference
|
||||
|
||||
| Tool | When to use | Command |
|
||||
|------|-------------|---------|
|
||||
| `query` | Find code by concept | `gitnexus_query({query: "auth validation"})` |
|
||||
| `context` | 360-degree view of one symbol | `gitnexus_context({name: "validateUser"})` |
|
||||
| `impact` | Blast radius before editing | `gitnexus_impact({target: "X", direction: "upstream"})` |
|
||||
| `detect_changes` | Pre-commit scope check | `gitnexus_detect_changes({scope: "staged"})` |
|
||||
| `rename` | Safe multi-file rename | `gitnexus_rename({symbol_name: "old", new_name: "new", dry_run: true})` |
|
||||
| `cypher` | Custom graph queries | `gitnexus_cypher({query: "MATCH ..."})` |
|
||||
|
||||
## Impact Risk Levels
|
||||
|
||||
| Depth | Meaning | Action |
|
||||
|-------|---------|--------|
|
||||
| d=1 | WILL BREAK — direct callers/importers | MUST update these |
|
||||
| d=2 | LIKELY AFFECTED — indirect deps | Should test |
|
||||
| d=3 | MAY NEED TESTING — transitive | Test if critical path |
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| `gitnexus://repo/GitNexus/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/GitNexus/clusters` | All functional areas |
|
||||
| `gitnexus://repo/GitNexus/processes` | All execution flows |
|
||||
| `gitnexus://repo/GitNexus/process/{name}` | Step-by-step execution trace |
|
||||
|
||||
## Self-Check Before Finishing
|
||||
|
||||
Before completing any code modification task, verify:
|
||||
1. `gitnexus_impact` was run for all modified symbols
|
||||
2. No HIGH/CRITICAL risk warnings were ignored
|
||||
3. `gitnexus_detect_changes()` confirms changes match expected scope
|
||||
4. All d=1 (WILL BREAK) dependents were updated
|
||||
|
||||
## Keeping the Index Fresh
|
||||
|
||||
After committing code changes, the GitNexus index becomes stale. Re-run analyze to update it:
|
||||
|
||||
```bash
|
||||
npx gitnexus analyze
|
||||
```
|
||||
|
||||
If the index previously included embeddings, preserve them by adding `--embeddings`:
|
||||
|
||||
```bash
|
||||
npx gitnexus analyze --embeddings
|
||||
```
|
||||
|
||||
To check whether embeddings exist, inspect `.gitnexus/meta.json` — the `stats.embeddings` field shows the count (0 means no embeddings). **Running analyze without `--embeddings` will delete any previously generated embeddings.**
|
||||
|
||||
> Claude Code users: A PostToolUse hook handles this automatically after `git commit` and `git merge`.
|
||||
|
||||
## CLI
|
||||
|
||||
| Task | Read this skill file |
|
||||
|------|---------------------|
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Migration Guide
|
||||
|
||||
## OVERRIDES → METHOD_OVERRIDES (PR #642)
|
||||
|
||||
The `OVERRIDES` relationship type has been renamed to `METHOD_OVERRIDES` for
|
||||
consistency with the new `METHOD_IMPLEMENTS` edge type.
|
||||
|
||||
### Do I need to migrate?
|
||||
|
||||
**No.** Backward compatibility is handled automatically at runtime:
|
||||
|
||||
- `local-backend.ts` dual-reads both `OVERRIDES` and `METHOD_OVERRIDES` in all
|
||||
impact-analysis and context queries. Existing stored graphs with `OVERRIDES`
|
||||
edges continue to return correct results without any manual intervention.
|
||||
- The `REL_TYPES` array in `schema-constants.ts` includes both names so Cypher
|
||||
queries that reference either will work.
|
||||
|
||||
### What happens on re-index?
|
||||
|
||||
Running `npx gitnexus analyze` on a repository produces `METHOD_OVERRIDES`
|
||||
edges going forward. The old `OVERRIDES` edges are replaced as part of the
|
||||
normal full re-index.
|
||||
|
||||
### When will the legacy alias be removed?
|
||||
|
||||
The `OVERRIDES` compat alias will remain until a future major version. Removal
|
||||
will be announced in this file and in the changelog before it happens.
|
||||
@@ -52,7 +52,7 @@ https://github.com/user-attachments/assets/172685ba-8e54-4ea7-9ad1-e31a3398da72
|
||||
| **What** | Index repos locally, connect AI agents via MCP | Visual graph explorer + AI chat in browser |
|
||||
| **For** | Daily development with Cursor, Claude Code, Codex, Windsurf, OpenCode | Quick exploration, demos, one-off analysis |
|
||||
| **Scale** | Full repos, any size | Limited by browser memory (~5k files), or unlimited via backend mode |
|
||||
| **Install** | `npm install -g gitnexus` | No install —[gitnexus.vercel.app](https://gitnexus.vercel.app) |
|
||||
| **Install** | `npm install -g gitnexus` | No install — [gitnexus.vercel.app](https://gitnexus.vercel.app) |
|
||||
| **Storage** | LadybugDB native (fast, persistent) | LadybugDB WASM (in-memory, per session) |
|
||||
| **Parsing** | Tree-sitter native bindings | Tree-sitter WASM |
|
||||
| **Privacy** | Everything local, no network | Everything in-browser, no server |
|
||||
@@ -119,7 +119,6 @@ To configure MCP for your editor, run `npx gitnexus setup` once — or set it up
|
||||
| **Codex** | Yes | Yes | — | MCP + Skills |
|
||||
| **Windsurf** | Yes | — | — | MCP |
|
||||
| **OpenCode** | Yes | Yes | — | MCP + Skills |
|
||||
| **Codex** | Yes | — | — | MCP |
|
||||
|
||||
> **Claude Code** gets the deepest integration: MCP tools + agent skills + PreToolUse hooks that enrich searches with graph context + PostToolUse hooks that auto-reindex after commits.
|
||||
|
||||
@@ -206,11 +205,21 @@ gitnexus clean --all --force # Delete all indexes
|
||||
gitnexus wiki [path] # Generate repository wiki from knowledge graph
|
||||
gitnexus wiki --model <model> # Wiki with custom LLM model (default: gpt-4o-mini)
|
||||
gitnexus wiki --base-url <url> # Wiki with custom LLM API base URL
|
||||
|
||||
# Repository groups (multi-repo / monorepo service tracking)
|
||||
gitnexus group create <name> # Create a repository group
|
||||
gitnexus group add <name> <repo> # Add a repo to a group
|
||||
gitnexus group remove <name> <repo> # Remove a repo from a group
|
||||
gitnexus group list [name] # List groups, or show one group's config
|
||||
gitnexus group sync <name> # Extract contracts and match across repos/services
|
||||
gitnexus group contracts <name> # Inspect extracted contracts and cross-links
|
||||
gitnexus group query <name> <q> # Search execution flows across all repos in a group
|
||||
gitnexus group status <name> # Check staleness of repos in a group
|
||||
```
|
||||
|
||||
### What Your AI Agent Gets
|
||||
|
||||
**7 tools** exposed via MCP:
|
||||
**16 tools** exposed via MCP (11 per-repo + 5 group):
|
||||
|
||||
| Tool | What It Does | `repo` Param |
|
||||
| ------------------ | ----------------------------------------------------------------- | -------------- |
|
||||
@@ -221,6 +230,11 @@ gitnexus wiki --base-url <url> # Wiki with custom LLM API base URL
|
||||
| `detect_changes` | Git-diff impact — maps changed lines to affected processes | Optional |
|
||||
| `rename` | Multi-file coordinated rename with graph + text search | Optional |
|
||||
| `cypher` | Raw Cypher graph queries | Optional |
|
||||
| `group_list` | List configured repository groups | — |
|
||||
| `group_sync` | Extract contracts and match across repos/services | — |
|
||||
| `group_contracts`| Inspect extracted contracts and cross-links | — |
|
||||
| `group_query` | Search execution flows across all repos in a group | — |
|
||||
| `group_status` | Check staleness of repos in a group | — |
|
||||
|
||||
> When only one repo is indexed, the `repo` parameter is optional. With multiple repos, specify which one: `query({query: "auth", repo: "my-app"})`.
|
||||
|
||||
|
||||
@@ -0,0 +1,725 @@
|
||||
# PR #626 HIGH-Priority Fixes Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Fix 4 HIGH-priority issues from PR #626 code review before merge.
|
||||
|
||||
**Architecture:** Minimal targeted fixes — each task is independent. TDD: tests first, then implementation. No refactoring beyond what's needed.
|
||||
|
||||
**Tech Stack:** TypeScript, Vitest, Node.js fs/path APIs
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-04-02-pr626-high-fixes-design.md`
|
||||
|
||||
**Paths:** All file paths are relative to the monorepo root (`GitNexus/`). Git commands run from the root. The `gitnexus/` prefix is a package subdirectory, not a separate repo.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Path Traversal — Validate Group Name
|
||||
|
||||
**Files:**
|
||||
- Modify: `gitnexus/src/core/group/storage.ts:17-19` (getGroupDir) and `:63-68` (createGroupDir)
|
||||
- Test: `gitnexus/test/unit/group/storage.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests for validateGroupName**
|
||||
|
||||
In `gitnexus/test/unit/group/storage.test.ts`, add `createGroupDir` and `validateGroupName` to the existing import from `'../../../src/core/group/storage.js'` (line 6-11). Then add these describe blocks at the end of the outer `describe('Group storage', ...)`:
|
||||
|
||||
```typescript
|
||||
describe('validateGroupName', () => {
|
||||
it('test_validateGroupName_traversal_path_throws', () => {
|
||||
expect(() => validateGroupName('../../evil')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_validateGroupName_slash_in_name_throws', () => {
|
||||
expect(() => validateGroupName('foo/bar')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_validateGroupName_empty_string_throws', () => {
|
||||
expect(() => validateGroupName('')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_validateGroupName_starts_with_dash_throws', () => {
|
||||
expect(() => validateGroupName('-leading-dash')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_validateGroupName_starts_with_underscore_throws', () => {
|
||||
expect(() => validateGroupName('_leading')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_validateGroupName_dots_throws', () => {
|
||||
expect(() => validateGroupName('com.example')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_validateGroupName_valid_alphanumeric_passes', () => {
|
||||
expect(() => validateGroupName('my-group_01')).not.toThrow();
|
||||
});
|
||||
|
||||
it('test_validateGroupName_single_char_passes', () => {
|
||||
expect(() => validateGroupName('A')).not.toThrow();
|
||||
});
|
||||
|
||||
it('test_validateGroupName_all_digits_passes', () => {
|
||||
expect(() => validateGroupName('123')).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGroupDir rejects invalid names', () => {
|
||||
it('test_getGroupDir_traversal_throws', () => {
|
||||
expect(() => getGroupDir(tmpDir, '../../etc')).toThrow(/Invalid group name/);
|
||||
});
|
||||
|
||||
it('test_getGroupDir_valid_name_returns_path', () => {
|
||||
const dir = getGroupDir(tmpDir, 'company');
|
||||
expect(dir).toBe(path.join(tmpDir, 'groups', 'company'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('createGroupDir rejects invalid names', () => {
|
||||
it('test_createGroupDir_traversal_throws', async () => {
|
||||
await expect(createGroupDir(tmpDir, '../evil')).rejects.toThrow(/Invalid group name/);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/storage.test.ts`
|
||||
Expected: FAIL — `validateGroupName` is not exported, `getGroupDir` does not throw.
|
||||
|
||||
- [ ] **Step 3: Implement validateGroupName and wire into getGroupDir and createGroupDir**
|
||||
|
||||
In `gitnexus/src/core/group/storage.ts`, add the validation function before `getGroupDir` and call it:
|
||||
|
||||
```typescript
|
||||
const GROUP_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
||||
|
||||
export function validateGroupName(name: string): void {
|
||||
if (!GROUP_NAME_RE.test(name)) {
|
||||
throw new Error(
|
||||
`Invalid group name "${name}". Names must start with a letter or digit and contain only [a-zA-Z0-9_-].`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function getGroupDir(gitnexusDir: string, groupName: string): string {
|
||||
validateGroupName(groupName);
|
||||
return path.join(gitnexusDir, 'groups', groupName);
|
||||
}
|
||||
```
|
||||
|
||||
`createGroupDir` already calls `getGroupDir` at line 68, so it inherits validation automatically. No change needed in `createGroupDir`.
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/storage.test.ts`
|
||||
Expected: ALL PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
cd gitnexus && git add src/core/group/storage.ts test/unit/group/storage.test.ts
|
||||
git commit -m "fix(group): validate group name to prevent path traversal
|
||||
|
||||
Add validateGroupName() with regex [a-zA-Z0-9][a-zA-Z0-9_-]*.
|
||||
Called in getGroupDir (defense in depth) which covers all CLI entry
|
||||
points: create, add, remove, status, sync.
|
||||
|
||||
Addresses PR #626 review item 1 (HIGH).
|
||||
|
||||
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Directory Exclusions in Service Boundary Detector
|
||||
|
||||
**Files:**
|
||||
- Modify: `gitnexus/src/core/group/service-boundary-detector.ts:24-51` (add constant), `:78` (walkForBoundaries), `:130` (hasSourceFilesInSubdirs)
|
||||
- Test: `gitnexus/test/unit/group/service-boundary-detector.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests for excluded directories**
|
||||
|
||||
Add this describe block inside the existing `detectServiceBoundaries` describe in `gitnexus/test/unit/group/service-boundary-detector.test.ts`:
|
||||
|
||||
```typescript
|
||||
it('test_detect_skips_vendor_directory', async () => {
|
||||
writeFile('services/auth/package.json', '{}');
|
||||
writeFile('services/auth/src/index.ts', '');
|
||||
// vendor should be skipped — its contents should not create a boundary
|
||||
writeFile('vendor/some-dep/package.json', '{}');
|
||||
writeFile('vendor/some-dep/src/lib.go', '');
|
||||
|
||||
const boundaries = await detectServiceBoundaries(tmpDir);
|
||||
|
||||
const paths = boundaries.map((b) => b.servicePath);
|
||||
expect(paths).toContain('services/auth');
|
||||
expect(paths).not.toContain('vendor/some-dep');
|
||||
});
|
||||
|
||||
it('test_detect_skips_target_directory', async () => {
|
||||
writeFile('services/api/go.mod', 'module api');
|
||||
writeFile('services/api/main.go', '');
|
||||
writeFile('target/classes/Main.java', '');
|
||||
writeFile('target/pom.xml', '<project/>');
|
||||
|
||||
const boundaries = await detectServiceBoundaries(tmpDir);
|
||||
|
||||
const paths = boundaries.map((b) => b.servicePath);
|
||||
expect(paths).toContain('services/api');
|
||||
expect(paths).not.toContain('target');
|
||||
});
|
||||
|
||||
it('test_detect_skips_pycache_directory', async () => {
|
||||
writeFile('services/ml/pyproject.toml', '[project]');
|
||||
writeFile('services/ml/model.py', '');
|
||||
// __pycache__ with a marker + source files — would be detected as
|
||||
// a boundary if not excluded, since it has package.json + .py file
|
||||
writeFile('__pycache__/package.json', '{}');
|
||||
writeFile('__pycache__/cached.py', '');
|
||||
|
||||
const boundaries = await detectServiceBoundaries(tmpDir);
|
||||
|
||||
const paths = boundaries.map((b) => b.servicePath);
|
||||
expect(paths).toContain('services/ml');
|
||||
expect(paths.every((p) => !p.includes('__pycache__'))).toBe(true);
|
||||
});
|
||||
|
||||
it('test_detect_skips_dotfile_directories_regression', async () => {
|
||||
writeFile('services/api/package.json', '{}');
|
||||
writeFile('services/api/src/index.ts', '');
|
||||
writeFile('.hidden/package.json', '{}');
|
||||
writeFile('.hidden/src/index.ts', '');
|
||||
|
||||
const boundaries = await detectServiceBoundaries(tmpDir);
|
||||
|
||||
const paths = boundaries.map((b) => b.servicePath);
|
||||
expect(paths).toContain('services/api');
|
||||
expect(paths).not.toContain('.hidden');
|
||||
});
|
||||
|
||||
it('test_detect_does_not_skip_regular_source_directories', async () => {
|
||||
writeFile('services/api/package.json', '{}');
|
||||
writeFile('services/api/src/index.ts', '');
|
||||
|
||||
const boundaries = await detectServiceBoundaries(tmpDir);
|
||||
|
||||
expect(boundaries).toHaveLength(1);
|
||||
expect(boundaries[0].serviceName).toBe('api');
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify `vendor` and `target` tests fail**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/service-boundary-detector.test.ts`
|
||||
Expected: `test_detect_skips_vendor_directory` and `test_detect_skips_target_directory` FAIL (vendor/target not excluded). Other new tests may pass since dotfile exclusion already exists.
|
||||
|
||||
- [ ] **Step 3: Add EXCLUDED_DIRS constant and update both walking functions**
|
||||
|
||||
In `gitnexus/src/core/group/service-boundary-detector.ts`:
|
||||
|
||||
After `SOURCE_EXTENSIONS` (after line 51), add:
|
||||
|
||||
```typescript
|
||||
const EXCLUDED_DIRS = new Set([
|
||||
'node_modules',
|
||||
'vendor',
|
||||
'target',
|
||||
'build',
|
||||
'dist',
|
||||
'__pycache__',
|
||||
'.venv',
|
||||
'venv',
|
||||
'.tox',
|
||||
'.mypy_cache',
|
||||
'.gradle',
|
||||
'.mvn',
|
||||
'out',
|
||||
'bin',
|
||||
]);
|
||||
```
|
||||
|
||||
In `walkForBoundaries`, replace line 78:
|
||||
```typescript
|
||||
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
||||
```
|
||||
with:
|
||||
```typescript
|
||||
if (entry.name.startsWith('.') || EXCLUDED_DIRS.has(entry.name)) continue;
|
||||
```
|
||||
|
||||
In `hasSourceFilesInSubdirs`, replace line 130:
|
||||
```typescript
|
||||
if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
|
||||
```
|
||||
with:
|
||||
```typescript
|
||||
if (entry.isDirectory() && !entry.name.startsWith('.') && !EXCLUDED_DIRS.has(entry.name)) {
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/service-boundary-detector.test.ts`
|
||||
Expected: ALL PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
cd gitnexus && git add src/core/group/service-boundary-detector.ts test/unit/group/service-boundary-detector.test.ts
|
||||
git commit -m "fix(group): add directory exclusions to service boundary detector
|
||||
|
||||
Add EXCLUDED_DIRS set: vendor, target, build, dist, __pycache__,
|
||||
.venv, venv, .tox, .mypy_cache, .gradle, .mvn, out, bin.
|
||||
Applied in walkForBoundaries and hasSourceFilesInSubdirs.
|
||||
Replaces inline node_modules check.
|
||||
|
||||
Addresses PR #626 review item 3 (HIGH).
|
||||
|
||||
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Remove Double-Close of LadybugDB Pools
|
||||
|
||||
**Files:**
|
||||
- Modify: `gitnexus/src/cli/group.ts:160` (remove import), `:187-189` (remove finally block body)
|
||||
- Test: `gitnexus/test/unit/group/sync.test.ts` (add pool cleanup test)
|
||||
- Test: `gitnexus/test/integration/group/group-cli.test.ts` (verify no blanket close in source)
|
||||
|
||||
- [ ] **Step 1: Write unit tests for per-id pool cleanup in sync.ts**
|
||||
|
||||
Add to `gitnexus/test/unit/group/sync.test.ts`, inside the existing `describe('syncGroup', ...)`:
|
||||
|
||||
```typescript
|
||||
it('test_syncGroup_closes_only_opened_pools', async () => {
|
||||
const config = makeConfig({
|
||||
'app/backend': 'backend-repo',
|
||||
'app/frontend': 'frontend-repo',
|
||||
});
|
||||
|
||||
const closedIds: string[] = [];
|
||||
|
||||
// Mock initLbug/closeLbug via per-repo override that tracks pool lifecycle
|
||||
const { vi } = await import('vitest');
|
||||
const poolAdapter = await import('../../../src/core/lbug/pool-adapter.js');
|
||||
const initSpy = vi.spyOn(poolAdapter, 'initLbug').mockResolvedValue(undefined);
|
||||
const closeSpy = vi.spyOn(poolAdapter, 'closeLbug').mockImplementation(async (id?: string) => {
|
||||
if (id) closedIds.push(id);
|
||||
});
|
||||
|
||||
try {
|
||||
await syncGroup(config, {
|
||||
resolveRepoHandle: async (_name, groupPath) => ({
|
||||
id: groupPath.replace(/\//g, '-'),
|
||||
path: groupPath,
|
||||
repoPath: '/tmp/' + groupPath,
|
||||
storagePath: '/tmp/' + groupPath + '/.gitnexus',
|
||||
}),
|
||||
skipWrite: true,
|
||||
}).catch(() => {});
|
||||
// Regardless of extraction errors, closeLbug should be called per id
|
||||
// closeLbug should only receive specific pool ids, never undefined/empty
|
||||
for (const id of closedIds) {
|
||||
expect(id).toBeTruthy();
|
||||
expect(typeof id).toBe('string');
|
||||
}
|
||||
// No blanket close (no-arg call)
|
||||
const blanketCalls = closeSpy.mock.calls.filter((args) => args.length === 0 || !args[0]);
|
||||
expect(blanketCalls).toHaveLength(0);
|
||||
} finally {
|
||||
initSpy.mockRestore();
|
||||
closeSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run sync unit test to verify it passes (sync.ts already does per-id cleanup)**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/sync.test.ts`
|
||||
Expected: PASS — sync.ts already cleans up correctly. This test locks the behavior.
|
||||
|
||||
- [ ] **Step 3: Write test verifying CLI source has no blanket closeLbug()**
|
||||
|
||||
Add to `gitnexus/test/integration/group/group-cli.test.ts`:
|
||||
|
||||
```typescript
|
||||
it('test_sync_command_source_does_not_call_blanket_closeLbug', () => {
|
||||
const cliGroupPath = path.join(repoRoot, 'src', 'cli', 'group.ts');
|
||||
const source = fs.readFileSync(cliGroupPath, 'utf-8');
|
||||
|
||||
// closeLbug() without arguments (blanket close) must not appear.
|
||||
// closeLbug(id) with argument is fine (that's in sync.ts, not here).
|
||||
// Match closeLbug() but not closeLbug(someArg)
|
||||
const blanketClosePattern = /closeLbug\s*\(\s*\)/;
|
||||
expect(source).not.toMatch(blanketClosePattern);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it fails**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/integration/group/group-cli.test.ts`
|
||||
Expected: FAIL — `closeLbug()` (no args) exists at line 188.
|
||||
|
||||
- [ ] **Step 5: Remove blanket closeLbug() from cli/group.ts**
|
||||
|
||||
In `gitnexus/src/cli/group.ts`:
|
||||
|
||||
Remove the `closeLbug` import at line 160:
|
||||
```typescript
|
||||
const { closeLbug } = await import('../core/lbug/pool-adapter.js');
|
||||
```
|
||||
|
||||
Replace the try/finally wrapper (lines 162-189):
|
||||
```typescript
|
||||
try {
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
|
||||
console.log(`Syncing group "${name}" (${Object.keys(config.repos).length} repos)...\n`);
|
||||
|
||||
const result = await syncGroup(config, {
|
||||
groupDir,
|
||||
allowStale: Boolean(opts.allowStale),
|
||||
verbose: Boolean(opts.verbose),
|
||||
skipEmbeddings: Boolean(opts.skipEmbeddings),
|
||||
exactOnly: Boolean(opts.exactOnly),
|
||||
});
|
||||
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(`\nMatching cascade:`);
|
||||
const exactLinks = result.crossLinks.filter((l) => l.matchType === 'exact');
|
||||
console.log(` exact: ${exactLinks.length} cross-links (confidence 1.0)`);
|
||||
console.log(` unmatched: ${result.unmatched.length} contracts`);
|
||||
console.log(
|
||||
`\nWrote contracts.json (${result.contracts.length} contracts, ${result.crossLinks.length} cross-links)`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await closeLbug().catch(() => {});
|
||||
}
|
||||
```
|
||||
|
||||
Becomes (remove try/finally entirely, since sync.ts handles its own cleanup):
|
||||
```typescript
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
|
||||
console.log(`Syncing group "${name}" (${Object.keys(config.repos).length} repos)...\n`);
|
||||
|
||||
const result = await syncGroup(config, {
|
||||
groupDir,
|
||||
allowStale: Boolean(opts.allowStale),
|
||||
verbose: Boolean(opts.verbose),
|
||||
skipEmbeddings: Boolean(opts.skipEmbeddings),
|
||||
exactOnly: Boolean(opts.exactOnly),
|
||||
});
|
||||
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(`\nMatching cascade:`);
|
||||
const exactLinks = result.crossLinks.filter((l) => l.matchType === 'exact');
|
||||
console.log(` exact: ${exactLinks.length} cross-links (confidence 1.0)`);
|
||||
console.log(` unmatched: ${result.unmatched.length} contracts`);
|
||||
console.log(
|
||||
`\nWrote contracts.json (${result.contracts.length} contracts, ${result.crossLinks.length} cross-links)`,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run tests to verify they pass**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/integration/group/group-cli.test.ts test/unit/group/sync.test.ts`
|
||||
Expected: ALL PASS
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
cd gitnexus && git add src/cli/group.ts test/integration/group/group-cli.test.ts test/unit/group/sync.test.ts
|
||||
git commit -m "fix(group): remove blanket closeLbug() from CLI sync command
|
||||
|
||||
sync.ts already closes pools per-id in its finally block.
|
||||
The blanket closeLbug() in cli/group.ts tears down ALL active pools
|
||||
including unrelated ones in MCP server context.
|
||||
|
||||
Addresses PR #626 review item 4 (HIGH).
|
||||
|
||||
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: gRPC Proto Regex — Brace-Depth Counter
|
||||
|
||||
**Files:**
|
||||
- Modify: `gitnexus/src/core/group/extractors/grpc-extractor.ts:101-130` (parseProtoFile)
|
||||
- Test: `gitnexus/test/unit/group/grpc-extractor.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests for nested braces in proto services**
|
||||
|
||||
Add this describe block inside the existing `proto file parsing` describe in `gitnexus/test/unit/group/grpc-extractor.test.ts`:
|
||||
|
||||
```typescript
|
||||
it('test_extract_proto_with_google_api_http_nested_braces', async () => {
|
||||
writeFile(
|
||||
'api/gateway.proto',
|
||||
`syntax = "proto3";
|
||||
package gateway.v1;
|
||||
|
||||
import "google/api/annotations.proto";
|
||||
|
||||
service GatewayService {
|
||||
rpc GetUser (GetUserRequest) returns (UserResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/v1/users/{user_id}"
|
||||
};
|
||||
}
|
||||
rpc CreateUser (CreateUserRequest) returns (UserResponse) {
|
||||
option (google.api.http) = {
|
||||
post: "/v1/users"
|
||||
body: "*"
|
||||
};
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
const contracts = await extractor.extract(null, tmpDir, makeRepo(tmpDir));
|
||||
const providers = contracts.filter(
|
||||
(c) => c.role === 'provider' && c.symbolRef.filePath === 'api/gateway.proto',
|
||||
);
|
||||
|
||||
expect(providers).toHaveLength(2);
|
||||
const ids = providers.map((c) => c.contractId).sort();
|
||||
expect(ids).toEqual([
|
||||
'grpc::gateway.v1.GatewayService/CreateUser',
|
||||
'grpc::gateway.v1.GatewayService/GetUser',
|
||||
]);
|
||||
});
|
||||
|
||||
it('test_extract_proto_with_multiple_services', async () => {
|
||||
writeFile(
|
||||
'api/multi.proto',
|
||||
`syntax = "proto3";
|
||||
package multi;
|
||||
|
||||
service ServiceA {
|
||||
rpc MethodA (Req) returns (Res);
|
||||
}
|
||||
|
||||
service ServiceB {
|
||||
rpc MethodB1 (Req) returns (Res);
|
||||
rpc MethodB2 (Req) returns (Res);
|
||||
}`,
|
||||
);
|
||||
|
||||
const contracts = await extractor.extract(null, tmpDir, makeRepo(tmpDir));
|
||||
const providers = contracts.filter(
|
||||
(c) => c.role === 'provider' && c.symbolRef.filePath === 'api/multi.proto',
|
||||
);
|
||||
|
||||
expect(providers).toHaveLength(3);
|
||||
const ids = providers.map((c) => c.contractId).sort();
|
||||
expect(ids).toEqual([
|
||||
'grpc::multi.ServiceA/MethodA',
|
||||
'grpc::multi.ServiceB/MethodB1',
|
||||
'grpc::multi.ServiceB/MethodB2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('test_extract_proto_with_nested_option_blocks_in_rpc', async () => {
|
||||
writeFile(
|
||||
'api/nested.proto',
|
||||
`syntax = "proto3";
|
||||
package nested;
|
||||
|
||||
service DeepService {
|
||||
rpc DeepMethod (Req) returns (Res) {
|
||||
option (google.api.http) = {
|
||||
post: "/v1/deep"
|
||||
body: "*"
|
||||
additional_bindings {
|
||||
get: "/v1/deep/{id}"
|
||||
}
|
||||
};
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
const contracts = await extractor.extract(null, tmpDir, makeRepo(tmpDir));
|
||||
const providers = contracts.filter(
|
||||
(c) => c.role === 'provider' && c.symbolRef.filePath === 'api/nested.proto',
|
||||
);
|
||||
|
||||
expect(providers).toHaveLength(1);
|
||||
expect(providers[0].contractId).toBe('grpc::nested.DeepService/DeepMethod');
|
||||
});
|
||||
|
||||
it('test_extract_proto_malformed_unclosed_brace_skips_service', async () => {
|
||||
writeFile(
|
||||
'api/broken.proto',
|
||||
`syntax = "proto3";
|
||||
package broken;
|
||||
|
||||
service IncompleteService {
|
||||
rpc SomeMethod (Req) returns (Res);
|
||||
// Missing closing brace — EOF before depth returns to 0
|
||||
`,
|
||||
);
|
||||
|
||||
// Should not throw; incomplete service is silently skipped
|
||||
const contracts = await extractor.extract(null, tmpDir, makeRepo(tmpDir));
|
||||
const providers = contracts.filter(
|
||||
(c) => c.role === 'provider' && c.symbolRef.filePath === 'api/broken.proto',
|
||||
);
|
||||
|
||||
// The old regex would find partial match; the new parser should skip it
|
||||
expect(providers).toHaveLength(0);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify the nested brace test fails**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/grpc-extractor.test.ts`
|
||||
Expected: `test_extract_proto_with_google_api_http_nested_braces` FAIL — regex stops at first `}` inside the `option` block.
|
||||
|
||||
- [ ] **Step 3: Replace serviceRe regex with extractServiceBlocks function**
|
||||
|
||||
In `gitnexus/src/core/group/extractors/grpc-extractor.ts`, replace the `parseProtoFile` method (lines 101-130):
|
||||
|
||||
```typescript
|
||||
private parseProtoFile(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
const pkgMatch = content.match(/^package\s+([\w.]+)\s*;/m);
|
||||
const pkg = pkgMatch ? pkgMatch[1] : '';
|
||||
|
||||
for (const { name: serviceName, body } of extractServiceBlocks(content)) {
|
||||
const rpcRe = /rpc\s+(\w+)\s*\(/g;
|
||||
let rpcMatch: RegExpExecArray | null;
|
||||
while ((rpcMatch = rpcRe.exec(body)) !== null) {
|
||||
const methodName = rpcMatch[1];
|
||||
const cid = contractId(pkg, serviceName, methodName);
|
||||
out.push(
|
||||
makeContract(cid, 'provider', filePath, `${serviceName}.${methodName}`, 0.85, {
|
||||
package: pkg,
|
||||
service: serviceName,
|
||||
method: methodName,
|
||||
source: 'proto',
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
```
|
||||
|
||||
Add this function before the class (e.g. after `serviceOnlyContractId`, around line 26):
|
||||
|
||||
```typescript
|
||||
function extractServiceBlocks(content: string): Array<{ name: string; body: string }> {
|
||||
const results: Array<{ name: string; body: string }> = [];
|
||||
const headerRe = /service\s+(\w+)\s*\{/g;
|
||||
let headerMatch: RegExpExecArray | null;
|
||||
|
||||
while ((headerMatch = headerRe.exec(content)) !== null) {
|
||||
const serviceName = headerMatch[1];
|
||||
const bodyStart = headerMatch.index + headerMatch[0].length;
|
||||
let depth = 1;
|
||||
let pos = bodyStart;
|
||||
|
||||
while (pos < content.length && depth > 0) {
|
||||
const ch = content[pos];
|
||||
if (ch === '{') depth++;
|
||||
else if (ch === '}') depth--;
|
||||
pos++;
|
||||
}
|
||||
|
||||
// If EOF before depth returns to 0, skip incomplete service
|
||||
if (depth !== 0) continue;
|
||||
|
||||
// body is between opening { (consumed by regex) and closing } (pos is one past it)
|
||||
const body = content.slice(bodyStart, pos - 1);
|
||||
results.push({ name: serviceName, body });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/grpc-extractor.test.ts`
|
||||
Expected: ALL PASS (including existing regression tests)
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
cd gitnexus && git add src/core/group/extractors/grpc-extractor.ts test/unit/group/grpc-extractor.test.ts
|
||||
git commit -m "fix(group): replace gRPC proto regex with brace-depth counter
|
||||
|
||||
The serviceRe regex used [^}]* which stopped at the first '}'.
|
||||
Proto services with google.api.http annotations contain nested {}
|
||||
blocks, causing methods to be missed.
|
||||
|
||||
New extractServiceBlocks() uses a brace-depth counter (init depth=1
|
||||
after opening {, scan char-by-char). Malformed protos with unclosed
|
||||
braces are silently skipped.
|
||||
|
||||
Addresses PR #626 review item 2 (HIGH).
|
||||
|
||||
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Run Full Test Suite
|
||||
|
||||
- [ ] **Step 1: Run all group-related tests**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/unit/group/ test/integration/group/`
|
||||
Expected: ALL PASS
|
||||
|
||||
- [ ] **Step 2: Run full test suite to catch regressions**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run`
|
||||
Expected: ALL PASS, 0 failures
|
||||
|
||||
- [ ] **Step 3: Run typecheck**
|
||||
|
||||
Run: `cd gitnexus && npx tsc --noEmit`
|
||||
Expected: No errors
|
||||
|
||||
---
|
||||
|
||||
### Task 6: CLI Integration Smoke Test
|
||||
|
||||
- [ ] **Step 1: Add CLI smoke test for path traversal**
|
||||
|
||||
Add to `gitnexus/test/integration/group/group-cli.test.ts` inside the existing `group CLI` describe:
|
||||
|
||||
```typescript
|
||||
it('test_create_with_invalid_name_fails', () => {
|
||||
const result = runGroup(['create', '../../evil']);
|
||||
expect(result.status).not.toBe(0);
|
||||
expect(result.stderr).toContain('Invalid group name');
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test**
|
||||
|
||||
Run: `cd gitnexus && npx vitest run test/integration/group/group-cli.test.ts`
|
||||
Expected: ALL PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
cd gitnexus && git add test/integration/group/group-cli.test.ts
|
||||
git commit -m "test(group): add CLI smoke test for path traversal rejection
|
||||
|
||||
Verifies that 'group create ../../evil' fails with Invalid group name.
|
||||
|
||||
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>"
|
||||
```
|
||||
@@ -0,0 +1,175 @@
|
||||
# PR #626 HIGH-Priority Fixes Design
|
||||
|
||||
**Date:** 2026-04-02
|
||||
**PR:** abhigyanpatwari/GitNexus#626 — Intra-repo service communication tracking
|
||||
**Scope:** 4 HIGH-priority issues identified by abhigyanpatwari and xkonjin
|
||||
**Approach:** Minimal targeted fixes (option A) — no refactoring, no scope creep
|
||||
|
||||
---
|
||||
|
||||
## Fix 1: Path Traversal via Group Name
|
||||
|
||||
**File:** `gitnexus/src/core/group/storage.ts`
|
||||
**Risk:** A group name like `../../etc` creates directories outside the intended path.
|
||||
|
||||
### Solution
|
||||
|
||||
Add `validateGroupName(name: string): void` that enforces `/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/`.
|
||||
|
||||
- Call in `createGroupDir` (primary entry point)
|
||||
- Call in `getGroupDir` (defense in depth)
|
||||
- Throw descriptive error on invalid names
|
||||
|
||||
**Legacy:** Groups already on disk with names outside this pattern are not auto-renamed; only new `create` / resolved paths are validated.
|
||||
|
||||
### Why regex over path.resolve + startsWith
|
||||
|
||||
- abhigyanpatwari explicitly requested `[a-zA-Z0-9_-]`
|
||||
- Stricter: disallows spaces, dots, Unicode edge cases
|
||||
- Simpler to reason about
|
||||
|
||||
### Tests
|
||||
|
||||
- `../../evil` throws
|
||||
- `foo/bar` throws
|
||||
- Empty string throws
|
||||
- `my-group_01` passes
|
||||
- `A` (single char) passes
|
||||
- CLI smoke: one integration test that hits `getGroupDir` / `createGroupDir` (e.g. `group create` or `group add`) with an invalid name proves wiring for every subcommand that resolves a group through storage
|
||||
|
||||
### CLI/API entry points accepting groupName
|
||||
|
||||
All paths flow through `getGroupDir` (which validates), so coverage is implicit. For reference:
|
||||
|
||||
| Command | Entry | Calls |
|
||||
|---------|-------|-------|
|
||||
| `group create` | `cli/group.ts` action | `createGroupDir` -> `getGroupDir` |
|
||||
| `group add` | `cli/group.ts` action | `getGroupDir` |
|
||||
| `group remove` | `cli/group.ts` action | `getGroupDir` |
|
||||
| `group list` | `cli/group.ts` action | reads `groups/` dir directly — no traversal risk (reads, not writes) |
|
||||
| `group status` | `cli/group.ts` action | `getGroupDir` |
|
||||
| `group sync` | `cli/group.ts` action | `getGroupDir` |
|
||||
|
||||
**`listGroups`:** Reads directory names from disk without validation. Not a write path, so no traversal risk. May surface manually-created directories with non-conforming names — accepted as-is, not in scope.
|
||||
|
||||
---
|
||||
|
||||
## Fix 2: gRPC Proto Regex -> Brace-Depth Counter
|
||||
|
||||
**File:** `gitnexus/src/core/group/extractors/grpc-extractor.ts`
|
||||
**Risk:** `serviceRe = /service\s+(\w+)\s*\{([^}]*)}/gs` stops at first `}`. Proto services with `google.api.http` annotations inside RPCs contain nested `{ }` blocks.
|
||||
|
||||
### Solution
|
||||
|
||||
Replace `serviceRe` regex with `extractServiceBlocks(content: string): Array<{ name: string; body: string }>`:
|
||||
|
||||
1. Use regex only to find `service <Name> {` start positions (regex consumes the opening `{`)
|
||||
2. Initialise depth to 1 immediately after the opening `{`
|
||||
3. Scan forward char by char: `{` -> depth++, `}` -> depth--; collect into body
|
||||
4. Stop when depth reaches 0 (the matching closing `}`)
|
||||
5. Return name + body pairs
|
||||
|
||||
Inner `rpcRe` regex remains unchanged — it operates on the already-extracted body.
|
||||
|
||||
**Malformed input:** If EOF is reached before `depth` returns to 0, skip the incomplete service (do not add to results). Lock this in the test.
|
||||
|
||||
**Scope limitation (v1):** Brace-depth only — no lexer for string literals or comments containing `{`/`}`. Sufficient for `google.api.http` annotations. Known false positive: braces inside `//` comments or quoted strings within proto options. Accepted for v1; a proper proto lexer is out of scope.
|
||||
|
||||
### Tests
|
||||
|
||||
- Proto with single service, no nesting (regression)
|
||||
- Proto with `google.api.http` nested braces inside RPC options
|
||||
- Proto with multiple services
|
||||
- Proto with nested `option` blocks inside RPC (e.g. `google.api.http`)
|
||||
- Malformed proto with unclosed brace (graceful handling)
|
||||
|
||||
---
|
||||
|
||||
## Fix 3: Directory Exclusions in Service Boundary Detector
|
||||
|
||||
**File:** `gitnexus/src/core/group/service-boundary-detector.ts`
|
||||
**Risk:** Walks entire repo tree, only skipping dotfiles and `node_modules`. Extremely slow on repos with `vendor/`, `target/`, `__pycache__/`, `.venv/`.
|
||||
|
||||
### Solution
|
||||
|
||||
Create `EXCLUDED_DIRS` as a `Set<string>` (alongside existing `SERVICE_MARKERS`, `SOURCE_EXTENSIONS`), for example:
|
||||
|
||||
```text
|
||||
node_modules, vendor, target, build, dist,
|
||||
__pycache__, .venv, venv, .tox, .mypy_cache,
|
||||
.gradle, .mvn, out, bin
|
||||
```
|
||||
|
||||
(Implement as `new Set([...])` — the list above is the membership, not a string literal.)
|
||||
|
||||
Apply in both:
|
||||
- `walkForBoundaries` (line 77-78) — replace current inline `=== 'node_modules'` check with `EXCLUDED_DIRS.has(entry.name)`
|
||||
- `hasSourceFilesInSubdirs` (line 130) — replace `entry.name !== 'node_modules'` with `!EXCLUDED_DIRS.has(entry.name)`
|
||||
|
||||
Note: remove the old `=== 'node_modules'` literal from both locations — it is covered by `EXCLUDED_DIRS`.
|
||||
Dotfile exclusion (`.` prefix) remains as a separate check since it's a pattern, not a name.
|
||||
Exclusions apply only to `isDirectory()` entries — file names are never checked against `EXCLUDED_DIRS`.
|
||||
|
||||
**Tradeoff:** Rare layouts that keep source under names like `out/` or `bin/` will be skipped; accepted for performance on typical monorepos.
|
||||
|
||||
**Case sensitivity:** `Set.has` is case-sensitive (matches current `=== 'node_modules'` behavior). Windows case-insensitive FS not handled — accepted as-is, consistent with existing code.
|
||||
|
||||
### Tests
|
||||
|
||||
- Directory named `vendor/` is skipped
|
||||
- Directory named `target/` is skipped
|
||||
- Directory named `__pycache__/` is skipped
|
||||
- Regular source directories are NOT skipped
|
||||
- Dotfile directories still skipped (regression)
|
||||
|
||||
---
|
||||
|
||||
## Fix 4: Double-Close of LadybugDB Pools
|
||||
|
||||
**Files:**
|
||||
- `gitnexus/src/core/group/sync.ts` (lines 155-157) — per-id cleanup (KEEP)
|
||||
- `gitnexus/src/cli/group.ts` (line 188) — blanket `closeLbug()` (REMOVE)
|
||||
|
||||
**Risk:** In MCP server context, `closeLbug()` without arguments tears down ALL active pools, including ones from unrelated operations.
|
||||
|
||||
### Solution
|
||||
|
||||
Remove the `closeLbug()` call (no arguments) from `cli/group.ts` finally block. The per-id cleanup in `sync.ts` is sufficient:
|
||||
|
||||
```typescript
|
||||
// sync.ts — KEEP: cleans up only pools opened by this sync
|
||||
finally {
|
||||
for (const id of [...new Set(openPoolIds)]) {
|
||||
await closeLbug(id).catch(() => {});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// cli/group.ts — REMOVE: blanket close that kills all pools
|
||||
finally {
|
||||
await closeLbug().catch(() => {}); // DELETE THIS
|
||||
}
|
||||
```
|
||||
|
||||
Remove the `closeLbug` import from `cli/group.ts` — after removing the `finally` call it has no remaining usages.
|
||||
|
||||
### Tests (unit level — mock pool adapter)
|
||||
|
||||
- `syncGroup` closes only the pools it opened (mock `closeLbug`, assert called with specific ids)
|
||||
- Two-pool scenario: sync opens pools A and B, both closed in finally; pool C (opened elsewhere) not touched
|
||||
- CLI `sync` command does not call blanket `closeLbug()` (verify no zero-arg call in source — static check or grep-based test)
|
||||
|
||||
---
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- JSON -> LadybugDB migration (tracked in #606)
|
||||
- MEDIUM/LOW issues (items 5-10 from review summary)
|
||||
- Test gap coverage beyond what's needed for these 4 fixes
|
||||
- Any refactoring or architectural changes
|
||||
|
||||
## Execution Order
|
||||
|
||||
Fixes are independent — can be implemented in parallel or any order.
|
||||
Recommended order for review clarity: 1 -> 3 -> 4 -> 2 (simplest to most complex).
|
||||
@@ -97,7 +97,8 @@ export type RelationshipType =
|
||||
| 'CONTAINS'
|
||||
| 'CALLS'
|
||||
| 'INHERITS'
|
||||
| 'OVERRIDES'
|
||||
| 'METHOD_OVERRIDES'
|
||||
| 'METHOD_IMPLEMENTS'
|
||||
| 'IMPORTS'
|
||||
| 'USES'
|
||||
| 'DEFINES'
|
||||
|
||||
@@ -19,6 +19,7 @@ export type { NodeTableName, RelType } from './lbug/schema-constants.js';
|
||||
// Language support
|
||||
export { SupportedLanguages } from './languages.js';
|
||||
export { getLanguageFromFilename, getSyntaxLanguageFromFilename } from './language-detection.js';
|
||||
export type { MroStrategy } from './mro-strategy.js';
|
||||
|
||||
// Pipeline progress
|
||||
export type { PipelinePhase, PipelineProgress } from './pipeline.js';
|
||||
|
||||
@@ -41,6 +41,7 @@ const EXTENSION_MAP: Record<SupportedLanguages, readonly string[]> = {
|
||||
[SupportedLanguages.Kotlin]: ['.kt', '.kts'],
|
||||
[SupportedLanguages.Swift]: ['.swift'],
|
||||
[SupportedLanguages.Dart]: ['.dart'],
|
||||
[SupportedLanguages.Vue]: ['.vue'],
|
||||
[SupportedLanguages.Cobol]: ['.cbl', '.cob', '.cpy', '.cobol'],
|
||||
} satisfies Record<SupportedLanguages, readonly string[]>; // Ensure exhaustiveness
|
||||
|
||||
@@ -98,6 +99,7 @@ const SYNTAX_MAP: Record<SupportedLanguages, string> = {
|
||||
[SupportedLanguages.Kotlin]: 'kotlin',
|
||||
[SupportedLanguages.Swift]: 'swift',
|
||||
[SupportedLanguages.Dart]: 'dart',
|
||||
[SupportedLanguages.Vue]: 'typescript',
|
||||
[SupportedLanguages.Cobol]: 'cobol',
|
||||
} satisfies Record<SupportedLanguages, string>; // Ensure exhaustiveness
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ export enum SupportedLanguages {
|
||||
Kotlin = 'kotlin',
|
||||
Swift = 'swift',
|
||||
Dart = 'dart',
|
||||
Vue = 'vue',
|
||||
/** Standalone regex processor — no tree-sitter, no LanguageProvider. */
|
||||
Cobol = 'cobol',
|
||||
}
|
||||
|
||||
@@ -55,7 +55,9 @@ export const REL_TYPES = [
|
||||
'HAS_METHOD',
|
||||
'HAS_PROPERTY',
|
||||
'ACCESSES',
|
||||
'OVERRIDES',
|
||||
'METHOD_OVERRIDES',
|
||||
'OVERRIDES', // Legacy compat alias — kept until all stored indexes are migrated
|
||||
'METHOD_IMPLEMENTS',
|
||||
'MEMBER_OF',
|
||||
'STEP_IN_PROCESS',
|
||||
'HANDLES_ROUTE',
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* MRO (Method Resolution Order) strategy — shared between CLI and any
|
||||
* future consumer that reasons about multiple-inheritance semantics.
|
||||
*
|
||||
* Lives in `gitnexus-shared` so the low-level resolution module
|
||||
* (`core/ingestion/model/resolve.ts`) does not need to import from
|
||||
* `languages/` — keeping the `model/` layer free of language-registry
|
||||
* coupling.
|
||||
*
|
||||
* Strategy semantics:
|
||||
* - `first-wins`: BFS ancestor walk, first match wins (default).
|
||||
* - `leftmost-base`: BFS ancestor walk, leftmost base wins (C++).
|
||||
* - `c3`: C3-linearized ancestor order, first match wins (Python).
|
||||
* - `implements-split`: BFS walk, first match wins (Java/C#/Kotlin) — full
|
||||
* interface-default ambiguity is handled at graph level.
|
||||
* - `qualified-syntax`: No auto-resolution (Rust — requires `<T as Trait>::m`).
|
||||
*/
|
||||
export type MroStrategy =
|
||||
| 'first-wins'
|
||||
| 'c3'
|
||||
| 'leftmost-base'
|
||||
| 'implements-split'
|
||||
| 'qualified-syntax';
|
||||
@@ -0,0 +1,109 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* E2E tests for heartbeat disconnect/reconnect behavior.
|
||||
*
|
||||
* Verifies the key regression: when the heartbeat fails, the UI shows a
|
||||
* "reconnecting" banner instead of resetting to the onboarding screen.
|
||||
*
|
||||
* Strategy: block /api/heartbeat via route interception BEFORE loading the
|
||||
* graph. The heartbeat EventSource can never connect, so onReconnecting
|
||||
* fires on the first retry attempt. This reliably tests the banner behavior
|
||||
* without depending on setOffline timing (which varies across CI environments).
|
||||
*/
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:4747';
|
||||
const FRONTEND_URL = process.env.FRONTEND_URL ?? 'http://localhost:5173';
|
||||
|
||||
test.beforeAll(async () => {
|
||||
if (process.env.E2E) return;
|
||||
try {
|
||||
const [backendRes, frontendRes] = await Promise.allSettled([
|
||||
fetch(`${BACKEND_URL}/api/repos`),
|
||||
fetch(FRONTEND_URL),
|
||||
]);
|
||||
if (
|
||||
backendRes.status === 'rejected' ||
|
||||
(backendRes.status === 'fulfilled' && !backendRes.value.ok)
|
||||
) {
|
||||
test.skip(true, 'gitnexus serve not available');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
frontendRes.status === 'rejected' ||
|
||||
(frontendRes.status === 'fulfilled' && !frontendRes.value.ok)
|
||||
) {
|
||||
test.skip(true, 'Vite dev server not available');
|
||||
return;
|
||||
}
|
||||
if (backendRes.status === 'fulfilled') {
|
||||
const repos = await backendRes.value.json();
|
||||
if (!repos.length) {
|
||||
test.skip(true, 'No indexed repos');
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
test.skip(true, 'servers not available');
|
||||
}
|
||||
});
|
||||
|
||||
test.describe('Heartbeat Reconnect', () => {
|
||||
test('shows reconnecting banner instead of onboarding reset when heartbeat is unavailable', async ({
|
||||
page,
|
||||
}) => {
|
||||
// Block the heartbeat BEFORE navigating — the EventSource will fail
|
||||
// immediately on every connection attempt, triggering onReconnecting.
|
||||
await page.route('**/api/heartbeat', (route) => route.abort('connectionrefused'));
|
||||
|
||||
// Load the app and connect to a repo (all other endpoints work normally)
|
||||
await page.goto('/');
|
||||
|
||||
const landingCard = page.locator('[data-testid="landing-repo-card"]').first();
|
||||
try {
|
||||
await landingCard.waitFor({ state: 'visible', timeout: 15_000 });
|
||||
await landingCard.click();
|
||||
} catch {
|
||||
// auto-connect may skip the landing screen
|
||||
}
|
||||
|
||||
// Wait for graph to load (heartbeat is blocked, but graph loads fine)
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// The reconnecting banner should appear (heartbeat is failing)
|
||||
const banner = page.getByText('Server connection lost');
|
||||
await expect(banner).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// The graph canvas should STILL be visible — NOT reset to onboarding
|
||||
await expect(page.locator('canvas').first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('banner clears when heartbeat becomes available', async ({ page }) => {
|
||||
// Start with heartbeat blocked
|
||||
await page.route('**/api/heartbeat', (route) => route.abort('connectionrefused'));
|
||||
|
||||
await page.goto('/');
|
||||
const landingCard = page.locator('[data-testid="landing-repo-card"]').first();
|
||||
try {
|
||||
await landingCard.waitFor({ state: 'visible', timeout: 15_000 });
|
||||
await landingCard.click();
|
||||
} catch {
|
||||
// auto-connect may skip the landing screen
|
||||
}
|
||||
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// Verify banner appears
|
||||
const banner = page.getByText('Server connection lost');
|
||||
await expect(banner).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Unblock heartbeat — the real server is running, so reconnect will succeed
|
||||
await page.unroute('**/api/heartbeat');
|
||||
|
||||
// Banner should disappear as heartbeat reconnects
|
||||
await expect(banner).not.toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// Graph should still be there
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* E2E tests for multi-repo scoping and URL persistence.
|
||||
*
|
||||
* Verifies that:
|
||||
* - Connecting via ?server= loads data and sets ?project= in the URL
|
||||
* - The repo name appears in the UI after connecting
|
||||
* - F5 with ?server=&project= reconnects to the correct repo
|
||||
*
|
||||
* Runs against the single indexed repo in CI — validates the plumbing
|
||||
* works end-to-end even with one repo.
|
||||
*/
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:4747';
|
||||
const FRONTEND_URL = process.env.FRONTEND_URL ?? 'http://localhost:5173';
|
||||
|
||||
let firstRepoName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
if (process.env.E2E) {
|
||||
// Still need to fetch the repo name for assertions
|
||||
try {
|
||||
const res = await fetch(`${BACKEND_URL}/api/repos`);
|
||||
const repos = await res.json();
|
||||
firstRepoName = repos[0]?.name ?? '';
|
||||
} catch {
|
||||
firstRepoName = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [backendRes, frontendRes] = await Promise.allSettled([
|
||||
fetch(`${BACKEND_URL}/api/repos`),
|
||||
fetch(FRONTEND_URL),
|
||||
]);
|
||||
if (
|
||||
backendRes.status === 'rejected' ||
|
||||
(backendRes.status === 'fulfilled' && !backendRes.value.ok)
|
||||
) {
|
||||
test.skip(true, 'gitnexus serve not available');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
frontendRes.status === 'rejected' ||
|
||||
(frontendRes.status === 'fulfilled' && !frontendRes.value.ok)
|
||||
) {
|
||||
test.skip(true, 'Vite dev server not available');
|
||||
return;
|
||||
}
|
||||
if (backendRes.status === 'fulfilled') {
|
||||
const repos = await backendRes.value.json();
|
||||
if (!repos.length) {
|
||||
test.skip(true, 'No indexed repos');
|
||||
return;
|
||||
}
|
||||
firstRepoName = repos[0].name;
|
||||
}
|
||||
} catch {
|
||||
test.skip(true, 'servers not available');
|
||||
}
|
||||
});
|
||||
|
||||
test.describe('Multi-Repo Scoping', () => {
|
||||
test('auto-connect via ?server= sets ?project= in URL', async ({ page }) => {
|
||||
// Navigate with ?server= param (the bookmarkable shortcut)
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
|
||||
// Wait for graph to load
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// URL should now contain ?project= with the repo name
|
||||
const url = new URL(page.url());
|
||||
const project = url.searchParams.get('project');
|
||||
expect(project).toBeTruthy();
|
||||
expect(project).toBe(firstRepoName);
|
||||
});
|
||||
|
||||
test('?server= is preserved in URL for F5 recovery', async ({ page }) => {
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// URL should still have ?server=
|
||||
const url = new URL(page.url());
|
||||
expect(url.searchParams.get('server')).toBeTruthy();
|
||||
|
||||
// F5 should reconnect (not show onboarding)
|
||||
await page.reload();
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
});
|
||||
|
||||
test('node count in status bar matches backend data', async ({ page }) => {
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// Fetch expected node count from backend
|
||||
const res = await fetch(`${BACKEND_URL}/api/repo?repo=${encodeURIComponent(firstRepoName)}`);
|
||||
const repoInfo = await res.json();
|
||||
const expectedNodes = repoInfo.stats?.nodes;
|
||||
|
||||
if (expectedNodes) {
|
||||
// Status bar shows node count — use the status-ready area to avoid
|
||||
// matching multiple elements (file tree, header may also show counts)
|
||||
const statusBar = page.locator('footer');
|
||||
const nodeText = statusBar.getByText(/\d+ nodes/).first();
|
||||
await expect(nodeText).toBeVisible({ timeout: 10_000 });
|
||||
const text = await nodeText.textContent();
|
||||
const displayedNodes = parseInt(text?.match(/(\d+)\s*nodes/)?.[1] ?? '0', 10);
|
||||
expect(displayedNodes).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* E2E tests for the repo-switching and false-404 fixes.
|
||||
*
|
||||
* Most tests use the live backend (same pattern as multi-repo-scoping.spec.ts).
|
||||
* The 503 hold-queue test uses route interception to simulate a slow analysis.
|
||||
*/
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:4747';
|
||||
const FRONTEND_URL = process.env.FRONTEND_URL ?? 'http://localhost:5173';
|
||||
|
||||
let firstRepoName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
if (process.env.E2E) {
|
||||
try {
|
||||
const res = await fetch(`${BACKEND_URL}/api/repos`);
|
||||
const repos = await res.json();
|
||||
firstRepoName = repos[0]?.name ?? '';
|
||||
} catch {
|
||||
firstRepoName = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [backendRes, frontendRes] = await Promise.allSettled([
|
||||
fetch(`${BACKEND_URL}/api/repos`),
|
||||
fetch(FRONTEND_URL),
|
||||
]);
|
||||
if (
|
||||
backendRes.status === 'rejected' ||
|
||||
(backendRes.status === 'fulfilled' && !backendRes.value.ok)
|
||||
) {
|
||||
test.skip(true, 'gitnexus serve not available');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
frontendRes.status === 'rejected' ||
|
||||
(frontendRes.status === 'fulfilled' && !frontendRes.value.ok)
|
||||
) {
|
||||
test.skip(true, 'Vite dev server not available');
|
||||
return;
|
||||
}
|
||||
if (backendRes.status === 'fulfilled') {
|
||||
const repos = await backendRes.value.json();
|
||||
if (!repos.length) {
|
||||
test.skip(true, 'No indexed repos');
|
||||
return;
|
||||
}
|
||||
firstRepoName = repos[0].name;
|
||||
}
|
||||
} catch {
|
||||
test.skip(true, 'servers not available');
|
||||
}
|
||||
});
|
||||
|
||||
// ── 1. Hold-queue: 503 → descriptive user message ────────────────────────────
|
||||
|
||||
test.describe('Hold-queue timeout error', () => {
|
||||
test('shows descriptive message when /api/repo returns 503', async ({ page }, testInfo) => {
|
||||
// Intercept only /api/repo (singular) — not /api/repos — to return a 503
|
||||
// regex: /api/repo followed by end, ?, or # — NOT /api/repos
|
||||
await page.route(/\/api\/repo(?!s)(\?.*)?$/, (route) =>
|
||||
route.fulfill({
|
||||
status: 503,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
error: `Repository analysis for "${firstRepoName}" is taking longer than expected. Please try again in a moment.`,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
|
||||
// UI should show the 503 error message
|
||||
await expect(page.getByText(/taking longer than expected/i)).toBeVisible({
|
||||
timeout: 20_000,
|
||||
});
|
||||
|
||||
await page.screenshot({ path: testInfo.outputPath('hold-queue-503.png') });
|
||||
});
|
||||
});
|
||||
|
||||
// ── 2. ?project= URL persistence ─────────────────────────────────────────────
|
||||
|
||||
test.describe('?project= URL persistence', () => {
|
||||
test('?project= is set in URL after connecting via ?server=', async ({ page }) => {
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const url = new URL(page.url());
|
||||
const project = url.searchParams.get('project');
|
||||
expect(project).toBeTruthy();
|
||||
// first repo returned by the live backend
|
||||
if (firstRepoName) expect(project).toBe(firstRepoName);
|
||||
});
|
||||
|
||||
test('?project= is still present after F5 reload', async ({ page }) => {
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// After connect, URL has ?server=&project= — F5 re-uses both params
|
||||
await page.reload();
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const url = new URL(page.url());
|
||||
expect(url.searchParams.get('project')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ── 3. ?project= + ?server= combined auto-connect ────────────────────────────
|
||||
|
||||
test.describe('?project= auto-connect', () => {
|
||||
test('navigating with ?server=&project= connects to the correct repo', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
if (!firstRepoName) test.skip(true, 'no repo name available');
|
||||
|
||||
await page.goto(
|
||||
`/?server=${encodeURIComponent(BACKEND_URL)}&project=${encodeURIComponent(firstRepoName)}`,
|
||||
);
|
||||
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// ?project= in URL should match what we passed in
|
||||
const url = new URL(page.url());
|
||||
expect(url.searchParams.get('project')).toBe(firstRepoName);
|
||||
|
||||
await page.screenshot({ path: testInfo.outputPath('project-param-connect.png') });
|
||||
});
|
||||
});
|
||||
|
||||
// ── 4. Windows path normalization ─────────────────────────────────────────────
|
||||
|
||||
test.describe('Windows path normalization', () => {
|
||||
test('project name uses basename when /api/repo returns a Windows-style repoPath', async ({
|
||||
page,
|
||||
}) => {
|
||||
const repoName = firstRepoName || 'test-repo';
|
||||
const windowsPath = `C:\\Users\\LENOVO\\.gitnexus\\repos\\${repoName}`;
|
||||
|
||||
// Mock /api/repo to return a Windows backslash path while keeping name correct
|
||||
await page.route(/\/api\/repo(?!s)(\?.*)?$/, (route) =>
|
||||
route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
// intentionally omit `name` to force path-based extraction
|
||||
path: windowsPath,
|
||||
repoPath: windowsPath,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto(`/?server=${encodeURIComponent(BACKEND_URL)}`);
|
||||
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// URL ?project= must be the short basename, NOT the full Windows path
|
||||
const url = new URL(page.url());
|
||||
const project = url.searchParams.get('project');
|
||||
expect(project).toBeTruthy();
|
||||
expect(project).not.toContain('\\');
|
||||
expect(project).not.toContain('LENOVO');
|
||||
expect(project).toBe(repoName);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect, type TestInfo } from '@playwright/test';
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* E2E tests for the GitNexus web UI — exploring view features.
|
||||
@@ -58,36 +58,41 @@ test.beforeAll(async () => {
|
||||
* For these tests we require at least one indexed repo, so pick the first
|
||||
* landing card when present and then wait for the exploring view.
|
||||
*/
|
||||
async function waitForGraphLoaded(page: import('@playwright/test').Page, testInfo: TestInfo) {
|
||||
async function waitForGraphLoaded(page: import('@playwright/test').Page) {
|
||||
await page.goto('/');
|
||||
|
||||
const landingCard = page.locator('[data-testid="landing-repo-card"]').first();
|
||||
const landingCards = page.locator('[data-testid="landing-repo-card"]');
|
||||
const preferredLandingCard = landingCards
|
||||
.filter({ hasText: /GitNexus|local-integration/ })
|
||||
.first();
|
||||
try {
|
||||
await landingCard.waitFor({ state: 'visible', timeout: 15_000 });
|
||||
await landingCards.first().waitFor({ state: 'visible', timeout: 15_000 });
|
||||
const landingCard =
|
||||
(await preferredLandingCard.count()) > 0 ? preferredLandingCard : landingCards.first();
|
||||
await landingCard.click();
|
||||
} catch {
|
||||
// Landing screen may not appear (e.g. ?server auto-connect)
|
||||
}
|
||||
|
||||
await expect(page.locator('[data-testid="status-ready"]')).toBeVisible({ timeout: 30_000 });
|
||||
await expect(page.getByText(/\d+ nodes/).first()).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath('graph-loaded.png') });
|
||||
const statusBar = page.getByRole('contentinfo');
|
||||
await expect(statusBar.getByText('Ready', { exact: true })).toBeVisible({ timeout: 45_000 });
|
||||
await expect(statusBar).toContainText(/nodes/, {
|
||||
timeout: 20_000,
|
||||
});
|
||||
}
|
||||
|
||||
test.describe('Server Connection & Graph Loading', () => {
|
||||
test('selects a repo from landing and loads graph', async ({ page }, testInfo) => {
|
||||
await waitForGraphLoaded(page, testInfo);
|
||||
await page.screenshot({ path: testInfo.outputPath('graph-loaded-full.png'), fullPage: true });
|
||||
test('selects a repo from landing and loads graph', async ({ page }) => {
|
||||
await waitForGraphLoaded(page);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Nexus AI', () => {
|
||||
test('panel opens and agent initializes without error', async ({ page }, testInfo) => {
|
||||
await waitForGraphLoaded(page, testInfo);
|
||||
test('panel opens and agent initializes without error', async ({ page }) => {
|
||||
await waitForGraphLoaded(page);
|
||||
|
||||
await page.getByRole('button', { name: 'Nexus AI' }).click();
|
||||
await expect(page.getByText('Ask me anything')).toBeVisible({ timeout: 15_000 });
|
||||
await page.screenshot({ path: testInfo.outputPath('nexus-ai-panel.png'), fullPage: true });
|
||||
|
||||
const errorBanner = page.getByText('Database not ready');
|
||||
expect(await errorBanner.isVisible().catch(() => false)).toBe(false);
|
||||
@@ -95,8 +100,8 @@ test.describe('Nexus AI', () => {
|
||||
});
|
||||
|
||||
test.describe('Processes Panel', () => {
|
||||
test('shows process list and View button works', async ({ page }, testInfo) => {
|
||||
await waitForGraphLoaded(page, testInfo);
|
||||
test('shows process list and View button works', async ({ page }) => {
|
||||
await waitForGraphLoaded(page);
|
||||
|
||||
await page.getByRole('button', { name: 'Nexus AI' }).click();
|
||||
await page.getByText('Processes').click();
|
||||
@@ -104,7 +109,6 @@ test.describe('Processes Panel', () => {
|
||||
await expect(page.locator('[data-testid="process-list-loaded"]')).toBeVisible({
|
||||
timeout: 15_000,
|
||||
});
|
||||
await page.screenshot({ path: testInfo.outputPath('processes-panel.png'), fullPage: true });
|
||||
|
||||
const processRow = page.locator('[data-testid="process-row"]').first();
|
||||
await expect(processRow).toBeVisible({ timeout: 10_000 });
|
||||
@@ -114,14 +118,10 @@ test.describe('Processes Panel', () => {
|
||||
await viewBtn.waitFor({ state: 'visible', timeout: 5_000 });
|
||||
await viewBtn.click();
|
||||
await expect(page.locator('[data-testid="process-modal"]')).toBeVisible({ timeout: 5_000 });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath('process-view-clicked.png'),
|
||||
fullPage: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('lightbulb highlights nodes in graph', async ({ page }, testInfo) => {
|
||||
await waitForGraphLoaded(page, testInfo);
|
||||
test('lightbulb highlights nodes in graph', async ({ page }) => {
|
||||
await waitForGraphLoaded(page);
|
||||
|
||||
await page.getByRole('button', { name: 'Nexus AI' }).click();
|
||||
await page.getByText('Processes').click();
|
||||
@@ -137,13 +137,12 @@ test.describe('Processes Panel', () => {
|
||||
await lightbulb.waitFor({ state: 'visible', timeout: 5_000 });
|
||||
await lightbulb.click();
|
||||
await expect(processRow).toHaveClass(/bg-amber-950/, { timeout: 5_000 });
|
||||
await page.screenshot({ path: testInfo.outputPath('after-highlight.png'), fullPage: true });
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Turn Off All Highlights', () => {
|
||||
test('selecting a node dims others, button clears it', async ({ page }, testInfo) => {
|
||||
await waitForGraphLoaded(page, testInfo);
|
||||
test('selecting a node dims others, button clears it', async ({ page }) => {
|
||||
await waitForGraphLoaded(page);
|
||||
|
||||
await expect(page.locator('canvas').first()).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
@@ -160,6 +159,5 @@ test.describe('Turn Off All Highlights', () => {
|
||||
await expect(highlightToggle).toHaveAttribute('title', 'Turn on AI highlights', {
|
||||
timeout: 5_000,
|
||||
});
|
||||
await page.screenshot({ path: testInfo.outputPath('highlights-cleared.png'), fullPage: true });
|
||||
});
|
||||
});
|
||||
|
||||
+84
-49
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { AppStateProvider, useAppState } from './hooks/useAppState';
|
||||
import { DropZone } from './components/DropZone';
|
||||
import { LoadingOverlay } from './components/LoadingOverlay';
|
||||
@@ -36,7 +36,6 @@ const AppContent = () => {
|
||||
refreshLLMSettings,
|
||||
initializeAgent,
|
||||
startEmbeddingsWithFallback,
|
||||
embeddingStatus,
|
||||
codeReferences,
|
||||
selectedNode,
|
||||
isCodePanelOpen,
|
||||
@@ -45,17 +44,25 @@ const AppContent = () => {
|
||||
availableRepos,
|
||||
setAvailableRepos,
|
||||
switchRepo,
|
||||
setCurrentRepo,
|
||||
} = useAppState();
|
||||
|
||||
const graphCanvasRef = useRef<GraphCanvasHandle>(null);
|
||||
const [serverDisconnected, setServerDisconnected] = useState(false);
|
||||
|
||||
const handleServerConnect = useCallback(
|
||||
async (result: ConnectResult): Promise<void> => {
|
||||
// Extract project name from repoPath
|
||||
// Use the canonical repo name from the server response so all subsequent
|
||||
// backend calls (queries, search, grep, readFile) scope to this repo.
|
||||
const repoName = result.repoInfo.name;
|
||||
const repoPath = result.repoInfo.repoPath ?? result.repoInfo.path;
|
||||
const parts = (repoPath || '').split('/').filter((p) => p && !p.startsWith('.'));
|
||||
const projectName = parts[parts.length - 1] || parts[0] || 'server-project';
|
||||
// Normalize both Windows (\) and Unix (/) path separators before splitting
|
||||
const projectName =
|
||||
result.repoInfo.name ||
|
||||
(repoPath || '').replace(/\\/g, '/').split('/').filter(Boolean).pop() ||
|
||||
'server-project';
|
||||
setProjectName(projectName);
|
||||
setCurrentRepo(projectName);
|
||||
|
||||
// Build KnowledgeGraph from server data for visualization
|
||||
const graph = createKnowledgeGraph();
|
||||
@@ -67,6 +74,11 @@ const AppContent = () => {
|
||||
}
|
||||
setGraph(graph);
|
||||
|
||||
// Persist the active project in the URL for bookmarkability and F5 refresh resilience
|
||||
const urlObj = new URL(window.location.href);
|
||||
urlObj.searchParams.set('project', projectName);
|
||||
window.history.replaceState(null, '', urlObj.toString());
|
||||
|
||||
// Transition directly to exploring view
|
||||
setViewMode('exploring');
|
||||
|
||||
@@ -80,20 +92,26 @@ const AppContent = () => {
|
||||
console.warn('Failed to initialize agent:', err);
|
||||
}
|
||||
},
|
||||
[setViewMode, setGraph, setProjectName, initializeAgent, startEmbeddingsWithFallback],
|
||||
[
|
||||
setViewMode,
|
||||
setGraph,
|
||||
setProjectName,
|
||||
setCurrentRepo,
|
||||
initializeAgent,
|
||||
startEmbeddingsWithFallback,
|
||||
],
|
||||
);
|
||||
|
||||
// Auto-connect when ?server query param is present (bookmarkable shortcut)
|
||||
// Auto-connect when ?server or ?project query param is present (bookmarkable shortcut)
|
||||
const autoConnectRan = useRef(false);
|
||||
useEffect(() => {
|
||||
if (autoConnectRan.current) return;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (!params.has('server')) return;
|
||||
autoConnectRan.current = true;
|
||||
const serverUrlParam = params.get('server');
|
||||
const projectParam = params.get('project');
|
||||
|
||||
// Clean the URL so a refresh won't re-trigger
|
||||
const cleanUrl = window.location.pathname + window.location.hash;
|
||||
window.history.replaceState(null, '', cleanUrl);
|
||||
if (!serverUrlParam && !projectParam) return;
|
||||
autoConnectRan.current = true;
|
||||
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
@@ -103,36 +121,45 @@ const AppContent = () => {
|
||||
});
|
||||
setViewMode('loading');
|
||||
|
||||
const serverUrl = params.get('server') || window.location.origin;
|
||||
|
||||
const serverUrl = serverUrlParam || window.location.origin;
|
||||
const baseUrl = normalizeServerUrl(serverUrl);
|
||||
|
||||
connectToServer(serverUrl, (phase, downloaded, total) => {
|
||||
if (phase === 'validating') {
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
percent: 5,
|
||||
message: 'Connecting to server...',
|
||||
detail: 'Validating server',
|
||||
});
|
||||
} else if (phase === 'downloading') {
|
||||
const pct = total ? Math.round((downloaded / total) * 90) + 5 : 50;
|
||||
const mb = (downloaded / (1024 * 1024)).toFixed(1);
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
percent: pct,
|
||||
message: 'Downloading graph...',
|
||||
detail: `${mb} MB downloaded`,
|
||||
});
|
||||
} else if (phase === 'extracting') {
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
percent: 97,
|
||||
message: 'Processing...',
|
||||
detail: 'Extracting file contents',
|
||||
});
|
||||
}
|
||||
})
|
||||
const tryConnect = async () => {
|
||||
return await connectToServer(
|
||||
serverUrl,
|
||||
(phase, downloaded, total) => {
|
||||
if (phase === 'validating') {
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
percent: 5,
|
||||
message: 'Connecting to server...',
|
||||
detail: 'Validating server',
|
||||
});
|
||||
} else if (phase === 'downloading') {
|
||||
const pct = total ? Math.round((downloaded / total) * 90) + 5 : 50;
|
||||
const mb = (downloaded / (1024 * 1024)).toFixed(1);
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
percent: pct,
|
||||
message: 'Downloading graph...',
|
||||
detail: `${mb} MB downloaded`,
|
||||
});
|
||||
} else if (phase === 'extracting') {
|
||||
setProgress({
|
||||
phase: 'extracting',
|
||||
percent: 97,
|
||||
message: 'Processing...',
|
||||
detail: 'Extracting file contents',
|
||||
});
|
||||
}
|
||||
},
|
||||
undefined,
|
||||
projectParam || undefined,
|
||||
{ awaitAnalysis: true }, // enable backend hold-queue for repos still being analyzed
|
||||
);
|
||||
};
|
||||
|
||||
tryConnect()
|
||||
.then(async (result) => {
|
||||
await handleServerConnect(result);
|
||||
setProgress(null);
|
||||
@@ -169,21 +196,18 @@ const AppContent = () => {
|
||||
|
||||
// ── Server heartbeat: detect when server goes down while exploring ────────
|
||||
// Uses SSE (EventSource) for instant detection — no polling delay.
|
||||
// On disconnect: show a reconnecting banner instead of resetting to onboarding.
|
||||
// The heartbeat retries indefinitely with capped backoff and recovers automatically.
|
||||
useEffect(() => {
|
||||
if (viewMode !== 'exploring') return;
|
||||
|
||||
const cleanup = connectHeartbeat(
|
||||
() => {}, // onConnect — already connected, no action needed
|
||||
() => {
|
||||
// Server went down — return to onboarding
|
||||
setViewMode('onboarding');
|
||||
setGraph(null);
|
||||
setProgress(null);
|
||||
},
|
||||
() => setServerDisconnected(false),
|
||||
() => setServerDisconnected(true),
|
||||
);
|
||||
|
||||
return cleanup;
|
||||
}, [viewMode, setViewMode, setGraph, setProgress]);
|
||||
}, [viewMode]);
|
||||
|
||||
// Render based on view mode
|
||||
if (viewMode === 'onboarding') {
|
||||
@@ -196,7 +220,12 @@ const AppContent = () => {
|
||||
await handleServerConnect(result);
|
||||
setProgress(null);
|
||||
if (serverUrl) {
|
||||
setServerBaseUrl(normalizeServerUrl(serverUrl));
|
||||
const base = normalizeServerUrl(serverUrl);
|
||||
setServerBaseUrl(base);
|
||||
// Add ?server= so F5 reconnects to this server
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('server', base);
|
||||
window.history.replaceState(null, '', url.toString());
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -268,6 +297,12 @@ const AppContent = () => {
|
||||
|
||||
<StatusBar />
|
||||
|
||||
{serverDisconnected && (
|
||||
<div className="fixed bottom-12 left-1/2 z-50 -translate-x-1/2 rounded-lg border border-yellow-500/30 bg-yellow-900/80 px-4 py-2 text-sm text-yellow-200 shadow-lg backdrop-blur">
|
||||
Server connection lost — reconnecting…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Settings Panel (modal) */}
|
||||
<SettingsPanel
|
||||
isOpen={isSettingsPanelOpen}
|
||||
|
||||
@@ -54,6 +54,7 @@ export const CodeReferencesPanel = ({ onFocusNode }: CodeReferencesPanelProps) =
|
||||
clearCodeReferences,
|
||||
setSelectedNode,
|
||||
codeReferenceFocus,
|
||||
projectName,
|
||||
} = useAppState();
|
||||
|
||||
const nodeById = useMemo(() => {
|
||||
@@ -174,7 +175,7 @@ export const CodeReferencesPanel = ({ onFocusNode }: CodeReferencesPanelProps) =
|
||||
return () => {
|
||||
rafIds.forEach((id) => cancelAnimationFrame(id));
|
||||
};
|
||||
}, [codeReferenceFocus?.ts, aiReferences]);
|
||||
}, [codeReferenceFocus, aiReferences]);
|
||||
|
||||
const refsWithSnippets = useMemo(() => {
|
||||
return aiReferences.map((ref) => {
|
||||
@@ -223,13 +224,14 @@ export const CodeReferencesPanel = ({ onFocusNode }: CodeReferencesPanelProps) =
|
||||
const isWholeFile = selectedIsFile || startLine === undefined;
|
||||
|
||||
const options = isWholeFile
|
||||
? undefined
|
||||
? { repo: projectName }
|
||||
: {
|
||||
startLine: Math.max(0, startLine - CONTEXT_LINES),
|
||||
endLine: (endLine ?? startLine) + CONTEXT_LINES,
|
||||
repo: projectName,
|
||||
};
|
||||
|
||||
readFile(selectedFilePath, options)
|
||||
readFile(selectedFilePath, { ...options, repo: projectName || undefined })
|
||||
.then((result) => {
|
||||
if (!cancelled) {
|
||||
setFileResult(result);
|
||||
@@ -251,6 +253,7 @@ export const CodeReferencesPanel = ({ onFocusNode }: CodeReferencesPanelProps) =
|
||||
selectedNode?.properties?.startLine,
|
||||
selectedNode?.properties?.endLine,
|
||||
selectedIsFile,
|
||||
projectName,
|
||||
]);
|
||||
|
||||
// Scroll to the selected node's startLine after content loads
|
||||
|
||||
@@ -201,7 +201,7 @@ interface OnboardingGuideProps {
|
||||
}
|
||||
|
||||
export const OnboardingGuide = ({ isPolling }: OnboardingGuideProps) => {
|
||||
const primary = isDev ? 'cd gitnexus && npm run serve' : 'npx gitnexus@latest serve';
|
||||
const primary = isDev ? 'npm run --prefix gitnexus serve' : 'npx gitnexus@latest serve';
|
||||
const termLabel = isDev ? 'Start backend' : 'Terminal';
|
||||
|
||||
// Step states: step 1 = copy command, step 2 = run/wait, step 3 = auto-connect
|
||||
@@ -277,7 +277,9 @@ export const OnboardingGuide = ({ isPolling }: OnboardingGuideProps) => {
|
||||
state={step2State}
|
||||
number={2}
|
||||
title={isPolling ? 'Waiting for server to start' : 'Paste and run in your terminal'}
|
||||
description={isPolling ? undefined : 'Open a new terminal window, paste, and hit Enter.'}
|
||||
description={
|
||||
isPolling ? undefined : 'Open a terminal at the project root, paste, and hit Enter.'
|
||||
}
|
||||
>
|
||||
{isPolling && <PollingBar />}
|
||||
</StepRow>
|
||||
|
||||
@@ -64,7 +64,7 @@ export const StatusBar = () => {
|
||||
</a>
|
||||
|
||||
{/* Right - Stats */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-3" data-testid="graph-stats">
|
||||
{graph && (
|
||||
<>
|
||||
<span>{nodeCount} nodes</span>
|
||||
|
||||
@@ -145,6 +145,7 @@ interface AppState {
|
||||
availableRepos: BackendRepo[];
|
||||
setAvailableRepos: (repos: BackendRepo[]) => void;
|
||||
switchRepo: (repoName: string) => Promise<void>;
|
||||
setCurrentRepo: (repoName: string) => void;
|
||||
|
||||
// Worker API (shared across app)
|
||||
runQuery: (cypher: string) => Promise<any[]>;
|
||||
@@ -456,6 +457,10 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
// Backend client — direct HTTP calls (no Worker/Comlink)
|
||||
const repoRef = useRef<string | undefined>(undefined);
|
||||
|
||||
const setCurrentRepo = useCallback((repoName: string) => {
|
||||
repoRef.current = repoName;
|
||||
}, []);
|
||||
|
||||
const runQuery = useCallback(async (cypher: string): Promise<any[]> => {
|
||||
return backendRunQuery(cypher, repoRef.current);
|
||||
}, []);
|
||||
@@ -574,6 +579,13 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
|
||||
try {
|
||||
const effectiveProjectName = overrideProjectName || projectName || 'project';
|
||||
|
||||
// Sync repoRef so all agent backend calls target the correct repo.
|
||||
// initializeAgent can be called from App.tsx (handleServerConnect) which
|
||||
// never sets repoRef.current directly — without this, queries default to repo[0].
|
||||
if (overrideProjectName) {
|
||||
repoRef.current = overrideProjectName;
|
||||
}
|
||||
const repo = repoRef.current;
|
||||
|
||||
// Build backend interface for Graph RAG tools
|
||||
@@ -605,7 +617,8 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
setIsAgentInitializing(false);
|
||||
}
|
||||
},
|
||||
[projectName],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[], // repoRef is a stable ref — we sync it explicitly on entry; no state deps needed
|
||||
);
|
||||
|
||||
const sendChatMessage = useCallback(
|
||||
@@ -1037,6 +1050,9 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
setCodePanelOpen(false);
|
||||
setCodeReferenceFocus(null);
|
||||
|
||||
let connectedRepo: BackendRepo | undefined;
|
||||
let pNameStr = repoName || 'server-project';
|
||||
|
||||
try {
|
||||
const result: ConnectResult = await connectToServer(
|
||||
serverBaseUrl,
|
||||
@@ -1068,39 +1084,28 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
},
|
||||
undefined,
|
||||
repoName,
|
||||
{ awaitAnalysis: true }, // enable backend hold-queue for repos still being analyzed
|
||||
);
|
||||
|
||||
// Build graph for visualization
|
||||
const repoPath = result.repoInfo.repoPath ?? result.repoInfo.path;
|
||||
// Prefer the registry name, then normalize Windows \ and Unix / paths
|
||||
const pName =
|
||||
repoName || result.repoInfo.name || repoPath?.split('/').pop() || 'server-project';
|
||||
repoName ||
|
||||
result.repoInfo.name ||
|
||||
(repoPath || '').replace(/\\/g, '/').split('/').filter(Boolean).pop() ||
|
||||
'server-project';
|
||||
setProjectName(pName);
|
||||
repoRef.current = pName;
|
||||
|
||||
connectedRepo = result.repoInfo;
|
||||
pNameStr = pName;
|
||||
|
||||
const newGraph = createKnowledgeGraph();
|
||||
for (const node of result.nodes) newGraph.addNode(node);
|
||||
for (const rel of result.relationships) newGraph.addRelationship(rel);
|
||||
setGraph(newGraph);
|
||||
|
||||
// No fileContents needed — grep/read tools use backend HTTP
|
||||
|
||||
// Initialize agent with backend queries, then start embeddings
|
||||
try {
|
||||
if (getActiveProviderConfig()) {
|
||||
await initializeAgent(pName);
|
||||
}
|
||||
setViewMode('exploring');
|
||||
startEmbeddingsWithFallback();
|
||||
setProgress(null);
|
||||
} catch (err) {
|
||||
console.warn('Failed to initialize agent:', err);
|
||||
setIsAgentReady(false);
|
||||
agentRef.current = null;
|
||||
setAgentError('Failed to initialize agent');
|
||||
setViewMode('exploring');
|
||||
setProgress(null);
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (err: unknown) {
|
||||
console.error('Repo switch failed:', err);
|
||||
setProgress({
|
||||
phase: 'error',
|
||||
@@ -1114,6 +1119,36 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
setViewMode('exploring');
|
||||
setProgress(null);
|
||||
}, ERROR_RESET_DELAY_MS);
|
||||
return; // Abort the whole switchRepo process
|
||||
}
|
||||
|
||||
if (pNameStr) {
|
||||
// Persist the selected project in the URL so a refresh re-opens it
|
||||
const urlObj = new URL(window.location.href);
|
||||
urlObj.searchParams.set('project', pNameStr);
|
||||
window.history.replaceState(null, '', urlObj.toString());
|
||||
}
|
||||
|
||||
// Reset the agent and clear chat history so the AI starts fresh for the new repo
|
||||
agentRef.current = null;
|
||||
setIsAgentReady(false);
|
||||
setChatMessages([]);
|
||||
|
||||
// Re-initialize agent with the new repo's graph context
|
||||
try {
|
||||
if (getActiveProviderConfig()) {
|
||||
await initializeAgent(pNameStr);
|
||||
}
|
||||
setViewMode('exploring');
|
||||
startEmbeddingsWithFallback();
|
||||
setProgress(null);
|
||||
} catch (err) {
|
||||
console.warn('Failed to initialize agent:', err);
|
||||
setIsAgentReady(false);
|
||||
agentRef.current = null;
|
||||
setAgentError('Failed to initialize agent');
|
||||
setViewMode('exploring');
|
||||
setProgress(null);
|
||||
}
|
||||
},
|
||||
[
|
||||
@@ -1133,6 +1168,7 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
setCodeReferences,
|
||||
setCodePanelOpen,
|
||||
setCodeReferenceFocus,
|
||||
setChatMessages,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1219,6 +1255,7 @@ const AppStateProviderInner = ({ children }: { children: ReactNode }) => {
|
||||
availableRepos,
|
||||
setAvailableRepos,
|
||||
switchRepo,
|
||||
setCurrentRepo,
|
||||
runQuery,
|
||||
isDatabaseReady,
|
||||
// Embedding state and methods
|
||||
|
||||
@@ -222,7 +222,7 @@ export function normalizeServerUrl(input: string): string {
|
||||
|
||||
// ── Internal Helpers ───────────────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const PROBE_TIMEOUT_MS = 2_000;
|
||||
|
||||
const fetchWithTimeout = async (
|
||||
@@ -264,11 +264,13 @@ const fetchWithTimeout = async (
|
||||
const assertOk = async (response: Response): Promise<void> => {
|
||||
if (response.ok) return;
|
||||
|
||||
let message = `Backend returned ${response.status} ${response.statusText}`;
|
||||
let message = response.statusText;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body && typeof body.error === 'string') {
|
||||
message = body.error;
|
||||
} else if (body && typeof body.message === 'string') {
|
||||
message = body.message;
|
||||
}
|
||||
} catch {
|
||||
// Response body was not JSON
|
||||
@@ -302,16 +304,26 @@ export const fetchServerInfo = async (): Promise<ServerInfo> => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Connect an SSE heartbeat to the backend. Fires `onDisconnect` when the
|
||||
* server goes down (after one retry to avoid false positives from transient
|
||||
* network hiccups). Returns a cleanup function.
|
||||
* Connect an SSE heartbeat to the backend. Retries indefinitely with capped
|
||||
* exponential backoff so transient hiccups don't reset the UI.
|
||||
*
|
||||
* - `onConnect` fires on every successful (re)connection.
|
||||
* - `onReconnecting` fires on the first retry after a drop — use it to show
|
||||
* a "reconnecting" banner while keeping the current view intact.
|
||||
*
|
||||
* Returns a cleanup function that tears down the EventSource and timers.
|
||||
*/
|
||||
export const connectHeartbeat = (onConnect: () => void, onDisconnect: () => void): (() => void) => {
|
||||
export const connectHeartbeat = (
|
||||
onConnect: () => void,
|
||||
onReconnecting: () => void,
|
||||
): (() => void) => {
|
||||
let closed = false;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let es: EventSource | null = null;
|
||||
let attempt = 0;
|
||||
const MAX_RETRIES = 3;
|
||||
/** Whether we've already fired onReconnecting for the current drop. */
|
||||
let notifiedReconnecting = false;
|
||||
const MAX_BACKOFF_MS = 15_000;
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return;
|
||||
@@ -319,6 +331,7 @@ export const connectHeartbeat = (onConnect: () => void, onDisconnect: () => void
|
||||
es.onopen = () => {
|
||||
if (!closed) {
|
||||
attempt = 0;
|
||||
notifiedReconnecting = false;
|
||||
onConnect();
|
||||
}
|
||||
};
|
||||
@@ -326,13 +339,15 @@ export const connectHeartbeat = (onConnect: () => void, onDisconnect: () => void
|
||||
es?.close();
|
||||
es = null;
|
||||
if (closed) return;
|
||||
if (attempt < MAX_RETRIES) {
|
||||
const delay = 1_000 * Math.pow(2, attempt);
|
||||
attempt++;
|
||||
retryTimer = setTimeout(connect, delay);
|
||||
} else {
|
||||
onDisconnect();
|
||||
|
||||
if (!notifiedReconnecting) {
|
||||
notifiedReconnecting = true;
|
||||
onReconnecting();
|
||||
}
|
||||
|
||||
const delay = Math.min(1_000 * Math.pow(2, attempt), MAX_BACKOFF_MS);
|
||||
attempt++;
|
||||
retryTimer = setTimeout(connect, delay);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -373,10 +388,22 @@ export const fetchRepos = async (): Promise<BackendRepo[]> => {
|
||||
return response.json() as Promise<BackendRepo[]>;
|
||||
};
|
||||
|
||||
/** Fetch repo metadata. */
|
||||
export const fetchRepoInfo = async (repo?: string): Promise<BackendRepo> => {
|
||||
/** Fetch repo metadata.
|
||||
* Pass `awaitAnalysis: true` when connecting to a repo that may still be cloning/analyzing —
|
||||
* this enables the backend's hold-queue and uses a 5-minute timeout to match.
|
||||
* Normal calls (e.g. repo switching between already-indexed repos) use the default 10s timeout.
|
||||
*
|
||||
* Must stay in sync with HOLD_QUEUE_TIMEOUT_SECS in gitnexus/src/server/api.ts.
|
||||
*/
|
||||
const HOLD_QUEUE_TIMEOUT_MS = 300_000; // 5 minutes — matches backend HOLD_QUEUE_TIMEOUT_SECS
|
||||
|
||||
export const fetchRepoInfo = async (
|
||||
repo?: string,
|
||||
opts?: { awaitAnalysis?: boolean },
|
||||
): Promise<BackendRepo> => {
|
||||
const url = `${_backendUrl}/api/repo${repo ? `?${repoParam(repo)}` : ''}`;
|
||||
const response = await fetchWithTimeout(url);
|
||||
const timeout = opts?.awaitAnalysis ? HOLD_QUEUE_TIMEOUT_MS : undefined;
|
||||
const response = await fetchWithTimeout(url, {}, timeout);
|
||||
await assertOk(response);
|
||||
const data = await response.json();
|
||||
return { ...data, repoPath: data.repoPath ?? data.path };
|
||||
@@ -391,13 +418,19 @@ export const fetchGraph = async (
|
||||
onProgress?: (downloaded: number, total: number | null) => void;
|
||||
},
|
||||
): Promise<{ nodes: GraphNode[]; relationships: GraphRelationship[] }> => {
|
||||
const params = [repoParam(repo), opts?.includeContent ? 'includeContent=true' : '']
|
||||
const params = [repoParam(repo), opts?.includeContent ? 'includeContent=true' : '', 'stream=true']
|
||||
.filter(Boolean)
|
||||
.join('&');
|
||||
const url = `${_backendUrl}/api/graph${params ? `?${params}` : ''}`;
|
||||
const response = await fetchWithTimeout(url, { signal: opts?.signal }, 60_000);
|
||||
// Large repos can take a while to serialize the graph — use an elevated timeout
|
||||
const response = await fetchWithTimeout(url, { signal: opts?.signal }, 120_000);
|
||||
await assertOk(response);
|
||||
|
||||
const contentType = response.headers.get('Content-Type') || '';
|
||||
if (contentType.includes('application/x-ndjson')) {
|
||||
return parseNdjsonGraphResponse(response, opts?.onProgress);
|
||||
}
|
||||
|
||||
if (!opts?.onProgress || !response.body) {
|
||||
return response.json() as Promise<{ nodes: GraphNode[]; relationships: GraphRelationship[] }>;
|
||||
}
|
||||
@@ -426,6 +459,66 @@ export const fetchGraph = async (
|
||||
return JSON.parse(new TextDecoder().decode(combined));
|
||||
};
|
||||
|
||||
const parseNdjsonGraphResponse = async (
|
||||
response: Response,
|
||||
onProgress?: (downloaded: number, total: number | null) => void,
|
||||
): Promise<{ nodes: GraphNode[]; relationships: GraphRelationship[] }> => {
|
||||
if (!response.body) {
|
||||
throw new BackendError('No response body', response.status, 'server');
|
||||
}
|
||||
|
||||
const contentLength = response.headers.get('Content-Length');
|
||||
const total = contentLength ? parseInt(contentLength, 10) : null;
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const nodes: GraphNode[] = [];
|
||||
const relationships: GraphRelationship[] = [];
|
||||
let buffer = '';
|
||||
let downloaded = 0;
|
||||
|
||||
const parseLine = (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
|
||||
const record = JSON.parse(trimmed) as
|
||||
| { type: 'node'; data: GraphNode }
|
||||
| { type: 'relationship'; data: GraphRelationship }
|
||||
| { type: 'error'; error: string };
|
||||
|
||||
if (record.type === 'node') {
|
||||
nodes.push(record.data);
|
||||
return;
|
||||
}
|
||||
if (record.type === 'relationship') {
|
||||
relationships.push(record.data);
|
||||
return;
|
||||
}
|
||||
if (record.type === 'error') {
|
||||
throw new BackendError(record.error, response.status || 500, 'server');
|
||||
}
|
||||
};
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
downloaded += value.length;
|
||||
onProgress?.(downloaded, total);
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
for (const line of lines) {
|
||||
parseLine(line);
|
||||
}
|
||||
}
|
||||
|
||||
buffer += decoder.decode();
|
||||
parseLine(buffer);
|
||||
|
||||
return { nodes, relationships };
|
||||
};
|
||||
|
||||
/** Execute a Cypher query. Returns rows. */
|
||||
export const runQuery = async (
|
||||
cypher: string,
|
||||
@@ -657,18 +750,21 @@ export interface ConnectResult {
|
||||
/**
|
||||
* Connect to a server: validate, fetch repo info, download graph.
|
||||
* Content is NOT included (use readFile/grep for file access).
|
||||
* Pass `awaitAnalysis: true` when the repo may still be cloning/analyzing —
|
||||
* this enables the backend hold-queue and a 5-minute fetch timeout.
|
||||
*/
|
||||
export async function connectToServer(
|
||||
url: string,
|
||||
onProgress?: (phase: string, downloaded: number, total: number | null) => void,
|
||||
signal?: AbortSignal,
|
||||
repoName?: string,
|
||||
opts?: { awaitAnalysis?: boolean },
|
||||
): Promise<ConnectResult> {
|
||||
const baseUrl = normalizeServerUrl(url);
|
||||
setBackendUrl(baseUrl);
|
||||
|
||||
onProgress?.('validating', 0, null);
|
||||
const repoInfo = await fetchRepoInfo(repoName);
|
||||
const repoInfo = await fetchRepoInfo(repoName, { awaitAnalysis: opts?.awaitAnalysis });
|
||||
|
||||
onProgress?.('downloading', 0, null);
|
||||
const { nodes, relationships } = await fetchGraph(repoName, {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { connectHeartbeat } from '../../src/services/backend-client';
|
||||
|
||||
// Mock EventSource to simulate SSE behavior
|
||||
class MockEventSource {
|
||||
onopen: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
closed = false;
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
let lastEventSource: MockEventSource | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
lastEventSource = null;
|
||||
vi.stubGlobal(
|
||||
'EventSource',
|
||||
vi.fn().mockImplementation(() => {
|
||||
lastEventSource = new MockEventSource();
|
||||
return lastEventSource;
|
||||
}),
|
||||
);
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('connectHeartbeat', () => {
|
||||
it('calls onConnect when EventSource opens', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
lastEventSource!.onopen!();
|
||||
expect(onConnect).toHaveBeenCalledOnce();
|
||||
expect(onReconnecting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onReconnecting on first error, then retries', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
// Simulate connection drop
|
||||
lastEventSource!.onerror!();
|
||||
|
||||
expect(onReconnecting).toHaveBeenCalledOnce();
|
||||
expect(lastEventSource!.closed).toBe(true);
|
||||
|
||||
// Advance past first retry delay (1s)
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
// A new EventSource should have been created
|
||||
expect(EventSource).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('fires onReconnecting only once per disconnect', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
// First error
|
||||
lastEventSource!.onerror!();
|
||||
expect(onReconnecting).toHaveBeenCalledOnce();
|
||||
|
||||
// Second retry fires error again
|
||||
vi.advanceTimersByTime(1_000);
|
||||
lastEventSource!.onerror!();
|
||||
expect(onReconnecting).toHaveBeenCalledOnce(); // still 1
|
||||
|
||||
// Third retry fires error
|
||||
vi.advanceTimersByTime(2_000);
|
||||
lastEventSource!.onerror!();
|
||||
expect(onReconnecting).toHaveBeenCalledOnce(); // still 1
|
||||
});
|
||||
|
||||
it('retries indefinitely instead of giving up after 3 attempts', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
// Simulate 10 consecutive failures — should never stop retrying
|
||||
for (let i = 0; i < 10; i++) {
|
||||
lastEventSource!.onerror!();
|
||||
// Advance past the max backoff (15s) to ensure the next retry fires
|
||||
vi.advanceTimersByTime(16_000);
|
||||
}
|
||||
|
||||
// Should have created 11 EventSources (1 initial + 10 retries)
|
||||
expect(EventSource).toHaveBeenCalledTimes(11);
|
||||
});
|
||||
|
||||
it('resets reconnecting state when connection recovers', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
// Drop
|
||||
lastEventSource!.onerror!();
|
||||
expect(onReconnecting).toHaveBeenCalledOnce();
|
||||
|
||||
// Retry succeeds
|
||||
vi.advanceTimersByTime(1_000);
|
||||
lastEventSource!.onopen!();
|
||||
expect(onConnect).toHaveBeenCalledOnce();
|
||||
|
||||
// Drop again — should fire onReconnecting again (reset after recovery)
|
||||
lastEventSource!.onerror!();
|
||||
expect(onReconnecting).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('caps backoff at 15 seconds', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
// Fail many times to push backoff past the cap
|
||||
for (let i = 0; i < 6; i++) {
|
||||
lastEventSource!.onerror!();
|
||||
// The delay for attempt i is min(1000 * 2^i, 15000)
|
||||
// i=0: 1s, i=1: 2s, i=2: 4s, i=3: 8s, i=4: 15s (capped), i=5: 15s (capped)
|
||||
vi.advanceTimersByTime(16_000);
|
||||
}
|
||||
|
||||
// All retries should have fired — 7 EventSources total
|
||||
expect(EventSource).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it('stops retrying when cleanup is called', () => {
|
||||
const onConnect = vi.fn();
|
||||
const onReconnecting = vi.fn();
|
||||
const cleanup = connectHeartbeat(onConnect, onReconnecting);
|
||||
|
||||
lastEventSource!.onerror!();
|
||||
cleanup();
|
||||
|
||||
// Advance time — no new EventSource should be created
|
||||
vi.advanceTimersByTime(30_000);
|
||||
expect(EventSource).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { normalizeServerUrl } from '../../src/services/backend-client';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fetchGraph, normalizeServerUrl, setBackendUrl } from '../../src/services/backend-client';
|
||||
|
||||
describe('normalizeServerUrl', () => {
|
||||
it('adds http:// to localhost', () => {
|
||||
@@ -31,3 +31,137 @@ describe('normalizeServerUrl', () => {
|
||||
expect(normalizeServerUrl('https://gitnexus.example.com')).toBe('https://gitnexus.example.com');
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('fetchGraph', () => {
|
||||
it('requests streamed graph responses from the backend', async () => {
|
||||
setBackendUrl('http://localhost:4747');
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response('{"nodes":[],"relationships":[]}', {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await fetchGraph('big-repo');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/api/graph?repo=big-repo&stream=true'),
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it('parses NDJSON graph streams incrementally', async () => {
|
||||
setBackendUrl('http://localhost:4747');
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
[
|
||||
'{"type":"node","data":{"id":"File:src/app.ts","label":"File","properties":{"name":"app.ts","filePath":"src/app.ts"}}}\n',
|
||||
'{"type":"relationship","data":{"id":"File:src/app.ts_CONTAINS_Function:src/app.ts:main","type":"CONTAINS","sourceId":"File:src/app.ts","targetId":"Function:src/app.ts:main"}}\n',
|
||||
].join(''),
|
||||
),
|
||||
);
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(stream, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-ndjson',
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const progress = vi.fn();
|
||||
const result = await fetchGraph('big-repo', { onProgress: progress });
|
||||
|
||||
expect(result.nodes).toHaveLength(1);
|
||||
expect(result.relationships).toHaveLength(1);
|
||||
expect(result.nodes[0].id).toBe('File:src/app.ts');
|
||||
expect(result.relationships[0].type).toBe('CONTAINS');
|
||||
expect(progress).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('parses NDJSON graph lines split across chunks', async () => {
|
||||
setBackendUrl('http://localhost:4747');
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
'{"type":"node","data":{"id":"File:src/app.ts","label":"File","properties":{"name":"app.ts"',
|
||||
),
|
||||
);
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
',"filePath":"src/app.ts"}}}\n{"type":"relationship","data":{"id":"File:src/app.ts_CONTAINS_Function:src/app.ts:main","type":"CONTAINS","sourceId":"File:src/app.ts","targetId":"Function:src/app.ts:main"}}\n',
|
||||
),
|
||||
);
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(stream, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-ndjson',
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await fetchGraph('big-repo');
|
||||
|
||||
expect(result.nodes).toHaveLength(1);
|
||||
expect(result.relationships).toHaveLength(1);
|
||||
expect(result.nodes[0].properties.filePath).toBe('src/app.ts');
|
||||
});
|
||||
|
||||
it('throws backend errors emitted in the NDJSON stream', async () => {
|
||||
setBackendUrl('http://localhost:4747');
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode('{"type":"error","error":"stream failed"}\n'));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(stream, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-ndjson',
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(fetchGraph('big-repo')).rejects.toMatchObject({
|
||||
message: 'stream failed',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,104 @@
|
||||
|
||||
All notable changes to GitNexus will be documented in this file.
|
||||
|
||||
## [1.6.0] - 2026-04-12
|
||||
|
||||
### Added
|
||||
- **SemanticModel architecture refactor (SM-8 through SM-19)** — extracted registries into `model/` module with ISP-compliant interfaces: TypeRegistry, MethodRegistry, FieldRegistry, RegistrationTable, ResolutionContext (#786)
|
||||
- HeritageMap built from accumulated `ExtractedHeritage[]` for MRO-aware resolution (#739)
|
||||
- `lookupMethodByOwnerWithMRO` using HeritageMap for cross-class method dispatch (#740)
|
||||
- MRO fast path before D2 fuzzy widening in call resolution (#741)
|
||||
- BindingAccumulator for cross-file return type propagation (#743, #763)
|
||||
- Restructured `resolveUncached` replacing `lookupFuzzy` data source for all tiers (#764)
|
||||
- Deleted `lookupFuzzy`, `lookupFuzzyCallable`, `globalIndex`, `callableIndex` — replaced with structured lookups (#769)
|
||||
- Deleted `resolveCallTarget` god-method — replaced with thin dispatcher delegating to `resolveMemberCall` (#744), `resolveStaticCall` (#754), `resolveFreeCall` (#756) (#770)
|
||||
- **Service group infrastructure** — service boundary detection, contract extractors, sync pipeline, CLI/MCP tools, monorepo fixture; bridge.lbug storage and contract matching expansion (#795)
|
||||
- **C# interface-to-interface heritage** capture (#789)
|
||||
- **Vue SFC support** with destructured call result tracking (#604)
|
||||
- **Java method reference** resolution — `obj::method` as call sites (#622)
|
||||
- **C/C++ MethodExtractor** config with pure virtual detection (#617)
|
||||
- **MethodExtractor configs** for Python, PHP, Swift, Dart, Rust, Ruby (#624)
|
||||
- **METHOD_IMPLEMENTS edges** with overload disambiguation and MethodExtractor unification (#642)
|
||||
- **Same-arity overload disambiguation** via type-hash suffix (#658)
|
||||
- **`GITNEXUS_HOME` env var** to customize global directory (#746)
|
||||
- **Verbose analyze output** prints skipped large file paths (#745)
|
||||
- **Class name lookup index** for O(1) qualified lookups (#707, #716)
|
||||
- **`lookupMethodByOwner` index** for O(1) cross-class chain resolution (#665)
|
||||
- **Fuzzy lookup counters** for performance visibility (#708)
|
||||
|
||||
### Fixed
|
||||
- **Stack overflow on large PHP files** — iterative AST traversal (#783)
|
||||
- **Large repository graph loading** failure (#732)
|
||||
- **Windows multi-repo switching** — false 404 errors and stale repo context (#633)
|
||||
- **`detect_changes` diff mapping** — map diff hunks to symbol line ranges (#779)
|
||||
- **HTTP client vs Express route detection** and Spring interface attribution (#780)
|
||||
- **VECTOR extension** not loaded during DB init for semantic search (#782)
|
||||
- **tree-sitter-swift** postinstall patch for macOS ARM64 (#788)
|
||||
- **tree-sitter-c** peer dependency conflict pinned (#723)
|
||||
- **Constructor indexing** in methodByOwner (#694, #753)
|
||||
- **Named binding processor** — `lookupExact` replaced with `lookupExactAll` (#755)
|
||||
- **`.gitnexusignore` negation patterns** now respected (#654)
|
||||
- **MCP setup** prefers global gitnexus binary over npx (#653)
|
||||
- **CORS rejection** returns clean error instead of 500 (#646)
|
||||
- **Array.push stack overflow** — replaced spread with loop (#650)
|
||||
- **MCP stdout silencing** prevents embedder/pool-adapter conflicts (#645)
|
||||
- **Web heartbeat** — graceful reconnection replaces aggressive disconnect (#643)
|
||||
- **Web repo scoping** — backend calls scoped to active repo (#644)
|
||||
- **OpenCode config path** and FTS extension load order (#781)
|
||||
- **OnboardingGuide** dev-mode serve command corrected (#725)
|
||||
- **Security issues** and critical bugs from code review (#709)
|
||||
|
||||
### Changed
|
||||
- Replaced class-type fuzzy lookups with structured indices in type-env (#733, #734, #736)
|
||||
- Extracted `CLASS_LIKE_TYPES` constant (#693)
|
||||
|
||||
## [1.5.3] - 2026-04-01
|
||||
|
||||
### Added
|
||||
- **TypeScript/JavaScript MethodExtractor** config (#588)
|
||||
|
||||
### Fixed
|
||||
- **Wiki Azure OpenAI** compat and HTML viewer script injection (#618)
|
||||
|
||||
## [1.5.2] - 2026-04-01
|
||||
|
||||
### Fixed
|
||||
- **`gitnexus-shared` module not found** — `gitnexus-shared` was a `file:` workspace dependency never published to npm, causing `ERR_MODULE_NOT_FOUND` when installing `gitnexus` globally. The build now bundles shared code into `dist/_shared/` and rewrites imports to relative paths (#613)
|
||||
- **v1.5.1 publish regression** — npm's `prepare` lifecycle ran `tsc` after `prepack`, overwriting the rewritten imports before packing; both scripts now run the full build so the final tarball is always correct
|
||||
|
||||
## [1.5.1] - 2026-04-01 [YANKED]
|
||||
|
||||
### Fixed
|
||||
- Incomplete fix for `gitnexus-shared` bundling — `prepare` script overwrote rewritten imports during publish
|
||||
|
||||
## [1.5.0] - 2026-04-01
|
||||
|
||||
### Added
|
||||
- **Repo landing screen** — when the backend detects indexed repositories, the web UI now shows a landing page with selectable repo cards (name, stats, indexed date) instead of auto-loading the first repo; users can also analyze new repos directly from the landing screen (#607)
|
||||
- **Unified web & CLI ingestion pipeline** — complete architectural migration of the web app from a self-contained WASM browser app to a thin client backed by the CLI server; new `gitnexus-shared` package for cross-package type unification (#536)
|
||||
- New server endpoints: `/api/heartbeat` (SSE liveness), `/api/info`, `/api/repos`, `/api/file`, `/api/grep`, `/api/analyze` (SSE progress), `/api/embed`, `/api/mcp` (MCP-over-StreamableHTTP)
|
||||
- Onboarding flow: auto-detect server → connect → repo landing or analyze
|
||||
- Header repo dropdown: switch, re-analyze, or delete repos
|
||||
- **Azure OpenAI support for wiki command** — fixed broken Azure auth (`api-key` header), `api-version` URL parameter, reasoning model handling (`max_completion_tokens`, no `temperature`), content filter error messages; added interactive setup wizard, `--api-version` and `--reasoning-model` CLI flags (#562)
|
||||
- **Java method references & interface dispatch** — `obj::method` treated as call sites, overload selection via typed variable args (not just literals), interface dispatch emits additional CALLS edges to implementing classes (#540)
|
||||
- **MethodExtractor abstraction** — structured method metadata extraction (isAbstract, isFinal, annotations, visibility, parameter types) with config-driven factory pattern (#576)
|
||||
- Java and Kotlin configs with overload-safe `methodInfoCache` keyed by `name:line`
|
||||
- C# config with `sealed`, `params`/`out`/`ref`/optional parameters, `[Attribute]` syntax, `internal` visibility (#582)
|
||||
- **`--skip-agents-md` CLI flag** — opt out of overwriting GitNexus-managed sections in AGENTS.md and CLAUDE.md during `gitnexus analyze` (#517)
|
||||
- **Prettier** — monorepo-wide code formatter with lint-staged + Husky pre-commit hook, `.prettierrc` config, Tailwind CSS v4 plugin, `endOfLine: "lf"` + `.gitattributes` for Windows consistency (#563)
|
||||
- **ESLint v9** — flat config with `unused-imports` auto-removal, `@typescript-eslint` rules, React hooks rules, CI `lint` job (#564)
|
||||
|
||||
### Fixed
|
||||
- **OpenCode MCP configuration** — corrected README MCP setup for OpenCode which requires `command` as an array containing both executable and arguments (#363)
|
||||
- **litellm security** — excluded vulnerable versions 1.82.7 and 1.82.8 in eval harness `pyproject.toml` (#580)
|
||||
|
||||
### Changed
|
||||
- **Reduced explicit `any` types** — 128 `no-explicit-any` warnings eliminated (689 → 561, 19% reduction) across `NodeProperties` index signature, ~80 `SyntaxNode` substitutions, typed worker protocol, and graphology community detection (#566)
|
||||
|
||||
### Docs
|
||||
- Added `gitnexus-shared` build step to web UI quick start instructions (#585)
|
||||
- Added enterprise offering section to README (#579)
|
||||
|
||||
## [1.4.10] - 2026-03-27
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -164,6 +164,16 @@ gitnexus clean # Delete index for current repo
|
||||
gitnexus clean --all --force # Delete all indexes
|
||||
gitnexus wiki [path] # Generate LLM-powered docs from knowledge graph
|
||||
gitnexus wiki --model <model> # Wiki with custom LLM model (default: gpt-4o-mini)
|
||||
|
||||
# Repository groups (multi-repo / monorepo service tracking)
|
||||
gitnexus group create <name> # Create a repository group
|
||||
gitnexus group add <name> <repo> # Add a repo to a group
|
||||
gitnexus group remove <name> <repo> # Remove a repo from a group
|
||||
gitnexus group list [name] # List groups, or show one group's config
|
||||
gitnexus group sync <name> # Extract contracts and match across repos/services
|
||||
gitnexus group contracts <name> # Inspect extracted contracts and cross-links
|
||||
gitnexus group query <name> <q> # Search execution flows across all repos in a group
|
||||
gitnexus group status <name> # Check staleness of repos in a group
|
||||
```
|
||||
|
||||
## Remote Embeddings
|
||||
|
||||
Generated
+40
-2
@@ -1,17 +1,19 @@
|
||||
{
|
||||
"name": "gitnexus",
|
||||
"version": "1.4.10",
|
||||
"version": "1.6.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gitnexus",
|
||||
"version": "1.4.10",
|
||||
"version": "1.6.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "PolyForm-Noncommercial-1.0.0",
|
||||
"dependencies": {
|
||||
"@huggingface/transformers": "^3.0.0",
|
||||
"@ladybugdb/core": "^0.15.2",
|
||||
"@modelcontextprotocol/sdk": "^1.0.0",
|
||||
"@scarf/scarf": "^1.4.0",
|
||||
"cli-progress": "^3.12.0",
|
||||
"commander": "^12.0.0",
|
||||
"cors": "^2.8.5",
|
||||
@@ -22,6 +24,7 @@
|
||||
"graphology-indices": "^0.17.0",
|
||||
"graphology-utils": "^2.3.0",
|
||||
"ignore": "^7.0.5",
|
||||
"js-yaml": "^4.1.1",
|
||||
"lru-cache": "^11.0.0",
|
||||
"mnemonist": "^0.39.0",
|
||||
"onnxruntime-node": "^1.24.0",
|
||||
@@ -47,9 +50,11 @@
|
||||
"@types/cli-progress": "^3.11.6",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.0.0",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
"gitnexus-shared": "file:../gitnexus-shared",
|
||||
"tsx": "^4.0.0",
|
||||
"typescript": "^5.4.5",
|
||||
"vitest": "^4.0.18"
|
||||
@@ -65,6 +70,7 @@
|
||||
},
|
||||
"../gitnexus-shared": {
|
||||
"version": "1.0.0",
|
||||
"dev": true,
|
||||
"devDependencies": {
|
||||
"typescript": "^6.0.2"
|
||||
}
|
||||
@@ -1875,6 +1881,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@scarf/scarf": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",
|
||||
"integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@standard-schema/spec": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
@@ -1992,6 +2005,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/js-yaml": {
|
||||
"version": "4.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",
|
||||
"integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/mime": {
|
||||
"version": "1.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",
|
||||
@@ -2285,6 +2305,12 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/array-flatten": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
@@ -3566,6 +3592,18 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"js-yaml": "bin/js-yaml.js"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
|
||||
+12
-6
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gitnexus",
|
||||
"version": "1.5.0",
|
||||
"version": "1.6.0",
|
||||
"description": "Graph-powered code intelligence for AI agents. Index any codebase, query via MCP or CLI.",
|
||||
"author": "Abhigyan Patwari",
|
||||
"license": "PolyForm-Noncommercial-1.0.0",
|
||||
@@ -38,7 +38,7 @@
|
||||
"vendor"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"build": "node scripts/build.js",
|
||||
"serve": "tsx src/cli/index.ts serve",
|
||||
"dev": "tsx watch src/cli/index.ts",
|
||||
"test": "vitest run",
|
||||
@@ -46,23 +46,26 @@
|
||||
"test:integration": "vitest run test/integration",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"prepare": "npm run build",
|
||||
"prepack": "npm run build && chmod +x dist/cli/index.js"
|
||||
"postinstall": "node scripts/patch-tree-sitter-swift.cjs",
|
||||
"prepare": "node scripts/build.js",
|
||||
"prepack": "node scripts/build.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"gitnexus-shared": "file:../gitnexus-shared",
|
||||
"@huggingface/transformers": "^3.0.0",
|
||||
"@ladybugdb/core": "^0.15.2",
|
||||
"@modelcontextprotocol/sdk": "^1.0.0",
|
||||
"@scarf/scarf": "^1.4.0",
|
||||
"cli-progress": "^3.12.0",
|
||||
"commander": "^12.0.0",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.19.2",
|
||||
"gitnexus-shared": "file:../gitnexus-shared",
|
||||
"glob": "^11.0.0",
|
||||
"graphology": "^0.25.4",
|
||||
"graphology-indices": "^0.17.0",
|
||||
"graphology-utils": "^2.3.0",
|
||||
"ignore": "^7.0.5",
|
||||
"js-yaml": "^4.1.1",
|
||||
"lru-cache": "^11.0.0",
|
||||
"mnemonist": "^0.39.0",
|
||||
"onnxruntime-node": "^1.24.0",
|
||||
@@ -87,9 +90,11 @@
|
||||
"tree-sitter-swift": "^0.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"gitnexus-shared": "file:../gitnexus-shared",
|
||||
"@types/cli-progress": "^3.11.6",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.0.0",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
@@ -100,7 +105,8 @@
|
||||
"overrides": {
|
||||
"@huggingface/transformers": {
|
||||
"onnxruntime-node": "$onnxruntime-node"
|
||||
}
|
||||
},
|
||||
"tree-sitter-c": "0.23.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Build script that compiles gitnexus and inlines gitnexus-shared into the dist.
|
||||
*
|
||||
* Steps:
|
||||
* 1. Build gitnexus-shared (tsc)
|
||||
* 2. Build gitnexus (tsc)
|
||||
* 3. Copy gitnexus-shared/dist → dist/_shared
|
||||
* 4. Rewrite bare 'gitnexus-shared' specifiers → relative paths
|
||||
*/
|
||||
import { execSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const SHARED_ROOT = path.resolve(ROOT, '..', 'gitnexus-shared');
|
||||
const DIST = path.join(ROOT, 'dist');
|
||||
const SHARED_DEST = path.join(DIST, '_shared');
|
||||
|
||||
// ── 1. Build gitnexus-shared ───────────────────────────────────────
|
||||
console.log('[build] compiling gitnexus-shared…');
|
||||
execSync('npx tsc', { cwd: SHARED_ROOT, stdio: 'inherit' });
|
||||
|
||||
// ── 2. Build gitnexus ──────────────────────────────────────────────
|
||||
console.log('[build] compiling gitnexus…');
|
||||
execSync('npx tsc', { cwd: ROOT, stdio: 'inherit' });
|
||||
|
||||
// ── 3. Copy shared dist ────────────────────────────────────────────
|
||||
console.log('[build] copying shared module into dist/_shared…');
|
||||
fs.cpSync(path.join(SHARED_ROOT, 'dist'), SHARED_DEST, { recursive: true });
|
||||
|
||||
// ── 4. Rewrite imports ─────────────────────────────────────────────
|
||||
console.log('[build] rewriting gitnexus-shared imports…');
|
||||
let rewritten = 0;
|
||||
|
||||
function rewriteFile(filePath) {
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
if (!content.includes('gitnexus-shared')) return;
|
||||
|
||||
const relDir = path.relative(path.dirname(filePath), SHARED_DEST);
|
||||
// Always use posix separators and point to the package index
|
||||
const relImport = relDir.split(path.sep).join('/') + '/index.js';
|
||||
|
||||
const updated = content
|
||||
.replace(/from\s+['"]gitnexus-shared['"]/g, `from '${relImport}'`)
|
||||
.replace(/import\(\s*['"]gitnexus-shared['"]\s*\)/g, `import('${relImport}')`);
|
||||
|
||||
if (updated !== content) {
|
||||
fs.writeFileSync(filePath, updated);
|
||||
rewritten++;
|
||||
}
|
||||
}
|
||||
|
||||
function walk(dir, extensions, cb) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
walk(full, extensions, cb);
|
||||
} else if (extensions.some((ext) => entry.name.endsWith(ext))) {
|
||||
cb(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(DIST, ['.js', '.d.ts'], rewriteFile);
|
||||
|
||||
// ── 5. Make CLI entry executable ────────────────────────────────────
|
||||
const cliEntry = path.join(DIST, 'cli', 'index.js');
|
||||
if (fs.existsSync(cliEntry)) fs.chmodSync(cliEntry, 0o755);
|
||||
|
||||
console.log(`[build] done — rewrote ${rewritten} files.`);
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* WORKAROUND: tree-sitter-swift@0.6.0 binding.gyp build failure
|
||||
*
|
||||
* Background:
|
||||
* tree-sitter-swift@0.6.0's binding.gyp contains an "actions" array that
|
||||
* invokes `tree-sitter generate` to regenerate parser.c from grammar.js.
|
||||
* This is intended for grammar developers, but the published npm package
|
||||
* already ships pre-generated parser files (parser.c, scanner.c), so the
|
||||
* actions are unnecessary for consumers. Since consumers don't have
|
||||
* tree-sitter-cli installed, the actions always fail during `npm install`.
|
||||
*
|
||||
* Why we can't just upgrade:
|
||||
* tree-sitter-swift@0.7.1 fixes this (removes postinstall, ships prebuilds),
|
||||
* but it requires tree-sitter@^0.22.1. The upstream project pins tree-sitter
|
||||
* to ^0.21.0 and all other grammar packages depend on that version.
|
||||
* Upgrading tree-sitter would be a separate breaking change.
|
||||
*
|
||||
* How this workaround works:
|
||||
* 1. tree-sitter-swift's own postinstall fails (npm warns but continues)
|
||||
* 2. This script runs as gitnexus's postinstall
|
||||
* 3. It removes the "actions" array from binding.gyp
|
||||
* 4. It rebuilds the native binding with the cleaned binding.gyp
|
||||
*
|
||||
* TODO: Remove this script when tree-sitter is upgraded to ^0.22.x,
|
||||
* which allows using tree-sitter-swift@0.7.1+ directly.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
const swiftDir = path.join(__dirname, '..', 'node_modules', 'tree-sitter-swift');
|
||||
const bindingPath = path.join(swiftDir, 'binding.gyp');
|
||||
|
||||
try {
|
||||
if (!fs.existsSync(bindingPath)) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(bindingPath, 'utf8');
|
||||
let needsRebuild = false;
|
||||
|
||||
if (content.includes('"actions"')) {
|
||||
// Strip Python-style comments (#) and trailing commas before JSON parsing
|
||||
const cleaned = content
|
||||
.replace(/#[^\n]*/g, '') // Remove # comments
|
||||
.replace(/,(\s*[\]}])/g, '$1'); // Remove trailing commas before ] or }
|
||||
const gyp = JSON.parse(cleaned);
|
||||
|
||||
if (gyp.targets && gyp.targets[0] && gyp.targets[0].actions) {
|
||||
delete gyp.targets[0].actions;
|
||||
fs.writeFileSync(bindingPath, JSON.stringify(gyp, null, 2) + '\n');
|
||||
console.log('[tree-sitter-swift] Patched binding.gyp (removed actions array)');
|
||||
needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if native binding exists
|
||||
const bindingNode = path.join(swiftDir, 'build', 'Release', 'tree_sitter_swift_binding.node');
|
||||
if (!fs.existsSync(bindingNode)) {
|
||||
needsRebuild = true;
|
||||
}
|
||||
|
||||
if (needsRebuild) {
|
||||
console.log('[tree-sitter-swift] Rebuilding native binding...');
|
||||
execSync('npx node-gyp rebuild', {
|
||||
cwd: swiftDir,
|
||||
stdio: 'pipe',
|
||||
timeout: 120000,
|
||||
});
|
||||
console.log('[tree-sitter-swift] Native binding built successfully');
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[tree-sitter-swift] Could not build native binding:', err.message);
|
||||
console.warn(
|
||||
'[tree-sitter-swift] You may need to manually run: cd node_modules/tree-sitter-swift && npx node-gyp rebuild',
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ interface RepoStats {
|
||||
|
||||
export interface AIContextOptions {
|
||||
skipAgentsMd?: boolean;
|
||||
noStats?: boolean;
|
||||
}
|
||||
|
||||
const GITNEXUS_START_MARKER = '<!-- gitnexus:start -->';
|
||||
@@ -42,10 +43,29 @@ const GITNEXUS_END_MARKER = '<!-- gitnexus:end -->';
|
||||
* - Exact tool commands with parameters — vague directives get ignored
|
||||
* - Self-review checklist — forces model to verify its own work
|
||||
*/
|
||||
async function findGroupsContainingRegistryName(registryName: string): Promise<string[]> {
|
||||
const { listGroups, getDefaultGitnexusDir, getGroupDir } =
|
||||
await import('../core/group/storage.js');
|
||||
const { loadGroupConfig } = await import('../core/group/config-parser.js');
|
||||
const names = await listGroups();
|
||||
const hits: string[] = [];
|
||||
for (const g of names) {
|
||||
try {
|
||||
const config = await loadGroupConfig(getGroupDir(getDefaultGitnexusDir(), g));
|
||||
if (Object.values(config.repos).some((r) => r === registryName)) hits.push(config.name);
|
||||
} catch {
|
||||
// skip invalid or unreadable groups
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
function generateGitNexusContent(
|
||||
projectName: string,
|
||||
stats: RepoStats,
|
||||
generatedSkills?: GeneratedSkillInfo[],
|
||||
groupNames?: string[],
|
||||
noStats?: boolean,
|
||||
): string {
|
||||
const generatedRows =
|
||||
generatedSkills && generatedSkills.length > 0
|
||||
@@ -69,7 +89,7 @@ function generateGitNexusContent(
|
||||
return `${GITNEXUS_START_MARKER}
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **${projectName}** (${stats.nodes || 0} symbols, ${stats.edges || 0} relationships, ${stats.processes || 0} execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **${projectName}**${noStats ? '' : ` (${stats.nodes || 0} symbols, ${stats.edges || 0} relationships, ${stats.processes || 0} execution flows)`}. Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> If any GitNexus tool warns the index is stale, run \`npx gitnexus analyze\` in terminal first.
|
||||
|
||||
@@ -155,7 +175,15 @@ To check whether embeddings exist, inspect \`.gitnexus/meta.json\` — the \`sta
|
||||
|
||||
> Claude Code users: A PostToolUse hook handles this automatically after \`git commit\` and \`git merge\`.
|
||||
|
||||
## CLI
|
||||
${
|
||||
groupNames && groupNames.length > 0
|
||||
? `## Cross-Repo Groups
|
||||
|
||||
This repository is listed under GitNexus **group(s): ${groupNames.join(', ')}** (see \`~/.gitnexus/groups/\`). For blast radius across repository boundaries, use MCP tools \`group_impact\`, \`group_sync\`, \`group_query\`, \`group_contracts\`, \`group_status\`, and \`group_list\`. From the terminal: \`npx gitnexus group list\`, \`npx gitnexus group sync <name>\`, \`npx gitnexus group impact <name> --target <symbol> --repo <group-path>\`.
|
||||
|
||||
`
|
||||
: ''
|
||||
}## CLI
|
||||
|
||||
${skillsTable}
|
||||
|
||||
@@ -305,7 +333,14 @@ export async function generateAIContextFiles(
|
||||
generatedSkills?: GeneratedSkillInfo[],
|
||||
options?: AIContextOptions,
|
||||
): Promise<{ files: string[] }> {
|
||||
const content = generateGitNexusContent(projectName, stats, generatedSkills);
|
||||
const groupNames = await findGroupsContainingRegistryName(projectName);
|
||||
const content = generateGitNexusContent(
|
||||
projectName,
|
||||
stats,
|
||||
generatedSkills,
|
||||
groupNames,
|
||||
options?.noStats,
|
||||
);
|
||||
const createdFiles: string[] = [];
|
||||
|
||||
if (!options?.skipAgentsMd) {
|
||||
|
||||
@@ -47,6 +47,8 @@ export interface AnalyzeOptions {
|
||||
verbose?: boolean;
|
||||
/** Skip AGENTS.md and CLAUDE.md gitnexus block updates. */
|
||||
skipAgentsMd?: boolean;
|
||||
/** Omit volatile symbol/relationship counts from AGENTS.md and CLAUDE.md. */
|
||||
noStats?: boolean;
|
||||
/** Index the folder even when no .git directory is present. */
|
||||
skipGit?: boolean;
|
||||
}
|
||||
@@ -177,6 +179,7 @@ export const analyzeCommand = async (inputPath?: string, options?: AnalyzeOption
|
||||
embeddings: options?.embeddings,
|
||||
skipGit: options?.skipGit,
|
||||
skipAgentsMd: options?.skipAgentsMd,
|
||||
noStats: options?.noStats,
|
||||
},
|
||||
{
|
||||
onProgress: (_phase, percent, message) => {
|
||||
@@ -240,7 +243,7 @@ export const analyzeCommand = async (inputPath?: string, options?: AnalyzeOption
|
||||
processes: s.processes,
|
||||
},
|
||||
skillResult.skills,
|
||||
{ skipAgentsMd: options?.skipAgentsMd },
|
||||
{ skipAgentsMd: options?.skipAgentsMd, noStats: options?.noStats },
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
// gitnexus/src/cli/group.ts
|
||||
import { createRequire } from 'node:module';
|
||||
import type { Command } from 'commander';
|
||||
|
||||
const _require = createRequire(import.meta.url);
|
||||
const yaml = _require('js-yaml') as typeof import('js-yaml');
|
||||
|
||||
export function registerGroupCommands(program: Command): void {
|
||||
const group = program
|
||||
.command('group')
|
||||
.description('Manage repository groups for cross-index impact analysis');
|
||||
|
||||
group
|
||||
.command('create <name>')
|
||||
.description('Create a new group with template group.yaml')
|
||||
.option('--force', 'Overwrite existing group')
|
||||
.action(async (name: string, opts: { force?: boolean }) => {
|
||||
const { createGroupDir, getDefaultGitnexusDir } = await import('../core/group/storage.js');
|
||||
const dir = await createGroupDir(getDefaultGitnexusDir(), name, opts.force);
|
||||
console.log(`Created group "${name}" at ${dir}`);
|
||||
console.log('Edit group.yaml to add repos, then run: gitnexus group sync ' + name);
|
||||
});
|
||||
|
||||
group
|
||||
.command('add <group> <groupPath> <registryName>')
|
||||
.description(
|
||||
'Add a repo to a group. <groupPath> = hierarchy path (e.g. hr/hiring/backend), <registryName> = name from registry',
|
||||
)
|
||||
.action(async (groupName: string, groupPath: string, registryName: string) => {
|
||||
const { getGroupDir, getDefaultGitnexusDir } = await import('../core/group/storage.js');
|
||||
const { loadGroupConfig } = await import('../core/group/config-parser.js');
|
||||
const path = await import('node:path');
|
||||
const fs = await import('node:fs/promises');
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), groupName);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
config.repos[groupPath] = registryName;
|
||||
|
||||
await fs.writeFile(path.join(groupDir, 'group.yaml'), yaml.dump(config), 'utf-8');
|
||||
console.log(`Added ${registryName} as "${groupPath}" to group "${groupName}"`);
|
||||
console.log(`Run: gitnexus group sync ${groupName}`);
|
||||
});
|
||||
|
||||
group
|
||||
.command('remove <group> <path>')
|
||||
.description('Remove a repo from a group')
|
||||
.action(async (groupName: string, repoPath: string) => {
|
||||
const { getGroupDir, getDefaultGitnexusDir } = await import('../core/group/storage.js');
|
||||
const { loadGroupConfig } = await import('../core/group/config-parser.js');
|
||||
const path = await import('node:path');
|
||||
const fs = await import('node:fs/promises');
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), groupName);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
if (!(repoPath in config.repos)) {
|
||||
console.error(`Repo path "${repoPath}" not found in group "${groupName}"`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
delete config.repos[repoPath];
|
||||
await fs.writeFile(path.join(groupDir, 'group.yaml'), yaml.dump(config), 'utf-8');
|
||||
console.log(`Removed "${repoPath}" from group "${groupName}"`);
|
||||
});
|
||||
|
||||
group
|
||||
.command('list [name]')
|
||||
.description('List all groups or details of one')
|
||||
.action(async (name?: string) => {
|
||||
const { listGroups, getDefaultGitnexusDir, getGroupDir } =
|
||||
await import('../core/group/storage.js');
|
||||
if (!name) {
|
||||
const groups = await listGroups();
|
||||
if (groups.length === 0) {
|
||||
console.log('No groups configured. Create one with: gitnexus group create <name>');
|
||||
return;
|
||||
}
|
||||
console.log('Groups:');
|
||||
groups.forEach((g) => console.log(` ${g}`));
|
||||
return;
|
||||
}
|
||||
const { loadGroupConfig } = await import('../core/group/config-parser.js');
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
console.log(`Group: ${config.name}`);
|
||||
if (config.description) console.log(`Description: ${config.description}`);
|
||||
console.log(`\nRepos (${Object.keys(config.repos).length}):`);
|
||||
for (const [p, id] of Object.entries(config.repos)) {
|
||||
console.log(` ${p} -> ${id}`);
|
||||
}
|
||||
if (config.links.length > 0) {
|
||||
console.log(`\nManifest links (${config.links.length}):`);
|
||||
for (const link of config.links) {
|
||||
console.log(` ${link.from} -> ${link.to} [${link.type}: ${link.contract}]`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
group
|
||||
.command('status <name>')
|
||||
.description('Check staleness of group and repos')
|
||||
.action(async (name: string) => {
|
||||
const { readContractRegistry, getGroupDir, getDefaultGitnexusDir } =
|
||||
await import('../core/group/storage.js');
|
||||
const { LocalBackend } = await import('../mcp/local/local-backend.js');
|
||||
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const registry = await readContractRegistry(groupDir);
|
||||
|
||||
console.log(
|
||||
`Group: ${name}${registry ? ` (last sync: ${registry.generatedAt})` : ' (never synced)'}\n`,
|
||||
);
|
||||
|
||||
const backend = new LocalBackend();
|
||||
try {
|
||||
await backend.init();
|
||||
const raw = await backend.getGroupService().groupStatus({ name });
|
||||
const st = raw as {
|
||||
repos?: Record<
|
||||
string,
|
||||
{
|
||||
indexStale: boolean;
|
||||
contractsStale: boolean;
|
||||
missing: boolean;
|
||||
commitsBehind?: number;
|
||||
}
|
||||
>;
|
||||
missingRepos?: string[];
|
||||
};
|
||||
|
||||
console.log(' Repo index / contracts staleness:');
|
||||
for (const [repoPath, row] of Object.entries(st.repos || {})) {
|
||||
if (row.missing) {
|
||||
console.log(` ${repoPath.padEnd(25)} MISSING (not in registry or unreadable)`);
|
||||
continue;
|
||||
}
|
||||
const idx = row.indexStale
|
||||
? `STALE (${row.commitsBehind ?? '?'} commits behind)`
|
||||
: 'OK ';
|
||||
const ctr = row.contractsStale ? ' CONTRACTS_STALE' : '';
|
||||
console.log(` ${repoPath.padEnd(25)} ${idx}${ctr}`);
|
||||
}
|
||||
if ((st.missingRepos || []).length > 0) {
|
||||
console.log(`\n Last sync missing repos: ${st.missingRepos!.join(', ')}`);
|
||||
}
|
||||
} finally {
|
||||
await backend.dispose().catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
group
|
||||
.command('sync <name>')
|
||||
.description('Sync Contract Registry — extract contracts and build cross-links')
|
||||
.option('--skip-embeddings', 'Exact + BM25 only (no embedding fallback)')
|
||||
.option('--exact-only', 'Exact match only')
|
||||
.option('--allow-stale', 'Skip stale index warnings')
|
||||
.option('--verbose', 'Show each cross-link detail')
|
||||
.option('--json', 'JSON output')
|
||||
.action(async (name: string, opts: Record<string, boolean | undefined>) => {
|
||||
const { getGroupDir, getDefaultGitnexusDir } = await import('../core/group/storage.js');
|
||||
const { loadGroupConfig } = await import('../core/group/config-parser.js');
|
||||
const { syncGroup } = await import('../core/group/sync.js');
|
||||
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
|
||||
console.log(`Syncing group "${name}" (${Object.keys(config.repos).length} repos)...\n`);
|
||||
|
||||
const result = await syncGroup(config, {
|
||||
groupDir,
|
||||
allowStale: Boolean(opts.allowStale),
|
||||
verbose: Boolean(opts.verbose),
|
||||
skipEmbeddings: Boolean(opts.skipEmbeddings),
|
||||
exactOnly: Boolean(opts.exactOnly),
|
||||
});
|
||||
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(`\nMatching cascade:`);
|
||||
const exactLinks = result.crossLinks.filter((l) => l.matchType === 'exact');
|
||||
console.log(` exact: ${exactLinks.length} cross-links (confidence 1.0)`);
|
||||
console.log(` unmatched: ${result.unmatched.length} contracts`);
|
||||
console.log(
|
||||
`\nWrote contracts.json (${result.contracts.length} contracts, ${result.crossLinks.length} cross-links)`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
group
|
||||
.command('query <name> <query>')
|
||||
.description('Search execution flows across all repos in a group')
|
||||
.option('--subgroup <path>', 'Limit search scope')
|
||||
.option('--limit <n>', 'Max merged results', '5')
|
||||
.option('--json', 'JSON output')
|
||||
.action(
|
||||
async (
|
||||
name: string,
|
||||
queryText: string,
|
||||
opts: Record<string, string | boolean | undefined>,
|
||||
) => {
|
||||
const { LocalBackend } = await import('../mcp/local/local-backend.js');
|
||||
|
||||
const limit = parseInt(String(opts.limit ?? '5'), 10) || 5;
|
||||
const subgroup = opts.subgroup as string | undefined;
|
||||
const backend = new LocalBackend();
|
||||
try {
|
||||
await backend.init();
|
||||
|
||||
console.log(`Searching "${queryText}" across group "${name}"...\n`);
|
||||
|
||||
const raw = await backend.getGroupService().groupQuery({
|
||||
name,
|
||||
query: queryText,
|
||||
limit,
|
||||
subgroup,
|
||||
});
|
||||
const merged = raw as {
|
||||
results: Array<Record<string, unknown>>;
|
||||
per_repo: Array<{ repo: string; count: number }>;
|
||||
};
|
||||
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(raw, null, 2));
|
||||
} else {
|
||||
console.log(`Results (top ${merged.results.length}):\n`);
|
||||
for (const p of merged.results) {
|
||||
const label = (p.summary || p.heuristicLabel || p.name || 'unnamed') as string;
|
||||
console.log(` [${p._repo}] ${label} (rrf: ${(p._rrf_score as number).toFixed(4)})`);
|
||||
}
|
||||
if (merged.results.length === 0) {
|
||||
console.log(' No matching execution flows found.');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await backend.dispose().catch(() => {});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
group
|
||||
.command('contracts <name>')
|
||||
.description('Inspect Contract Registry')
|
||||
.option('--type <type>', 'Filter by contract type')
|
||||
.option('--repo <repo>', 'Filter by repo')
|
||||
.option('--unmatched', 'Show only unmatched contracts')
|
||||
.option('--json', 'JSON output')
|
||||
.action(async (name: string, opts: Record<string, string | boolean | undefined>) => {
|
||||
const { LocalBackend } = await import('../mcp/local/local-backend.js');
|
||||
|
||||
const backend = new LocalBackend();
|
||||
try {
|
||||
await backend.init();
|
||||
const raw = await backend.getGroupService().groupContracts({
|
||||
name,
|
||||
type: opts.type as string | undefined,
|
||||
repo: opts.repo as string | undefined,
|
||||
unmatchedOnly: Boolean(opts.unmatched),
|
||||
});
|
||||
|
||||
if (raw && typeof raw === 'object' && 'error' in raw) {
|
||||
console.error(String((raw as { error: string }).error));
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const { contracts, crossLinks } = raw as {
|
||||
contracts: Array<{
|
||||
role: string;
|
||||
contractId: string;
|
||||
repo: string;
|
||||
symbolRef: { name: string };
|
||||
}>;
|
||||
crossLinks: Array<{
|
||||
from: { repo: string };
|
||||
to: { repo: string };
|
||||
matchType: string;
|
||||
confidence: number;
|
||||
contractId: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify({ contracts, crossLinks }, null, 2));
|
||||
} else {
|
||||
console.log(`Contracts (${contracts.length}):`);
|
||||
for (const c of contracts) {
|
||||
console.log(` [${c.role}] ${c.contractId} (${c.repo}) ${c.symbolRef.name}`);
|
||||
}
|
||||
console.log(`\nCross-links (${crossLinks.length}):`);
|
||||
for (const l of crossLinks) {
|
||||
console.log(
|
||||
` ${l.from.repo} -> ${l.to.repo} [${l.matchType}, conf=${l.confidence}] ${l.contractId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await backend.dispose().catch(() => {});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
import { Command } from 'commander';
|
||||
import { createRequire } from 'node:module';
|
||||
import { createLazyAction } from './lazy-action.js';
|
||||
import { registerGroupCommands } from './group.js';
|
||||
|
||||
const _require = createRequire(import.meta.url);
|
||||
const pkg = _require('../../package.json');
|
||||
@@ -25,6 +26,7 @@ program
|
||||
.option('--embeddings', 'Enable embedding generation for semantic search (off by default)')
|
||||
.option('--skills', 'Generate repo-specific skill files from detected communities')
|
||||
.option('--skip-agents-md', 'Skip updating the gitnexus section in AGENTS.md and CLAUDE.md')
|
||||
.option('--no-stats', 'Omit volatile file/symbol counts from AGENTS.md and CLAUDE.md')
|
||||
.option('--skip-git', 'Index a folder without requiring a .git directory')
|
||||
.option('-v, --verbose', 'Enable verbose ingestion warnings (default: false)')
|
||||
.addHelpText(
|
||||
@@ -148,4 +150,6 @@ program
|
||||
.option('--idle-timeout <seconds>', 'Auto-shutdown after N seconds idle (0 = disabled)', '0')
|
||||
.action(createLazyAction(() => import('./eval-server.js'), 'evalServerCommand'));
|
||||
|
||||
registerGroupCommands(program);
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
@@ -14,7 +14,10 @@ process.on('unhandledRejection', (reason: any) => {
|
||||
|
||||
export const serveCommand = async (options?: { port?: string; host?: string }) => {
|
||||
const port = Number(options?.port ?? 4747);
|
||||
const host = options?.host ?? '127.0.0.1';
|
||||
// Default to 'localhost' so the OS decides whether to bind to 127.0.0.1 or
|
||||
// ::1 based on system configuration, avoiding spurious CORS errors when the
|
||||
// hosted frontend at gitnexus.vercel.app connects to localhost.
|
||||
const host = options?.host ?? 'localhost';
|
||||
|
||||
try {
|
||||
await createServer(port, host);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { execFile } from 'child_process';
|
||||
import { execFile, execFileSync } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { glob } from 'glob';
|
||||
@@ -25,11 +25,44 @@ interface SetupResult {
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the absolute path to the `gitnexus` binary if it's installed
|
||||
* globally (or via npm -g / yarn global). Returns null when not found.
|
||||
*/
|
||||
function resolveGitnexusBin(): string | null {
|
||||
try {
|
||||
const cmd = process.platform === 'win32' ? 'where' : 'which';
|
||||
const resolved = execFileSync(cmd, ['gitnexus'], {
|
||||
encoding: 'utf-8',
|
||||
timeout: 5000,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
.split('\n')[0]
|
||||
.trim();
|
||||
return resolved || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The MCP server entry for all editors.
|
||||
* On Windows, npx must be invoked via cmd /c since it's a .cmd script.
|
||||
*
|
||||
* Prefers the globally-installed `gitnexus` binary (starts in ~1 s) over
|
||||
* `npx -y gitnexus@latest` (cold-cache install of native deps can take
|
||||
* >60 s, exceeding Claude Code's 30 s MCP connection timeout).
|
||||
*
|
||||
* Falls back to npx when the binary isn't on PATH — e.g. first-time
|
||||
* users who ran `npx gitnexus analyze` but haven't done `npm i -g`.
|
||||
*/
|
||||
function getMcpEntry() {
|
||||
const bin = resolveGitnexusBin();
|
||||
|
||||
if (bin) {
|
||||
return { command: bin, args: ['mcp'] };
|
||||
}
|
||||
|
||||
// Fallback: npx (works without a global install, but slow cold-start)
|
||||
if (process.platform === 'win32') {
|
||||
return {
|
||||
command: 'cmd',
|
||||
@@ -232,7 +265,7 @@ async function setupOpenCode(result: SetupResult): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
const configPath = path.join(opencodeDir, 'config.json');
|
||||
const configPath = path.join(opencodeDir, 'opencode.json');
|
||||
try {
|
||||
const existing = await readJsonFile(configPath);
|
||||
const config = existing || {};
|
||||
|
||||
+18
-58
@@ -232,65 +232,28 @@ export const wikiCommand = async (inputPath?: string, options?: WikiCommandOptio
|
||||
|
||||
llmConfig = { ...llmConfig, provider: 'cursor', model, apiKey: '', baseUrl: '' };
|
||||
} else if (choice === '3') {
|
||||
// Azure OpenAI guided setup
|
||||
console.log('\n Azure OpenAI setup.');
|
||||
console.log(
|
||||
' You need: your resource name, deployment name, and API key from the Azure portal.\n',
|
||||
);
|
||||
// Azure OpenAI guided setup — minimal prompts
|
||||
console.log('\n Azure OpenAI setup.\n');
|
||||
|
||||
const resourceName = (
|
||||
await prompt(' Azure resource name (e.g. my-openai-resource): ')
|
||||
).trim();
|
||||
if (!resourceName) {
|
||||
console.log('\n No resource name provided. Aborting.\n');
|
||||
const endpoint = (
|
||||
await prompt(' Endpoint URL (e.g. https://my-resource.openai.azure.com): ')
|
||||
)
|
||||
.trim()
|
||||
.replace(/\/+$/, '');
|
||||
if (!endpoint) {
|
||||
console.log('\n No endpoint provided. Aborting.\n');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const deploymentName = (
|
||||
await prompt(' Deployment name (the name you gave your model deployment): ')
|
||||
).trim();
|
||||
const deploymentName = (await prompt(' Deployment name: ')).trim();
|
||||
if (!deploymentName) {
|
||||
console.log('\n No deployment name provided. Aborting.\n');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
// Offer v1 or legacy URL
|
||||
console.log('\n API format:');
|
||||
console.log(' [1] v1 API — recommended (no api-version needed)');
|
||||
console.log(' [2] Legacy — uses api-version query param\n');
|
||||
const apiFormat = await prompt(' Select format (1/2, default: 1): ');
|
||||
|
||||
let azureApiVersion: string | undefined;
|
||||
let azureBaseUrl: string;
|
||||
if (apiFormat === '2') {
|
||||
const versionInput = await prompt(' api-version (default: 2024-10-21): ');
|
||||
azureApiVersion = versionInput || '2024-10-21';
|
||||
azureBaseUrl = `https://${resourceName}.openai.azure.com/openai/deployments/${deploymentName}`;
|
||||
} else {
|
||||
azureBaseUrl = `https://${resourceName}.openai.azure.com/openai/v1`;
|
||||
azureApiVersion = undefined;
|
||||
}
|
||||
|
||||
defaultModel = deploymentName;
|
||||
|
||||
// Ask if this is a reasoning model deployment
|
||||
const reasoningAnswer = await prompt(
|
||||
' Is this a reasoning model (o1, o3, o4-mini)? (y/N): ',
|
||||
);
|
||||
const isReasoningModelDeployment = ['y', 'yes'].includes(reasoningAnswer.toLowerCase());
|
||||
|
||||
if (isReasoningModelDeployment) {
|
||||
console.log(
|
||||
' Note: temperature and max_tokens will be omitted for this deployment (Azure reasoning model requirement).\n',
|
||||
);
|
||||
}
|
||||
|
||||
const modelInput = await prompt(` Model / deployment name (default: ${defaultModel}): `);
|
||||
const model = modelInput || defaultModel;
|
||||
|
||||
// API key
|
||||
// API key — use env var if available
|
||||
const envKey = process.env.GITNEXUS_API_KEY || process.env.OPENAI_API_KEY || '';
|
||||
let azureKey: string;
|
||||
if (envKey) {
|
||||
@@ -311,26 +274,23 @@ export const wikiCommand = async (inputPath?: string, options?: WikiCommandOptio
|
||||
return;
|
||||
}
|
||||
|
||||
// Save Azure config including optional apiVersion and isReasoningModel
|
||||
const azureConfig: Parameters<typeof saveCLIConfig>[0] = {
|
||||
// Always use v1 API format — no need for api-version
|
||||
const azureBaseUrl = `${endpoint}/openai/v1`;
|
||||
|
||||
await saveCLIConfig({
|
||||
apiKey: azureKey,
|
||||
baseUrl: azureBaseUrl,
|
||||
model,
|
||||
model: deploymentName,
|
||||
provider: 'azure',
|
||||
isReasoningModel: isReasoningModelDeployment,
|
||||
};
|
||||
if (azureApiVersion) azureConfig.apiVersion = azureApiVersion;
|
||||
await saveCLIConfig(azureConfig);
|
||||
});
|
||||
console.log(' Config saved to ~/.gitnexus/config.json\n');
|
||||
|
||||
llmConfig = {
|
||||
...llmConfig,
|
||||
apiKey: azureKey,
|
||||
baseUrl: azureBaseUrl,
|
||||
model,
|
||||
model: deploymentName,
|
||||
provider: 'azure',
|
||||
apiVersion: azureApiVersion,
|
||||
isReasoningModel: isReasoningModelDeployment,
|
||||
};
|
||||
} else {
|
||||
// OpenAI-compatible provider (OpenAI, OpenRouter, Custom)
|
||||
|
||||
@@ -398,11 +398,16 @@ export const createIgnoreFilter = async (repoPath: string, options?: IgnoreOptio
|
||||
// defense-in-depth — do not remove `dot: false` assuming this covers it.
|
||||
if (DEFAULT_IGNORE_LIST.has(p.name)) return true;
|
||||
// Check against .gitignore / .gitnexusignore patterns.
|
||||
// Test both bare path and path with trailing slash to handle
|
||||
// bare-name patterns (e.g. `local`) and dir-only patterns (e.g. `local/`).
|
||||
// Since childrenIgnored is only called for directories, always test with
|
||||
// a trailing slash. This ensures directory-only negation patterns (e.g.
|
||||
// `!iOS/`) are applied correctly — without the slash, `ig.ignores('iOS')`
|
||||
// treats the path as a file and misses the negation.
|
||||
// Bare-name patterns (e.g. `local`) still match `local/` per gitignore spec:
|
||||
// the `ignore` package normalizes `dir` and `dir/` to match directories.
|
||||
// See: https://github.com/kaelzhang/node-ignore#2-filenames-and-dirnames
|
||||
if (ig) {
|
||||
const rel = p.relative();
|
||||
if (rel && (ig.ignores(rel) || ig.ignores(rel + '/'))) return true;
|
||||
if (rel && ig.ignores(rel + '/')) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
@@ -93,7 +93,7 @@ export async function augment(pattern: string, cwd?: string): Promise<string> {
|
||||
if (!repo) return '';
|
||||
|
||||
// Lazy-load lbug adapter (skip unnecessary init)
|
||||
const { initLbug, executeQuery, isLbugReady } = await import('../../mcp/core/lbug-adapter.js');
|
||||
const { initLbug, executeQuery, isLbugReady } = await import('../lbug/pool-adapter.js');
|
||||
const { searchFTSFromLbug } = await import('../search/bm25-index.js');
|
||||
|
||||
const repoId = repo.name.toLowerCase();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Git working tree vs index commit staleness (used by MCP resources, group status, etc.).
|
||||
* Lives in core/ so application code does not depend on the MCP package layer.
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
|
||||
export interface StalenessInfo {
|
||||
isStale: boolean;
|
||||
commitsBehind: number;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check how many commits the index is behind HEAD (synchronous; uses git CLI).
|
||||
*/
|
||||
export function checkStaleness(repoPath: string, lastCommit: string): StalenessInfo {
|
||||
try {
|
||||
const result = execFileSync('git', ['rev-list', '--count', `${lastCommit}..HEAD`], {
|
||||
cwd: repoPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
}).trim();
|
||||
|
||||
const commitsBehind = parseInt(result, 10) || 0;
|
||||
|
||||
if (commitsBehind > 0) {
|
||||
return {
|
||||
isStale: true,
|
||||
commitsBehind,
|
||||
hint: `⚠️ Index is ${commitsBehind} commit${commitsBehind > 1 ? 's' : ''} behind HEAD. Run analyze tool to update.`,
|
||||
};
|
||||
}
|
||||
|
||||
return { isStale: false, commitsBehind: 0 };
|
||||
} catch {
|
||||
return { isStale: false, commitsBehind: 0 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
import fsp from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import lbug from '@ladybugdb/core';
|
||||
import type { LbugValue } from '@ladybugdb/core';
|
||||
import type { BridgeHandle, BridgeMeta, StoredContract, CrossLink, RepoSnapshot } from './types.js';
|
||||
import { BRIDGE_SCHEMA_QUERIES, BRIDGE_SCHEMA_VERSION } from './bridge-schema.js';
|
||||
import { dedupeContracts, dedupeCrossLinks } from './normalization.js';
|
||||
|
||||
export function contractNodeId(
|
||||
repo: string,
|
||||
contractId: string,
|
||||
role: string,
|
||||
filePath: string,
|
||||
): string {
|
||||
return createHash('sha256').update(`${repo}\0${contractId}\0${role}\0${filePath}`).digest('hex');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* ContractLookupIndex — in-memory lookup for findContractNode */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* In-memory index of contract node IDs keyed three ways, mirroring the
|
||||
* three-tier fallback lookup in {@link findContractNode}. Built once per
|
||||
* `writeBridge` call after all contracts are successfully inserted, then
|
||||
* consulted for every cross-link — which eliminates the former N+1 query
|
||||
* pattern (up to `6 × cross-links` DB round-trips) and turns cross-link
|
||||
* resolution into constant-time per link.
|
||||
*
|
||||
* Keys are deliberately flat strings (not tuples) so `Map<string, ...>`
|
||||
* works; the separator `\0` can't occur in any legal repo path / file
|
||||
* path / symbol identifier, which makes the encoding injection-safe.
|
||||
*/
|
||||
export interface ContractLookupIndex {
|
||||
/** tier 1: `repo + role + symbolUid` → contract node id */
|
||||
byUid: Map<string, string>;
|
||||
/** tier 2: `repo + role + filePath + symbolName` → contract node id */
|
||||
byRef: Map<string, string>;
|
||||
/** tier 3: `repo + role + filePath` → list of contract node ids in that file */
|
||||
byFile: Map<string, string[]>;
|
||||
}
|
||||
|
||||
export function createContractLookupIndex(): ContractLookupIndex {
|
||||
return {
|
||||
byUid: new Map(),
|
||||
byRef: new Map(),
|
||||
byFile: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
function uidKey(repo: string, role: string, symbolUid: string): string {
|
||||
return `${repo}\0${role}\0${symbolUid}`;
|
||||
}
|
||||
|
||||
function refKey(repo: string, role: string, filePath: string, symbolName: string): string {
|
||||
return `${repo}\0${role}\0${filePath}\0${symbolName}`;
|
||||
}
|
||||
|
||||
function fileKey(repo: string, role: string, filePath: string): string {
|
||||
return `${repo}\0${role}\0${filePath}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a successfully-inserted contract to the lookup index. Must be called
|
||||
* AFTER the DB insert succeeds (not before) so failed inserts don't poison
|
||||
* the index and cause cross-links to point at non-existent rows.
|
||||
*/
|
||||
export function indexContract(
|
||||
index: ContractLookupIndex,
|
||||
contract: StoredContract,
|
||||
nodeId: string,
|
||||
): void {
|
||||
if (contract.symbolUid) {
|
||||
index.byUid.set(uidKey(contract.repo, contract.role, contract.symbolUid), nodeId);
|
||||
}
|
||||
index.byRef.set(
|
||||
refKey(contract.repo, contract.role, contract.symbolRef.filePath, contract.symbolRef.name),
|
||||
nodeId,
|
||||
);
|
||||
const fk = fileKey(contract.repo, contract.role, contract.symbolRef.filePath);
|
||||
const existing = index.byFile.get(fk);
|
||||
if (existing) {
|
||||
existing.push(nodeId);
|
||||
} else {
|
||||
index.byFile.set(fk, [nodeId]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a cross-link endpoint (consumer or provider reference) to an
|
||||
* already-inserted contract node id. Returns `null` if no match — the
|
||||
* caller is expected to count that as a dropped link in `WriteBridgeReport`.
|
||||
*
|
||||
* The resolution order matches the pre-cache DB-query behavior:
|
||||
* 1. exact `symbolUid` match in the same `(repo, role)` scope
|
||||
* 2. exact `(filePath, symbolName)` match
|
||||
* 3. if exactly one contract lives in the file → that one (fallback for
|
||||
* legacy graph-assisted extractors that couldn't resolve a symbol name)
|
||||
*
|
||||
* This is a pure function — no I/O, no DB — so it's trivial to unit-test
|
||||
* in isolation (which was the reviewer's main clean-code concern on the
|
||||
* original 35-line inner closure in `writeBridge`).
|
||||
*/
|
||||
export function findContractNode(
|
||||
index: ContractLookupIndex,
|
||||
repo: string,
|
||||
role: 'consumer' | 'provider',
|
||||
symbolUid: string,
|
||||
filePath: string,
|
||||
symbolName: string,
|
||||
): string | null {
|
||||
if (symbolUid) {
|
||||
const uidHit = index.byUid.get(uidKey(repo, role, symbolUid));
|
||||
if (uidHit !== undefined) return uidHit;
|
||||
}
|
||||
|
||||
const refHit = index.byRef.get(refKey(repo, role, filePath, symbolName));
|
||||
if (refHit !== undefined) return refHit;
|
||||
|
||||
const fileCandidates = index.byFile.get(fileKey(repo, role, filePath));
|
||||
if (fileCandidates && fileCandidates.length === 1) return fileCandidates[0];
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function openBridgeDb(dbPath: string): Promise<BridgeHandle> {
|
||||
const parentDir = path.dirname(dbPath);
|
||||
await fsp.mkdir(parentDir, { recursive: true });
|
||||
const db = new lbug.Database(dbPath, 0, false, false); // writable
|
||||
const conn = new lbug.Connection(db);
|
||||
return { _db: db, _conn: conn, groupDir: parentDir } as BridgeHandle;
|
||||
}
|
||||
|
||||
/**
|
||||
* LadybugDB returns an error whose message contains this substring when a
|
||||
* CREATE NODE TABLE or CREATE REL TABLE statement hits an already-existing
|
||||
* table. LadybugDB DDL doesn't support IF NOT EXISTS, and its JS driver
|
||||
* doesn't expose typed error codes, so we match on the message substring —
|
||||
* the same pattern used by `core/lbug/lbug-adapter.ts`. If a future
|
||||
* LadybugDB release changes the wording, update this constant.
|
||||
*/
|
||||
const LBUG_ALREADY_EXISTS_MSG = 'already exists';
|
||||
|
||||
export async function ensureBridgeSchema(handle: BridgeHandle): Promise<void> {
|
||||
const conn = handle._conn as lbug.Connection;
|
||||
for (const q of BRIDGE_SCHEMA_QUERIES) {
|
||||
try {
|
||||
await conn.query(q);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
if (!msg.includes(LBUG_ALREADY_EXISTS_MSG)) throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function queryBridge<T>(
|
||||
handle: BridgeHandle,
|
||||
cypher: string,
|
||||
params?: Record<string, LbugValue>,
|
||||
): Promise<T[]> {
|
||||
const conn = handle._conn as lbug.Connection;
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
const stmt = await conn.prepare(cypher);
|
||||
if (!stmt.isSuccess()) {
|
||||
const errMsg = await stmt.getErrorMessage();
|
||||
throw new Error(`Bridge query prepare failed: ${errMsg}`);
|
||||
}
|
||||
const queryResult = await conn.execute(stmt, params);
|
||||
const result = unwrapQueryResult(queryResult);
|
||||
return (await result.getAll()) as T[];
|
||||
}
|
||||
const queryResult = await conn.query(cypher);
|
||||
const result = unwrapQueryResult(queryResult);
|
||||
return (await result.getAll()) as T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* LadybugDB's `conn.query` / `conn.execute` can return either a single
|
||||
* `QueryResult` (for a single statement) or an array of them (when a
|
||||
* multi-statement script is dispatched). We always pass a single statement,
|
||||
* so the array form is a wrapper we unwrap here — but an empty top-level
|
||||
* array would cause `.getAll()` on `undefined` and crash with a confusing
|
||||
* stack. Throwing an explicit error makes a driver-contract regression
|
||||
* visible immediately instead of masking it.
|
||||
*/
|
||||
function unwrapQueryResult(queryResult: lbug.QueryResult | lbug.QueryResult[]): lbug.QueryResult {
|
||||
if (Array.isArray(queryResult)) {
|
||||
if (queryResult.length === 0) {
|
||||
throw new Error('Bridge query returned an empty QueryResult array');
|
||||
}
|
||||
return queryResult[0];
|
||||
}
|
||||
return queryResult;
|
||||
}
|
||||
|
||||
export async function closeBridgeDb(handle: BridgeHandle): Promise<void> {
|
||||
try {
|
||||
await (handle._conn as lbug.Connection).close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
await (handle._db as lbug.Database).close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* retryRename — handles transient EBUSY/EPERM/EACCES on Windows */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const RETRY_CODES = new Set(['EBUSY', 'EPERM', 'EACCES']);
|
||||
|
||||
export async function retryRename(src: string, dst: string, attempts = 3): Promise<void> {
|
||||
for (let i = 1; i <= attempts; i++) {
|
||||
try {
|
||||
await fsp.rename(src, dst);
|
||||
return;
|
||||
} catch (err: unknown) {
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
if (!code || !RETRY_CODES.has(code) || i === attempts) throw err;
|
||||
await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i - 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* writeBridgeMeta / readBridgeMeta */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function writeBridgeMeta(groupDir: string, meta: BridgeMeta): Promise<void> {
|
||||
const target = path.join(groupDir, 'meta.json');
|
||||
const tmp = `${target}.tmp.${Date.now()}`;
|
||||
await fsp.writeFile(tmp, JSON.stringify(meta, null, 2), 'utf-8');
|
||||
// Use retryRename for consistency with writeBridge's atomic swap — on
|
||||
// Windows a concurrent reader can cause EBUSY/EPERM even on a tiny
|
||||
// meta.json, and we don't want meta write to be less robust than the
|
||||
// bridge.lbug swap it accompanies.
|
||||
await retryRename(tmp, target);
|
||||
}
|
||||
|
||||
export async function readBridgeMeta(groupDir: string): Promise<BridgeMeta> {
|
||||
try {
|
||||
const content = await fsp.readFile(path.join(groupDir, 'meta.json'), 'utf-8');
|
||||
return JSON.parse(content) as BridgeMeta;
|
||||
} catch {
|
||||
return { version: 0, generatedAt: '', missingRepos: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* writeBridge — atomic write-to-temp-then-rename */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface WriteBridgeInput {
|
||||
contracts: StoredContract[];
|
||||
crossLinks: CrossLink[];
|
||||
repoSnapshots: Record<string, RepoSnapshot>;
|
||||
missingRepos: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-fatal issues encountered during writeBridge. Callers can log these to
|
||||
* surface partial-success state without aborting the whole sync.
|
||||
* `sampleErrors` is capped at MAX_SAMPLE_ERRORS per category to bound memory.
|
||||
*/
|
||||
export interface WriteBridgeReport {
|
||||
contractsInserted: number;
|
||||
contractsFailed: number;
|
||||
snapshotsInserted: number;
|
||||
snapshotsFailed: number;
|
||||
linksInserted: number;
|
||||
linksFailed: number;
|
||||
/** Cross-links skipped because their from/to contract nodes weren't found. */
|
||||
linksDroppedMissingNode: number;
|
||||
sampleErrors: Array<{
|
||||
kind: 'contract' | 'snapshot' | 'link';
|
||||
id: string;
|
||||
message: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
const MAX_SAMPLE_ERRORS = 10;
|
||||
|
||||
function errMessage(err: unknown): string {
|
||||
if (err instanceof Error) return err.message;
|
||||
try {
|
||||
return String(err);
|
||||
} catch {
|
||||
return 'unknown error';
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeBridge(
|
||||
groupDir: string,
|
||||
input: WriteBridgeInput,
|
||||
): Promise<WriteBridgeReport> {
|
||||
await fsp.mkdir(groupDir, { recursive: true });
|
||||
const contracts = dedupeContracts(input.contracts);
|
||||
const crossLinks = dedupeCrossLinks(input.crossLinks);
|
||||
|
||||
const finalPath = path.join(groupDir, 'bridge.lbug');
|
||||
const tmpPath = path.join(groupDir, 'bridge.lbug.tmp');
|
||||
const bakPath = path.join(groupDir, 'bridge.lbug.bak');
|
||||
|
||||
const report: WriteBridgeReport = {
|
||||
contractsInserted: 0,
|
||||
contractsFailed: 0,
|
||||
snapshotsInserted: 0,
|
||||
snapshotsFailed: 0,
|
||||
linksInserted: 0,
|
||||
linksFailed: 0,
|
||||
linksDroppedMissingNode: 0,
|
||||
sampleErrors: [],
|
||||
};
|
||||
|
||||
const recordError = (kind: 'contract' | 'snapshot' | 'link', id: string, err: unknown) => {
|
||||
if (report.sampleErrors.length < MAX_SAMPLE_ERRORS) {
|
||||
report.sampleErrors.push({ kind, id, message: errMessage(err) });
|
||||
}
|
||||
};
|
||||
|
||||
// Clean up any leftover tmp
|
||||
try {
|
||||
await fsp.rm(tmpPath, { recursive: true, force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
// 1. Create temp DB, insert all data.
|
||||
//
|
||||
// Everything after `openBridgeDb` must run inside a try/finally so that
|
||||
// if ANY step before the explicit `closeBridgeDb` throws — schema
|
||||
// creation, a contract insert loop that rethrows, a snapshot write, the
|
||||
// cross-link loop, or anything else — the handle is still released. A
|
||||
// leaked handle holds the native LadybugDB file lock on tmpPath, which
|
||||
// (a) leaks a FD and (b) prevents the next writeBridge call from
|
||||
// reusing the same tmp slot.
|
||||
const handle = await openBridgeDb(tmpPath);
|
||||
let handleClosed = false;
|
||||
try {
|
||||
await ensureBridgeSchema(handle);
|
||||
|
||||
// Build the lookup index incrementally as contracts are inserted, so
|
||||
// failed inserts are never in the index (and therefore never resolved
|
||||
// by the cross-link loop below). This replaces a previous N+1 query
|
||||
// pattern where each link made up to 6 DB round-trips to find its
|
||||
// endpoints — see ContractLookupIndex.
|
||||
const lookupIndex = createContractLookupIndex();
|
||||
|
||||
// Insert contracts — tolerate individual failures (e.g., a corrupt meta
|
||||
// that can't be serialized). The whole sync must not fail because one
|
||||
// contract is broken.
|
||||
for (const c of contracts) {
|
||||
const id = contractNodeId(c.repo, c.contractId, c.role, c.symbolRef.filePath);
|
||||
try {
|
||||
await queryBridge(
|
||||
handle,
|
||||
`CREATE (n:Contract {
|
||||
id: $id,
|
||||
contractId: $contractId,
|
||||
type: $type,
|
||||
role: $role,
|
||||
repo: $repo,
|
||||
service: $service,
|
||||
symbolUid: $symbolUid,
|
||||
filePath: $filePath,
|
||||
symbolName: $symbolName,
|
||||
confidence: $confidence,
|
||||
meta: $meta
|
||||
})`,
|
||||
{
|
||||
id,
|
||||
contractId: c.contractId,
|
||||
type: c.type,
|
||||
role: c.role,
|
||||
repo: c.repo,
|
||||
service: c.service ?? '',
|
||||
symbolUid: c.symbolUid,
|
||||
filePath: c.symbolRef.filePath,
|
||||
symbolName: c.symbolName,
|
||||
confidence: c.confidence,
|
||||
meta: JSON.stringify(c.meta),
|
||||
},
|
||||
);
|
||||
report.contractsInserted++;
|
||||
// Only index on successful insert — the cross-link loop must never
|
||||
// resolve to a row that isn't actually in the DB.
|
||||
indexContract(lookupIndex, c, id);
|
||||
} catch (err) {
|
||||
report.contractsFailed++;
|
||||
recordError('contract', id, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Insert repo snapshots
|
||||
for (const [repoId, snap] of Object.entries(input.repoSnapshots)) {
|
||||
try {
|
||||
await queryBridge(
|
||||
handle,
|
||||
`CREATE (s:RepoSnapshot {
|
||||
id: $id,
|
||||
indexedAt: $indexedAt,
|
||||
lastCommit: $lastCommit
|
||||
})`,
|
||||
{
|
||||
id: repoId,
|
||||
indexedAt: snap.indexedAt,
|
||||
lastCommit: snap.lastCommit,
|
||||
},
|
||||
);
|
||||
report.snapshotsInserted++;
|
||||
} catch (err) {
|
||||
report.snapshotsFailed++;
|
||||
recordError('snapshot', repoId, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Insert cross-links (tolerating missing nodes).
|
||||
//
|
||||
// `findContractNode` consults the in-memory lookup index built above,
|
||||
// not the DB — that's an O(1) pure-function lookup per endpoint instead
|
||||
// of the previous 2-3 DB queries. For M cross-links, the previous code
|
||||
// issued up to 6M round-trips; this version issues zero.
|
||||
//
|
||||
// `link.contractId` may differ between the consumer and provider sides
|
||||
// (e.g. wildcard consumer `grpc::Service/*` → method-level provider
|
||||
// `grpc::Service/Method`) — that's why we resolve each endpoint
|
||||
// independently via its own `(repo, role, symbolUid, filePath, symbolName)`
|
||||
// tuple rather than matching on contractId.
|
||||
for (const link of crossLinks) {
|
||||
const linkId = `${link.from.repo}::${link.contractId}->${link.to.repo}::${link.contractId}`;
|
||||
try {
|
||||
const fromId = findContractNode(
|
||||
lookupIndex,
|
||||
link.from.repo,
|
||||
'consumer',
|
||||
link.from.symbolUid,
|
||||
link.from.symbolRef.filePath,
|
||||
link.from.symbolRef.name,
|
||||
);
|
||||
const toId = findContractNode(
|
||||
lookupIndex,
|
||||
link.to.repo,
|
||||
'provider',
|
||||
link.to.symbolUid,
|
||||
link.to.symbolRef.filePath,
|
||||
link.to.symbolRef.name,
|
||||
);
|
||||
if (!fromId || !toId) {
|
||||
report.linksDroppedMissingNode++;
|
||||
continue;
|
||||
}
|
||||
await queryBridge(
|
||||
handle,
|
||||
`
|
||||
MATCH (a:Contract), (b:Contract)
|
||||
WHERE a.id = $fromId AND b.id = $toId
|
||||
CREATE (a)-[:ContractLink {
|
||||
matchType: $matchType,
|
||||
confidence: $confidence,
|
||||
contractId: $contractId,
|
||||
fromRepo: $fromRepo,
|
||||
toRepo: $toRepo
|
||||
}]->(b)
|
||||
`,
|
||||
{
|
||||
fromId,
|
||||
toId,
|
||||
matchType: link.matchType,
|
||||
confidence: link.confidence,
|
||||
contractId: link.contractId,
|
||||
fromRepo: link.from.repo,
|
||||
toRepo: link.to.repo,
|
||||
},
|
||||
);
|
||||
report.linksInserted++;
|
||||
} catch (err) {
|
||||
report.linksFailed++;
|
||||
recordError('link', linkId, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Close temp DB (happy path). The finally block also calls
|
||||
// closeBridgeDb if we threw above; `handleClosed` prevents a
|
||||
// double-close on the native handle.
|
||||
await closeBridgeDb(handle);
|
||||
handleClosed = true;
|
||||
} finally {
|
||||
if (!handleClosed) {
|
||||
await closeBridgeDb(handle).catch(() => {
|
||||
/* ignore: cleanup path, best effort */
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Atomic swap: old→.bak, tmp→final, rm .bak
|
||||
try {
|
||||
await fsp.access(finalPath);
|
||||
await retryRename(finalPath, bakPath);
|
||||
} catch {
|
||||
/* no existing db */
|
||||
}
|
||||
await retryRename(tmpPath, finalPath);
|
||||
try {
|
||||
await fsp.rm(bakPath, { recursive: true, force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
// 4. Write meta.json
|
||||
await writeBridgeMeta(groupDir, {
|
||||
version: BRIDGE_SCHEMA_VERSION,
|
||||
generatedAt: new Date().toISOString(),
|
||||
missingRepos: input.missingRepos,
|
||||
});
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* openBridgeDbReadOnly */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function openBridgeDbReadOnly(groupDir: string): Promise<BridgeHandle | null> {
|
||||
const dbPath = path.join(groupDir, 'bridge.lbug');
|
||||
try {
|
||||
await fsp.access(dbPath);
|
||||
} catch {
|
||||
// Check for .bak recovery. Use `retryRename` (not `fsp.rename`) for the
|
||||
// exact same reason the rest of this file does: the scenario that
|
||||
// triggers bak recovery is an interrupted writer, which on Windows may
|
||||
// still be holding an open handle on `.bak` for a few milliseconds when
|
||||
// a reader races in. EBUSY/EPERM retries recover that case silently.
|
||||
const bakPath = path.join(groupDir, 'bridge.lbug.bak');
|
||||
try {
|
||||
await fsp.access(bakPath);
|
||||
await retryRename(bakPath, dbPath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// Version gate: check meta.json version compatibility
|
||||
const meta = await readBridgeMeta(groupDir);
|
||||
if (meta.version > 0 && meta.version !== BRIDGE_SCHEMA_VERSION) {
|
||||
return null; // incompatible schema version — fallback to JSON or re-sync
|
||||
}
|
||||
|
||||
// Open the native handle. If Connection construction throws AFTER
|
||||
// Database was successfully allocated, we'd leak the native Database
|
||||
// object. Wrap each step separately and tear down the partial handle.
|
||||
let db: lbug.Database | undefined;
|
||||
let conn: lbug.Connection | undefined;
|
||||
try {
|
||||
db = new lbug.Database(dbPath, 0, false, true); // readOnly
|
||||
conn = new lbug.Connection(db);
|
||||
return { _db: db, _conn: conn, groupDir } as BridgeHandle;
|
||||
} catch {
|
||||
if (conn) {
|
||||
try {
|
||||
await conn.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
if (db) {
|
||||
try {
|
||||
await db.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* bridgeExists */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function bridgeExists(groupDir: string): Promise<boolean> {
|
||||
const handle = await openBridgeDbReadOnly(groupDir);
|
||||
if (!handle) return false;
|
||||
await closeBridgeDb(handle);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Bridge LadybugDB schema for cross-repo Contract Registry.
|
||||
* Separate from per-repo schema in lbug/schema.ts.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Version of the bridge.lbug schema below. `openBridgeDbReadOnly` compares
|
||||
* this against `meta.json`'s version field and returns `null` on mismatch,
|
||||
* which trips the caller into either the JSON fallback path or a fresh
|
||||
* `group sync` that rebuilds `bridge.lbug` from scratch.
|
||||
*
|
||||
* Migration contract for contributors bumping this constant:
|
||||
* 1. Bump the number (e.g. `1` → `2`).
|
||||
* 2. Update the DDL below to match the new schema.
|
||||
* 3. DO NOT attempt an online migration in this file — the version gate
|
||||
* is intentionally a "discard and re-sync" strategy for V1. An old
|
||||
* bridge.lbug whose version doesn't match is treated as opaque and
|
||||
* rebuilt by the next `group sync`.
|
||||
* 4. If online migration becomes necessary (e.g. when groups accumulate
|
||||
* large amounts of embedding data), add a migration path as a
|
||||
* separate `bridge-migrations.ts` module rather than bloating this
|
||||
* file — keep schema and migration concerns separate.
|
||||
*/
|
||||
export const BRIDGE_SCHEMA_VERSION = 1;
|
||||
|
||||
export const CONTRACT_SCHEMA = `
|
||||
CREATE NODE TABLE Contract (
|
||||
id STRING,
|
||||
contractId STRING,
|
||||
type STRING,
|
||||
role STRING,
|
||||
repo STRING,
|
||||
service STRING DEFAULT '',
|
||||
symbolUid STRING DEFAULT '',
|
||||
filePath STRING DEFAULT '',
|
||||
symbolName STRING DEFAULT '',
|
||||
confidence DOUBLE DEFAULT 0.0,
|
||||
meta STRING DEFAULT '{}',
|
||||
PRIMARY KEY (id)
|
||||
)`;
|
||||
|
||||
export const REPO_SNAPSHOT_SCHEMA = `
|
||||
CREATE NODE TABLE RepoSnapshot (
|
||||
id STRING,
|
||||
indexedAt STRING DEFAULT '',
|
||||
lastCommit STRING DEFAULT '',
|
||||
PRIMARY KEY (id)
|
||||
)`;
|
||||
|
||||
export const CONTRACT_LINK_SCHEMA = `
|
||||
CREATE REL TABLE ContractLink (
|
||||
FROM Contract TO Contract,
|
||||
matchType STRING,
|
||||
confidence DOUBLE,
|
||||
contractId STRING,
|
||||
fromRepo STRING,
|
||||
toRepo STRING
|
||||
)`;
|
||||
|
||||
export const BRIDGE_SCHEMA_QUERIES = [CONTRACT_SCHEMA, REPO_SNAPSHOT_SCHEMA, CONTRACT_LINK_SCHEMA];
|
||||
@@ -0,0 +1,98 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import type { GroupConfig, GroupManifestLink, ContractType, ContractRole } from './types.js';
|
||||
|
||||
const _require = createRequire(import.meta.url);
|
||||
const yaml = _require('js-yaml') as typeof import('js-yaml');
|
||||
|
||||
const VALID_CONTRACT_TYPES: ContractType[] = ['http', 'grpc', 'topic', 'lib', 'custom'];
|
||||
const VALID_ROLES: ContractRole[] = ['provider', 'consumer'];
|
||||
|
||||
const DEFAULT_DETECT = {
|
||||
http: true,
|
||||
grpc: true,
|
||||
topics: true,
|
||||
shared_libs: true,
|
||||
embedding_fallback: true,
|
||||
};
|
||||
|
||||
const DEFAULT_MATCHING = {
|
||||
bm25_threshold: 0.7,
|
||||
embedding_threshold: 0.65,
|
||||
max_candidates_per_step: 3,
|
||||
};
|
||||
|
||||
export function parseGroupConfig(yamlContent: string): GroupConfig {
|
||||
const raw = yaml.load(yamlContent, { schema: yaml.JSON_SCHEMA }) as Record<string, unknown>;
|
||||
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new Error('Invalid YAML: expected an object');
|
||||
}
|
||||
|
||||
if (raw.version === undefined) throw new Error('version is required in group.yaml');
|
||||
if (raw.version !== 1) {
|
||||
throw new Error(`Unsupported group.yaml version: ${raw.version}. Expected 1.`);
|
||||
}
|
||||
if (!raw.name || typeof raw.name !== 'string') throw new Error('name is required in group.yaml');
|
||||
if (!raw.repos || typeof raw.repos !== 'object' || Array.isArray(raw.repos)) {
|
||||
throw new Error('repos is required in group.yaml (must be a mapping)');
|
||||
}
|
||||
|
||||
const repos = raw.repos as Record<string, string>;
|
||||
const repoPaths = new Set(Object.keys(repos));
|
||||
|
||||
const rawLinks = (raw.links as unknown[]) || [];
|
||||
const links: GroupManifestLink[] = rawLinks.map((l: unknown, i: number) => {
|
||||
const link = l as Record<string, unknown>;
|
||||
if (!link.from || !repoPaths.has(link.from as string)) {
|
||||
throw new Error(`links[${i}].from "${link.from}" does not match any repo path in group`);
|
||||
}
|
||||
if (!link.to || !repoPaths.has(link.to as string)) {
|
||||
throw new Error(`links[${i}].to "${link.to}" does not match any repo path in group`);
|
||||
}
|
||||
if (!VALID_CONTRACT_TYPES.includes(link.type as ContractType)) {
|
||||
throw new Error(
|
||||
`links[${i}].type "${link.type}" is invalid. Expected: ${VALID_CONTRACT_TYPES.join(', ')}`,
|
||||
);
|
||||
}
|
||||
if (!VALID_ROLES.includes(link.role as ContractRole)) {
|
||||
throw new Error(`links[${i}].role "${link.role}" is invalid. Expected: provider | consumer`);
|
||||
}
|
||||
if (
|
||||
link.contract === undefined ||
|
||||
link.contract === null ||
|
||||
String(link.contract).trim() === ''
|
||||
) {
|
||||
throw new Error(`links[${i}].contract is required`);
|
||||
}
|
||||
return {
|
||||
from: link.from as string,
|
||||
to: link.to as string,
|
||||
type: link.type as ContractType,
|
||||
contract: String(link.contract),
|
||||
role: link.role as ContractRole,
|
||||
};
|
||||
});
|
||||
|
||||
const detect = { ...DEFAULT_DETECT, ...((raw.detect as object) || {}) };
|
||||
const matching = { ...DEFAULT_MATCHING, ...((raw.matching as object) || {}) };
|
||||
const packages = (raw.packages as Record<string, Record<string, string>>) || {};
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
name: raw.name as string,
|
||||
description: (raw.description as string) || '',
|
||||
repos,
|
||||
links,
|
||||
packages,
|
||||
detect,
|
||||
matching,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadGroupConfig(groupDir: string): Promise<GroupConfig> {
|
||||
const fsp = await import('node:fs/promises');
|
||||
const path = await import('node:path');
|
||||
const yamlPath = path.join(groupDir, 'group.yaml');
|
||||
const content = await fsp.readFile(yamlPath, 'utf-8');
|
||||
return parseGroupConfig(content);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { ContractType, ExtractedContract, RepoHandle } from './types.js';
|
||||
|
||||
export interface ContractExtractor {
|
||||
type: ContractType;
|
||||
canExtract(repo: RepoHandle): Promise<boolean>;
|
||||
extract(
|
||||
dbExecutor: CypherExecutor | null,
|
||||
repoPath: string,
|
||||
repo: RepoHandle,
|
||||
): Promise<ExtractedContract[]>;
|
||||
}
|
||||
|
||||
export type CypherExecutor = (
|
||||
query: string,
|
||||
params?: Record<string, unknown>,
|
||||
) => Promise<Record<string, unknown>[]>;
|
||||
@@ -0,0 +1,357 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { glob } from 'glob';
|
||||
import type { ContractExtractor, CypherExecutor } from '../contract-extractor.js';
|
||||
import type { ExtractedContract, RepoHandle } from '../types.js';
|
||||
|
||||
function readSafe(repoPath: string, rel: string): string | null {
|
||||
const abs = path.resolve(repoPath, rel);
|
||||
const base = path.resolve(repoPath);
|
||||
const relToBase = path.relative(base, abs);
|
||||
if (relToBase.startsWith('..') || path.isAbsolute(relToBase)) return null;
|
||||
try {
|
||||
return fs.readFileSync(abs, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function contractId(pkg: string, service: string, method: string): string {
|
||||
const prefix = pkg ? `${pkg}.${service}` : service;
|
||||
return `grpc::${prefix}/${method}`;
|
||||
}
|
||||
|
||||
function serviceOnlyContractId(serviceName: string): string {
|
||||
return `grpc::${serviceName}/*`;
|
||||
}
|
||||
|
||||
function extractServiceBlocks(content: string): Array<{ name: string; body: string }> {
|
||||
const results: Array<{ name: string; body: string }> = [];
|
||||
// v1: brace-depth only — braces inside comments or string literals are not filtered (see spec Fix 2)
|
||||
const headerRe = /service\s+(\w+)\s*\{/g;
|
||||
let headerMatch: RegExpExecArray | null;
|
||||
|
||||
while ((headerMatch = headerRe.exec(content)) !== null) {
|
||||
const serviceName = headerMatch[1];
|
||||
const bodyStart = headerMatch.index + headerMatch[0].length;
|
||||
let depth = 1;
|
||||
let pos = bodyStart;
|
||||
|
||||
while (pos < content.length && depth > 0) {
|
||||
const ch = content[pos];
|
||||
if (ch === '{') depth++;
|
||||
else if (ch === '}') depth--;
|
||||
pos++;
|
||||
}
|
||||
|
||||
// If EOF before depth returns to 0, skip incomplete service
|
||||
if (depth !== 0) continue;
|
||||
|
||||
// body is between opening { (consumed by regex) and closing } (pos is one past it)
|
||||
const body = content.slice(bodyStart, pos - 1);
|
||||
results.push({ name: serviceName, body });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function makeContract(
|
||||
cid: string,
|
||||
role: 'provider' | 'consumer',
|
||||
filePath: string,
|
||||
symbolName: string,
|
||||
confidence: number,
|
||||
meta: Record<string, unknown>,
|
||||
): ExtractedContract {
|
||||
return {
|
||||
contractId: cid,
|
||||
type: 'grpc',
|
||||
role,
|
||||
symbolUid: '',
|
||||
symbolRef: { filePath: filePath.replace(/\\/g, '/'), name: symbolName },
|
||||
symbolName,
|
||||
confidence,
|
||||
meta: { ...meta, extractionStrategy: 'source_scan' },
|
||||
};
|
||||
}
|
||||
|
||||
export class GrpcExtractor implements ContractExtractor {
|
||||
type = 'grpc' as const;
|
||||
|
||||
async canExtract(_repo: RepoHandle): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
async extract(
|
||||
_dbExecutor: CypherExecutor | null,
|
||||
repoPath: string,
|
||||
_repo: RepoHandle,
|
||||
): Promise<ExtractedContract[]> {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
// Proto files — definitive provider source
|
||||
const protoFiles = await glob('**/*.proto', {
|
||||
cwd: repoPath,
|
||||
ignore: ['**/node_modules/**', '**/.git/**', '**/vendor/**'],
|
||||
nodir: true,
|
||||
});
|
||||
for (const rel of protoFiles) {
|
||||
const content = readSafe(repoPath, rel);
|
||||
if (content) out.push(...this.parseProtoFile(content, rel));
|
||||
}
|
||||
|
||||
// Source files — server/client detection
|
||||
const sourceFiles = await glob('**/*.{go,java,py,ts,tsx,js,jsx}', {
|
||||
cwd: repoPath,
|
||||
ignore: ['**/node_modules/**', '**/.git/**', '**/vendor/**', '**/dist/**', '**/build/**'],
|
||||
nodir: true,
|
||||
});
|
||||
for (const rel of sourceFiles) {
|
||||
const content = readSafe(repoPath, rel);
|
||||
if (!content) continue;
|
||||
const ext = path.extname(rel).toLowerCase();
|
||||
|
||||
if (ext === '.go') {
|
||||
out.push(...this.scanGoProviders(content, rel));
|
||||
out.push(...this.scanGoConsumers(content, rel));
|
||||
} else if (ext === '.java') {
|
||||
out.push(...this.scanJavaProviders(content, rel));
|
||||
out.push(...this.scanJavaConsumers(content, rel));
|
||||
} else if (ext === '.py') {
|
||||
out.push(...this.scanPythonProviders(content, rel));
|
||||
out.push(...this.scanPythonConsumers(content, rel));
|
||||
} else if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {
|
||||
out.push(...this.scanTsProviders(content, rel));
|
||||
}
|
||||
}
|
||||
|
||||
return this.dedupe(out);
|
||||
}
|
||||
|
||||
private parseProtoFile(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
const pkgMatch = content.match(/^package\s+([\w.]+)\s*;/m);
|
||||
const pkg = pkgMatch ? pkgMatch[1] : '';
|
||||
|
||||
for (const { name: serviceName, body } of extractServiceBlocks(content)) {
|
||||
const rpcRe = /rpc\s+(\w+)\s*\(/g;
|
||||
let rpcMatch: RegExpExecArray | null;
|
||||
while ((rpcMatch = rpcRe.exec(body)) !== null) {
|
||||
const methodName = rpcMatch[1];
|
||||
const cid = contractId(pkg, serviceName, methodName);
|
||||
out.push(
|
||||
makeContract(cid, 'provider', filePath, `${serviceName}.${methodName}`, 0.85, {
|
||||
package: pkg,
|
||||
service: serviceName,
|
||||
method: methodName,
|
||||
source: 'proto',
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanGoProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
// pb.RegisterXxxServer(
|
||||
const registerRe = /\w+\.Register(\w+)Server\s*\(/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = registerRe.exec(content)) !== null) {
|
||||
const serviceName = m[1];
|
||||
out.push(
|
||||
makeContract(
|
||||
serviceOnlyContractId(serviceName),
|
||||
'provider',
|
||||
filePath,
|
||||
`Register${serviceName}Server`,
|
||||
0.8,
|
||||
{ service: serviceName, source: 'go_register' },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// pb.UnimplementedXxxServer
|
||||
const unimplRe = /\w+\.Unimplemented(\w+)Server\b/g;
|
||||
while ((m = unimplRe.exec(content)) !== null) {
|
||||
const serviceName = m[1];
|
||||
out.push(
|
||||
makeContract(
|
||||
serviceOnlyContractId(serviceName),
|
||||
'provider',
|
||||
filePath,
|
||||
`Unimplemented${serviceName}Server`,
|
||||
0.8,
|
||||
{ service: serviceName, source: 'go_unimplemented' },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanGoConsumers(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
const re = /\w+\.New(\w+)Client\s*\(/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const serviceName = m[1];
|
||||
out.push(
|
||||
makeContract(
|
||||
serviceOnlyContractId(serviceName),
|
||||
'consumer',
|
||||
filePath,
|
||||
`New${serviceName}Client`,
|
||||
0.7,
|
||||
{ service: serviceName, source: 'go_client' },
|
||||
),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanJavaProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
// @GrpcService
|
||||
if (content.includes('@GrpcService')) {
|
||||
const implBaseRe = /extends\s+(\w+)Grpc\.(\w+)ImplBase/;
|
||||
const m = content.match(implBaseRe);
|
||||
if (m) {
|
||||
out.push(
|
||||
makeContract(serviceOnlyContractId(m[1]), 'provider', filePath, m[2], 0.8, {
|
||||
service: m[1],
|
||||
source: 'java_grpc_service',
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
// Try extracting service name from class name
|
||||
const classRe =
|
||||
/class\s+(\w*?)(?:Grpc)?(?:Service)?\s+extends\s+(\w+)(?:Grpc\.(\w+))?ImplBase/;
|
||||
const cm = content.match(classRe);
|
||||
if (cm) {
|
||||
const svcName = cm[2].replace(/Grpc$/, '');
|
||||
out.push(
|
||||
makeContract(serviceOnlyContractId(svcName), 'provider', filePath, cm[1], 0.8, {
|
||||
service: svcName,
|
||||
source: 'java_grpc_service',
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// extends XxxImplBase (without @GrpcService)
|
||||
if (!content.includes('@GrpcService')) {
|
||||
const implRe = /extends\s+(\w+?)(?:Grpc\.(\w+))?ImplBase/;
|
||||
const m = content.match(implRe);
|
||||
if (m) {
|
||||
const svcName = m[2] || m[1].replace(/Grpc$/, '');
|
||||
out.push(
|
||||
makeContract(serviceOnlyContractId(svcName), 'provider', filePath, svcName, 0.8, {
|
||||
service: svcName,
|
||||
source: 'java_impl_base',
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanJavaConsumers(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
// XxxGrpc.newBlockingStub( or XxxGrpc.newStub(
|
||||
const re = /(\w+)Grpc\.new(?:Blocking)?Stub\s*\(/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const serviceName = m[1];
|
||||
out.push(
|
||||
makeContract(
|
||||
serviceOnlyContractId(serviceName),
|
||||
'consumer',
|
||||
filePath,
|
||||
`${serviceName}Stub`,
|
||||
0.7,
|
||||
{ service: serviceName, source: 'java_stub' },
|
||||
),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanPythonProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
// add_XxxServicer_to_server(
|
||||
const re = /add_(\w+?)Servicer_to_server\s*\(/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const serviceName = m[1];
|
||||
out.push(
|
||||
makeContract(
|
||||
serviceOnlyContractId(serviceName),
|
||||
'provider',
|
||||
filePath,
|
||||
`add_${serviceName}Servicer_to_server`,
|
||||
0.8,
|
||||
{ service: serviceName, source: 'python_servicer' },
|
||||
),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanPythonConsumers(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
// XxxStub(
|
||||
const re = /(\w+)Stub\s*\(/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const name = m[1];
|
||||
// Filter out common false positives
|
||||
if (['Mock', 'Test', 'Fake', 'Stub'].includes(name)) continue;
|
||||
out.push(
|
||||
makeContract(serviceOnlyContractId(name), 'consumer', filePath, `${name}Stub`, 0.7, {
|
||||
service: name,
|
||||
source: 'python_stub',
|
||||
}),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanTsProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
// @GrpcMethod('ServiceName', 'MethodName')
|
||||
const re = /@GrpcMethod\s*\(\s*['"](\w+)['"]\s*,\s*['"](\w+)['"]\s*\)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const serviceName = m[1];
|
||||
const methodName = m[2];
|
||||
const cid = contractId('', serviceName, methodName);
|
||||
out.push(
|
||||
makeContract(cid, 'provider', filePath, `${serviceName}.${methodName}`, 0.8, {
|
||||
service: serviceName,
|
||||
method: methodName,
|
||||
source: 'ts_grpc_method',
|
||||
}),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private dedupe(items: ExtractedContract[]): ExtractedContract[] {
|
||||
const seen = new Set<string>();
|
||||
const out: ExtractedContract[] = [];
|
||||
for (const c of items) {
|
||||
const k = `${c.contractId}|${c.role}|${c.symbolRef.filePath}`;
|
||||
if (seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
out.push(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { glob } from 'glob';
|
||||
import type { ContractExtractor, CypherExecutor } from '../contract-extractor.js';
|
||||
import type { ExtractedContract, RepoHandle } from '../types.js';
|
||||
|
||||
const HANDLES_ROUTE_QUERY = `
|
||||
MATCH (handlerFile:File)-[r:CodeRelation {type: 'HANDLES_ROUTE'}]->(route:Route)
|
||||
RETURN handlerFile.id AS fileId, handlerFile.filePath AS filePath,
|
||||
route.name AS routePath, route.id AS routeId,
|
||||
route.responseKeys AS responseKeys,
|
||||
r.reason AS routeSource`;
|
||||
|
||||
const FETCHES_QUERY = `
|
||||
MATCH (callerFile:File)-[r:CodeRelation {type: 'FETCHES'}]->(route:Route)
|
||||
RETURN callerFile.id AS fileId, callerFile.filePath AS filePath,
|
||||
route.name AS routePath, route.id AS routeId,
|
||||
r.reason AS fetchReason`;
|
||||
|
||||
const CONTAINS_QUERY = `
|
||||
MATCH (file:File {id: $fileId})<-[:CodeRelation {type: 'CONTAINS'}]-(sym)
|
||||
WHERE sym.startLine IS NOT NULL
|
||||
RETURN sym.id AS uid, sym.name AS name, sym.filePath AS filePath, labels(sym) AS labels
|
||||
ORDER BY sym.startLine`;
|
||||
|
||||
export function normalizeHttpPath(p: string): string {
|
||||
let s = p.trim().split('?')[0].toLowerCase().replace(/\/+$/, '');
|
||||
s = s.replace(/:\w+/g, '{param}');
|
||||
s = s.replace(/\{[^}]+\}/g, '{param}');
|
||||
s = s.replace(/\[[^\]]+\]/g, '{param}');
|
||||
return s;
|
||||
}
|
||||
|
||||
function methodFromRouteReason(reason: string): string | null {
|
||||
const r = reason || '';
|
||||
if (/GetMapping|decorator-Get/i.test(r)) return 'GET';
|
||||
if (/PostMapping|decorator-Post/i.test(r)) return 'POST';
|
||||
if (/PutMapping|decorator-Put/i.test(r)) return 'PUT';
|
||||
if (/DeleteMapping|decorator-Delete/i.test(r)) return 'DELETE';
|
||||
if (/PatchMapping|decorator-Patch/i.test(r)) return 'PATCH';
|
||||
return null;
|
||||
}
|
||||
|
||||
function contractIdFor(method: string, pathNorm: string): string {
|
||||
return `http::${method.toUpperCase()}::${pathNorm}`;
|
||||
}
|
||||
|
||||
function readSafe(repoPath: string, rel: string): string | null {
|
||||
const abs = path.resolve(repoPath, rel);
|
||||
const base = path.resolve(repoPath);
|
||||
const relToBase = path.relative(base, abs);
|
||||
if (relToBase.startsWith('..') || path.isAbsolute(relToBase)) return null;
|
||||
try {
|
||||
return fs.readFileSync(abs, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function pickJavaHandlerName(
|
||||
content: string,
|
||||
routePath: string,
|
||||
httpMethod: string,
|
||||
): string | null {
|
||||
const tail = routePath.split('/').filter(Boolean).pop() || '';
|
||||
const mapNames: Record<string, string> = {
|
||||
GET: 'GetMapping',
|
||||
POST: 'PostMapping',
|
||||
PUT: 'PutMapping',
|
||||
DELETE: 'DeleteMapping',
|
||||
PATCH: 'PatchMapping',
|
||||
};
|
||||
const ann = mapNames[httpMethod] || 'GetMapping';
|
||||
const lines = content.split(/\r?\n/);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (!line.includes(`@${ann}`)) continue;
|
||||
if (!line.includes(`"${tail}"`) && !line.includes(`'${tail}'`) && tail && !line.includes(tail))
|
||||
continue;
|
||||
for (let j = i + 1; j < Math.min(i + 8, lines.length); j++) {
|
||||
const m = lines[j].match(/(?:public|protected|private)\s+[\w<>,\s\[\]]+\s+(\w+)\s*\(/);
|
||||
if (m) return m[1];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickSymbolUid(
|
||||
rows: Record<string, unknown>[],
|
||||
preferredName: string | null,
|
||||
): { uid: string; name: string; filePath: string } {
|
||||
const norm = (x: unknown) => String(x ?? '');
|
||||
const labeled = rows.filter((r) => {
|
||||
const labels = r.labels ?? r[3];
|
||||
const s = JSON.stringify(labels);
|
||||
return s.includes('Method') || s.includes('Function');
|
||||
});
|
||||
const pool = labeled.length > 0 ? labeled : rows;
|
||||
if (preferredName) {
|
||||
const hit = pool.find((r) => norm(r.name ?? r[1]) === preferredName);
|
||||
if (hit) {
|
||||
return {
|
||||
uid: norm(hit.uid ?? hit[0]),
|
||||
name: norm(hit.name ?? hit[1]),
|
||||
filePath: norm(hit.filePath ?? hit[2]),
|
||||
};
|
||||
}
|
||||
}
|
||||
const first = pool[0] || rows[0];
|
||||
return {
|
||||
uid: norm(first?.uid ?? first?.[0]),
|
||||
name: norm(first?.name ?? first?.[1]),
|
||||
filePath: norm(first?.filePath ?? first?.[2]),
|
||||
};
|
||||
}
|
||||
|
||||
export class HttpRouteExtractor implements ContractExtractor {
|
||||
type = 'http' as const;
|
||||
|
||||
async canExtract(_repo: RepoHandle): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
async extract(
|
||||
dbExecutor: CypherExecutor | null,
|
||||
repoPath: string,
|
||||
repo: RepoHandle,
|
||||
): Promise<ExtractedContract[]> {
|
||||
const graphP = dbExecutor != null ? await this.extractProvidersGraph(dbExecutor, repoPath) : [];
|
||||
const providers = graphP.length > 0 ? graphP : await this.extractProvidersSourceScan(repoPath);
|
||||
|
||||
const graphC = dbExecutor != null ? await this.extractConsumersGraph(dbExecutor, repoPath) : [];
|
||||
const consumers = graphC.length > 0 ? graphC : await this.extractConsumersSourceScan(repoPath);
|
||||
|
||||
return [...providers, ...consumers];
|
||||
}
|
||||
|
||||
private async extractProvidersGraph(
|
||||
db: CypherExecutor,
|
||||
repoPath: string,
|
||||
): Promise<ExtractedContract[]> {
|
||||
const out: ExtractedContract[] = [];
|
||||
let rows: Record<string, unknown>[];
|
||||
try {
|
||||
rows = await db(HANDLES_ROUTE_QUERY);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
const filePath = String(row.filePath ?? '');
|
||||
const routePath = String(row.routePath ?? '');
|
||||
const routeSource = String(row.routeSource ?? row.routeReason ?? '');
|
||||
let method = methodFromRouteReason(routeSource);
|
||||
const content = readSafe(repoPath, filePath);
|
||||
if (!method && content) {
|
||||
method = this.inferMethodFromFileScan(content, routePath, 'provider');
|
||||
}
|
||||
if (!method) method = 'GET';
|
||||
|
||||
const pathNorm = normalizeHttpPath(routePath);
|
||||
const cid = contractIdFor(method, pathNorm);
|
||||
const handlerName =
|
||||
content && routePath ? pickJavaHandlerName(content, routePath, method) : null;
|
||||
|
||||
let symbolUid = '';
|
||||
let symbolName = path.basename(filePath) || 'handler';
|
||||
let symPath = filePath;
|
||||
const fileId = row.fileId ?? row[0];
|
||||
if (fileId) {
|
||||
try {
|
||||
const syms = await db(CONTAINS_QUERY, { fileId });
|
||||
if (syms.length > 0) {
|
||||
const picked = pickSymbolUid(syms, handlerName);
|
||||
symbolUid = picked.uid;
|
||||
symbolName = picked.name;
|
||||
symPath = picked.filePath || filePath;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
out.push({
|
||||
contractId: cid,
|
||||
type: 'http',
|
||||
role: 'provider',
|
||||
symbolUid,
|
||||
symbolRef: { filePath: symPath, name: symbolName },
|
||||
symbolName,
|
||||
confidence: 0.9,
|
||||
meta: {
|
||||
method,
|
||||
path: pathNorm,
|
||||
pathSegments: pathNorm.split('/').filter(Boolean),
|
||||
extractionStrategy: 'graph_assisted',
|
||||
routeSource,
|
||||
},
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private inferMethodFromFileScan(
|
||||
content: string,
|
||||
routePath: string,
|
||||
_role: string,
|
||||
): string | null {
|
||||
const tail = routePath.split('/').filter(Boolean).pop() || '';
|
||||
for (const m of ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const) {
|
||||
const mapNames: Record<string, string> = {
|
||||
GET: 'GetMapping',
|
||||
POST: 'PostMapping',
|
||||
PUT: 'PutMapping',
|
||||
DELETE: 'DeleteMapping',
|
||||
PATCH: 'PatchMapping',
|
||||
};
|
||||
if (
|
||||
content.includes(`@${mapNames[m]}`) &&
|
||||
(content.includes(tail) || routePath.includes(tail))
|
||||
) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async extractProvidersSourceScan(repoPath: string): Promise<ExtractedContract[]> {
|
||||
const files = await glob('**/*.{ts,tsx,js,jsx,java,vue,svelte,php,py}', {
|
||||
cwd: repoPath,
|
||||
ignore: ['**/node_modules/**', '**/.git/**', '**/dist/**', '**/build/**'],
|
||||
nodir: true,
|
||||
});
|
||||
const out: ExtractedContract[] = [];
|
||||
for (const rel of files) {
|
||||
const content = readSafe(repoPath, rel);
|
||||
if (!content) continue;
|
||||
out.push(...this.scanSpringProviders(content, rel));
|
||||
out.push(...this.scanExpressProviders(content, rel));
|
||||
out.push(...this.scanLaravelProviders(content, rel));
|
||||
out.push(...this.scanFastApiProviders(content, rel));
|
||||
}
|
||||
return this.dedupeContracts(out);
|
||||
}
|
||||
|
||||
private dedupeContracts(items: ExtractedContract[]): ExtractedContract[] {
|
||||
const seen = new Set<string>();
|
||||
const out: ExtractedContract[] = [];
|
||||
for (const c of items) {
|
||||
const k = `${c.contractId}|${c.symbolRef.filePath}|${c.symbolRef.name}`;
|
||||
if (seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
out.push(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanSpringProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
// Skip Feign/client interfaces — annotated methods in interfaces are
|
||||
// consumers (Feign, JAX-RS proxies), not provider endpoints.
|
||||
// Anchored to line start (with optional access modifier) so we do not
|
||||
// match "interface" inside comments or string literals.
|
||||
if (
|
||||
/^\s*(?:public\s+)?interface\s+\w+/m.test(content) &&
|
||||
!/@(?:Rest)?Controller\b/.test(content)
|
||||
) {
|
||||
return out;
|
||||
}
|
||||
|
||||
let classPrefix = '';
|
||||
const classRm = content.match(/@RequestMapping\s*\(\s*"([^"]+)"/);
|
||||
if (classRm) classPrefix = classRm[1].replace(/\/+$/, '');
|
||||
|
||||
const re = /@(Get|Post|Put|Delete|Patch)Mapping\s*\(\s*"([^"]+)"/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const method = m[1].toUpperCase();
|
||||
let p = m[2];
|
||||
if (classPrefix) p = `${classPrefix}/${p.replace(/^\//, '')}`;
|
||||
const pathNorm = normalizeHttpPath(p);
|
||||
const sub = content.slice(m.index);
|
||||
const nameM = sub.match(/(?:public|protected|private)\s+[\w<>,\s\[\]]+\s+(\w+)\s*\(/);
|
||||
const name = nameM ? nameM[1] : m[0];
|
||||
out.push(this.makeProvider(filePath, method, pathNorm, name, 0.8));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanExpressProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
const re = /(?:router|app)\.(get|post|put|delete|patch)\s*\(\s*['"]([^'"]+)['"]/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const method = m[1].toUpperCase();
|
||||
const pathNorm = normalizeHttpPath(m[2]);
|
||||
out.push(this.makeProvider(filePath, method, pathNorm, 'handler', 0.8));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanLaravelProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
const re = /Route::(get|post|put|delete|patch)\s*\(\s*['"]([^'"]+)['"]/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const method = m[1].toUpperCase();
|
||||
const pathNorm = normalizeHttpPath(m[2]);
|
||||
out.push(this.makeProvider(filePath, method, pathNorm, 'route', 0.8));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private scanFastApiProviders(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
const re = /@app\.(get|post|put|delete|patch)\s*\(\s*['"]([^'"]+)['"]/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const method = m[1].toUpperCase();
|
||||
const pathNorm = normalizeHttpPath(m[2]);
|
||||
out.push(this.makeProvider(filePath, method, pathNorm, 'handler', 0.8));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private makeProvider(
|
||||
filePath: string,
|
||||
method: string,
|
||||
pathNorm: string,
|
||||
name: string,
|
||||
confidence: number,
|
||||
): ExtractedContract {
|
||||
const cid = contractIdFor(method, pathNorm);
|
||||
return {
|
||||
contractId: cid,
|
||||
type: 'http',
|
||||
role: 'provider',
|
||||
symbolUid: '',
|
||||
symbolRef: { filePath, name },
|
||||
symbolName: name,
|
||||
confidence,
|
||||
meta: {
|
||||
method,
|
||||
path: pathNorm,
|
||||
pathSegments: pathNorm.split('/').filter(Boolean),
|
||||
extractionStrategy: 'source_scan',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async extractConsumersGraph(
|
||||
db: CypherExecutor,
|
||||
repoPath: string,
|
||||
): Promise<ExtractedContract[]> {
|
||||
const out: ExtractedContract[] = [];
|
||||
let rows: Record<string, unknown>[];
|
||||
try {
|
||||
rows = await db(FETCHES_QUERY);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
for (const row of rows) {
|
||||
const filePath = String(row.filePath ?? '');
|
||||
const routePath = String(row.routePath ?? '');
|
||||
const pathNorm = normalizeHttpPath(routePath);
|
||||
let method = 'GET';
|
||||
const content = readSafe(repoPath, filePath);
|
||||
if (content) {
|
||||
const inferred = this.inferFetchMethod(content, pathNorm);
|
||||
if (inferred) method = inferred;
|
||||
}
|
||||
const cid = contractIdFor(method, pathNorm);
|
||||
let symbolUid = '';
|
||||
let symbolName = 'fetch';
|
||||
let symPath = filePath;
|
||||
const fileId = row.fileId ?? row[0];
|
||||
if (fileId) {
|
||||
try {
|
||||
const syms = await db(CONTAINS_QUERY, { fileId });
|
||||
if (syms.length > 0) {
|
||||
const picked = pickSymbolUid(syms, null);
|
||||
symbolUid = picked.uid;
|
||||
symbolName = picked.name;
|
||||
symPath = picked.filePath || filePath;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
out.push({
|
||||
contractId: cid,
|
||||
type: 'http',
|
||||
role: 'consumer',
|
||||
symbolUid,
|
||||
symbolRef: { filePath: symPath, name: symbolName },
|
||||
symbolName,
|
||||
confidence: 0.9,
|
||||
meta: {
|
||||
method,
|
||||
path: pathNorm,
|
||||
extractionStrategy: 'graph_assisted',
|
||||
fetchReason: String(row.fetchReason ?? ''),
|
||||
},
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private inferFetchMethod(content: string, pathNorm: string): string | null {
|
||||
const esc = pathNorm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const fetchRe = new RegExp(
|
||||
`fetch\\s*\\(\\s*['"\`]([^'"\`]*${esc}[^'"\`]*)['"\`]\\s*,\\s*\\{[^}]*method:\\s*['"](\\w+)['"]`,
|
||||
'i',
|
||||
);
|
||||
const m = content.match(fetchRe);
|
||||
if (m) return m[2].toUpperCase();
|
||||
return null;
|
||||
}
|
||||
|
||||
private async extractConsumersSourceScan(repoPath: string): Promise<ExtractedContract[]> {
|
||||
const files = await glob('**/*.{ts,tsx,js,jsx,vue,svelte}', {
|
||||
cwd: repoPath,
|
||||
ignore: ['**/node_modules/**', '**/.git/**'],
|
||||
nodir: true,
|
||||
});
|
||||
const out: ExtractedContract[] = [];
|
||||
for (const rel of files) {
|
||||
const content = readSafe(repoPath, rel);
|
||||
if (!content) continue;
|
||||
out.push(...this.scanFetchConsumers(content, rel));
|
||||
out.push(...this.scanAxiosConsumers(content, rel));
|
||||
}
|
||||
return this.dedupeContracts(out);
|
||||
}
|
||||
|
||||
private scanFetchConsumers(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
const re =
|
||||
/fetch\s*\(\s*['"`]([^'"`]+)['"`](?:\s*,\s*\{[^}]*method:\s*['"](\w+)['"][^}]*\})?\s*\)/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const pathNorm = normalizeHttpPath(this.templateToPattern(m[1]));
|
||||
const method = (m[2] || 'GET').toUpperCase();
|
||||
out.push(this.makeConsumer(filePath, method, pathNorm, 0.7));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private templateToPattern(url: string): string {
|
||||
return url.replace(/\$\{[^}]+\}/g, '{param}');
|
||||
}
|
||||
|
||||
private scanAxiosConsumers(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
const re = /axios\.(get|post|put|delete|patch)\s*\(\s*[`'"]([^`'"]+)[`'"]/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const method = m[1].toUpperCase();
|
||||
const pathNorm = normalizeHttpPath(this.templateToPattern(m[2]));
|
||||
out.push(this.makeConsumer(filePath, method, pathNorm, 0.7));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private makeConsumer(
|
||||
filePath: string,
|
||||
method: string,
|
||||
pathNorm: string,
|
||||
confidence: number,
|
||||
): ExtractedContract {
|
||||
return {
|
||||
contractId: contractIdFor(method, pathNorm),
|
||||
type: 'http',
|
||||
role: 'consumer',
|
||||
symbolUid: '',
|
||||
symbolRef: { filePath, name: 'fetch' },
|
||||
symbolName: 'fetch',
|
||||
confidence,
|
||||
meta: {
|
||||
method,
|
||||
path: pathNorm,
|
||||
extractionStrategy: 'source_scan',
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { glob } from 'glob';
|
||||
import type { ContractExtractor, CypherExecutor } from '../contract-extractor.js';
|
||||
import type { ExtractedContract, RepoHandle } from '../types.js';
|
||||
|
||||
type Broker = 'kafka' | 'rabbitmq' | 'nats';
|
||||
|
||||
function readSafe(repoPath: string, rel: string): string | null {
|
||||
const abs = path.resolve(repoPath, rel);
|
||||
const base = path.resolve(repoPath);
|
||||
const relToBase = path.relative(base, abs);
|
||||
if (relToBase.startsWith('..') || path.isAbsolute(relToBase)) return null;
|
||||
try {
|
||||
return fs.readFileSync(abs, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function makeContract(
|
||||
topicName: string,
|
||||
role: 'provider' | 'consumer',
|
||||
filePath: string,
|
||||
symbolName: string,
|
||||
confidence: number,
|
||||
broker: Broker,
|
||||
): ExtractedContract {
|
||||
return {
|
||||
contractId: `topic::${topicName}`,
|
||||
type: 'topic',
|
||||
role,
|
||||
symbolUid: '',
|
||||
symbolRef: { filePath: filePath.replace(/\\/g, '/'), name: symbolName },
|
||||
symbolName,
|
||||
confidence,
|
||||
meta: {
|
||||
broker,
|
||||
topicName,
|
||||
extractionStrategy: 'source_scan',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface PatternDef {
|
||||
regex: RegExp;
|
||||
role: 'provider' | 'consumer';
|
||||
broker: Broker;
|
||||
confidence: number;
|
||||
topicGroup: number;
|
||||
symbolName: string;
|
||||
}
|
||||
|
||||
// --- Kafka patterns ---
|
||||
const KAFKA_PATTERNS: PatternDef[] = [
|
||||
// Java: @KafkaListener(topics = "xxx")
|
||||
{
|
||||
regex: /@KafkaListener\s*\(\s*topics\s*=\s*"([^"]+)"/g,
|
||||
role: 'consumer',
|
||||
broker: 'kafka',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'kafkaListener',
|
||||
},
|
||||
// Java: kafkaTemplate.send("xxx"
|
||||
{
|
||||
regex: /kafkaTemplate\.send\s*\(\s*"([^"]+)"/gi,
|
||||
role: 'provider',
|
||||
broker: 'kafka',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'kafkaTemplate.send',
|
||||
},
|
||||
// Node: producer.send({ topic: 'xxx'
|
||||
{
|
||||
regex: /producer\.send\s*\(\s*\{\s*topic:\s*['"]([^'"]+)['"]/g,
|
||||
role: 'provider',
|
||||
broker: 'kafka',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'producer.send',
|
||||
},
|
||||
// Node: consumer.subscribe({ topic: 'xxx'
|
||||
{
|
||||
regex: /consumer\.subscribe\s*\(\s*\{\s*topic:\s*['"]([^'"]+)['"]/g,
|
||||
role: 'consumer',
|
||||
broker: 'kafka',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'consumer.subscribe',
|
||||
},
|
||||
// Go: consumer.ConsumePartition("xxx"
|
||||
{
|
||||
regex: /\.ConsumePartition\s*\(\s*"([^"]+)"/g,
|
||||
role: 'consumer',
|
||||
broker: 'kafka',
|
||||
confidence: 0.7,
|
||||
topicGroup: 1,
|
||||
symbolName: 'ConsumePartition',
|
||||
},
|
||||
// Python: KafkaConsumer('xxx'
|
||||
{
|
||||
regex: /KafkaConsumer\s*\(\s*['"]([^'"]+)['"]/g,
|
||||
role: 'consumer',
|
||||
broker: 'kafka',
|
||||
confidence: 0.7,
|
||||
topicGroup: 1,
|
||||
symbolName: 'KafkaConsumer',
|
||||
},
|
||||
// Python: producer.send('xxx' or producer.produce('xxx'
|
||||
{
|
||||
regex: /producer\.(?:send|produce)\s*\(\s*['"]([^'"]+)['"]/g,
|
||||
role: 'provider',
|
||||
broker: 'kafka',
|
||||
confidence: 0.7,
|
||||
topicGroup: 1,
|
||||
symbolName: 'producer.send',
|
||||
},
|
||||
];
|
||||
|
||||
// --- RabbitMQ patterns ---
|
||||
const RABBITMQ_PATTERNS: PatternDef[] = [
|
||||
// Java: @RabbitListener(queues = "xxx")
|
||||
{
|
||||
regex: /@RabbitListener\s*\(\s*queues\s*=\s*"([^"]+)"/g,
|
||||
role: 'consumer',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'rabbitListener',
|
||||
},
|
||||
// Java: rabbitTemplate.convertAndSend("xxx"
|
||||
{
|
||||
regex: /rabbitTemplate\.convertAndSend\s*\(\s*"([^"]+)"/gi,
|
||||
role: 'provider',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'rabbitTemplate.convertAndSend',
|
||||
},
|
||||
// Node: channel.consume("xxx"
|
||||
{
|
||||
regex: /channel\.consume\s*\(\s*"([^"]+)"/g,
|
||||
role: 'consumer',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'channel.consume',
|
||||
},
|
||||
// Node: channel.publish("xxx"
|
||||
{
|
||||
regex: /channel\.publish\s*\(\s*"([^"]+)"/g,
|
||||
role: 'provider',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'channel.publish',
|
||||
},
|
||||
// Node: channel.sendToQueue("xxx"
|
||||
{
|
||||
regex: /channel\.sendToQueue\s*\(\s*"([^"]+)"/g,
|
||||
role: 'provider',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'channel.sendToQueue',
|
||||
},
|
||||
// Python: channel.basic_consume(queue='xxx'
|
||||
{
|
||||
regex: /channel\.basic_consume\s*\(\s*queue\s*=\s*['"]([^'"]+)['"]/g,
|
||||
role: 'consumer',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.7,
|
||||
topicGroup: 1,
|
||||
symbolName: 'basic_consume',
|
||||
},
|
||||
// Python: channel.basic_publish(exchange='xxx'
|
||||
{
|
||||
regex: /channel\.basic_publish\s*\([^)]*exchange\s*=\s*['"]([^'"]+)['"]/g,
|
||||
role: 'provider',
|
||||
broker: 'rabbitmq',
|
||||
confidence: 0.7,
|
||||
topicGroup: 1,
|
||||
symbolName: 'basic_publish',
|
||||
},
|
||||
];
|
||||
|
||||
// --- NATS patterns ---
|
||||
const NATS_PATTERNS: PatternDef[] = [
|
||||
// Go/Node: nc.Subscribe("xxx" or nc.subscribe("xxx"
|
||||
{
|
||||
regex: /nc\.(?:S|s)ubscribe\s*\(\s*"([^"]+)"/g,
|
||||
role: 'consumer',
|
||||
broker: 'nats',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'nc.Subscribe',
|
||||
},
|
||||
// Go/Node: nc.Publish("xxx" or nc.publish("xxx"
|
||||
{
|
||||
regex: /nc\.(?:P|p)ublish\s*\(\s*"([^"]+)"/g,
|
||||
role: 'provider',
|
||||
broker: 'nats',
|
||||
confidence: 0.8,
|
||||
topicGroup: 1,
|
||||
symbolName: 'nc.Publish',
|
||||
},
|
||||
];
|
||||
|
||||
const ALL_PATTERNS: PatternDef[] = [...KAFKA_PATTERNS, ...RABBITMQ_PATTERNS, ...NATS_PATTERNS];
|
||||
|
||||
export class TopicExtractor implements ContractExtractor {
|
||||
type = 'topic' as const;
|
||||
|
||||
async canExtract(_repo: RepoHandle): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
async extract(
|
||||
_dbExecutor: CypherExecutor | null,
|
||||
repoPath: string,
|
||||
_repo: RepoHandle,
|
||||
): Promise<ExtractedContract[]> {
|
||||
const files = await glob('**/*.{ts,tsx,js,jsx,java,go,py}', {
|
||||
cwd: repoPath,
|
||||
ignore: ['**/node_modules/**', '**/.git/**', '**/vendor/**', '**/dist/**', '**/build/**'],
|
||||
nodir: true,
|
||||
});
|
||||
|
||||
const out: ExtractedContract[] = [];
|
||||
for (const rel of files) {
|
||||
const content = readSafe(repoPath, rel);
|
||||
if (!content) continue;
|
||||
out.push(...this.scanFile(content, rel));
|
||||
}
|
||||
|
||||
return this.dedupe(out);
|
||||
}
|
||||
|
||||
private scanFile(content: string, filePath: string): ExtractedContract[] {
|
||||
const out: ExtractedContract[] = [];
|
||||
|
||||
for (const pattern of ALL_PATTERNS) {
|
||||
// Reset regex state for each file
|
||||
const re = new RegExp(pattern.regex.source, pattern.regex.flags);
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(content)) !== null) {
|
||||
const topicName = m[pattern.topicGroup];
|
||||
if (!topicName) continue;
|
||||
out.push(
|
||||
makeContract(
|
||||
topicName,
|
||||
pattern.role,
|
||||
filePath,
|
||||
pattern.symbolName,
|
||||
pattern.confidence,
|
||||
pattern.broker,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
private dedupe(items: ExtractedContract[]): ExtractedContract[] {
|
||||
const seen = new Set<string>();
|
||||
const out: ExtractedContract[] = [];
|
||||
for (const c of items) {
|
||||
const k = `${c.contractId}|${c.role}|${c.symbolRef.filePath}`;
|
||||
if (seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
out.push(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import type { StoredContract, CrossLink } from './types.js';
|
||||
|
||||
export interface MatchResult {
|
||||
matched: CrossLink[];
|
||||
unmatched: StoredContract[];
|
||||
}
|
||||
|
||||
export interface WildcardMatchResult {
|
||||
matched: CrossLink[];
|
||||
remaining: StoredContract[];
|
||||
}
|
||||
|
||||
function isGrpcWildcard(cid: string): boolean {
|
||||
return cid.startsWith('grpc::') && cid.endsWith('/*');
|
||||
}
|
||||
|
||||
export function normalizeContractId(id: string): string {
|
||||
const colonIdx = id.indexOf('::');
|
||||
if (colonIdx === -1) return id;
|
||||
|
||||
const type = id.substring(0, colonIdx);
|
||||
const rest = id.substring(colonIdx + 2);
|
||||
|
||||
switch (type) {
|
||||
case 'http': {
|
||||
const parts = rest.split('::');
|
||||
if (parts.length >= 2) {
|
||||
const method = parts[0].toUpperCase();
|
||||
let pathPart = parts.slice(1).join('::');
|
||||
pathPart = pathPart.replace(/\/+$/, '');
|
||||
return `http::${method}::${pathPart}`;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
case 'grpc': {
|
||||
// Canonical form: `grpc::<lowercased-package-or-service>[/<method>]`.
|
||||
//
|
||||
// The package/service segment is lowercased because gRPC package
|
||||
// names are effectively case-insensitive across language bindings
|
||||
// (`auth.AuthService`, `auth.authservice`, `AUTH.AUTHSERVICE` all
|
||||
// describe the same wire protocol service). The RPC method segment
|
||||
// is preserved as-is because the HTTP/2 path used on the wire is
|
||||
// case-sensitive per the gRPC spec (`/Service/MethodName`), and
|
||||
// method names in generated clients match the proto source exactly.
|
||||
//
|
||||
// A package-only id (no slash) and a package/method id are treated
|
||||
// as DISTINCT canonical forms: `grpc::userservice` does not match
|
||||
// `grpc::userservice/Login`. That's by design — callers that want
|
||||
// service-level manifest matching against method-level providers
|
||||
// should use the gRPC wildcard form `grpc::UserService/*` which is
|
||||
// handled by runWildcardMatch below.
|
||||
const slashIdx = rest.indexOf('/');
|
||||
if (slashIdx > 0) {
|
||||
const pkg = rest.substring(0, slashIdx).toLowerCase();
|
||||
const method = rest.substring(slashIdx);
|
||||
return `grpc::${pkg}${method}`;
|
||||
}
|
||||
if (slashIdx === 0) {
|
||||
// Malformed "/method" with leading slash — keep as-is so two
|
||||
// equally malformed ids can still match each other.
|
||||
return `grpc::${rest}`;
|
||||
}
|
||||
// No slash: package/service only. Lowercase to match the package
|
||||
// segment produced by the pkg/method branch above.
|
||||
return `grpc::${rest.toLowerCase()}`;
|
||||
}
|
||||
case 'topic':
|
||||
return `topic::${rest.trim().toLowerCase()}`;
|
||||
case 'lib':
|
||||
return `lib::${rest.toLowerCase()}`;
|
||||
default:
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
function findMatchingKeys(contractId: string, index: Map<string, StoredContract[]>): string[] {
|
||||
const normalized = normalizeContractId(contractId);
|
||||
if (index.has(normalized)) return [normalized];
|
||||
|
||||
if (normalized.startsWith('http::*::')) {
|
||||
const pathPart = normalized.substring('http::*::'.length);
|
||||
const matches: string[] = [];
|
||||
for (const key of index.keys()) {
|
||||
if (key.startsWith('http::') && key.endsWith(`::${pathPart}`)) {
|
||||
matches.push(key);
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export function buildProviderIndex(contracts: StoredContract[]): Map<string, StoredContract[]> {
|
||||
const providers = contracts.filter((c) => c.role === 'provider');
|
||||
const index = new Map<string, StoredContract[]>();
|
||||
for (const p of providers) {
|
||||
const key = normalizeContractId(p.contractId);
|
||||
const list = index.get(key) || [];
|
||||
list.push(p);
|
||||
index.set(key, list);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
export function runExactMatch(
|
||||
contracts: StoredContract[],
|
||||
providerIndex?: Map<string, StoredContract[]>,
|
||||
): MatchResult {
|
||||
const index = providerIndex ?? buildProviderIndex(contracts);
|
||||
|
||||
// Skip gRPC wildcard consumers — they go to wildcard pass only
|
||||
const consumers = contracts.filter((c) => c.role === 'consumer' && !isGrpcWildcard(c.contractId));
|
||||
|
||||
const matched: CrossLink[] = [];
|
||||
const matchedConsumerIds = new Set<string>();
|
||||
const matchedProviderIds = new Set<string>();
|
||||
|
||||
for (const consumer of consumers) {
|
||||
const matchingKeys = findMatchingKeys(consumer.contractId, index);
|
||||
if (matchingKeys.length === 0) continue;
|
||||
|
||||
const allMatchingProviders = matchingKeys.flatMap((k) => index.get(k) || []);
|
||||
for (const provider of allMatchingProviders) {
|
||||
if (provider.repo === consumer.repo) {
|
||||
if (!provider.service || !consumer.service || provider.service === consumer.service) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
matched.push({
|
||||
from: {
|
||||
repo: consumer.repo,
|
||||
service: consumer.service,
|
||||
symbolUid: consumer.symbolUid,
|
||||
symbolRef: consumer.symbolRef,
|
||||
},
|
||||
to: {
|
||||
repo: provider.repo,
|
||||
service: provider.service,
|
||||
symbolUid: provider.symbolUid,
|
||||
symbolRef: provider.symbolRef,
|
||||
},
|
||||
type: consumer.type,
|
||||
contractId: consumer.contractId,
|
||||
matchType: 'exact',
|
||||
confidence: 1.0,
|
||||
});
|
||||
|
||||
matchedConsumerIds.add(`${consumer.repo}::${consumer.contractId}`);
|
||||
matchedProviderIds.add(`${provider.repo}::${provider.contractId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// normalUnmatched: contracts that weren't matched in exact pass
|
||||
const normalUnmatched = contracts.filter((c) => {
|
||||
if (isGrpcWildcard(c.contractId)) return false; // excluded from exact, handled separately
|
||||
const id = `${c.repo}::${c.contractId}`;
|
||||
return c.role === 'provider' ? !matchedProviderIds.has(id) : !matchedConsumerIds.has(id);
|
||||
});
|
||||
|
||||
// Re-add gRPC wildcard contracts — they were never in exact matching
|
||||
const grpcWildcards = contracts.filter((c) => isGrpcWildcard(c.contractId));
|
||||
const unmatched = [...normalUnmatched, ...grpcWildcards];
|
||||
|
||||
return { matched, unmatched };
|
||||
}
|
||||
|
||||
export function runWildcardMatch(
|
||||
unmatched: StoredContract[],
|
||||
providerIndex: Map<string, StoredContract[]>,
|
||||
): WildcardMatchResult {
|
||||
const wildcardConsumers = unmatched.filter(
|
||||
(c) => c.role === 'consumer' && isGrpcWildcard(c.contractId),
|
||||
);
|
||||
const matched: CrossLink[] = [];
|
||||
const matchedConsumerIds = new Set<string>();
|
||||
|
||||
for (const consumer of wildcardConsumers) {
|
||||
const normalized = normalizeContractId(consumer.contractId);
|
||||
// "grpc::com.example.userservice/*" → "com.example.userservice"
|
||||
// "grpc::userservice/*" → "userservice"
|
||||
const fqService = normalized.slice(normalized.indexOf('::') + 2, -2); // strip "grpc::" and "/*"
|
||||
|
||||
for (const [key, providers] of providerIndex) {
|
||||
// Only match against non-wildcard gRPC providers (method-level IDs)
|
||||
if (!key.startsWith('grpc::') || key.endsWith('/*')) continue;
|
||||
const afterPrefix = key.slice(6); // strip "grpc::"
|
||||
const slashIdx = afterPrefix.indexOf('/');
|
||||
if (slashIdx < 0) continue;
|
||||
const providerFqService = afterPrefix.slice(0, slashIdx);
|
||||
|
||||
// Match: exact FQ service, or bare-name match when consumer has no package
|
||||
const isMatch =
|
||||
providerFqService === fqService ||
|
||||
(!fqService.includes('.') && providerFqService.endsWith('.' + fqService));
|
||||
|
||||
if (!isMatch) continue;
|
||||
|
||||
for (const provider of providers) {
|
||||
// Skip same-repo same-service (same logic as runExactMatch)
|
||||
if (provider.repo === consumer.repo) {
|
||||
if (!provider.service || !consumer.service || provider.service === consumer.service) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
matched.push({
|
||||
from: {
|
||||
repo: consumer.repo,
|
||||
service: consumer.service,
|
||||
symbolUid: consumer.symbolUid,
|
||||
symbolRef: consumer.symbolRef,
|
||||
},
|
||||
to: {
|
||||
repo: provider.repo,
|
||||
service: provider.service,
|
||||
symbolUid: provider.symbolUid,
|
||||
symbolRef: provider.symbolRef,
|
||||
},
|
||||
type: consumer.type,
|
||||
contractId: consumer.contractId, // consumer's wildcard ID
|
||||
matchType: 'wildcard',
|
||||
confidence: Math.min(provider.confidence, consumer.confidence),
|
||||
});
|
||||
matchedConsumerIds.add(`${consumer.repo}::${consumer.contractId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const remaining = unmatched.filter((c) => {
|
||||
if (c.role !== 'consumer' || !isGrpcWildcard(c.contractId)) return true;
|
||||
return !matchedConsumerIds.has(`${c.repo}::${c.contractId}`);
|
||||
});
|
||||
|
||||
return { matched, remaining };
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { CrossLink, CrossLinkEndpoint, StoredContract } from './types.js';
|
||||
|
||||
function contractKey(contract: StoredContract): string {
|
||||
return [contract.repo, contract.contractId, contract.role, contract.symbolRef.filePath].join(
|
||||
'\0',
|
||||
);
|
||||
}
|
||||
|
||||
function endpointKey(endpoint: CrossLinkEndpoint): string {
|
||||
return [
|
||||
endpoint.repo,
|
||||
endpoint.service ?? '',
|
||||
endpoint.symbolRef.filePath,
|
||||
endpoint.symbolRef.name,
|
||||
].join('\0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Score a contract by how much information it carries, so `dedupeContracts`
|
||||
* can prefer the "richer" record when two contracts collide on the same
|
||||
* `(repo, contractId, role, filePath)` key.
|
||||
*
|
||||
* Weights express a priority ordering, not calibrated probabilities:
|
||||
* +3 — `symbolUid` resolved (tier 1 of the downstream lookup — highest
|
||||
* signal because it's the strongest anchor for cross-impact traversal
|
||||
* and the only one that's robust to renames)
|
||||
* +2 — any of `filePath`, `symbolRef.name`, or `symbolName` that's more
|
||||
* specific than the contractId itself (tier 2 signal — resolves
|
||||
* uniquely in most cases and survives across syncs)
|
||||
* +1 — `service` tag (monorepo attribution — useful but not sufficient
|
||||
* on its own) or non-manifest origin (auto-extracted contracts are
|
||||
* preferred over manifest-declared synthetic ones because the former
|
||||
* are grounded in real source code)
|
||||
*
|
||||
* The absolute numbers don't matter, only their relative ordering.
|
||||
*/
|
||||
function contractRichness(contract: StoredContract): number {
|
||||
let score = 0;
|
||||
if (contract.symbolUid) score += 3;
|
||||
if (contract.symbolRef.filePath) score += 2;
|
||||
if (contract.symbolRef.name && contract.symbolRef.name !== contract.contractId) score += 2;
|
||||
if (contract.symbolName && contract.symbolName !== contract.contractId) score += 2;
|
||||
if (contract.service) score += 1;
|
||||
if (contract.meta.source !== 'manifest') score += 1;
|
||||
return score;
|
||||
}
|
||||
|
||||
function mergeContracts(existing: StoredContract, incoming: StoredContract): StoredContract {
|
||||
const [primary, secondary] =
|
||||
contractRichness(incoming) > contractRichness(existing)
|
||||
? [incoming, existing]
|
||||
: [existing, incoming];
|
||||
const symbolRefName = primary.symbolRef.name || secondary.symbolRef.name;
|
||||
return {
|
||||
...secondary,
|
||||
...primary,
|
||||
symbolUid: primary.symbolUid || secondary.symbolUid,
|
||||
symbolRef: {
|
||||
filePath: primary.symbolRef.filePath || secondary.symbolRef.filePath,
|
||||
name: symbolRefName,
|
||||
},
|
||||
symbolName: primary.symbolName || secondary.symbolName || symbolRefName,
|
||||
confidence: Math.max(existing.confidence, incoming.confidence),
|
||||
service: primary.service ?? secondary.service,
|
||||
meta: { ...secondary.meta, ...primary.meta },
|
||||
};
|
||||
}
|
||||
|
||||
function mergeEndpoints(
|
||||
existing: CrossLinkEndpoint,
|
||||
incoming: CrossLinkEndpoint,
|
||||
): CrossLinkEndpoint {
|
||||
return {
|
||||
repo: existing.repo,
|
||||
service: existing.service ?? incoming.service,
|
||||
symbolUid: existing.symbolUid || incoming.symbolUid,
|
||||
symbolRef: {
|
||||
filePath: existing.symbolRef.filePath || incoming.symbolRef.filePath,
|
||||
name: existing.symbolRef.name || incoming.symbolRef.name,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function crossLinkKey(link: CrossLink): string {
|
||||
return [
|
||||
link.type,
|
||||
link.contractId,
|
||||
link.matchType,
|
||||
endpointKey(link.from),
|
||||
endpointKey(link.to),
|
||||
].join('\0');
|
||||
}
|
||||
|
||||
export function dedupeContracts(items: StoredContract[]): StoredContract[] {
|
||||
const deduped = new Map<string, StoredContract>();
|
||||
for (const contract of items) {
|
||||
const key = contractKey(contract);
|
||||
const existing = deduped.get(key);
|
||||
deduped.set(key, existing ? mergeContracts(existing, contract) : contract);
|
||||
}
|
||||
return [...deduped.values()];
|
||||
}
|
||||
|
||||
export function dedupeCrossLinks(items: CrossLink[]): CrossLink[] {
|
||||
const deduped = new Map<string, CrossLink>();
|
||||
for (const link of items) {
|
||||
const key = crossLinkKey(link);
|
||||
const existing = deduped.get(key);
|
||||
if (!existing) {
|
||||
deduped.set(key, link);
|
||||
continue;
|
||||
}
|
||||
const keepIncoming = link.confidence > existing.confidence;
|
||||
const primary = keepIncoming ? link : existing;
|
||||
const secondary = keepIncoming ? existing : link;
|
||||
deduped.set(key, {
|
||||
...primary,
|
||||
confidence: Math.max(existing.confidence, link.confidence),
|
||||
from: mergeEndpoints(primary.from, secondary.from),
|
||||
to: mergeEndpoints(primary.to, secondary.to),
|
||||
});
|
||||
}
|
||||
return [...deduped.values()];
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
export interface ServiceBoundary {
|
||||
servicePath: string;
|
||||
serviceName: string;
|
||||
markers: string[];
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
const SERVICE_MARKERS = [
|
||||
'package.json',
|
||||
'go.mod',
|
||||
'Dockerfile',
|
||||
'pom.xml',
|
||||
'build.gradle',
|
||||
'build.gradle.kts',
|
||||
'Cargo.toml',
|
||||
'pyproject.toml',
|
||||
'requirements.txt',
|
||||
'mix.exs',
|
||||
] as const;
|
||||
|
||||
const SOURCE_EXTENSIONS = new Set([
|
||||
'.ts',
|
||||
'.tsx',
|
||||
'.js',
|
||||
'.jsx',
|
||||
'.mjs',
|
||||
'.cjs',
|
||||
'.go',
|
||||
'.java',
|
||||
'.kt',
|
||||
'.kts',
|
||||
'.py',
|
||||
'.pyi',
|
||||
'.rs',
|
||||
'.c',
|
||||
'.cpp',
|
||||
'.h',
|
||||
'.hpp',
|
||||
'.cs',
|
||||
'.rb',
|
||||
'.php',
|
||||
'.swift',
|
||||
'.dart',
|
||||
'.ex',
|
||||
'.exs',
|
||||
'.erl',
|
||||
'.proto',
|
||||
]);
|
||||
|
||||
const EXCLUDED_DIRS = new Set([
|
||||
'node_modules',
|
||||
'vendor',
|
||||
'target',
|
||||
'build',
|
||||
'dist',
|
||||
'__pycache__',
|
||||
'.venv',
|
||||
'venv',
|
||||
'.tox',
|
||||
'.mypy_cache',
|
||||
'.gradle',
|
||||
'.mvn',
|
||||
'out',
|
||||
'bin',
|
||||
]);
|
||||
|
||||
export async function detectServiceBoundaries(repoPath: string): Promise<ServiceBoundary[]> {
|
||||
const boundaries: ServiceBoundary[] = [];
|
||||
await walkForBoundaries(repoPath, repoPath, boundaries);
|
||||
return boundaries;
|
||||
}
|
||||
|
||||
async function walkForBoundaries(
|
||||
dir: string,
|
||||
repoRoot: string,
|
||||
results: ServiceBoundary[],
|
||||
): Promise<void> {
|
||||
let entries: import('node:fs').Dirent[];
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const isRoot = path.resolve(dir) === path.resolve(repoRoot);
|
||||
|
||||
const foundMarkers: string[] = [];
|
||||
let hasSourceFiles = false;
|
||||
const subdirs: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith('.') || EXCLUDED_DIRS.has(entry.name)) continue;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
subdirs.push(path.join(dir, entry.name));
|
||||
} else if (entry.isFile()) {
|
||||
if (SERVICE_MARKERS.includes(entry.name as (typeof SERVICE_MARKERS)[number])) {
|
||||
foundMarkers.push(entry.name);
|
||||
}
|
||||
const ext = path.extname(entry.name).toLowerCase();
|
||||
if (SOURCE_EXTENSIONS.has(ext)) {
|
||||
hasSourceFiles = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check subdirectories for source files if not found at this level
|
||||
if (!hasSourceFiles && foundMarkers.length > 0) {
|
||||
hasSourceFiles = await hasSourceFilesInSubdirs(subdirs);
|
||||
}
|
||||
|
||||
if (!isRoot && foundMarkers.length >= 1 && hasSourceFiles) {
|
||||
const relativePath = path.relative(repoRoot, dir).replace(/\\/g, '/');
|
||||
const serviceName = path.basename(dir);
|
||||
const confidence = computeConfidence(foundMarkers.length);
|
||||
|
||||
results.push({
|
||||
servicePath: relativePath,
|
||||
serviceName,
|
||||
markers: foundMarkers,
|
||||
confidence,
|
||||
});
|
||||
}
|
||||
|
||||
// Recurse into subdirectories
|
||||
for (const subdir of subdirs) {
|
||||
await walkForBoundaries(subdir, repoRoot, results);
|
||||
}
|
||||
}
|
||||
|
||||
async function hasSourceFilesInSubdirs(subdirs: string[]): Promise<boolean> {
|
||||
for (const subdir of subdirs) {
|
||||
let entries: import('node:fs').Dirent[];
|
||||
try {
|
||||
entries = await fs.readdir(subdir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.isFile()) {
|
||||
const ext = path.extname(entry.name).toLowerCase();
|
||||
if (SOURCE_EXTENSIONS.has(ext)) return true;
|
||||
}
|
||||
if (entry.isDirectory() && !entry.name.startsWith('.') && !EXCLUDED_DIRS.has(entry.name)) {
|
||||
const deeper = await hasSourceFilesInSubdirs([path.join(subdir, entry.name)]);
|
||||
if (deeper) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function computeConfidence(markerCount: number): number {
|
||||
if (markerCount >= 3) return 1.0;
|
||||
if (markerCount === 2) return 0.9;
|
||||
return 0.75;
|
||||
}
|
||||
|
||||
export function assignService(filePath: string, boundaries: ServiceBoundary[]): string | undefined {
|
||||
const normalized = filePath.replace(/\\/g, '/');
|
||||
|
||||
let bestMatch: ServiceBoundary | undefined;
|
||||
let bestLength = 0;
|
||||
|
||||
for (const boundary of boundaries) {
|
||||
const prefix = boundary.servicePath + '/';
|
||||
if (normalized.startsWith(prefix) && boundary.servicePath.length > bestLength) {
|
||||
bestMatch = boundary;
|
||||
bestLength = boundary.servicePath.length;
|
||||
}
|
||||
}
|
||||
|
||||
return bestMatch?.servicePath;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* Group orchestration shared by MCP (LocalBackend) and CLI.
|
||||
* DB access is injected via GroupToolPort so this module stays free of LocalBackend private API.
|
||||
*/
|
||||
|
||||
import { checkStaleness } from '../git-staleness.js';
|
||||
import { loadGroupConfig } from './config-parser.js';
|
||||
import { getDefaultGitnexusDir, getGroupDir, listGroups, readContractRegistry } from './storage.js';
|
||||
import { syncGroup } from './sync.js';
|
||||
|
||||
export interface GroupRepoHandle {
|
||||
id: string;
|
||||
name: string;
|
||||
repoPath: string;
|
||||
storagePath: string;
|
||||
indexedAt?: string;
|
||||
lastCommit?: string;
|
||||
}
|
||||
|
||||
export interface GroupToolPort {
|
||||
resolveRepo(repoParam?: string): Promise<GroupRepoHandle>;
|
||||
impact(
|
||||
repo: GroupRepoHandle,
|
||||
params: {
|
||||
target: string;
|
||||
direction: 'upstream' | 'downstream';
|
||||
maxDepth?: number;
|
||||
relationTypes?: string[];
|
||||
includeTests?: boolean;
|
||||
minConfidence?: number;
|
||||
},
|
||||
): Promise<unknown>;
|
||||
query(
|
||||
repo: GroupRepoHandle,
|
||||
params: {
|
||||
query: string;
|
||||
task_context?: string;
|
||||
goal?: string;
|
||||
limit?: number;
|
||||
max_symbols?: number;
|
||||
include_content?: boolean;
|
||||
},
|
||||
): Promise<unknown>;
|
||||
impactByUid(
|
||||
repoId: string,
|
||||
uid: string,
|
||||
direction: string,
|
||||
opts: {
|
||||
maxDepth: number;
|
||||
relationTypes: string[];
|
||||
minConfidence: number;
|
||||
includeTests: boolean;
|
||||
},
|
||||
): Promise<unknown | null>;
|
||||
}
|
||||
|
||||
function repoInSubgroup(repoPath: string, subgroup?: string): boolean {
|
||||
if (!subgroup?.trim()) return true;
|
||||
const s = subgroup.replace(/\/+$/, '');
|
||||
return repoPath === s || repoPath.startsWith(`${s}/`);
|
||||
}
|
||||
|
||||
export class GroupService {
|
||||
constructor(private readonly port: GroupToolPort) {}
|
||||
|
||||
async groupList(params: Record<string, unknown>): Promise<unknown> {
|
||||
const name = typeof params.name === 'string' ? params.name.trim() : '';
|
||||
if (!name) {
|
||||
const groups = await listGroups();
|
||||
return { groups };
|
||||
}
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
return {
|
||||
name: config.name,
|
||||
description: config.description,
|
||||
repos: config.repos,
|
||||
links: config.links,
|
||||
};
|
||||
}
|
||||
|
||||
async groupSync(params: Record<string, unknown>): Promise<unknown> {
|
||||
const name = String(params.name ?? '').trim();
|
||||
if (!name) return { error: 'name is required' };
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
const result = await syncGroup(config, {
|
||||
groupDir,
|
||||
exactOnly: Boolean(params.exactOnly),
|
||||
skipEmbeddings: Boolean(params.skipEmbeddings),
|
||||
allowStale: Boolean(params.allowStale),
|
||||
verbose: Boolean(params.verbose),
|
||||
});
|
||||
return {
|
||||
contracts: result.contracts.length,
|
||||
crossLinks: result.crossLinks.length,
|
||||
unmatched: result.unmatched.length,
|
||||
missingRepos: result.missingRepos,
|
||||
};
|
||||
}
|
||||
|
||||
async groupContracts(params: Record<string, unknown>): Promise<unknown> {
|
||||
const name = String(params.name ?? '').trim();
|
||||
if (!name) return { error: 'name is required' };
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const registry = await readContractRegistry(groupDir);
|
||||
if (!registry) {
|
||||
return { error: `No contracts.json for group "${name}". Run group_sync first.` };
|
||||
}
|
||||
let contracts = registry.contracts;
|
||||
if (params.type) contracts = contracts.filter((c) => c.type === params.type);
|
||||
if (params.repo) contracts = contracts.filter((c) => c.repo === params.repo);
|
||||
if (params.unmatchedOnly) {
|
||||
const matchedIds = new Set(
|
||||
registry.crossLinks.flatMap((l) => [
|
||||
`${l.from.repo}::${l.contractId}`,
|
||||
`${l.to.repo}::${l.contractId}`,
|
||||
]),
|
||||
);
|
||||
contracts = contracts.filter((c) => !matchedIds.has(`${c.repo}::${c.contractId}`));
|
||||
}
|
||||
return { contracts, crossLinks: registry.crossLinks };
|
||||
}
|
||||
|
||||
async groupQuery(params: Record<string, unknown>): Promise<unknown> {
|
||||
const name = String(params.name ?? '').trim();
|
||||
const queryText = String(params.query ?? '').trim();
|
||||
if (!name || !queryText) return { error: 'name and query are required' };
|
||||
|
||||
const limit = typeof params.limit === 'number' && params.limit > 0 ? params.limit : 5;
|
||||
const subgroup = typeof params.subgroup === 'string' ? params.subgroup : undefined;
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
|
||||
const perRepo: Array<{ repo: string; score: number; processes: unknown[] }> = [];
|
||||
for (const [repoPath, registryName] of Object.entries(config.repos)) {
|
||||
if (!repoInSubgroup(repoPath, subgroup)) continue;
|
||||
try {
|
||||
const repoObj = await this.port.resolveRepo(registryName);
|
||||
const queryResult = (await this.port.query(repoObj, {
|
||||
query: queryText,
|
||||
limit,
|
||||
max_symbols: 10,
|
||||
include_content: false,
|
||||
})) as { processes?: Array<Record<string, unknown>> };
|
||||
const processes = queryResult.processes || [];
|
||||
const scored = processes.map((p, idx) => ({
|
||||
...p,
|
||||
_rrf_score: 1 / (idx + 1 + 60),
|
||||
_repo: repoPath,
|
||||
}));
|
||||
perRepo.push({ repo: repoPath, score: 0, processes: scored });
|
||||
} catch {
|
||||
perRepo.push({ repo: repoPath, score: 0, processes: [] });
|
||||
}
|
||||
}
|
||||
|
||||
const allProcesses = perRepo.flatMap((r) => r.processes as Array<Record<string, unknown>>);
|
||||
allProcesses.sort((a, b) => (b._rrf_score as number) - (a._rrf_score as number));
|
||||
const topN = allProcesses.slice(0, limit);
|
||||
|
||||
return {
|
||||
group: name,
|
||||
query: queryText,
|
||||
results: topN,
|
||||
per_repo: perRepo.map((r) => ({ repo: r.repo, count: r.processes.length })),
|
||||
};
|
||||
}
|
||||
|
||||
async groupStatus(params: Record<string, unknown>): Promise<unknown> {
|
||||
const name = String(params.name ?? '').trim();
|
||||
if (!name) return { error: 'name is required' };
|
||||
const groupDir = getGroupDir(getDefaultGitnexusDir(), name);
|
||||
const config = await loadGroupConfig(groupDir);
|
||||
const registry = await readContractRegistry(groupDir);
|
||||
|
||||
const repoStatuses: Record<
|
||||
string,
|
||||
{
|
||||
indexStale: boolean;
|
||||
contractsStale: boolean;
|
||||
missing: boolean;
|
||||
commitsBehind?: number;
|
||||
}
|
||||
> = {};
|
||||
|
||||
const fsp = await import('node:fs/promises');
|
||||
const pathMod = await import('node:path');
|
||||
|
||||
for (const [repoPath, registryName] of Object.entries(config.repos)) {
|
||||
try {
|
||||
const repoObj = await this.port.resolveRepo(registryName);
|
||||
const metaPath = pathMod.join(repoObj.storagePath, 'meta.json');
|
||||
const metaRaw = await fsp.readFile(metaPath, 'utf-8').catch(() => '{}');
|
||||
const meta = JSON.parse(metaRaw) as { lastCommit?: string; indexedAt?: string };
|
||||
|
||||
const staleness = meta.lastCommit
|
||||
? checkStaleness(repoObj.repoPath, meta.lastCommit)
|
||||
: { isStale: true, commitsBehind: -1 };
|
||||
|
||||
const snapshot = registry?.repoSnapshots[repoPath];
|
||||
const contractsStale =
|
||||
snapshot && meta.indexedAt ? snapshot.indexedAt !== meta.indexedAt : !snapshot;
|
||||
|
||||
repoStatuses[repoPath] = {
|
||||
indexStale: staleness.isStale,
|
||||
contractsStale: Boolean(contractsStale),
|
||||
missing: false,
|
||||
commitsBehind: staleness.commitsBehind,
|
||||
};
|
||||
} catch {
|
||||
repoStatuses[repoPath] = { indexStale: false, contractsStale: false, missing: true };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
group: name,
|
||||
lastSync: registry?.generatedAt || null,
|
||||
missingRepos: registry?.missingRepos || [],
|
||||
repos: repoStatuses,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as fsp from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import type { ContractRegistry } from './types.js';
|
||||
|
||||
const CONTRACTS_FILE = 'contracts.json';
|
||||
|
||||
export function getDefaultGitnexusDir(): string {
|
||||
return process.env.GITNEXUS_HOME || path.join(os.homedir(), '.gitnexus');
|
||||
}
|
||||
|
||||
export function getGroupsBaseDir(gitnexusDir?: string): string {
|
||||
return path.join(gitnexusDir || getDefaultGitnexusDir(), 'groups');
|
||||
}
|
||||
|
||||
const GROUP_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
||||
|
||||
export function validateGroupName(name: string): void {
|
||||
if (!GROUP_NAME_RE.test(name)) {
|
||||
throw new Error(
|
||||
`Invalid group name "${name}". Names must start with a letter or digit and contain only [a-zA-Z0-9_-].`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function getGroupDir(gitnexusDir: string, groupName: string): string {
|
||||
validateGroupName(groupName);
|
||||
return path.join(gitnexusDir, 'groups', groupName);
|
||||
}
|
||||
|
||||
export async function writeContractRegistry(
|
||||
groupDir: string,
|
||||
registry: ContractRegistry,
|
||||
): Promise<void> {
|
||||
const targetPath = path.join(groupDir, CONTRACTS_FILE);
|
||||
const tmpPath = `${targetPath}.tmp.${Date.now()}`;
|
||||
|
||||
await fsp.writeFile(tmpPath, JSON.stringify(registry, null, 2), 'utf-8');
|
||||
await fsp.rename(tmpPath, targetPath);
|
||||
}
|
||||
|
||||
export async function readContractRegistry(groupDir: string): Promise<ContractRegistry | null> {
|
||||
const filePath = path.join(groupDir, CONTRACTS_FILE);
|
||||
try {
|
||||
const content = await fsp.readFile(filePath, 'utf-8');
|
||||
return JSON.parse(content) as ContractRegistry;
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listGroups(gitnexusDir?: string): Promise<string[]> {
|
||||
const groupsDir = getGroupsBaseDir(gitnexusDir);
|
||||
try {
|
||||
const entries = await fsp.readdir(groupsDir, { withFileTypes: true });
|
||||
const names: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory()) {
|
||||
const yamlPath = path.join(groupsDir, entry.name, 'group.yaml');
|
||||
if (fs.existsSync(yamlPath)) {
|
||||
names.push(entry.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createGroupDir(
|
||||
gitnexusDir: string,
|
||||
groupName: string,
|
||||
force: boolean = false,
|
||||
): Promise<string> {
|
||||
const groupDir = getGroupDir(gitnexusDir, groupName);
|
||||
if (fs.existsSync(path.join(groupDir, 'group.yaml')) && !force) {
|
||||
throw new Error(`Group "${groupName}" already exists. Use --force to overwrite.`);
|
||||
}
|
||||
await fsp.mkdir(groupDir, { recursive: true });
|
||||
|
||||
const template = `version: 1
|
||||
name: ${groupName}
|
||||
description: ""
|
||||
|
||||
repos: {}
|
||||
|
||||
links: []
|
||||
|
||||
packages: {}
|
||||
|
||||
detect:
|
||||
http: true
|
||||
grpc: true
|
||||
topics: true
|
||||
shared_libs: true
|
||||
embedding_fallback: true
|
||||
|
||||
matching:
|
||||
bm25_threshold: 0.7
|
||||
embedding_threshold: 0.65
|
||||
max_candidates_per_step: 3
|
||||
`;
|
||||
await fsp.writeFile(path.join(groupDir, 'group.yaml'), template, 'utf-8');
|
||||
return groupDir;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { initLbug, closeLbug, executeParameterized } from '../lbug/pool-adapter.js';
|
||||
import { readRegistry, type RegistryEntry } from '../../storage/repo-manager.js';
|
||||
import type { GroupConfig, RepoHandle, RepoSnapshot, StoredContract, CrossLink } from './types.js';
|
||||
import { HttpRouteExtractor } from './extractors/http-route-extractor.js';
|
||||
import { GrpcExtractor } from './extractors/grpc-extractor.js';
|
||||
import { TopicExtractor } from './extractors/topic-extractor.js';
|
||||
import { runExactMatch } from './matching.js';
|
||||
import { detectServiceBoundaries, assignService } from './service-boundary-detector.js';
|
||||
import type { CypherExecutor } from './contract-extractor.js';
|
||||
import { writeContractRegistry } from './storage.js';
|
||||
import type { ContractRegistry } from './types.js';
|
||||
|
||||
export interface SyncOptions {
|
||||
extractorOverride?:
|
||||
| ((repo: RepoHandle) => Promise<StoredContract[]>)
|
||||
| (() => Promise<StoredContract[]>);
|
||||
resolveRepoHandle?: (registryName: string, groupPath: string) => Promise<RepoHandle | null>;
|
||||
skipWrite?: boolean;
|
||||
groupDir?: string;
|
||||
allowStale?: boolean;
|
||||
verbose?: boolean;
|
||||
exactOnly?: boolean;
|
||||
skipEmbeddings?: boolean;
|
||||
}
|
||||
|
||||
export interface SyncResult {
|
||||
contracts: StoredContract[];
|
||||
crossLinks: CrossLink[];
|
||||
unmatched: StoredContract[];
|
||||
missingRepos: string[];
|
||||
repoSnapshots: Record<string, RepoSnapshot>;
|
||||
}
|
||||
|
||||
export function stableRepoPoolId(entry: RegistryEntry, allEntries: RegistryEntry[]): string {
|
||||
const base = entry.name.toLowerCase();
|
||||
const resolved = path.resolve(entry.path);
|
||||
for (const other of allEntries) {
|
||||
if (other.name.toLowerCase() === base && path.resolve(other.path) !== resolved) {
|
||||
const hash = Buffer.from(entry.path).toString('base64url').slice(0, 6);
|
||||
return `${base}-${hash}`;
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function defaultResolveHandle(allEntries: RegistryEntry[]) {
|
||||
return async (registryName: string, groupPath: string): Promise<RepoHandle | null> => {
|
||||
const e = allEntries.find((en) => en.name === registryName);
|
||||
if (!e) return null;
|
||||
const poolId = stableRepoPoolId(e, allEntries);
|
||||
return {
|
||||
id: poolId,
|
||||
path: groupPath,
|
||||
repoPath: e.path,
|
||||
storagePath: e.storagePath,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export async function syncGroup(config: GroupConfig, opts?: SyncOptions): Promise<SyncResult> {
|
||||
const missingRepos: string[] = [];
|
||||
const repoSnapshots: Record<string, RepoSnapshot> = {};
|
||||
let autoContracts: StoredContract[] = [];
|
||||
let dbExecutors: Map<string, CypherExecutor> | undefined;
|
||||
|
||||
const eo = opts?.extractorOverride;
|
||||
if (eo && eo.length === 0) {
|
||||
autoContracts = await (eo as () => Promise<StoredContract[]>)();
|
||||
} else {
|
||||
const entries = await readRegistry();
|
||||
const resolve = opts?.resolveRepoHandle ?? defaultResolveHandle(entries);
|
||||
const httpEx = new HttpRouteExtractor();
|
||||
const grpcEx = new GrpcExtractor();
|
||||
const topicEx = new TopicExtractor();
|
||||
dbExecutors = new Map<string, CypherExecutor>();
|
||||
const openPoolIds: string[] = [];
|
||||
|
||||
try {
|
||||
for (const [groupPath, regName] of Object.entries(config.repos)) {
|
||||
const handle = await resolve(regName, groupPath);
|
||||
if (!handle) {
|
||||
missingRepos.push(groupPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
const poolId = handle.id;
|
||||
const lbugPath = path.join(handle.storagePath, 'lbug');
|
||||
try {
|
||||
await initLbug(poolId, lbugPath);
|
||||
openPoolIds.push(poolId);
|
||||
|
||||
const executor: CypherExecutor = (query, params) =>
|
||||
executeParameterized(poolId, query, params ?? {});
|
||||
|
||||
dbExecutors.set(groupPath, executor);
|
||||
|
||||
const boundaries = await detectServiceBoundaries(handle.repoPath);
|
||||
|
||||
if (config.detect.http) {
|
||||
const extracted = await httpEx.extract(executor, handle.repoPath, handle);
|
||||
for (const c of extracted) {
|
||||
autoContracts.push({
|
||||
...c,
|
||||
repo: groupPath,
|
||||
service: assignService(c.symbolRef.filePath, boundaries),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (config.detect.grpc) {
|
||||
const extracted = await grpcEx.extract(executor, handle.repoPath, handle);
|
||||
for (const c of extracted) {
|
||||
autoContracts.push({
|
||||
...c,
|
||||
repo: groupPath,
|
||||
service: assignService(c.symbolRef.filePath, boundaries),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (config.detect.topics) {
|
||||
const extracted = await topicEx.extract(executor, handle.repoPath, handle);
|
||||
for (const c of extracted) {
|
||||
autoContracts.push({
|
||||
...c,
|
||||
repo: groupPath,
|
||||
service: assignService(c.symbolRef.filePath, boundaries),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const metaPath = path.join(handle.storagePath, 'meta.json');
|
||||
try {
|
||||
const raw = await fs.readFile(metaPath, 'utf-8');
|
||||
const m = JSON.parse(raw) as { indexedAt?: string; lastCommit?: string };
|
||||
repoSnapshots[groupPath] = {
|
||||
indexedAt: m.indexedAt || '',
|
||||
lastCommit: m.lastCommit || '',
|
||||
};
|
||||
} catch {
|
||||
const e = entries.find((en) => en.name === regName);
|
||||
repoSnapshots[groupPath] = {
|
||||
indexedAt: e?.indexedAt || '',
|
||||
lastCommit: e?.lastCommit || '',
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
missingRepos.push(groupPath);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
for (const id of [...new Set(openPoolIds)]) {
|
||||
await closeLbug(id).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { matched, unmatched } = runExactMatch(autoContracts);
|
||||
const crossLinks: CrossLink[] = matched;
|
||||
const allContracts: StoredContract[] = autoContracts;
|
||||
|
||||
const registry: ContractRegistry = {
|
||||
version: 1,
|
||||
generatedAt: new Date().toISOString(),
|
||||
repoSnapshots,
|
||||
missingRepos,
|
||||
contracts: allContracts,
|
||||
crossLinks,
|
||||
};
|
||||
|
||||
if (opts?.groupDir && !opts.skipWrite) {
|
||||
await writeContractRegistry(opts.groupDir, registry);
|
||||
}
|
||||
|
||||
return {
|
||||
contracts: allContracts,
|
||||
crossLinks,
|
||||
unmatched,
|
||||
missingRepos,
|
||||
repoSnapshots,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
export type ContractType = 'http' | 'grpc' | 'topic' | 'lib' | 'custom';
|
||||
export type MatchType = 'exact' | 'manifest' | 'wildcard' | 'bm25' | 'embedding';
|
||||
export type ContractRole = 'provider' | 'consumer';
|
||||
|
||||
export interface GroupConfig {
|
||||
version: number;
|
||||
name: string;
|
||||
description: string;
|
||||
repos: Record<string, string>;
|
||||
links: GroupManifestLink[];
|
||||
packages: Record<string, Record<string, string>>;
|
||||
detect: DetectConfig;
|
||||
matching: MatchingConfig;
|
||||
}
|
||||
|
||||
export interface GroupManifestLink {
|
||||
from: string;
|
||||
to: string;
|
||||
type: ContractType;
|
||||
contract: string;
|
||||
role: ContractRole;
|
||||
}
|
||||
|
||||
export interface DetectConfig {
|
||||
http: boolean;
|
||||
grpc: boolean;
|
||||
topics: boolean;
|
||||
shared_libs: boolean;
|
||||
embedding_fallback: boolean;
|
||||
}
|
||||
|
||||
export interface MatchingConfig {
|
||||
bm25_threshold: number;
|
||||
embedding_threshold: number;
|
||||
max_candidates_per_step: number;
|
||||
}
|
||||
|
||||
export interface SymbolRef {
|
||||
filePath: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ExtractedContract {
|
||||
contractId: string;
|
||||
type: ContractType;
|
||||
role: ContractRole;
|
||||
symbolUid: string;
|
||||
symbolRef: SymbolRef;
|
||||
symbolName: string;
|
||||
confidence: number;
|
||||
meta: Record<string, unknown>;
|
||||
/** Service boundary within a monorepo (relative path from repo root, e.g. "services/auth"). */
|
||||
service?: string;
|
||||
}
|
||||
|
||||
export interface CrossLinkEndpoint {
|
||||
repo: string;
|
||||
/** Service boundary within a monorepo (relative path from repo root). */
|
||||
service?: string;
|
||||
symbolUid: string;
|
||||
symbolRef: SymbolRef;
|
||||
}
|
||||
|
||||
export interface CrossLink {
|
||||
from: CrossLinkEndpoint;
|
||||
to: CrossLinkEndpoint;
|
||||
type: ContractType;
|
||||
contractId: string;
|
||||
matchType: MatchType;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
export interface RepoSnapshot {
|
||||
indexedAt: string;
|
||||
lastCommit: string;
|
||||
}
|
||||
|
||||
export interface ContractRegistry {
|
||||
version: number;
|
||||
generatedAt: string;
|
||||
repoSnapshots: Record<string, RepoSnapshot>;
|
||||
missingRepos: string[];
|
||||
contracts: StoredContract[];
|
||||
crossLinks: CrossLink[];
|
||||
}
|
||||
|
||||
export interface StoredContract extends ExtractedContract {
|
||||
repo: string;
|
||||
}
|
||||
|
||||
/** Repo within a group (group path + paths; name collision with MCP RepoHandle — import from group/types only). */
|
||||
export interface RepoHandle {
|
||||
id: string;
|
||||
path: string;
|
||||
repoPath: string;
|
||||
storagePath: string;
|
||||
}
|
||||
|
||||
export interface GroupImpactResult {
|
||||
local: unknown;
|
||||
group: string;
|
||||
cross: CrossRepoImpact[];
|
||||
outOfScope: OutOfScopeLink[];
|
||||
truncated: boolean;
|
||||
truncatedRepos: string[];
|
||||
summary: {
|
||||
direct: number;
|
||||
processes_affected: number;
|
||||
modules_affected: number;
|
||||
cross_repo_hits: number;
|
||||
};
|
||||
risk: string;
|
||||
}
|
||||
|
||||
export interface CrossRepoImpact {
|
||||
repo: string;
|
||||
repo_path: string;
|
||||
contract: {
|
||||
id: string;
|
||||
type: ContractType;
|
||||
match_type: MatchType;
|
||||
confidence: number;
|
||||
};
|
||||
by_depth: Record<string, unknown[]>;
|
||||
affected_processes: string[];
|
||||
}
|
||||
|
||||
export interface OutOfScopeLink {
|
||||
from: string;
|
||||
to: string;
|
||||
contractId: string;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
/** Opaque handle to an open bridge LadybugDB. */
|
||||
export interface BridgeHandle {
|
||||
/** Internal — do not access directly. */
|
||||
readonly _db: unknown;
|
||||
readonly _conn: unknown;
|
||||
readonly groupDir: string;
|
||||
}
|
||||
|
||||
export interface BridgeMeta {
|
||||
version: number;
|
||||
generatedAt: string;
|
||||
missingRepos: string[];
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
/**
|
||||
* BindingAccumulator — read-append-only accumulator that collects TypeEnv
|
||||
* bindings across files in the GitNexus analyzer pipeline.
|
||||
*
|
||||
* **Current behavior (both execution paths):** The accumulator carries only
|
||||
* file-scope (`scope = ''`) entries. Function-scope bindings are stripped
|
||||
* at both write sites:
|
||||
*
|
||||
* - **Worker path**: `parse-worker.ts` serializes only
|
||||
* `typeEnv.fileScope()` entries across the IPC boundary.
|
||||
* - **Sequential path**: `type-env.ts::flush()` iterates only the FILE_SCOPE
|
||||
* entry of the env map and writes `BindingEntry` records with
|
||||
* `scope: ''` hardcoded.
|
||||
*
|
||||
* The narrowing exists because function-scope bindings have zero downstream
|
||||
* consumers today and were previously costing ~4.9 MB of heap + IPC on
|
||||
* every pipeline run. See `type-env.ts::flush()` and the `FileScopeBindings`
|
||||
* JSDoc in `parse-worker.ts` for the paired Phase 9 reversion checklist.
|
||||
*
|
||||
* **Historical quality asymmetry (Phase 9 consideration):** Even though
|
||||
* both paths now carry only file-scope data, the two paths were built
|
||||
* under different resolution capabilities, and a future Phase 9 reverter
|
||||
* that widens them back to all scopes will inherit that asymmetry:
|
||||
*
|
||||
* - **Sequential path** had (and would regain) access to the full
|
||||
* `SymbolTable` and `importedBindings`, so its bindings benefit from
|
||||
* Tier 2 cross-file propagation.
|
||||
* - **Worker path** runs without `SymbolTable` / `importedBindings` and
|
||||
* can only produce Tier 0 (annotation-declared) and local Tier 1
|
||||
* (same-file constructor inference) bindings.
|
||||
*
|
||||
* Phase 9 consumers that trust every entry equally will silently produce
|
||||
* worse results for large repos (worker-dominant) than small ones
|
||||
* (sequential-dominant). If Phase 9 needs homogeneous quality, either
|
||||
* (a) tag entries with their tier at insert time so consumers can filter,
|
||||
* or (b) post-process worker-path entries through a follow-up resolution
|
||||
* pass after the main-thread `SymbolTable` is complete.
|
||||
*
|
||||
* **Lifecycle contract**: `append → finalize → consume → dispose`. See
|
||||
* `finalize()` and `dispose()` for the state machine. Disposal is
|
||||
* orthogonal to finalization: either order is legal.
|
||||
*/
|
||||
|
||||
export interface BindingEntry {
|
||||
readonly scope: string; // '' for file-level, 'funcName@startIndex' for function-local
|
||||
readonly varName: string;
|
||||
readonly typeName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal graph-node shape required by `enrichExportedTypeMap()`. Intentionally
|
||||
* narrower than the full `GraphNode` type in `graph/types.ts` so tests can
|
||||
* construct a minimal mock without depending on the full graph module, and
|
||||
* so the enrichment logic is a pure function over this contract.
|
||||
*
|
||||
* Matches the shape of the real `KnowledgeGraph` node's `properties.isExported`
|
||||
* access path — tests that use a different shape silently pass while
|
||||
* production fails.
|
||||
*/
|
||||
export interface EnrichmentGraphNode {
|
||||
readonly id: string;
|
||||
readonly properties?: { readonly isExported?: boolean } | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal graph lookup interface used by `enrichExportedTypeMap()`.
|
||||
* Consumes only the method the enrichment loop actually calls.
|
||||
*/
|
||||
export interface EnrichmentGraphLookup {
|
||||
getNode(id: string): EnrichmentGraphNode | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge file-scope bindings from a (finalized) `BindingAccumulator` into an
|
||||
* `exportedTypeMap` for symbols whose graph nodes are marked as exported.
|
||||
*
|
||||
* This is the single source of truth for the worker-path ExportedTypeMap
|
||||
* enrichment loop. Previously the logic lived inline in `pipeline.ts` and
|
||||
* the test suite reimplemented it as a `runEnrichmentLoop` helper — a
|
||||
* drift-prone pattern that meant tests could pass while production regressed.
|
||||
* Extracting it here makes the production code call the same function the
|
||||
* tests call.
|
||||
*
|
||||
* **Node ID candidate order**: `Function:{filePath}:{name}` →
|
||||
* `Variable:{filePath}:{name}` → `Const:{filePath}:{name}`. First match wins.
|
||||
*
|
||||
* **Tier 0 priority**: if `exportedTypeMap` already has an entry for a
|
||||
* `(filePath, name)` pair, the accumulator entry does NOT overwrite it —
|
||||
* the SymbolTable tier-0 pass is authoritative. Without this guard, a
|
||||
* worker-path binding could clobber a higher-quality type from SymbolTable.
|
||||
*
|
||||
* **Finalize precondition**: the accumulator should be finalized before
|
||||
* calling this function. The lifecycle contract is
|
||||
* `append → finalize → enrich → dispose`. Finalization is not asserted
|
||||
* here (the test suite and pipeline both honor it separately), but any
|
||||
* append happening concurrently with this enrichment would be a lifecycle
|
||||
* bug at the caller level.
|
||||
*
|
||||
* @returns The number of new entries written into `exportedTypeMap`
|
||||
* (0 on empty accumulator or when every candidate was filtered
|
||||
* out by the export check or the Tier 0 guard).
|
||||
*/
|
||||
export function enrichExportedTypeMap(
|
||||
bindingAccumulator: BindingAccumulator,
|
||||
graph: EnrichmentGraphLookup,
|
||||
exportedTypeMap: Map<string, Map<string, string>>,
|
||||
): number {
|
||||
if (bindingAccumulator.fileCount === 0) return 0;
|
||||
let enriched = 0;
|
||||
for (const filePath of bindingAccumulator.files()) {
|
||||
for (const [name, type] of bindingAccumulator.fileScopeEntries(filePath)) {
|
||||
// Three-candidate-ID lookup mirrors the sequential-path export check
|
||||
// in `collectExportedBindings()` (call-processor.ts).
|
||||
const functionNodeId = `Function:${filePath}:${name}`;
|
||||
const variableNodeId = `Variable:${filePath}:${name}`;
|
||||
const constNodeId = `Const:${filePath}:${name}`;
|
||||
const node =
|
||||
graph.getNode(functionNodeId) ??
|
||||
graph.getNode(variableNodeId) ??
|
||||
graph.getNode(constNodeId);
|
||||
if (!node?.properties?.isExported) continue;
|
||||
|
||||
let fileExports = exportedTypeMap.get(filePath);
|
||||
if (!fileExports) {
|
||||
fileExports = new Map();
|
||||
exportedTypeMap.set(filePath, fileExports);
|
||||
}
|
||||
// Tier 0 priority: SymbolTable-populated entries are authoritative.
|
||||
if (!fileExports.has(name)) {
|
||||
fileExports.set(name, type);
|
||||
enriched++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return enriched;
|
||||
}
|
||||
|
||||
const ENTRY_OVERHEAD = 64; // bytes per entry (object overhead + property refs)
|
||||
const MAP_ENTRY_OVERHEAD = 80; // bytes per file entry in the map
|
||||
|
||||
export class BindingAccumulator {
|
||||
// Storage is split into two parallel maps so file-scope reads are fast.
|
||||
// - _allByFile holds every BindingEntry (used by getFile, memory estimate).
|
||||
// - _fileScopeByFile is a nested Map<filePath, Map<varName, typeName>> for
|
||||
// O(1) point-lookup via fileScopeGet(). For iteration-based consumers
|
||||
// (enrichExportedTypeMap), fileScopeEntries() iterates the inner Map.
|
||||
// Both maps carry the same key set modulo the `scope === ''` precondition:
|
||||
// _allByFile has a key as soon as any entry is appended; _fileScopeByFile
|
||||
// only has a key once a file-scope entry arrives. Code that iterates via
|
||||
// files() uses _allByFile so files with only function-scope entries
|
||||
// remain visible.
|
||||
//
|
||||
// Note: Map.set semantics mean a duplicate varName for the same file
|
||||
// overwrites the previous value (last-write-wins). This is the correct
|
||||
// behavior — duplicate top-level bindings in the same file shouldn't
|
||||
// happen in well-formed source, and if they do the last declaration
|
||||
// is typically the one the compiler sees.
|
||||
private readonly _allByFile = new Map<string, BindingEntry[]>();
|
||||
private readonly _fileScopeByFile = new Map<string, Map<string, string>>();
|
||||
private _totalBindings = 0;
|
||||
private _finalized = false;
|
||||
private _disposed = false;
|
||||
|
||||
/**
|
||||
* Append bindings for a file. Safe to call multiple times for the same file.
|
||||
* Throws if the accumulator has been finalized. Skips if entries is empty.
|
||||
*
|
||||
* The `entries` parameter is `readonly` — this method never mutates the
|
||||
* caller's array. Internally, the first `appendFile` call per filePath
|
||||
* makes a defensive copy (`slice()`), and subsequent calls push into the
|
||||
* accumulator's own storage.
|
||||
*/
|
||||
appendFile(filePath: string, entries: readonly BindingEntry[]): void {
|
||||
if (this._finalized) {
|
||||
throw new Error(
|
||||
'[BindingAccumulator] appendFile after finalize — no further appends allowed',
|
||||
);
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
return;
|
||||
}
|
||||
// Contract consistency: if this accumulator was previously disposed
|
||||
// without being finalized, `dispose()` is documented to leave it
|
||||
// "behaving like a fresh one" for subsequent appends. Clear the
|
||||
// `_disposed` flag here so the `disposed` getter tracks the actual
|
||||
// live state, not a stale signal from the prior lifecycle cycle.
|
||||
if (this._disposed) {
|
||||
this._disposed = false;
|
||||
}
|
||||
// Note on the file-scope-only invariant:
|
||||
// The accumulator does NOT reject function-scope entries at this
|
||||
// boundary. The narrowing contract is enforced by the two production
|
||||
// write sites — `parse-worker.ts` (which uses `typeEnv.fileScope()`
|
||||
// and hardcodes `scope: ''` in the pipeline adapter) and
|
||||
// `type-env.ts::flush()` (which iterates only `env.get(FILE_SCOPE)`).
|
||||
// The class JSDoc documents the invariant and the Phase 9 reversion
|
||||
// path. Making `appendFile` runtime-reject non-file-scope entries
|
||||
// would break the accumulator's own storage-split tests which
|
||||
// legitimately exercise mixed-scope entries. If a future write path
|
||||
// violates the invariant, tests should fail via missing exports in
|
||||
// the enrichment loop, not via an assertion here.
|
||||
// All-scope store.
|
||||
const existingAll = this._allByFile.get(filePath);
|
||||
if (existingAll !== undefined) {
|
||||
for (const e of entries) {
|
||||
existingAll.push(e);
|
||||
}
|
||||
} else {
|
||||
this._allByFile.set(filePath, entries.slice());
|
||||
}
|
||||
// File-scope fast-path store (nested Map for O(1) point-lookup via fileScopeGet).
|
||||
// Populated lazily on first file-scope entry per file.
|
||||
let fileScopeMap = this._fileScopeByFile.get(filePath);
|
||||
for (const e of entries) {
|
||||
if (e.scope === '') {
|
||||
if (fileScopeMap === undefined) {
|
||||
fileScopeMap = new Map();
|
||||
this._fileScopeByFile.set(filePath, fileScopeMap);
|
||||
}
|
||||
fileScopeMap.set(e.varName, e.typeName);
|
||||
}
|
||||
}
|
||||
this._totalBindings += entries.length;
|
||||
}
|
||||
|
||||
/** Lock the accumulator — no further appends. Idempotent. */
|
||||
finalize(): void {
|
||||
// Dev-mode invariant: verify the parallel storage split is consistent.
|
||||
// `_fileScopeByFile` must be a proper projection of `_allByFile`
|
||||
// where the outer key is a subset and the inner entries are exactly
|
||||
// the `scope === ''` subset of `_allByFile[key]`. A drift would
|
||||
// indicate a bug in `appendFile()` where one map was updated but
|
||||
// not the other.
|
||||
if (process.env.NODE_ENV !== 'production' && !this._finalized) {
|
||||
for (const [filePath, fileScopeMap] of this._fileScopeByFile) {
|
||||
const allEntries = this._allByFile.get(filePath);
|
||||
if (allEntries === undefined) {
|
||||
throw new Error(
|
||||
`[BindingAccumulator] storage split drift: file ${filePath} has file-scope entries ` +
|
||||
`but no _allByFile entry`,
|
||||
);
|
||||
}
|
||||
// Count unique file-scope varNames in _allByFile (to match Map dedup
|
||||
// semantics in _fileScopeByFile where Map.set deduplicates same-name).
|
||||
const projectedNames = new Set(
|
||||
allEntries.filter((e) => e.scope === '').map((e) => e.varName),
|
||||
);
|
||||
if (projectedNames.size !== fileScopeMap.size) {
|
||||
throw new Error(
|
||||
`[BindingAccumulator] storage split drift: file ${filePath} has ` +
|
||||
`${fileScopeMap.size} file-scope names in Map but ${projectedNames.size} unique ` +
|
||||
`file-scope varNames in _allByFile`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
this._finalized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the accumulator's heap footprint. Clears both internal storage
|
||||
* maps and resets `_totalBindings` to zero. Idempotent and orthogonal to
|
||||
* `finalize()` — calling `dispose()` does not change the finalized state.
|
||||
*
|
||||
* Post-dispose contract: all read methods return empty/undefined state
|
||||
* matching a never-appended-to accumulator. Specifically:
|
||||
* - `fileCount === 0`
|
||||
* - `totalBindings === 0`
|
||||
* - `files()` yields an empty iterator
|
||||
* - `getFile(x)` returns `undefined` for all `x`
|
||||
* - `fileScopeEntries(x)` returns `[]` for all `x`
|
||||
* - `estimateMemoryBytes()` returns `0`
|
||||
*
|
||||
* If `dispose()` is called **before** `finalize()`, subsequent `appendFile`
|
||||
* calls succeed — the accumulator behaves like a fresh one. If called
|
||||
* **after** `finalize()`, subsequent `appendFile` calls throw the existing
|
||||
* "finalized" error.
|
||||
*
|
||||
* Lifecycle note: the pipeline disposes the accumulator after both Phase 9
|
||||
* consumers (`processCallsFromExtracted`, `processAssignmentsFromExtracted`)
|
||||
* and the ExportedTypeMap enrichment loop have completed, so the heap is
|
||||
* released before Phase 14 (`runCrossFileBindingPropagation`) and
|
||||
* `runGraphAnalysisPhases` begin their long-running work.
|
||||
*/
|
||||
dispose(): void {
|
||||
this._allByFile.clear();
|
||||
this._fileScopeByFile.clear();
|
||||
this._totalBindings = 0;
|
||||
this._disposed = true;
|
||||
}
|
||||
|
||||
/** Get all bindings for a file, or undefined if the file is unknown. */
|
||||
getFile(filePath: string): readonly BindingEntry[] | undefined {
|
||||
return this._allByFile.get(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get only scope='' (file-level) entries as [varName, typeName] tuples.
|
||||
* For iteration-based consumers (e.g., `enrichExportedTypeMap`).
|
||||
* Returns an empty array for an unknown file.
|
||||
*
|
||||
* O(1) map lookup + O(n_file_scope) tuple reconstruction from the inner
|
||||
* Map. Does NOT walk function-scope entries.
|
||||
*
|
||||
* For point-lookup consumers (e.g., Phase 9 fallback), prefer
|
||||
* `fileScopeGet(filePath, name)` — O(1) with no allocation.
|
||||
*/
|
||||
fileScopeEntries(filePath: string): readonly (readonly [string, string])[] {
|
||||
const map = this._fileScopeByFile.get(filePath);
|
||||
return map ? [...map.entries()] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* O(1) point-lookup for a single file-scope binding by (filePath, name).
|
||||
* Returns the typeName if found, `undefined` otherwise.
|
||||
*
|
||||
* This is the preferred lookup path for Phase 9 consumers that resolve
|
||||
* a single callee's return type — avoids the O(n_file_scope) iteration
|
||||
* and defensive-copy allocation of `fileScopeEntries()`.
|
||||
*/
|
||||
fileScopeGet(filePath: string, name: string): string | undefined {
|
||||
return this._fileScopeByFile.get(filePath)?.get(name);
|
||||
}
|
||||
|
||||
/** Iterate over all file paths in insertion order. */
|
||||
files(): IterableIterator<string> {
|
||||
return this._allByFile.keys();
|
||||
}
|
||||
|
||||
/** Number of distinct files with at least one binding. */
|
||||
get fileCount(): number {
|
||||
return this._allByFile.size;
|
||||
}
|
||||
|
||||
/** Total number of binding entries across all files. */
|
||||
get totalBindings(): number {
|
||||
return this._totalBindings;
|
||||
}
|
||||
|
||||
/** Whether the accumulator has been finalized. */
|
||||
get finalized(): boolean {
|
||||
return this._finalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the accumulator has been disposed. Exposed for symmetry with
|
||||
* `finalized` so debug tooling and future Phase 9 consumers can detect a
|
||||
* disposed accumulator without inspecting empty state heuristically.
|
||||
*
|
||||
* Disposal and finalization are orthogonal: a disposed accumulator may or
|
||||
* may not be finalized, and vice versa. See `dispose()` for the full
|
||||
* lifecycle contract.
|
||||
*/
|
||||
get disposed(): boolean {
|
||||
return this._disposed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rough memory estimate in bytes (intentionally pessimistic).
|
||||
* Formula: sum of (ENTRY_OVERHEAD + char bytes of scope+varName+typeName) per entry
|
||||
* + MAP_ENTRY_OVERHEAD + char bytes of filePath per file.
|
||||
*
|
||||
* Note: V8 stores all-ASCII strings as Latin-1 (1 byte/char) and only upgrades
|
||||
* to UCS-2 (2 bytes/char) for non-Latin-1 code points. Source paths and type names
|
||||
* are typically all-ASCII, so actual heap cost is roughly half what this returns.
|
||||
* The pessimistic factor is intentional — better to over-budget than under-budget.
|
||||
*
|
||||
* **⚠ Cost profile**: O(totalBindings) — iterates every entry in
|
||||
* `_allByFile` and reads three string `.length` properties per entry.
|
||||
* At a typical repo scale (10k files × ~20 file-scope bindings) this is
|
||||
* ~200k property reads per call. Call at most once per pipeline run,
|
||||
* NOT per file, per chunk, or per progress tick. The current single
|
||||
* call site is the dev-mode telemetry log at the pipeline finalize
|
||||
* seam. Adding a per-file-progress caller would silently make it
|
||||
* quadratic in repo size.
|
||||
*/
|
||||
estimateMemoryBytes(): number {
|
||||
let total = 0;
|
||||
for (const [filePath, entries] of this._allByFile) {
|
||||
total += MAP_ENTRY_OVERHEAD + filePath.length * 2;
|
||||
for (const e of entries) {
|
||||
total += ENTRY_OVERHEAD + (e.scope.length + e.varName.length + e.typeName.length) * 2;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,177 @@
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import type {
|
||||
ClassExtractionConfig,
|
||||
ClassExtractor,
|
||||
ClassLikeNodeLabel,
|
||||
ExtractedClassSymbol,
|
||||
} from '../class-types.js';
|
||||
|
||||
const DEFAULT_SCOPE_NAME_NODE_TYPES = new Set([
|
||||
'nested_namespace_specifier',
|
||||
'scoped_identifier',
|
||||
'scoped_type_identifier',
|
||||
'qualified_name',
|
||||
'namespace_name',
|
||||
'namespace_identifier',
|
||||
'package_identifier',
|
||||
'type_identifier',
|
||||
'identifier',
|
||||
'name',
|
||||
'constant',
|
||||
]);
|
||||
|
||||
const DEFAULT_TYPE_NAME_NODE_TYPES = new Set([
|
||||
'type_identifier',
|
||||
'identifier',
|
||||
'simple_identifier',
|
||||
'namespace_identifier',
|
||||
'constant',
|
||||
'name',
|
||||
]);
|
||||
|
||||
const DEFAULT_LABEL_BY_NODE_TYPE: Record<string, ClassLikeNodeLabel> = {
|
||||
class_declaration: 'Class',
|
||||
abstract_class_declaration: 'Class',
|
||||
interface_declaration: 'Interface',
|
||||
struct_declaration: 'Struct',
|
||||
record_declaration: 'Record',
|
||||
enum_declaration: 'Enum',
|
||||
class_definition: 'Class',
|
||||
struct_specifier: 'Struct',
|
||||
class_specifier: 'Class',
|
||||
enum_specifier: 'Enum',
|
||||
struct_item: 'Struct',
|
||||
enum_item: 'Enum',
|
||||
class: 'Class',
|
||||
object_declaration: 'Class',
|
||||
companion_object: 'Class',
|
||||
protocol_declaration: 'Interface',
|
||||
extension_declaration: 'Class',
|
||||
};
|
||||
|
||||
const CLASS_LIKE_LABELS = new Set<ClassLikeNodeLabel>([
|
||||
'Class',
|
||||
'Struct',
|
||||
'Interface',
|
||||
'Enum',
|
||||
'Record',
|
||||
]);
|
||||
|
||||
const normalizeQualifiedName = (value: string): string =>
|
||||
value
|
||||
.replace(/\s+/g, '')
|
||||
.replace(/^::/, '')
|
||||
.replace(/::/g, '.')
|
||||
.replace(/\\/g, '.')
|
||||
.replace(/\.+/g, '.')
|
||||
.replace(/^\.+|\.+$/g, '');
|
||||
|
||||
const splitQualifiedName = (value: string): string[] => {
|
||||
const normalized = normalizeQualifiedName(value);
|
||||
return normalized ? normalized.split('.').filter(Boolean) : [];
|
||||
};
|
||||
|
||||
const extractScopeSegmentsFromNode = (
|
||||
scopeNode: SyntaxNode,
|
||||
scopeNameNodeTypes: ReadonlySet<string>,
|
||||
): string[] => {
|
||||
const nameNode =
|
||||
scopeNode.childForFieldName?.('name') ??
|
||||
scopeNode.namedChildren?.find((child) => scopeNameNodeTypes.has(child.type));
|
||||
return nameNode ? splitQualifiedName(nameNode.text) : [];
|
||||
};
|
||||
|
||||
const extractTypeNameFromNode = (node: SyntaxNode): string | undefined => {
|
||||
const nameField = node.childForFieldName?.('name');
|
||||
if (nameField) return nameField.text;
|
||||
const nameChild = node.namedChildren?.find((child) =>
|
||||
DEFAULT_TYPE_NAME_NODE_TYPES.has(child.type),
|
||||
);
|
||||
return nameChild?.text;
|
||||
};
|
||||
|
||||
const isClassLikeLabel = (label: NodeLabel | null | undefined): label is ClassLikeNodeLabel =>
|
||||
label !== undefined && label !== null && CLASS_LIKE_LABELS.has(label as ClassLikeNodeLabel);
|
||||
|
||||
export function createClassExtractor(config: ClassExtractionConfig): ClassExtractor {
|
||||
const typeDeclarationSet = new Set(config.typeDeclarationNodes);
|
||||
const fileScopeSet = new Set(config.fileScopeNodeTypes ?? []);
|
||||
const ancestorScopeSet = new Set(config.ancestorScopeNodeTypes ?? []);
|
||||
const scopeNameNodeTypes = new Set([
|
||||
...DEFAULT_SCOPE_NAME_NODE_TYPES,
|
||||
...(config.scopeNameNodeTypes ?? []),
|
||||
]);
|
||||
|
||||
const buildQualifiedName = (node: SyntaxNode, simpleName: string): string => {
|
||||
let root = node;
|
||||
while (root.parent) root = root.parent;
|
||||
|
||||
const readScopeSegments = (scopeNode: SyntaxNode): string[] =>
|
||||
config.extractScopeSegments?.(scopeNode) ??
|
||||
extractScopeSegmentsFromNode(scopeNode, scopeNameNodeTypes);
|
||||
|
||||
const fileScopeSegments: string[] = [];
|
||||
for (const child of root.namedChildren ?? []) {
|
||||
if (fileScopeSet.has(child.type)) {
|
||||
fileScopeSegments.push(...readScopeSegments(child));
|
||||
}
|
||||
}
|
||||
|
||||
const ancestorScopes: string[][] = [];
|
||||
let current = node.parent;
|
||||
while (current) {
|
||||
if (ancestorScopeSet.has(current.type)) {
|
||||
const segments = readScopeSegments(current);
|
||||
if (segments.length > 0) ancestorScopes.push(segments);
|
||||
}
|
||||
current = current.parent;
|
||||
}
|
||||
|
||||
return [
|
||||
...fileScopeSegments,
|
||||
...ancestorScopes.reverse().flat(),
|
||||
...splitQualifiedName(simpleName),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('.');
|
||||
};
|
||||
|
||||
const extract = (
|
||||
node: SyntaxNode,
|
||||
fallback?: {
|
||||
name?: string;
|
||||
type?: NodeLabel | null;
|
||||
},
|
||||
): ExtractedClassSymbol | null => {
|
||||
if (!typeDeclarationSet.has(node.type)) return null;
|
||||
|
||||
const name = config.extractName?.(node) ?? extractTypeNameFromNode(node) ?? fallback?.name;
|
||||
const type =
|
||||
config.extractType?.(node) ??
|
||||
DEFAULT_LABEL_BY_NODE_TYPE[node.type] ??
|
||||
(isClassLikeLabel(fallback?.type) ? fallback.type : undefined);
|
||||
|
||||
if (!name || !type) return null;
|
||||
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
qualifiedName: buildQualifiedName(node, name) || name,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
language: config.language,
|
||||
|
||||
isTypeDeclaration(node: SyntaxNode): boolean {
|
||||
return typeDeclarationSet.has(node.type);
|
||||
},
|
||||
|
||||
extract,
|
||||
|
||||
extractQualifiedName(node: SyntaxNode, simpleName: string): string | null {
|
||||
return extract(node, { name: simpleName })?.qualifiedName ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { NodeLabel, SupportedLanguages } from 'gitnexus-shared';
|
||||
import type { SyntaxNode } from './utils/ast-helpers.js';
|
||||
|
||||
export type ClassLikeNodeLabel = Extract<
|
||||
NodeLabel,
|
||||
'Class' | 'Struct' | 'Interface' | 'Enum' | 'Record'
|
||||
>;
|
||||
|
||||
export interface ExtractedClassSymbol {
|
||||
name: string;
|
||||
type: ClassLikeNodeLabel;
|
||||
qualifiedName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-language qualified type names are normalized to dot-separated scope
|
||||
* segments:
|
||||
* - file/package scope contributes leading segments when the language has one
|
||||
* - lexical namespace/module/type scope contributes enclosing segments
|
||||
* - the simple type name is always the trailing segment
|
||||
*/
|
||||
export interface ClassExtractor {
|
||||
language: SupportedLanguages;
|
||||
isTypeDeclaration(node: SyntaxNode): boolean;
|
||||
extract(
|
||||
node: SyntaxNode,
|
||||
fallback?: {
|
||||
name?: string;
|
||||
type?: NodeLabel | null;
|
||||
},
|
||||
): ExtractedClassSymbol | null;
|
||||
extractQualifiedName(node: SyntaxNode, simpleName: string): string | null;
|
||||
}
|
||||
|
||||
export interface ClassExtractionConfig {
|
||||
language: SupportedLanguages;
|
||||
typeDeclarationNodes: string[];
|
||||
fileScopeNodeTypes?: string[];
|
||||
ancestorScopeNodeTypes?: string[];
|
||||
scopeNameNodeTypes?: string[];
|
||||
extractName?: (node: SyntaxNode) => string | undefined;
|
||||
extractType?: (node: SyntaxNode) => ClassLikeNodeLabel | undefined;
|
||||
extractScopeSegments?: (node: SyntaxNode) => string[] | null | undefined;
|
||||
}
|
||||
@@ -226,6 +226,7 @@ export const ENTRY_POINT_PATTERNS = {
|
||||
/^onEvent$/, // BLoC event handler
|
||||
/^mapEventToState$/, // Legacy BLoC pattern
|
||||
],
|
||||
[SupportedLanguages.Vue]: [], // Vue uses TypeScript queries — entry points handled via TS patterns
|
||||
[SupportedLanguages.Cobol]: [], // Standalone regex processor — no tree-sitter entry points
|
||||
} satisfies Record<SupportedLanguages, RegExp[]>;
|
||||
|
||||
|
||||
@@ -15,12 +15,17 @@ import type { FieldVisibility } from '../../field-types.js';
|
||||
|
||||
/**
|
||||
* Check whether any child of `node` (named or unnamed) has .text matching
|
||||
* one of the given `keywords`.
|
||||
* the given `keyword`.
|
||||
*
|
||||
* Skips the `name` field child to avoid false positives when a method is
|
||||
* named after a contextual keyword (e.g. `abstract()` in TypeScript).
|
||||
*/
|
||||
export function hasKeyword(node: SyntaxNode, keyword: string): boolean {
|
||||
const nameNode = node.childForFieldName('name');
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
if (child && child.text.trim() === keyword) return true;
|
||||
if (!child || child === nameNode) continue;
|
||||
if (child.text.trim() === keyword) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -46,6 +51,7 @@ export function hasModifier(node: SyntaxNode, modifierType: string, keyword: str
|
||||
/**
|
||||
* Return the first matching visibility keyword found either as a direct keyword
|
||||
* child or inside a modifier wrapper node.
|
||||
* Skips the `name` field child (same rationale as hasKeyword).
|
||||
*/
|
||||
export function findVisibility(
|
||||
node: SyntaxNode,
|
||||
@@ -53,10 +59,12 @@ export function findVisibility(
|
||||
defaultVis: FieldVisibility,
|
||||
modifierNodeType?: string,
|
||||
): FieldVisibility {
|
||||
const nameNode = node.childForFieldName('name');
|
||||
// Direct keyword children
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
const text = child?.text.trim() as FieldVisibility | undefined;
|
||||
if (!child || child === nameNode) continue;
|
||||
const text = child.text.trim() as FieldVisibility | undefined;
|
||||
if (text && (keywords as ReadonlySet<string>).has(text)) return text;
|
||||
}
|
||||
// Modifier wrapper
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// gitnexus/src/core/ingestion/field-types.ts
|
||||
|
||||
import type { TypeEnvironment } from './type-env.js';
|
||||
import type { SymbolTable } from './symbol-table.js';
|
||||
import type { SymbolTableReader } from './model/symbol-table.js';
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
|
||||
/**
|
||||
@@ -57,7 +57,7 @@ export interface FieldExtractorContext {
|
||||
/** Type environment for resolution */
|
||||
typeEnv: TypeEnvironment;
|
||||
/** Symbol table for FQN lookups */
|
||||
symbolTable: SymbolTable;
|
||||
symbolTable: SymbolTableReader;
|
||||
/** Current file path */
|
||||
filePath: string;
|
||||
/** Language ID */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isVerboseIngestionEnabled } from './utils/verbose.js';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import { glob } from 'glob';
|
||||
@@ -43,6 +44,7 @@ export const walkRepositoryPaths = async (
|
||||
const entries: ScannedFile[] = [];
|
||||
let processed = 0;
|
||||
let skippedLarge = 0;
|
||||
const skippedLargePaths: string[] = [];
|
||||
|
||||
for (let start = 0; start < filtered.length; start += READ_CONCURRENCY) {
|
||||
const batch = filtered.slice(start, start + READ_CONCURRENCY);
|
||||
@@ -52,6 +54,7 @@ export const walkRepositoryPaths = async (
|
||||
const stat = await fs.stat(fullPath);
|
||||
if (stat.size > MAX_FILE_SIZE) {
|
||||
skippedLarge++;
|
||||
skippedLargePaths.push(relativePath.replace(/\\/g, '/'));
|
||||
return null;
|
||||
}
|
||||
return { path: relativePath.replace(/\\/g, '/'), size: stat.size };
|
||||
@@ -73,6 +76,11 @@ export const walkRepositoryPaths = async (
|
||||
console.warn(
|
||||
` Skipped ${skippedLarge} large files (>${MAX_FILE_SIZE / 1024}KB, likely generated/vendored)`,
|
||||
);
|
||||
if (isVerboseIngestionEnabled()) {
|
||||
for (const p of skippedLargePaths) {
|
||||
console.warn(` - ${p}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
|
||||
@@ -891,6 +891,7 @@ export const AST_FRAMEWORK_PATTERNS_BY_LANGUAGE = {
|
||||
patterns: FRAMEWORK_AST_PATTERNS.riverpod,
|
||||
},
|
||||
],
|
||||
[SupportedLanguages.Vue]: [], // Vue uses TypeScript AST framework detection
|
||||
[SupportedLanguages.Cobol]: [], // Standalone regex processor — no AST framework patterns
|
||||
} satisfies Record<SupportedLanguages, AstFrameworkPatternConfig[]>;
|
||||
|
||||
|
||||
@@ -19,47 +19,34 @@ import { ASTCache } from './ast-cache.js';
|
||||
import Parser from 'tree-sitter';
|
||||
import { isLanguageAvailable, loadParser, loadLanguage } from '../tree-sitter/parser-loader.js';
|
||||
import { generateId } from '../../lib/utils.js';
|
||||
import { getLanguageFromFilename } from 'gitnexus-shared';
|
||||
import { getLanguageFromFilename, type SupportedLanguages } from 'gitnexus-shared';
|
||||
import { isVerboseIngestionEnabled } from './utils/verbose.js';
|
||||
import { yieldToEventLoop } from './utils/event-loop.js';
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { getProvider } from './languages/index.js';
|
||||
import { getTreeSitterBufferSize } from './constants.js';
|
||||
import type { ExtractedHeritage } from './workers/parse-worker.js';
|
||||
import type { ResolutionContext } from './resolution-context.js';
|
||||
import { TIER_CONFIDENCE } from './resolution-context.js';
|
||||
import type {
|
||||
ExtractedHeritage,
|
||||
HeritageResolutionStrategy,
|
||||
HeritageStrategyLookup,
|
||||
} from './model/heritage-map.js';
|
||||
import { resolveExtendsType } from './model/heritage-map.js';
|
||||
import type { ResolutionContext } from './model/resolution-context.js';
|
||||
import { TIER_CONFIDENCE } from './model/resolution-context.js';
|
||||
|
||||
/**
|
||||
* Determine whether a heritage.extends capture is actually an IMPLEMENTS relationship.
|
||||
* Uses the symbol table first (authoritative — Tier 1); falls back to provider-defined
|
||||
* heuristics for external symbols not present in the graph:
|
||||
* - interfaceNamePattern: matched against parent name (e.g., /^I[A-Z]/ for C#/Java)
|
||||
* - heritageDefaultEdge: 'IMPLEMENTS' causes all unresolved parents to map to IMPLEMENTS
|
||||
* - All others: default EXTENDS
|
||||
* Derive the heritage-resolution strategy for a language from its
|
||||
* `LanguageProvider`. This is the production wiring that `buildHeritageMap`
|
||||
* and the standalone `resolveExtendsType` call site use — the model layer
|
||||
* itself stays unaware of the provider registry.
|
||||
*/
|
||||
/** Exported for implementor-map construction (C#/Java: `extends` rows in base_list may be interfaces). */
|
||||
export const resolveExtendsType = (
|
||||
parentName: string,
|
||||
currentFilePath: string,
|
||||
ctx: ResolutionContext,
|
||||
language: SupportedLanguages,
|
||||
): { type: 'EXTENDS' | 'IMPLEMENTS'; idPrefix: string } => {
|
||||
const resolved = ctx.resolve(parentName, currentFilePath);
|
||||
if (resolved && resolved.candidates.length > 0) {
|
||||
const isInterface = resolved.candidates[0].type === 'Interface';
|
||||
return isInterface
|
||||
? { type: 'IMPLEMENTS', idPrefix: 'Interface' }
|
||||
: { type: 'EXTENDS', idPrefix: 'Class' };
|
||||
}
|
||||
// Unresolved symbol — fall back to provider-defined heuristics
|
||||
const provider = getProvider(language);
|
||||
if (provider.interfaceNamePattern?.test(parentName)) {
|
||||
return { type: 'IMPLEMENTS', idPrefix: 'Interface' };
|
||||
}
|
||||
if (provider.heritageDefaultEdge === 'IMPLEMENTS') {
|
||||
return { type: 'IMPLEMENTS', idPrefix: 'Interface' };
|
||||
}
|
||||
return { type: 'EXTENDS', idPrefix: 'Class' };
|
||||
export const getHeritageStrategyForLanguage: HeritageStrategyLookup = (
|
||||
lang: SupportedLanguages,
|
||||
): HeritageResolutionStrategy => {
|
||||
const provider = getProvider(lang);
|
||||
return {
|
||||
interfaceNamePattern: provider.interfaceNamePattern,
|
||||
defaultEdge: provider.heritageDefaultEdge ?? 'EXTENDS',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -180,7 +167,7 @@ export const processHeritage = async (
|
||||
parentClassName,
|
||||
file.path,
|
||||
ctx,
|
||||
language,
|
||||
getHeritageStrategyForLanguage(language),
|
||||
);
|
||||
|
||||
const child = resolveHeritageId(
|
||||
@@ -296,7 +283,7 @@ export const processHeritageFromExtracted = async (
|
||||
h.parentName,
|
||||
h.filePath,
|
||||
ctx,
|
||||
fileLanguage,
|
||||
getHeritageStrategyForLanguage(fileLanguage),
|
||||
);
|
||||
|
||||
const child = resolveHeritageId(
|
||||
@@ -372,7 +359,7 @@ export const processHeritageFromExtracted = async (
|
||||
/**
|
||||
* Walk source files with the same heritage captures as parse-worker, producing
|
||||
* {@link ExtractedHeritage} rows without mutating the graph. Used on the
|
||||
* sequential pipeline path so `buildImplementorMap(..., ctx)` can run before
|
||||
* sequential pipeline path so `buildHeritageMap(..., ctx)` can run before
|
||||
* `processCalls` (worker path defers calls until heritage from all chunks exists).
|
||||
*/
|
||||
export async function extractExtractedHeritageFromFiles(
|
||||
|
||||
@@ -12,7 +12,11 @@ import type { ExtractedImport } from './workers/parse-worker.js';
|
||||
import { getTreeSitterBufferSize } from './constants.js';
|
||||
import { loadImportConfigs } from './language-config.js';
|
||||
import { buildSuffixIndex } from './import-resolvers/utils.js';
|
||||
import type { ResolutionContext, ModuleAliasMap } from './resolution-context.js';
|
||||
import type {
|
||||
ResolutionContext,
|
||||
ModuleAliasMap,
|
||||
NamedImportMap,
|
||||
} from './model/resolution-context.js';
|
||||
import type {
|
||||
ImportResult,
|
||||
ResolveCtx,
|
||||
@@ -61,30 +65,6 @@ function wireImplicitImports(
|
||||
// Avoids expanding every Go package import into N individual ImportMap edges.
|
||||
export type PackageMap = Map<string, Set<string>>;
|
||||
|
||||
// Type: Map<ImportingFilePath, Map<LocalName, {sourcePath, exportedName}>>
|
||||
// Tracks which specific names a file imports from which sources (TS/Python only).
|
||||
// Used to tighten Tier 2a resolution: `import { User } from './models'`
|
||||
// means only `User` (not `Repo`) is visible from models.ts via this import.
|
||||
// Stores both the resolved source path and the original exported name so that
|
||||
// aliased imports (`import { User as U }`) can resolve U → User in the source file.
|
||||
export interface NamedImportBinding {
|
||||
sourcePath: string;
|
||||
exportedName: string;
|
||||
}
|
||||
export type NamedImportMap = Map<string, Map<string, NamedImportBinding>>;
|
||||
|
||||
/**
|
||||
* Check if a file path is directly inside a package directory identified by its suffix.
|
||||
* Used by the symbol resolver for Go and C# directory-level import matching.
|
||||
*/
|
||||
export function isFileInPackageDir(filePath: string, dirSuffix: string): boolean {
|
||||
// Prepend '/' so paths like "internal/auth/service.go" match suffix "/internal/auth/"
|
||||
const normalized = '/' + filePath.replace(/\\/g, '/');
|
||||
if (!normalized.includes(dirSuffix)) return false;
|
||||
const afterDir = normalized.substring(normalized.indexOf(dirSuffix) + dirSuffix.length);
|
||||
return !afterDir.includes('/');
|
||||
}
|
||||
|
||||
// ImportResolutionContext is defined in ./import-resolvers/types.ts — re-exported here for consumers.
|
||||
|
||||
export function buildImportResolutionContext(allPaths: string[]): ImportResolutionContext {
|
||||
|
||||
@@ -11,6 +11,7 @@ export const EXTENSIONS = [
|
||||
'.ts',
|
||||
'.jsx',
|
||||
'.js',
|
||||
'.vue',
|
||||
'/index.tsx',
|
||||
'/index.ts',
|
||||
'/index.jsx',
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Vue import resolver — delegates to TypeScript's standard resolver.
|
||||
*
|
||||
* Vue <script> blocks use the same import syntax as TypeScript (including
|
||||
* tsconfig path aliases like `@/`), so no custom resolution logic is needed.
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { resolveStandard } from './standard.js';
|
||||
import type { ImportResolverFn } from './types.js';
|
||||
|
||||
export const resolveVueImport: ImportResolverFn = (raw, fp, ctx) =>
|
||||
resolveStandard(raw, fp, ctx, SupportedLanguages.TypeScript);
|
||||
@@ -9,9 +9,10 @@
|
||||
* so adding a language to the enum without creating a provider is a compiler error.
|
||||
*/
|
||||
|
||||
import type { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type { SupportedLanguages, MroStrategy } from 'gitnexus-shared';
|
||||
import type { LanguageTypeConfig } from './type-extractors/types.js';
|
||||
import type { CallRouter } from './call-routing.js';
|
||||
import type { ClassExtractor } from './class-types.js';
|
||||
import type { ExportChecker } from './export-detection.js';
|
||||
import type { FieldExtractor } from './field-extractor.js';
|
||||
import type { MethodExtractor } from './method-types.js';
|
||||
@@ -25,13 +26,10 @@ import type { NodeLabel } from 'gitnexus-shared';
|
||||
export type CaptureMap = Record<string, SyntaxNode | undefined>;
|
||||
|
||||
// ── Strategy tag types ─────────────────────────────────────────────────────
|
||||
/** MRO strategy for multiple inheritance resolution. */
|
||||
export type MroStrategy =
|
||||
| 'first-wins'
|
||||
| 'c3'
|
||||
| 'leftmost-base'
|
||||
| 'implements-split'
|
||||
| 'qualified-syntax';
|
||||
// NOTE: `MroStrategy` is defined in `gitnexus-shared` and re-exported above
|
||||
// so `core/ingestion/model/resolve.ts` can consume it without importing from
|
||||
// this file (which would pull in the full language-registry dependency graph).
|
||||
|
||||
/** How a language handles imports — determines wildcard synthesis behavior. */
|
||||
export type ImportSemantics = 'named' | 'wildcard' | 'namespace';
|
||||
|
||||
@@ -131,6 +129,10 @@ interface LanguageProviderConfig {
|
||||
* declarations. Produces MethodInfo[] with name, parameters, visibility, isAbstract,
|
||||
* isFinal, annotations metadata. Default: undefined (no method extraction). */
|
||||
readonly methodExtractor?: MethodExtractor;
|
||||
/** Class/type extractor for deriving canonical qualified names for class-like symbols.
|
||||
* Uses the same provider-driven strategy pattern as method/field extraction so
|
||||
* namespace/package/module rules stay language-specific. */
|
||||
readonly classExtractor?: ClassExtractor;
|
||||
/** Extract a semantic description for a definition node (e.g., PHP Eloquent
|
||||
* property arrays, relation method descriptions).
|
||||
* Default: undefined (no description extraction). */
|
||||
|
||||
@@ -9,19 +9,34 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as cCppConfig } from '../type-extractors/c-cpp.js';
|
||||
import { cCppExportChecker } from '../export-detection.js';
|
||||
import { resolveCImport, resolveCppImport } from '../import-resolvers/standard.js';
|
||||
import { C_QUERIES, CPP_QUERIES } from '../tree-sitter-queries.js';
|
||||
|
||||
import { isCppInsideClassOrStruct } from '../utils/ast-helpers.js';
|
||||
/**
|
||||
* Node types for standard function declarations that need C/C++ declarator handling.
|
||||
* Used by cCppExtractFunctionName to determine how to extract the function name.
|
||||
*/
|
||||
const FUNCTION_DECLARATION_TYPES = new Set([
|
||||
'function_declaration',
|
||||
'function_definition',
|
||||
'async_function_declaration',
|
||||
'generator_function_declaration',
|
||||
'function_item',
|
||||
]);
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import type { LanguageProvider } from '../language-provider.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import {
|
||||
cConfig as cFieldConfig,
|
||||
cppConfig as cppFieldConfig,
|
||||
} from '../field-extractors/configs/c-cpp.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { cMethodConfig, cppMethodConfig } from '../method-extractors/configs/c-cpp.js';
|
||||
|
||||
const C_BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'printf',
|
||||
@@ -130,6 +145,165 @@ const C_BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'put',
|
||||
]);
|
||||
|
||||
const cClassExtractor = createClassExtractor({
|
||||
language: SupportedLanguages.C,
|
||||
typeDeclarationNodes: ['struct_specifier', 'enum_specifier'],
|
||||
});
|
||||
|
||||
const cppClassExtractor = createClassExtractor({
|
||||
language: SupportedLanguages.CPlusPlus,
|
||||
typeDeclarationNodes: ['class_specifier', 'struct_specifier', 'enum_specifier'],
|
||||
ancestorScopeNodeTypes: ['namespace_definition', 'class_specifier', 'struct_specifier'],
|
||||
});
|
||||
|
||||
/**
|
||||
* C/C++ function name extraction — unwraps pointer_declarator / reference_declarator /
|
||||
* function_declarator / qualified_identifier chains to find the actual function name.
|
||||
* Handles field_identifier (method inside class body) and parenthesized_declarator.
|
||||
*/
|
||||
const cCppExtractFunctionName = (
|
||||
node: SyntaxNode,
|
||||
): { funcName: string | null; label: NodeLabel } | null => {
|
||||
if (!FUNCTION_DECLARATION_TYPES.has(node.type)) return null;
|
||||
|
||||
let funcName: string | null = null;
|
||||
let label: NodeLabel = 'Function';
|
||||
|
||||
// C/C++: function_definition -> [pointer_declarator ->] function_declarator -> qualified_identifier/identifier
|
||||
// Unwrap pointer_declarator / reference_declarator wrappers to reach function_declarator
|
||||
let declarator = node.childForFieldName?.('declarator');
|
||||
if (!declarator) {
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const c = node.child(i);
|
||||
if (c?.type === 'function_declarator') {
|
||||
declarator = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
while (
|
||||
declarator &&
|
||||
(declarator.type === 'pointer_declarator' || declarator.type === 'reference_declarator')
|
||||
) {
|
||||
let nextDeclarator = declarator.childForFieldName?.('declarator');
|
||||
if (!nextDeclarator) {
|
||||
for (let i = 0; i < declarator.childCount; i++) {
|
||||
const c = declarator.child(i);
|
||||
if (
|
||||
c?.type === 'function_declarator' ||
|
||||
c?.type === 'pointer_declarator' ||
|
||||
c?.type === 'reference_declarator'
|
||||
) {
|
||||
nextDeclarator = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
declarator = nextDeclarator;
|
||||
}
|
||||
if (declarator) {
|
||||
let innerDeclarator = declarator.childForFieldName?.('declarator');
|
||||
if (!innerDeclarator) {
|
||||
for (let i = 0; i < declarator.childCount; i++) {
|
||||
const c = declarator.child(i);
|
||||
if (
|
||||
c?.type === 'qualified_identifier' ||
|
||||
c?.type === 'identifier' ||
|
||||
c?.type === 'field_identifier' ||
|
||||
c?.type === 'parenthesized_declarator'
|
||||
) {
|
||||
innerDeclarator = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (innerDeclarator?.type === 'qualified_identifier') {
|
||||
let nameNode = innerDeclarator.childForFieldName?.('name');
|
||||
if (!nameNode) {
|
||||
for (let i = 0; i < innerDeclarator.childCount; i++) {
|
||||
const c = innerDeclarator.child(i);
|
||||
if (c?.type === 'identifier') {
|
||||
nameNode = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nameNode?.text) {
|
||||
funcName = nameNode.text;
|
||||
label = 'Method';
|
||||
}
|
||||
} else if (
|
||||
innerDeclarator?.type === 'identifier' ||
|
||||
innerDeclarator?.type === 'field_identifier'
|
||||
) {
|
||||
// field_identifier is used for method names inside C++ class bodies
|
||||
funcName = innerDeclarator.text;
|
||||
if (innerDeclarator.type === 'field_identifier') label = 'Method';
|
||||
} else if (innerDeclarator?.type === 'parenthesized_declarator') {
|
||||
let nestedId: SyntaxNode | null = null;
|
||||
for (let i = 0; i < innerDeclarator.childCount; i++) {
|
||||
const c = innerDeclarator.child(i);
|
||||
if (c?.type === 'qualified_identifier' || c?.type === 'identifier') {
|
||||
nestedId = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (nestedId?.type === 'qualified_identifier') {
|
||||
let nameNode = nestedId.childForFieldName?.('name');
|
||||
if (!nameNode) {
|
||||
for (let i = 0; i < nestedId.childCount; i++) {
|
||||
const c = nestedId.child(i);
|
||||
if (c?.type === 'identifier') {
|
||||
nameNode = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nameNode?.text) {
|
||||
funcName = nameNode.text;
|
||||
label = 'Method';
|
||||
}
|
||||
} else if (nestedId?.type === 'identifier') {
|
||||
funcName = nestedId.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for other node types in FUNCTION_DECLARATION_TYPES (e.g. function_item for Rust in C++ tree)
|
||||
if (!funcName) {
|
||||
let nameNode = node.childForFieldName?.('name');
|
||||
if (!nameNode) {
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const c = node.child(i);
|
||||
if (
|
||||
c?.type === 'identifier' ||
|
||||
c?.type === 'property_identifier' ||
|
||||
c?.type === 'simple_identifier'
|
||||
) {
|
||||
nameNode = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
funcName = nameNode?.text ?? null;
|
||||
}
|
||||
|
||||
return { funcName, label };
|
||||
};
|
||||
|
||||
/** Check if a C/C++ function_definition is inside a class or struct body.
|
||||
* Used by cppLabelOverride to skip duplicate function captures
|
||||
* that are already covered by definition.method queries. */
|
||||
function isCppInsideClassOrStruct(functionNode: SyntaxNode): boolean {
|
||||
let ancestor: SyntaxNode | null = functionNode?.parent ?? null;
|
||||
while (ancestor) {
|
||||
if (ancestor.type === 'class_specifier' || ancestor.type === 'struct_specifier') return true;
|
||||
ancestor = ancestor.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Label override shared by C and C++: skip function_definition captures inside class/struct
|
||||
* bodies (they're duplicates of definition.method captures). */
|
||||
const cppLabelOverride: NonNullable<LanguageProvider['labelOverride']> = (
|
||||
@@ -149,6 +323,11 @@ export const cProvider = defineLanguage({
|
||||
importResolver: resolveCImport,
|
||||
importSemantics: 'wildcard',
|
||||
fieldExtractor: createFieldExtractor(cFieldConfig),
|
||||
methodExtractor: createMethodExtractor({
|
||||
...cMethodConfig,
|
||||
extractFunctionName: cCppExtractFunctionName,
|
||||
}),
|
||||
classExtractor: cClassExtractor,
|
||||
labelOverride: cppLabelOverride,
|
||||
builtInNames: C_BUILT_INS,
|
||||
});
|
||||
@@ -163,6 +342,11 @@ export const cppProvider = defineLanguage({
|
||||
importSemantics: 'wildcard',
|
||||
mroStrategy: 'leftmost-base',
|
||||
fieldExtractor: createFieldExtractor(cppFieldConfig),
|
||||
methodExtractor: createMethodExtractor({
|
||||
...cppMethodConfig,
|
||||
extractFunctionName: cCppExtractFunctionName,
|
||||
}),
|
||||
classExtractor: cppClassExtractor,
|
||||
labelOverride: cppLabelOverride,
|
||||
builtInNames: C_BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as csharpConfig } from '../type-extractors/csharp.js';
|
||||
import { csharpExportChecker } from '../export-detection.js';
|
||||
@@ -125,5 +126,24 @@ export const csharpProvider = defineLanguage({
|
||||
mroStrategy: 'implements-split',
|
||||
fieldExtractor: createFieldExtractor(csharpFieldConfig),
|
||||
methodExtractor: createMethodExtractor(csharpMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.CSharp,
|
||||
typeDeclarationNodes: [
|
||||
'class_declaration',
|
||||
'interface_declaration',
|
||||
'struct_declaration',
|
||||
'enum_declaration',
|
||||
'record_declaration',
|
||||
],
|
||||
fileScopeNodeTypes: ['file_scoped_namespace_declaration'],
|
||||
ancestorScopeNodeTypes: [
|
||||
'namespace_declaration',
|
||||
'class_declaration',
|
||||
'interface_declaration',
|
||||
'struct_declaration',
|
||||
'enum_declaration',
|
||||
'record_declaration',
|
||||
],
|
||||
}),
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -12,8 +12,9 @@
|
||||
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { FUNCTION_NODE_TYPES, extractFunctionName } from '../utils/ast-helpers.js';
|
||||
import { FUNCTION_NODE_TYPES } from '../utils/ast-helpers.js';
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as dartConfig } from '../type-extractors/dart.js';
|
||||
import { dartExportChecker } from '../export-detection.js';
|
||||
@@ -21,6 +22,8 @@ import { resolveDartImport } from '../import-resolvers/dart.js';
|
||||
import { DART_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { dartConfig as dartFieldConfig } from '../field-extractors/configs/dart.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { dartMethodConfig } from '../method-extractors/configs/dart.js';
|
||||
|
||||
/**
|
||||
* Resolve the enclosing function from a `function_body` node by looking at its
|
||||
@@ -28,8 +31,8 @@ import { dartConfig as dartFieldConfig } from '../field-extractors/configs/dart.
|
||||
* function_body are siblings under program or class_body, unlike most languages
|
||||
* where the function declaration wraps both.
|
||||
*
|
||||
* Delegates name extraction to the shared `extractFunctionName` which already
|
||||
* handles Dart's function_signature and method_signature node types.
|
||||
* Extracts the function name inline — Dart uses function_signature and
|
||||
* method_signature (which wraps function_signature) as its FUNCTION_NODE_TYPES.
|
||||
*/
|
||||
const dartEnclosingFunctionFinder = (
|
||||
node: SyntaxNode,
|
||||
@@ -37,7 +40,21 @@ const dartEnclosingFunctionFinder = (
|
||||
if (node.type !== 'function_body') return null;
|
||||
const prev = node.previousSibling;
|
||||
if (!prev || !FUNCTION_NODE_TYPES.has(prev.type)) return null;
|
||||
const { funcName, label } = extractFunctionName(prev);
|
||||
|
||||
// method_signature wraps function_signature — unwrap to reach the name
|
||||
let target = prev;
|
||||
let label: NodeLabel = 'Function';
|
||||
if (prev.type === 'method_signature') {
|
||||
label = 'Method';
|
||||
for (let i = 0; i < prev.childCount; i++) {
|
||||
const c = prev.child(i);
|
||||
if (c?.type === 'function_signature') {
|
||||
target = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const funcName = target.childForFieldName?.('name')?.text ?? null;
|
||||
return funcName ? { funcName, label } : null;
|
||||
};
|
||||
|
||||
@@ -75,6 +92,12 @@ export const dartProvider = defineLanguage({
|
||||
importResolver: resolveDartImport,
|
||||
importSemantics: 'wildcard',
|
||||
fieldExtractor: createFieldExtractor(dartFieldConfig),
|
||||
methodExtractor: createMethodExtractor(dartMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Dart,
|
||||
typeDeclarationNodes: ['class_definition', 'extension_declaration', 'enum_declaration'],
|
||||
ancestorScopeNodeTypes: ['class_definition', 'extension_declaration', 'enum_declaration'],
|
||||
}),
|
||||
enclosingFunctionFinder: dartEnclosingFunctionFinder,
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as goConfig } from '../type-extractors/go.js';
|
||||
import { goExportChecker } from '../export-detection.js';
|
||||
@@ -17,6 +18,8 @@ import { resolveGoImport } from '../import-resolvers/go.js';
|
||||
import { GO_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { goConfig as goFieldConfig } from '../field-extractors/configs/go.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { goMethodConfig } from '../method-extractors/configs/go.js';
|
||||
|
||||
export const goProvider = defineLanguage({
|
||||
id: SupportedLanguages.Go,
|
||||
@@ -27,4 +30,21 @@ export const goProvider = defineLanguage({
|
||||
importResolver: resolveGoImport,
|
||||
importSemantics: 'wildcard',
|
||||
fieldExtractor: createFieldExtractor(goFieldConfig),
|
||||
methodExtractor: createMethodExtractor(goMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Go,
|
||||
typeDeclarationNodes: ['type_declaration'],
|
||||
fileScopeNodeTypes: ['package_clause'],
|
||||
extractName(node) {
|
||||
const typeSpec = node.namedChildren.find((child) => child.type === 'type_spec');
|
||||
return typeSpec?.childForFieldName('name')?.text;
|
||||
},
|
||||
extractType(node) {
|
||||
const typeSpec = node.namedChildren.find((child) => child.type === 'type_spec');
|
||||
const typeNode = typeSpec?.childForFieldName('type');
|
||||
if (typeNode?.type === 'struct_type') return 'Struct';
|
||||
if (typeNode?.type === 'interface_type') return 'Interface';
|
||||
return undefined;
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -23,6 +23,7 @@ import { phpProvider } from './php.js';
|
||||
import { rubyProvider } from './ruby.js';
|
||||
import { swiftProvider } from './swift.js';
|
||||
import { dartProvider } from './dart.js';
|
||||
import { vueProvider } from './vue.js';
|
||||
import { cobolProvider } from './cobol.js';
|
||||
|
||||
export const providers = {
|
||||
@@ -40,6 +41,7 @@ export const providers = {
|
||||
[SupportedLanguages.Ruby]: rubyProvider,
|
||||
[SupportedLanguages.Swift]: swiftProvider,
|
||||
[SupportedLanguages.Dart]: dartProvider,
|
||||
[SupportedLanguages.Vue]: vueProvider,
|
||||
[SupportedLanguages.Cobol]: cobolProvider,
|
||||
} satisfies Record<SupportedLanguages, LanguageProvider>;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { javaTypeConfig } from '../type-extractors/jvm.js';
|
||||
import { javaExportChecker } from '../export-detection.js';
|
||||
@@ -31,4 +32,20 @@ export const javaProvider = defineLanguage({
|
||||
mroStrategy: 'implements-split',
|
||||
fieldExtractor: createFieldExtractor(javaConfig),
|
||||
methodExtractor: createMethodExtractor(javaMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Java,
|
||||
typeDeclarationNodes: [
|
||||
'class_declaration',
|
||||
'interface_declaration',
|
||||
'enum_declaration',
|
||||
'record_declaration',
|
||||
],
|
||||
fileScopeNodeTypes: ['package_declaration'],
|
||||
ancestorScopeNodeTypes: [
|
||||
'class_declaration',
|
||||
'interface_declaration',
|
||||
'enum_declaration',
|
||||
'record_declaration',
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { kotlinTypeConfig } from '../type-extractors/jvm.js';
|
||||
import { kotlinExportChecker } from '../export-detection.js';
|
||||
@@ -15,12 +16,26 @@ import { resolveKotlinImport } from '../import-resolvers/jvm.js';
|
||||
import { extractKotlinNamedBindings } from '../named-bindings/kotlin.js';
|
||||
import { appendKotlinWildcard } from '../import-resolvers/jvm.js';
|
||||
import { KOTLIN_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { isKotlinClassMethod } from '../utils/ast-helpers.js';
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { kotlinConfig } from '../field-extractors/configs/jvm.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { kotlinMethodConfig } from '../method-extractors/configs/jvm.js';
|
||||
|
||||
/** Check if a Kotlin function_declaration capture is inside a class_body (i.e., a method).
|
||||
* Kotlin grammar uses function_declaration for both top-level functions and class methods.
|
||||
* Returns true when the captured definition node has a class_body ancestor. */
|
||||
function isKotlinClassMethod(
|
||||
captureNode: { parent?: SyntaxNode | null } | null | undefined,
|
||||
): boolean {
|
||||
let ancestor = captureNode?.parent;
|
||||
while (ancestor) {
|
||||
if (ancestor.type === 'class_body') return true;
|
||||
ancestor = ancestor.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'println',
|
||||
'print',
|
||||
@@ -92,6 +107,16 @@ export const kotlinProvider = defineLanguage({
|
||||
mroStrategy: 'implements-split',
|
||||
fieldExtractor: createFieldExtractor(kotlinConfig),
|
||||
methodExtractor: createMethodExtractor(kotlinMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Kotlin,
|
||||
typeDeclarationNodes: ['class_declaration', 'object_declaration', 'companion_object'],
|
||||
fileScopeNodeTypes: ['package_header'],
|
||||
ancestorScopeNodeTypes: ['class_declaration', 'object_declaration', 'companion_object'],
|
||||
extractType(node) {
|
||||
if (node.type !== 'class_declaration') return undefined;
|
||||
return node.children.some((child) => child?.text === 'interface') ? 'Interface' : 'Class';
|
||||
},
|
||||
}),
|
||||
builtInNames: BUILT_INS,
|
||||
labelOverride: (functionNode, defaultLabel) => {
|
||||
if (defaultLabel !== 'Function') return defaultLabel;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as phpConfig } from '../type-extractors/php.js';
|
||||
import { phpExportChecker } from '../export-detection.js';
|
||||
@@ -17,6 +18,8 @@ import { findDescendant, extractStringContent, type SyntaxNode } from '../utils/
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { phpConfig as phpFieldConfig } from '../field-extractors/configs/php.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { phpMethodConfig } from '../method-extractors/configs/php.js';
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'echo',
|
||||
@@ -157,18 +160,22 @@ function extractPhpPropertyDescription(propName: string, propDeclNode: SyntaxNod
|
||||
* Returns description like "hasMany(Post)" or null.
|
||||
*/
|
||||
function extractEloquentRelationDescription(methodNode: SyntaxNode): string | null {
|
||||
function findRelationCall(node: SyntaxNode): SyntaxNode | null {
|
||||
if (node.type === 'member_call_expression') {
|
||||
function findRelationCall(root: SyntaxNode): SyntaxNode | null {
|
||||
const stack: SyntaxNode[] = [root];
|
||||
while (stack.length > 0) {
|
||||
const node = stack.pop()!;
|
||||
if (node.type === 'member_call_expression') {
|
||||
const children = node.children ?? [];
|
||||
const objectNode = children.find(
|
||||
(c: SyntaxNode) => c.type === 'variable_name' && c.text === '$this',
|
||||
);
|
||||
const nameNode = children.find((c: SyntaxNode) => c.type === 'name');
|
||||
if (objectNode && nameNode && ELOQUENT_RELATIONS.has(nameNode.text)) return node;
|
||||
}
|
||||
const children = node.children ?? [];
|
||||
const objectNode = children.find(
|
||||
(c: SyntaxNode) => c.type === 'variable_name' && c.text === '$this',
|
||||
);
|
||||
const nameNode = children.find((c: SyntaxNode) => c.type === 'name');
|
||||
if (objectNode && nameNode && ELOQUENT_RELATIONS.has(nameNode.text)) return node;
|
||||
}
|
||||
for (const child of node.children ?? []) {
|
||||
const found = findRelationCall(child);
|
||||
if (found) return found;
|
||||
for (let i = children.length - 1; i >= 0; i--) {
|
||||
stack.push(children[i]);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -231,6 +238,12 @@ export const phpProvider = defineLanguage({
|
||||
importResolver: resolvePhpImport,
|
||||
namedBindingExtractor: extractPhpNamedBindings,
|
||||
fieldExtractor: createFieldExtractor(phpFieldConfig),
|
||||
methodExtractor: createMethodExtractor(phpMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.PHP,
|
||||
typeDeclarationNodes: ['class_declaration', 'interface_declaration', 'enum_declaration'],
|
||||
ancestorScopeNodeTypes: ['namespace_definition'],
|
||||
}),
|
||||
descriptionExtractor: phpDescriptionExtractor,
|
||||
isRouteFile: isPhpRouteFile,
|
||||
builtInNames: BUILT_INS,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as pythonConfig } from '../type-extractors/python.js';
|
||||
import { pythonExportChecker } from '../export-detection.js';
|
||||
@@ -19,6 +20,8 @@ import { extractPythonNamedBindings } from '../named-bindings/python.js';
|
||||
import { PYTHON_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { pythonConfig as pythonFieldConfig } from '../field-extractors/configs/python.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { pythonMethodConfig } from '../method-extractors/configs/python.js';
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'print',
|
||||
@@ -61,5 +64,11 @@ export const pythonProvider = defineLanguage({
|
||||
importSemantics: 'namespace',
|
||||
mroStrategy: 'c3',
|
||||
fieldExtractor: createFieldExtractor(pythonFieldConfig),
|
||||
methodExtractor: createMethodExtractor(pythonMethodConfig),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Python,
|
||||
typeDeclarationNodes: ['class_definition'],
|
||||
ancestorScopeNodeTypes: ['class_definition'],
|
||||
}),
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import { typeConfig as rubyConfig } from '../type-extractors/ruby.js';
|
||||
import { routeRubyCall } from '../call-routing.js';
|
||||
import { rubyExportChecker } from '../export-detection.js';
|
||||
@@ -16,6 +19,27 @@ import { resolveRubyImport } from '../import-resolvers/ruby.js';
|
||||
import { RUBY_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { rubyConfig as rubyFieldConfig } from '../field-extractors/configs/ruby.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { rubyMethodConfig } from '../method-extractors/configs/ruby.js';
|
||||
|
||||
/** Ruby method/singleton_method: extract name from 'name' field, label as Method. */
|
||||
const rubyExtractFunctionName = (
|
||||
node: SyntaxNode,
|
||||
): { funcName: string | null; label: NodeLabel } | null => {
|
||||
if (node.type !== 'method' && node.type !== 'singleton_method') return null;
|
||||
|
||||
let nameNode = node.childForFieldName?.('name');
|
||||
if (!nameNode) {
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const c = node.child(i);
|
||||
if (c?.type === 'identifier') {
|
||||
nameNode = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { funcName: nameNode?.text ?? null, label: 'Method' };
|
||||
};
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'puts',
|
||||
@@ -85,5 +109,14 @@ export const rubyProvider = defineLanguage({
|
||||
callRouter: routeRubyCall,
|
||||
importSemantics: 'wildcard',
|
||||
fieldExtractor: createFieldExtractor(rubyFieldConfig),
|
||||
methodExtractor: createMethodExtractor({
|
||||
...rubyMethodConfig,
|
||||
extractFunctionName: rubyExtractFunctionName,
|
||||
}),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Ruby,
|
||||
typeDeclarationNodes: ['class'],
|
||||
ancestorScopeNodeTypes: ['module', 'class'],
|
||||
}),
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -11,7 +11,10 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import { typeConfig as rustConfig } from '../type-extractors/rust.js';
|
||||
import { rustExportChecker } from '../export-detection.js';
|
||||
import { resolveRustImport } from '../import-resolvers/rust.js';
|
||||
@@ -19,6 +22,37 @@ import { extractRustNamedBindings } from '../named-bindings/rust.js';
|
||||
import { RUST_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { rustConfig as rustFieldConfig } from '../field-extractors/configs/rust.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { rustMethodConfig } from '../method-extractors/configs/rust.js';
|
||||
|
||||
/** Rust impl_item: find the function_item child and extract its name as a Method. */
|
||||
const rustExtractFunctionName = (
|
||||
node: SyntaxNode,
|
||||
): { funcName: string | null; label: NodeLabel } | null => {
|
||||
if (node.type !== 'impl_item') return null;
|
||||
|
||||
let funcItem: SyntaxNode | null = null;
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const c = node.child(i);
|
||||
if (c?.type === 'function_item') {
|
||||
funcItem = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!funcItem) return null;
|
||||
|
||||
let nameNode = funcItem.childForFieldName?.('name');
|
||||
if (!nameNode) {
|
||||
for (let i = 0; i < funcItem.childCount; i++) {
|
||||
const c = funcItem.child(i);
|
||||
if (c?.type === 'identifier') {
|
||||
nameNode = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { funcName: nameNode?.text ?? null, label: 'Method' };
|
||||
};
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'unwrap',
|
||||
@@ -87,5 +121,14 @@ export const rustProvider = defineLanguage({
|
||||
namedBindingExtractor: extractRustNamedBindings,
|
||||
mroStrategy: 'qualified-syntax',
|
||||
fieldExtractor: createFieldExtractor(rustFieldConfig),
|
||||
methodExtractor: createMethodExtractor({
|
||||
...rustMethodConfig,
|
||||
extractFunctionName: rustExtractFunctionName,
|
||||
}),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Rust,
|
||||
typeDeclarationNodes: ['struct_item', 'enum_item'],
|
||||
ancestorScopeNodeTypes: ['mod_item', 'struct_item', 'enum_item'],
|
||||
}),
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -11,14 +11,19 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as swiftConfig } from '../type-extractors/swift.js';
|
||||
import { swiftExportChecker } from '../export-detection.js';
|
||||
import { resolveSwiftImport } from '../import-resolvers/swift.js';
|
||||
import { SWIFT_QUERIES } from '../tree-sitter-queries.js';
|
||||
import type { SwiftPackageConfig } from '../language-config.js';
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { swiftConfig as swiftFieldConfig } from '../field-extractors/configs/swift.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import { swiftMethodConfig } from '../method-extractors/configs/swift.js';
|
||||
|
||||
/**
|
||||
* Group Swift files by SPM target for implicit module visibility.
|
||||
@@ -107,6 +112,15 @@ function wireSwiftImplicitImports(
|
||||
}
|
||||
}
|
||||
|
||||
/** Swift init/deinit declarations have special names and Constructor label. */
|
||||
const swiftExtractFunctionName = (
|
||||
node: SyntaxNode,
|
||||
): { funcName: string | null; label: NodeLabel } | null => {
|
||||
if (node.type === 'init_declaration') return { funcName: 'init', label: 'Constructor' };
|
||||
if (node.type === 'deinit_declaration') return { funcName: 'deinit', label: 'Constructor' };
|
||||
return null; // fall through to generic
|
||||
};
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'print',
|
||||
'debugPrint',
|
||||
@@ -227,6 +241,22 @@ export const swiftProvider = defineLanguage({
|
||||
importSemantics: 'wildcard',
|
||||
heritageDefaultEdge: 'IMPLEMENTS',
|
||||
fieldExtractor: createFieldExtractor(swiftFieldConfig),
|
||||
methodExtractor: createMethodExtractor({
|
||||
...swiftMethodConfig,
|
||||
extractFunctionName: swiftExtractFunctionName,
|
||||
}),
|
||||
classExtractor: createClassExtractor({
|
||||
language: SupportedLanguages.Swift,
|
||||
typeDeclarationNodes: ['class_declaration', 'protocol_declaration'],
|
||||
ancestorScopeNodeTypes: ['class_declaration', 'protocol_declaration'],
|
||||
extractType(node) {
|
||||
if (node.type === 'protocol_declaration') return 'Interface';
|
||||
if (node.type !== 'class_declaration') return undefined;
|
||||
if (node.children.some((child) => child?.text === 'struct')) return 'Struct';
|
||||
if (node.children.some((child) => child?.text === 'enum')) return 'Enum';
|
||||
return 'Class';
|
||||
},
|
||||
}),
|
||||
implicitImportWirer: wireSwiftImplicitImports,
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import type { ClassExtractionConfig } from '../class-types.js';
|
||||
import type { SyntaxNode } from '../utils/ast-helpers.js';
|
||||
import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js';
|
||||
import { tsExportChecker } from '../export-detection.js';
|
||||
import { resolveTypescriptImport, resolveJavascriptImport } from '../import-resolvers/standard.js';
|
||||
@@ -17,8 +21,38 @@ import { TYPESCRIPT_QUERIES, JAVASCRIPT_QUERIES } from '../tree-sitter-queries.j
|
||||
import { typescriptFieldExtractor } from '../field-extractors/typescript.js';
|
||||
import { createFieldExtractor } from '../field-extractors/generic.js';
|
||||
import { javascriptConfig } from '../field-extractors/configs/typescript-javascript.js';
|
||||
import { createMethodExtractor } from '../method-extractors/generic.js';
|
||||
import {
|
||||
typescriptMethodConfig,
|
||||
javascriptMethodConfig,
|
||||
} from '../method-extractors/configs/typescript-javascript.js';
|
||||
|
||||
const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
/**
|
||||
* TypeScript/JavaScript: arrow_function and function_expression get their name
|
||||
* from the parent variable_declarator (e.g. `const foo = () => {}`).
|
||||
*/
|
||||
const tsExtractFunctionName = (
|
||||
node: SyntaxNode,
|
||||
): { funcName: string | null; label: NodeLabel } | null => {
|
||||
if (node.type !== 'arrow_function' && node.type !== 'function_expression') return null;
|
||||
|
||||
const parent = node.parent;
|
||||
if (parent?.type !== 'variable_declarator') return null;
|
||||
|
||||
let nameNode = parent.childForFieldName?.('name');
|
||||
if (!nameNode) {
|
||||
for (let i = 0; i < parent.childCount; i++) {
|
||||
const c = parent.child(i);
|
||||
if (c?.type === 'identifier') {
|
||||
nameNode = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { funcName: nameNode?.text ?? null, label: 'Function' };
|
||||
};
|
||||
|
||||
export const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'console',
|
||||
'log',
|
||||
'warn',
|
||||
@@ -115,6 +149,22 @@ const BUILT_INS: ReadonlySet<string> = new Set([
|
||||
'valueOf',
|
||||
]);
|
||||
|
||||
const tsJsClassConfig: ClassExtractionConfig = {
|
||||
language: SupportedLanguages.TypeScript,
|
||||
typeDeclarationNodes: [
|
||||
'class_declaration',
|
||||
'abstract_class_declaration',
|
||||
'interface_declaration',
|
||||
'enum_declaration',
|
||||
],
|
||||
ancestorScopeNodeTypes: [
|
||||
'class_declaration',
|
||||
'abstract_class_declaration',
|
||||
'interface_declaration',
|
||||
'enum_declaration',
|
||||
],
|
||||
};
|
||||
|
||||
export const typescriptProvider = defineLanguage({
|
||||
id: SupportedLanguages.TypeScript,
|
||||
extensions: ['.ts', '.tsx'],
|
||||
@@ -124,6 +174,11 @@ export const typescriptProvider = defineLanguage({
|
||||
importResolver: resolveTypescriptImport,
|
||||
namedBindingExtractor: extractTsNamedBindings,
|
||||
fieldExtractor: typescriptFieldExtractor,
|
||||
methodExtractor: createMethodExtractor({
|
||||
...typescriptMethodConfig,
|
||||
extractFunctionName: tsExtractFunctionName,
|
||||
}),
|
||||
classExtractor: createClassExtractor(tsJsClassConfig),
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -136,5 +191,13 @@ export const javascriptProvider = defineLanguage({
|
||||
importResolver: resolveJavascriptImport,
|
||||
namedBindingExtractor: extractTsNamedBindings,
|
||||
fieldExtractor: createFieldExtractor(javascriptConfig),
|
||||
methodExtractor: createMethodExtractor({
|
||||
...javascriptMethodConfig,
|
||||
extractFunctionName: tsExtractFunctionName,
|
||||
}),
|
||||
classExtractor: createClassExtractor({
|
||||
...tsJsClassConfig,
|
||||
language: SupportedLanguages.JavaScript,
|
||||
}),
|
||||
builtInNames: BUILT_INS,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Vue language provider.
|
||||
*
|
||||
* Vue SFCs are preprocessed by extracting the <script> / <script setup>
|
||||
* block content, which is then parsed as TypeScript. This provider reuses
|
||||
* nearly all TypeScript infrastructure — queries, type config, field
|
||||
* extraction, and named binding extraction.
|
||||
*
|
||||
* Export detection for <script setup> is handled directly in the parse
|
||||
* worker (all top-level bindings are implicitly exported). The export
|
||||
* checker here is used as fallback for non-setup <script> blocks.
|
||||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js';
|
||||
import { tsExportChecker } from '../export-detection.js';
|
||||
import { resolveVueImport } from '../import-resolvers/vue.js';
|
||||
import { extractTsNamedBindings } from '../named-bindings/typescript.js';
|
||||
import { TYPESCRIPT_QUERIES } from '../tree-sitter-queries.js';
|
||||
import { typescriptFieldExtractor } from '../field-extractors/typescript.js';
|
||||
import { BUILT_INS as TS_BUILT_INS } from './typescript.js';
|
||||
|
||||
const VUE_SPECIFIC_BUILT_INS = [
|
||||
'ref',
|
||||
'reactive',
|
||||
'computed',
|
||||
'watch',
|
||||
'watchEffect',
|
||||
'onMounted',
|
||||
'onUnmounted',
|
||||
'onBeforeMount',
|
||||
'onBeforeUnmount',
|
||||
'onUpdated',
|
||||
'onBeforeUpdate',
|
||||
'nextTick',
|
||||
'defineProps',
|
||||
'defineEmits',
|
||||
'defineExpose',
|
||||
'defineOptions',
|
||||
'defineSlots',
|
||||
'defineModel',
|
||||
'withDefaults',
|
||||
'toRef',
|
||||
'toRefs',
|
||||
'unref',
|
||||
'isRef',
|
||||
'shallowRef',
|
||||
'triggerRef',
|
||||
'provide',
|
||||
'inject',
|
||||
'useSlots',
|
||||
'useAttrs',
|
||||
] as const;
|
||||
|
||||
const VUE_BUILT_INS: ReadonlySet<string> = new Set([...TS_BUILT_INS, ...VUE_SPECIFIC_BUILT_INS]);
|
||||
|
||||
const vueClassExtractor = createClassExtractor({
|
||||
language: SupportedLanguages.Vue,
|
||||
typeDeclarationNodes: [
|
||||
'class_declaration',
|
||||
'abstract_class_declaration',
|
||||
'interface_declaration',
|
||||
'enum_declaration',
|
||||
],
|
||||
ancestorScopeNodeTypes: [
|
||||
'class_declaration',
|
||||
'abstract_class_declaration',
|
||||
'interface_declaration',
|
||||
'enum_declaration',
|
||||
],
|
||||
});
|
||||
|
||||
export const vueProvider = defineLanguage({
|
||||
id: SupportedLanguages.Vue,
|
||||
extensions: ['.vue'],
|
||||
treeSitterQueries: TYPESCRIPT_QUERIES,
|
||||
typeConfig: typescriptConfig,
|
||||
exportChecker: tsExportChecker,
|
||||
importResolver: resolveVueImport,
|
||||
namedBindingExtractor: extractTsNamedBindings,
|
||||
fieldExtractor: typescriptFieldExtractor,
|
||||
classExtractor: vueClassExtractor,
|
||||
builtInNames: VUE_BUILT_INS,
|
||||
});
|
||||
@@ -0,0 +1,409 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/c-cpp.ts
|
||||
// Verified against tree-sitter-cpp ^0.23.4
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { hasKeyword } from '../../field-extractors/configs/helpers.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C/C++ helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Find the function_declarator inside a method node, handling pointer/reference
|
||||
* return types where the function_declarator is nested inside a pointer_declarator
|
||||
* or reference_declarator.
|
||||
*/
|
||||
function findFunctionDeclarator(node: SyntaxNode): SyntaxNode | null {
|
||||
const declarator = node.childForFieldName('declarator');
|
||||
if (!declarator) return null;
|
||||
if (declarator.type === 'function_declarator') return declarator;
|
||||
// Recursively unwrap pointer_declarator / reference_declarator chains
|
||||
// (e.g. int** (*pfn)() has pointer_declarator → pointer_declarator → function_declarator)
|
||||
let current: SyntaxNode | null = declarator;
|
||||
while (current) {
|
||||
for (let i = 0; i < current.namedChildCount; i++) {
|
||||
const child = current.namedChild(i);
|
||||
if (child?.type === 'function_declarator') return child;
|
||||
}
|
||||
// Go deeper into nested pointer/reference declarators
|
||||
const next = current.namedChildren.find(
|
||||
(c) => c.type === 'pointer_declarator' || c.type === 'reference_declarator',
|
||||
);
|
||||
current = next ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect `= delete` and `= default` special member function declarations.
|
||||
* These are not callable methods and should be suppressed from extraction.
|
||||
* tree-sitter-cpp ^0.23.4 emits `delete_method_clause` / `default_method_clause`
|
||||
* as named children of the function_definition node.
|
||||
*/
|
||||
function isDeletedOrDefaulted(node: SyntaxNode): boolean {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === 'delete_method_clause' || child?.type === 'default_method_clause') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract method name from a function_declarator.
|
||||
* The name is the `declarator` field of the function_declarator — typically a
|
||||
* field_identifier, but can be a destructor_name (~ClassName) or operator name.
|
||||
*/
|
||||
function extractCppMethodName(node: SyntaxNode): string | undefined {
|
||||
const funcDecl = findFunctionDeclarator(node);
|
||||
if (!funcDecl) return undefined;
|
||||
|
||||
// Suppress `= delete` and `= default` special members — these are not callable
|
||||
// methods and should not appear in HAS_METHOD edges.
|
||||
if (isDeletedOrDefaulted(node)) return undefined;
|
||||
|
||||
const nameNode = funcDecl.childForFieldName('declarator');
|
||||
if (!nameNode) return undefined;
|
||||
// destructor_name: ~ClassName
|
||||
if (nameNode.type === 'destructor_name') return nameNode.text;
|
||||
// operator_name: operator==, operator+, etc.
|
||||
if (nameNode.type === 'operator_name') return nameNode.text;
|
||||
return nameNode.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract return type from the `type` field of the method node.
|
||||
* tree-sitter-cpp puts the return type as the `type` field on field_declaration
|
||||
* and function_definition nodes.
|
||||
*/
|
||||
function extractCppReturnType(node: SyntaxNode): string | undefined {
|
||||
const typeNode = node.childForFieldName('type');
|
||||
if (typeNode) {
|
||||
const typeText = typeNode.text?.trim();
|
||||
// C++11 trailing return type: `auto foo() -> ReturnType`
|
||||
// When the declared type is `auto`, check for a trailing_return_type on the
|
||||
// function_declarator which holds the actual return type.
|
||||
if (typeText === 'auto') {
|
||||
const funcDecl = findFunctionDeclarator(node);
|
||||
if (funcDecl) {
|
||||
for (let i = 0; i < funcDecl.namedChildCount; i++) {
|
||||
const child = funcDecl.namedChild(i);
|
||||
if (child?.type === 'trailing_return_type') {
|
||||
// trailing_return_type contains a type_descriptor with the real type
|
||||
const typeDesc = child.firstNamedChild;
|
||||
if (typeDesc) return typeDesc.text?.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return typeText;
|
||||
}
|
||||
// Fallback: first type-like named child (for declarations without type field)
|
||||
const first = node.firstNamedChild;
|
||||
if (
|
||||
first &&
|
||||
(first.type === 'primitive_type' ||
|
||||
first.type === 'type_identifier' ||
|
||||
first.type === 'sized_type_specifier' ||
|
||||
first.type === 'template_type')
|
||||
) {
|
||||
return first.text?.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from the parameter_list inside the function_declarator.
|
||||
*
|
||||
* C/C++ uses parameter_declaration (required) and optional_parameter_declaration
|
||||
* (with default value). Variadic `...` appears as a variadic_parameter_declaration.
|
||||
*/
|
||||
function extractCppParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const funcDecl = findFunctionDeclarator(node);
|
||||
if (!funcDecl) return [];
|
||||
const paramList = funcDecl.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
switch (param.type) {
|
||||
case 'parameter_declaration': {
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const declNode = param.childForFieldName('declarator');
|
||||
// Extract name — may be wrapped in pointer_declarator or reference_declarator
|
||||
const name = extractParamName(declNode);
|
||||
params.push({
|
||||
name: name ?? typeNode?.text?.trim() ?? '?',
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'optional_parameter_declaration': {
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const declNode = param.childForFieldName('declarator');
|
||||
const name = extractParamName(declNode);
|
||||
params.push({
|
||||
name: name ?? typeNode?.text?.trim() ?? '?',
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: true,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'variadic_parameter_declaration': {
|
||||
// C-style `...` or typed variadic `T... args`
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const declNode = param.childForFieldName('declarator');
|
||||
const name = extractParamName(declNode);
|
||||
params.push({
|
||||
name: name ?? '...',
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'variadic_parameter': {
|
||||
// Bare `...` (C-style)
|
||||
params.push({
|
||||
name: '...',
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// C/C++: bare `...` token in parameter list is an unnamed child (not a named node).
|
||||
// Check all children for the unnamed `...` token when no variadic was detected above.
|
||||
if (!params.some((p) => p.isVariadic)) {
|
||||
for (let i = 0; i < paramList.childCount; i++) {
|
||||
const child = paramList.child(i);
|
||||
if (child && !child.isNamed && child.text === '...') {
|
||||
params.push({
|
||||
name: '...',
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/** Extract parameter name, recursively unwrapping pointer/reference declarators. */
|
||||
function extractParamName(declNode: SyntaxNode | null): string | undefined {
|
||||
if (!declNode) return undefined;
|
||||
if (declNode.type === 'identifier') return declNode.text;
|
||||
// Recursively unwrap pointer_declarator / reference_declarator chains (e.g. int** ptr)
|
||||
for (let i = 0; i < declNode.namedChildCount; i++) {
|
||||
const child = declNode.namedChild(i);
|
||||
if (!child) continue;
|
||||
if (child.type === 'identifier') return child.text;
|
||||
if (child.type === 'pointer_declarator' || child.type === 'reference_declarator') {
|
||||
return extractParamName(child);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect C++ access specifier by walking backwards through siblings.
|
||||
* Mirrors the field extractor pattern in c-cpp.ts.
|
||||
*/
|
||||
function extractCppVisibility(node: SyntaxNode): MethodVisibility {
|
||||
// If this node was unwrapped from a template_declaration, the access_specifier
|
||||
// is a sibling of the template_declaration in field_declaration_list, not of
|
||||
// this node — climb up one level before walking backward.
|
||||
const startNode = node.parent?.type === 'template_declaration' ? node.parent : node;
|
||||
|
||||
let sibling = startNode.previousNamedSibling;
|
||||
while (sibling) {
|
||||
if (sibling.type === 'access_specifier') {
|
||||
const text = sibling.text.replace(':', '').trim();
|
||||
if (text === 'public' || text === 'private' || text === 'protected') return text;
|
||||
}
|
||||
sibling = sibling.previousNamedSibling;
|
||||
}
|
||||
// Default: struct/union = public, class = private
|
||||
const parent = startNode.parent?.parent;
|
||||
return parent?.type === 'struct_specifier' || parent?.type === 'union_specifier'
|
||||
? 'public'
|
||||
: 'private';
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect pure virtual methods (`= 0`).
|
||||
* tree-sitter-cpp emits `=` (unnamed) followed by `number_literal` with text `0`.
|
||||
*/
|
||||
function isPureVirtual(node: SyntaxNode): boolean {
|
||||
let foundEquals = false;
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
if (!child) continue;
|
||||
if (child.text === '=') {
|
||||
foundEquals = true;
|
||||
} else if (foundEquals && child.type === 'number_literal' && child.text === '0') {
|
||||
return true;
|
||||
} else if (foundEquals) {
|
||||
foundEquals = false; // Reset if something else follows `=`
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a virtual_specifier ('final' or 'override') inside the function_declarator.
|
||||
* In tree-sitter-cpp, these are named children of the function_declarator, not the
|
||||
* method node itself.
|
||||
*/
|
||||
function hasVirtualSpecifier(node: SyntaxNode, keyword: string): boolean {
|
||||
const funcDecl = findFunctionDeclarator(node);
|
||||
if (!funcDecl) return false;
|
||||
for (let i = 0; i < funcDecl.namedChildCount; i++) {
|
||||
const child = funcDecl.namedChild(i);
|
||||
if (child?.type === 'virtual_specifier' && child.text === keyword) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C++ config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// C++ methods appear as field_declaration (declarations) or function_definition
|
||||
// (inline definitions) inside field_declaration_list. The generic extractor
|
||||
// iterates bodyNodeTypes children and matches against methodNodeTypes.
|
||||
//
|
||||
// Key difference from TS/JVM/C#: C++ has no dedicated method_declaration node.
|
||||
// A field_declaration is a method if it contains a function_declarator.
|
||||
// The generic extractor calls extractName() on every methodNodeType node — if
|
||||
// extractName returns undefined (no function_declarator), the method is skipped.
|
||||
//
|
||||
// Known gaps:
|
||||
// - Out-of-class method definitions (void Foo::bar() {}) are not linked as
|
||||
// HAS_METHOD — they appear as top-level function_definition nodes.
|
||||
// This includes namespace-wrapped and nested classes.
|
||||
// - Friend declarations are not extracted.
|
||||
// - Template method declarations with explicit specialization.
|
||||
// - const-qualified method overloads (e.g. begin() vs begin() const) are
|
||||
// disambiguated via isConst flag and $const ID suffix.
|
||||
export const cppMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.CPlusPlus,
|
||||
typeDeclarationNodes: ['class_specifier', 'struct_specifier', 'union_specifier'],
|
||||
// declaration covers constructors/destructors; field_declaration covers method
|
||||
// declarations; function_definition covers inline method definitions.
|
||||
// Non-method declarations (variables, typedefs) are filtered by extractName
|
||||
// returning undefined when no function_declarator is found.
|
||||
methodNodeTypes: ['field_declaration', 'function_definition', 'declaration'],
|
||||
bodyNodeTypes: ['field_declaration_list'],
|
||||
|
||||
extractName: extractCppMethodName,
|
||||
extractReturnType: extractCppReturnType,
|
||||
extractParameters: extractCppParameters,
|
||||
extractVisibility: extractCppVisibility,
|
||||
|
||||
isStatic(node) {
|
||||
return hasKeyword(node, 'static');
|
||||
},
|
||||
|
||||
isAbstract(node) {
|
||||
return isPureVirtual(node);
|
||||
},
|
||||
|
||||
isFinal(node) {
|
||||
return hasVirtualSpecifier(node, 'final');
|
||||
},
|
||||
|
||||
isVirtual(node) {
|
||||
// In C++, override and method-level final are only legal on virtual functions,
|
||||
// so they imply virtual even without the explicit keyword.
|
||||
return (
|
||||
hasKeyword(node, 'virtual') ||
|
||||
hasVirtualSpecifier(node, 'override') ||
|
||||
hasVirtualSpecifier(node, 'final')
|
||||
);
|
||||
},
|
||||
|
||||
isOverride(node) {
|
||||
return hasVirtualSpecifier(node, 'override');
|
||||
},
|
||||
|
||||
isConst(node) {
|
||||
// const qualifier appears as a type_qualifier child of function_declarator,
|
||||
// after the parameter_list: e.g. `int size() const` → funcDecl has
|
||||
// type_qualifier child with text "const". Not to be confused with return-type
|
||||
// const (e.g. `const int& begin()`) which is at a different AST level.
|
||||
const funcDecl = findFunctionDeclarator(node);
|
||||
if (!funcDecl) return false;
|
||||
for (let i = 0; i < funcDecl.namedChildCount; i++) {
|
||||
const child = funcDecl.namedChild(i);
|
||||
if (child?.type === 'type_qualifier' && child.text === 'const') return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C config (minimal — C has no classes/methods, only struct function pointers)
|
||||
// Verified against tree-sitter-c 0.23.2
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// C does not have methods in the OOP sense. Structs with function pointer fields
|
||||
// are handled by the field extractor. This config exists for completeness but
|
||||
// will rarely match since C structs don't contain function_definition nodes.
|
||||
export const cMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.C,
|
||||
typeDeclarationNodes: ['struct_specifier'],
|
||||
methodNodeTypes: ['function_definition'],
|
||||
bodyNodeTypes: ['field_declaration_list'],
|
||||
|
||||
extractName: extractCppMethodName,
|
||||
extractReturnType: extractCppReturnType,
|
||||
extractParameters: extractCppParameters,
|
||||
|
||||
extractVisibility() {
|
||||
return 'public'; // C has no access control
|
||||
},
|
||||
|
||||
isStatic(node) {
|
||||
return hasKeyword(node, 'static');
|
||||
},
|
||||
|
||||
isAbstract() {
|
||||
return false; // C has no virtual/abstract
|
||||
},
|
||||
|
||||
isFinal() {
|
||||
return false;
|
||||
},
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/csharp.ts
|
||||
// Verified against tree-sitter-c-sharp 0.23.1
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
@@ -85,6 +86,7 @@ function extractParametersFromList(paramList: SyntaxNode): ParameterInfo[] {
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
@@ -126,6 +128,7 @@ function extractParametersFromList(paramList: SyntaxNode): ParameterInfo[] {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: typeName,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional,
|
||||
isVariadic: false,
|
||||
});
|
||||
@@ -186,6 +189,7 @@ export const csharpMethodConfig: MethodExtractionConfig = {
|
||||
'destructor_declaration',
|
||||
'operator_declaration',
|
||||
'conversion_operator_declaration',
|
||||
'local_function_statement',
|
||||
],
|
||||
bodyNodeTypes: ['declaration_list'],
|
||||
|
||||
@@ -221,7 +225,7 @@ export const csharpMethodConfig: MethodExtractionConfig = {
|
||||
// Constructors and destructors have no return type
|
||||
// operator_declaration and conversion_operator_declaration use 'type' field, not 'returns'
|
||||
const returnsNode = node.childForFieldName('returns');
|
||||
if (returnsNode) return extractSimpleTypeName(returnsNode) ?? returnsNode.text?.trim();
|
||||
if (returnsNode) return returnsNode.text?.trim();
|
||||
// Fallback for operator/conversion declarations that use 'type' as return type field
|
||||
if (node.type === 'operator_declaration' || node.type === 'conversion_operator_declaration') {
|
||||
const typeNode = node.childForFieldName('type');
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/dart.ts
|
||||
// Verified against tree-sitter-dart 1.0.0 (80e23c07)
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dart helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Type node types that represent a return type in function/getter/setter signatures. */
|
||||
const TYPE_NODE_TYPES = new Set([
|
||||
'type_identifier',
|
||||
'generic_type',
|
||||
'function_type',
|
||||
'nullable_type',
|
||||
'void_type',
|
||||
'record_type',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Dart method_signature is a WRAPPER node containing one inner signature:
|
||||
* function_signature, constructor_signature, getter_signature, setter_signature,
|
||||
* operator_signature, or factory_constructor_signature.
|
||||
*
|
||||
* Name, parameters, and return type live on the INNER signature, not on
|
||||
* method_signature itself.
|
||||
*/
|
||||
function getInnerSignature(node: SyntaxNode): SyntaxNode | null {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (
|
||||
child &&
|
||||
(child.type === 'function_signature' ||
|
||||
child.type === 'constructor_signature' ||
|
||||
child.type === 'getter_signature' ||
|
||||
child.type === 'setter_signature' ||
|
||||
child.type === 'operator_signature' ||
|
||||
child.type === 'factory_constructor_signature')
|
||||
) {
|
||||
return child;
|
||||
}
|
||||
}
|
||||
// `declaration` nodes (abstract methods) also wrap function_signature as a
|
||||
// named child — handled by the loop above.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the method name from a method_signature node.
|
||||
*
|
||||
* Descends into the inner signature to find the name field/identifier.
|
||||
*/
|
||||
function extractDartName(node: SyntaxNode): string | undefined {
|
||||
const inner = getInnerSignature(node);
|
||||
if (!inner) return undefined;
|
||||
|
||||
// constructor_signature name field may include "ClassName.namedCtor" via multiple children.
|
||||
// getter_signature, setter_signature, function_signature all have a 'name' field.
|
||||
if (inner.type === 'operator_signature') {
|
||||
// operator_signature has no 'name' field; name is 'operator' + the operator symbol
|
||||
for (let i = 0; i < inner.namedChildCount; i++) {
|
||||
const child = inner.namedChild(i);
|
||||
if (child?.type === 'binary_operator') {
|
||||
return `operator ${child.text.trim()}`;
|
||||
}
|
||||
}
|
||||
// Check for unnamed operator tokens like []= or ~
|
||||
for (let i = 0; i < inner.childCount; i++) {
|
||||
const child = inner.child(i);
|
||||
if (child && !child.isNamed && child.text.trim() !== 'operator') {
|
||||
const text = child.text.trim();
|
||||
if (text && !TYPE_NODE_TYPES.has(child.type)) {
|
||||
return `operator ${text}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (inner.type === 'getter_signature') {
|
||||
const nameNode = inner.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
}
|
||||
|
||||
if (inner.type === 'setter_signature') {
|
||||
const nameNode = inner.childForFieldName('name');
|
||||
return nameNode ? `set ${nameNode.text}` : undefined;
|
||||
}
|
||||
|
||||
if (inner.type === 'factory_constructor_signature') {
|
||||
// Collect all identifier children to form "ClassName" or "ClassName.named"
|
||||
const parts: string[] = [];
|
||||
for (let i = 0; i < inner.childCount; i++) {
|
||||
const child = inner.child(i);
|
||||
if (child?.isNamed && child.type === 'identifier') {
|
||||
parts.push(child.text);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join('.') : undefined;
|
||||
}
|
||||
|
||||
// function_signature and constructor_signature both have a 'name' field
|
||||
const nameNode = inner.childForFieldName('name');
|
||||
if (nameNode) {
|
||||
// constructor_signature: name field may be multiple identifiers joined by '.'
|
||||
return nameNode.text;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the return type from the inner signature.
|
||||
*
|
||||
* function_signature children include type nodes before the name.
|
||||
* getter_signature children include type nodes before 'get' keyword.
|
||||
* constructor/setter signatures have no return type.
|
||||
*/
|
||||
function extractDartReturnType(node: SyntaxNode): string | undefined {
|
||||
const inner = getInnerSignature(node);
|
||||
if (!inner) return undefined;
|
||||
|
||||
// Constructors and setters have no return type
|
||||
if (
|
||||
inner.type === 'constructor_signature' ||
|
||||
inner.type === 'setter_signature' ||
|
||||
inner.type === 'factory_constructor_signature'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// For function_signature, getter_signature, operator_signature:
|
||||
// The type node is a named child before the name/operator
|
||||
for (let i = 0; i < inner.namedChildCount; i++) {
|
||||
const child = inner.namedChild(i);
|
||||
if (child && TYPE_NODE_TYPES.has(child.type)) {
|
||||
return child.text?.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from the inner signature's formal_parameter_list.
|
||||
*
|
||||
* Dart parameters can be:
|
||||
* - Positional required: `int x`
|
||||
* - Optional positional: `[int? x]` — wrapped in optional_formal_parameters with '['
|
||||
* - Optional named: `{int? x}` or `{required int x}` — wrapped in optional_formal_parameters with '{'
|
||||
*/
|
||||
function extractDartParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const inner = getInnerSignature(node);
|
||||
if (!inner) return [];
|
||||
|
||||
// getter_signature has no parameters
|
||||
if (inner.type === 'getter_signature') return [];
|
||||
|
||||
// Find formal_parameter_list — it's a child, not a field in function_signature
|
||||
let paramList: SyntaxNode | null = null;
|
||||
if (inner.type === 'constructor_signature' || inner.type === 'factory_constructor_signature') {
|
||||
paramList = inner.childForFieldName('parameters');
|
||||
}
|
||||
if (!paramList) {
|
||||
for (let i = 0; i < inner.namedChildCount; i++) {
|
||||
const child = inner.namedChild(i);
|
||||
if (child?.type === 'formal_parameter_list') {
|
||||
paramList = child;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!paramList) return [];
|
||||
|
||||
return extractParamsFromList(paramList, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract ParameterInfo entries from a formal_parameter_list or optional_formal_parameters node.
|
||||
*/
|
||||
function extractParamsFromList(listNode: SyntaxNode, isOptionalBlock: boolean): ParameterInfo[] {
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < listNode.namedChildCount; i++) {
|
||||
const child = listNode.namedChild(i);
|
||||
if (!child) continue;
|
||||
|
||||
if (child.type === 'formal_parameter') {
|
||||
params.push(extractSingleParam(child, isOptionalBlock));
|
||||
} else if (child.type === 'optional_formal_parameters') {
|
||||
// Determine if these are named ({}) or positional ([]) optional params
|
||||
// by checking the surrounding delimiters
|
||||
params.push(...extractParamsFromList(child, true));
|
||||
}
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a single ParameterInfo from a formal_parameter node.
|
||||
*/
|
||||
function extractSingleParam(param: SyntaxNode, isOptionalBlock: boolean): ParameterInfo {
|
||||
const nameNode = param.childForFieldName('name');
|
||||
const name = nameNode?.text ?? '<unknown>';
|
||||
|
||||
// Find the type node
|
||||
let typeName: string | null = null;
|
||||
let rawTypeName: string | null = null;
|
||||
for (let i = 0; i < param.namedChildCount; i++) {
|
||||
const child = param.namedChild(i);
|
||||
if (child && TYPE_NODE_TYPES.has(child.type)) {
|
||||
rawTypeName = child.text?.trim() ?? null;
|
||||
typeName = extractSimpleTypeName(child) ?? rawTypeName;
|
||||
break;
|
||||
}
|
||||
// Also check type_identifier
|
||||
if (child?.type === 'type_identifier') {
|
||||
rawTypeName = child.text?.trim() ?? null;
|
||||
typeName = rawTypeName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for 'required' keyword:
|
||||
// 1. Among children of the param node itself
|
||||
let hasRequired = false;
|
||||
for (let i = 0; i < param.childCount; i++) {
|
||||
const child = param.child(i);
|
||||
if (child && child.text.trim() === 'required') {
|
||||
hasRequired = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 2. In tree-sitter-dart, `required` may be an anonymous sibling token
|
||||
// immediately preceding the formal_parameter inside optional_formal_parameters.
|
||||
if (!hasRequired) {
|
||||
let prev = param.previousSibling;
|
||||
// Skip comma separators
|
||||
while (prev && !prev.isNamed && prev.text.trim() === ',') {
|
||||
prev = prev.previousSibling;
|
||||
}
|
||||
if (prev && !prev.isNamed && prev.text.trim() === 'required') {
|
||||
hasRequired = true;
|
||||
}
|
||||
}
|
||||
|
||||
// A parameter is optional if it's inside an optional_formal_parameters block
|
||||
// and does NOT have the 'required' keyword
|
||||
const isOptional = isOptionalBlock && !hasRequired;
|
||||
|
||||
return {
|
||||
name,
|
||||
type: typeName,
|
||||
rawType: rawTypeName,
|
||||
isOptional,
|
||||
isVariadic: false, // Dart has no variadic params
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dart visibility: underscore prefix = private, else public.
|
||||
*
|
||||
* We resolve the name by descending into the inner signature.
|
||||
*/
|
||||
function extractDartVisibility(node: SyntaxNode): MethodVisibility {
|
||||
const name = extractDartName(node);
|
||||
if (!name) return 'public';
|
||||
|
||||
// Strip 'set ' or 'operator ' prefix to get the raw name
|
||||
const rawName = name.startsWith('set ')
|
||||
? name.slice(4)
|
||||
: name.startsWith('operator ')
|
||||
? name.slice(9)
|
||||
: name;
|
||||
|
||||
return rawName.startsWith('_') ? 'private' : 'public';
|
||||
}
|
||||
|
||||
/**
|
||||
* In tree-sitter-dart, `static` is an anonymous child token of
|
||||
* `method_signature` (or `declaration`), not a previous sibling.
|
||||
*
|
||||
* We check children first, then fall back to previous siblings for
|
||||
* grammar variants.
|
||||
*/
|
||||
function isDartStatic(node: SyntaxNode): boolean {
|
||||
// In tree-sitter-dart, `static` is an anonymous child token of method_signature
|
||||
// (or declaration), not a previous sibling.
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
if (child && !child.isNamed && child.text.trim() === 'static') return true;
|
||||
// Stop once we hit the inner signature — static always precedes it
|
||||
if (child?.isNamed) break;
|
||||
}
|
||||
// Also check previous siblings (fallback for grammar variants)
|
||||
let sibling = node.previousSibling;
|
||||
while (sibling) {
|
||||
if (sibling.isNamed && sibling.type !== 'annotation') break;
|
||||
if (!sibling.isNamed && sibling.text.trim() === 'static') return true;
|
||||
sibling = sibling.previousSibling;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Dart method is abstract if it has no function_body sibling following it.
|
||||
* In the tree-sitter grammar, function_body is a sibling of method_signature
|
||||
* in class_body.
|
||||
*/
|
||||
function isDartAbstract(node: SyntaxNode, _ownerNode: SyntaxNode): boolean {
|
||||
// `declaration` nodes in class_body represent abstract methods (no body, followed by ';').
|
||||
// Note: extension bodies cannot have abstract members in Dart, but `declaration` nodes
|
||||
// do not appear in extension_body in practice since extensions must provide implementations.
|
||||
if (node.type === 'declaration') return true;
|
||||
// For method_signature nodes, check if the next named sibling is a function_body
|
||||
const next = node.nextNamedSibling;
|
||||
return !next || next.type !== 'function_body';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for `async`, `async*`, or `sync*` keyword in the function_body sibling.
|
||||
* The keyword appears as an unnamed child of function_body, or
|
||||
* as a sibling keyword before function_body.
|
||||
*
|
||||
* Dart has three async-like forms: `async` (Future), `async*` (Stream), `sync*` (Iterable).
|
||||
* All three are treated as async for graph purposes.
|
||||
*/
|
||||
function isDartAsync(node: SyntaxNode): boolean {
|
||||
let sibling: SyntaxNode | null = node.nextSibling;
|
||||
let limit = 3;
|
||||
while (sibling && limit > 0) {
|
||||
if (!sibling.isNamed) {
|
||||
const text = sibling.text.trim();
|
||||
if (text === 'async' || text === 'async*' || text === 'sync*') return true;
|
||||
}
|
||||
if (sibling.isNamed && sibling.type === 'function_body') {
|
||||
// Check first child of function_body for async/async*/sync*
|
||||
for (let i = 0; i < sibling.childCount; i++) {
|
||||
const child = sibling.child(i);
|
||||
if (child) {
|
||||
const text = child.text.trim();
|
||||
if (text === 'async' || text === 'async*' || text === 'sync*') return true;
|
||||
}
|
||||
// Stop at first substantial child
|
||||
if (child?.isNamed) break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
sibling = sibling.nextSibling;
|
||||
limit--;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract annotations that appear as sibling nodes before the method_signature
|
||||
* in class_body. Each annotation node is prefixed with '@'.
|
||||
*/
|
||||
function extractDartAnnotations(node: SyntaxNode): string[] {
|
||||
const annotations: string[] = [];
|
||||
let sibling = node.previousNamedSibling;
|
||||
while (sibling && sibling.type === 'annotation') {
|
||||
// annotation node text already includes '@', e.g. "@override"
|
||||
const text = sibling.text?.trim();
|
||||
if (text) {
|
||||
// Normalize: strip arguments from annotation if present, keep just the name
|
||||
// e.g. "@deprecated" -> "@deprecated", "@JsonKey(name: 'id')" -> "@JsonKey"
|
||||
const match = text.match(/^@(\w+)/);
|
||||
if (match) {
|
||||
annotations.unshift('@' + match[1]);
|
||||
} else {
|
||||
annotations.unshift(text);
|
||||
}
|
||||
}
|
||||
sibling = sibling.previousNamedSibling;
|
||||
}
|
||||
return annotations;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dart config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const dartMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.Dart,
|
||||
typeDeclarationNodes: ['class_definition', 'mixin_declaration', 'extension_declaration'],
|
||||
methodNodeTypes: ['method_signature', 'declaration'],
|
||||
bodyNodeTypes: ['class_body', 'extension_body'],
|
||||
|
||||
extractName: extractDartName,
|
||||
extractReturnType: extractDartReturnType,
|
||||
extractParameters: extractDartParameters,
|
||||
extractVisibility: extractDartVisibility,
|
||||
|
||||
isStatic: isDartStatic,
|
||||
isAbstract: isDartAbstract,
|
||||
isFinal: () => false, // Dart methods cannot be 'final'
|
||||
isAsync: isDartAsync,
|
||||
|
||||
extractAnnotations: extractDartAnnotations,
|
||||
};
|
||||
@@ -0,0 +1,195 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/go.ts
|
||||
// Verified against tree-sitter-go 0.23.4
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Go helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Extract the method/function name.
|
||||
* - method_declaration: name is a `field_identifier`
|
||||
* - function_declaration: name is an `identifier`
|
||||
*/
|
||||
function extractGoName(node: SyntaxNode): string | undefined {
|
||||
const nameNode = node.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract return type from the `result` field.
|
||||
*
|
||||
* Go supports single return (`int`) and multi-return (`(User, error)`).
|
||||
* Multi-return appears as a `parameter_list` — extract the first type.
|
||||
*/
|
||||
function extractGoReturnType(node: SyntaxNode): string | undefined {
|
||||
const result = node.childForFieldName('result');
|
||||
if (!result) return undefined;
|
||||
|
||||
// Single return type (type_identifier, pointer_type, etc.)
|
||||
if (result.type !== 'parameter_list') {
|
||||
return result.text?.trim();
|
||||
}
|
||||
|
||||
// Multi-return: (Type, error) — extract first parameter's type
|
||||
for (let i = 0; i < result.namedChildCount; i++) {
|
||||
const param = result.namedChild(i);
|
||||
if (param?.type === 'parameter_declaration') {
|
||||
const typeNode = param.childForFieldName('type');
|
||||
if (typeNode) return typeNode.text?.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from the `parameters` field.
|
||||
*
|
||||
* Go parameter_list contains parameter_declaration nodes with optional
|
||||
* `name` and required `type` fields. Go allows multiple names for one type:
|
||||
* `func(a, b int)` — each name shares the type.
|
||||
*
|
||||
* Handles variadic_parameter_declaration (`...string`).
|
||||
*/
|
||||
function extractGoParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
if (param.type === 'parameter_declaration') {
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const typeName = typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null;
|
||||
|
||||
// Go allows multiple names for one type: func(a, b int)
|
||||
const names: string[] = [];
|
||||
for (let j = 0; j < param.namedChildCount; j++) {
|
||||
const child = param.namedChild(j);
|
||||
if (child?.type === 'identifier') {
|
||||
names.push(child.text);
|
||||
}
|
||||
}
|
||||
|
||||
const rawType = typeNode?.text?.trim() ?? null;
|
||||
if (names.length === 0) {
|
||||
// Unnamed parameter: func(int, string)
|
||||
params.push({
|
||||
name: `_${i}`,
|
||||
type: typeName,
|
||||
rawType,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
} else {
|
||||
for (const name of names) {
|
||||
params.push({ name, type: typeName, rawType, isOptional: false, isVariadic: false });
|
||||
}
|
||||
}
|
||||
} else if (param.type === 'variadic_parameter_declaration') {
|
||||
const nameNode = param.childForFieldName('name');
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const typeName = typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null;
|
||||
params.push({
|
||||
name: nameNode?.text ?? `_${i}`,
|
||||
type: typeName,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Go visibility: uppercase first character = exported (public), lowercase = unexported (private).
|
||||
*/
|
||||
function extractGoVisibility(node: SyntaxNode): MethodVisibility {
|
||||
const name = extractGoName(node);
|
||||
if (!name || name.length === 0) return 'private';
|
||||
const first = name[0];
|
||||
return first === first.toUpperCase() && first !== first.toLowerCase() ? 'public' : 'private';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract receiver type from the `receiver` field.
|
||||
*
|
||||
* The receiver is a parameter_list with one parameter_declaration:
|
||||
* (r *Repo) → pointer_type → type_identifier "Repo"
|
||||
* (r Repo) → type_identifier "Repo"
|
||||
*/
|
||||
function extractGoReceiverType(node: SyntaxNode): string | undefined {
|
||||
const receiver = node.childForFieldName('receiver');
|
||||
if (!receiver) return undefined;
|
||||
|
||||
for (let i = 0; i < receiver.namedChildCount; i++) {
|
||||
const param = receiver.namedChild(i);
|
||||
if (param?.type === 'parameter_declaration') {
|
||||
const typeNode = param.childForFieldName('type');
|
||||
if (!typeNode) continue;
|
||||
// Unwrap pointer_type: *User → User
|
||||
const inner = typeNode.type === 'pointer_type' ? typeNode.firstNamedChild : typeNode;
|
||||
return inner?.text;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve owner name from the receiver type.
|
||||
* For function_declaration (no receiver), returns undefined.
|
||||
*/
|
||||
function extractGoOwnerName(node: SyntaxNode): string | undefined {
|
||||
return extractGoReceiverType(node);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const goMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.Go,
|
||||
|
||||
// Each method_declaration/function_declaration is treated as its own "container"
|
||||
// for extractFromNode() — not used with extract() in the traditional sense.
|
||||
// method_elem covers interface method signatures (abstract methods).
|
||||
typeDeclarationNodes: ['method_declaration', 'function_declaration', 'method_elem'],
|
||||
methodNodeTypes: ['method_declaration', 'function_declaration', 'method_elem'],
|
||||
bodyNodeTypes: [],
|
||||
|
||||
extractName: extractGoName,
|
||||
extractReturnType: extractGoReturnType,
|
||||
extractParameters: extractGoParameters,
|
||||
extractVisibility: extractGoVisibility,
|
||||
extractReceiverType: extractGoReceiverType,
|
||||
extractOwnerName: extractGoOwnerName,
|
||||
|
||||
isStatic(node) {
|
||||
// Go functions (no receiver) are effectively static
|
||||
return node.type === 'function_declaration';
|
||||
},
|
||||
|
||||
isAbstract(node, _ownerNode) {
|
||||
// Go interface method signatures (method_elem) are abstract — no body
|
||||
return node.type === 'method_elem';
|
||||
},
|
||||
|
||||
isFinal(_node) {
|
||||
return false; // Go has no final methods
|
||||
},
|
||||
};
|
||||
@@ -19,7 +19,9 @@ const INTERFACE_OWNER_TYPES = new Set(['interface_declaration', 'annotation_type
|
||||
function extractReturnTypeFromField(node: SyntaxNode): string | undefined {
|
||||
const typeNode = node.childForFieldName('type');
|
||||
if (!typeNode) return undefined;
|
||||
return extractSimpleTypeName(typeNode) ?? typeNode.text?.trim();
|
||||
// Use .text to preserve full generic types (e.g. List<User>, Stream<T>)
|
||||
// needed by the call resolver for return-type inference.
|
||||
return typeNode.text?.trim();
|
||||
}
|
||||
|
||||
function extractAnnotations(node: SyntaxNode, modifierType: string): string[] {
|
||||
@@ -68,6 +70,7 @@ function extractJavaParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: typeNode ? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim()) : null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
@@ -76,6 +79,7 @@ function extractJavaParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
// Varargs: type_identifier + "..." + variable_declarator
|
||||
let paramName: string | undefined;
|
||||
let paramType: string | null = null;
|
||||
let paramRawType: string | null = null;
|
||||
for (let j = 0; j < param.namedChildCount; j++) {
|
||||
const c = param.namedChild(j);
|
||||
if (!c) continue;
|
||||
@@ -90,13 +94,15 @@ function extractJavaParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
c.type === 'floating_point_type' ||
|
||||
c.type === 'boolean_type'
|
||||
) {
|
||||
paramType = extractSimpleTypeName(c) ?? c.text?.trim();
|
||||
paramRawType = c.text?.trim() ?? null;
|
||||
paramType = extractSimpleTypeName(c) ?? paramRawType;
|
||||
}
|
||||
}
|
||||
if (paramName) {
|
||||
params.push({
|
||||
name: paramName,
|
||||
type: paramType,
|
||||
rawType: paramRawType,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
@@ -192,6 +198,7 @@ function extractKotlinParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
|
||||
let paramName: string | undefined;
|
||||
let paramType: string | null = null;
|
||||
let paramRawType: string | null = null;
|
||||
let hasDefault = false;
|
||||
const isVariadic = nextIsVariadic;
|
||||
nextIsVariadic = false;
|
||||
@@ -206,7 +213,8 @@ function extractKotlinParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
part.type === 'nullable_type' ||
|
||||
part.type === 'function_type'
|
||||
) {
|
||||
paramType = extractSimpleTypeName(part) ?? part.text?.trim();
|
||||
paramRawType = part.text?.trim() ?? null;
|
||||
paramType = extractSimpleTypeName(part) ?? paramRawType;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,6 +231,7 @@ function extractKotlinParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
params.push({
|
||||
name: paramName,
|
||||
type: paramType,
|
||||
rawType: paramRawType,
|
||||
isOptional: hasDefault,
|
||||
isVariadic: isVariadic,
|
||||
});
|
||||
@@ -252,7 +261,7 @@ function extractKotlinReturnType(node: SyntaxNode): string | undefined {
|
||||
child.type === 'nullable_type' ||
|
||||
child.type === 'function_type')
|
||||
) {
|
||||
return extractSimpleTypeName(child) ?? child.text?.trim();
|
||||
return child.text?.trim();
|
||||
}
|
||||
if (child.type === 'function_body') break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/php.ts
|
||||
// Verified against tree-sitter-php 0.23.12
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PHP helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Regex to extract PHPDoc @return annotations: `@return User` */
|
||||
const PHPDOC_RETURN_RE = /@return\s+(\S+)/;
|
||||
|
||||
/** Node types to skip when walking backwards through siblings for PHPDoc. */
|
||||
const PHPDOC_SKIP_NODE_TYPES: ReadonlySet<string> = new Set(['attribute_list', 'attribute']);
|
||||
|
||||
/**
|
||||
* Normalize a PHPDoc return type for the MethodExtractor.
|
||||
* Strips nullable prefix, null/false/void unions, namespace prefixes, and
|
||||
* rejects uninformative types (mixed, void, self, static, object, array).
|
||||
*/
|
||||
function normalizePhpReturnType(raw: string): string | undefined {
|
||||
let type = raw.startsWith('?') ? raw.slice(1) : raw;
|
||||
const parts = type
|
||||
.split('|')
|
||||
.filter((p) => p !== 'null' && p !== 'false' && p !== 'void' && p !== 'mixed');
|
||||
if (parts.length !== 1) return undefined;
|
||||
type = parts[0];
|
||||
const segments = type.split('\\');
|
||||
type = segments[segments.length - 1];
|
||||
if (
|
||||
type === 'mixed' ||
|
||||
type === 'void' ||
|
||||
type === 'self' ||
|
||||
type === 'static' ||
|
||||
type === 'object' ||
|
||||
type === 'array'
|
||||
)
|
||||
return undefined;
|
||||
if (/^\w+(\[\])?$/.test(type) || /^\w+\s*</.test(type)) return type;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk backwards through preceding siblings of `node` to find a PHPDoc
|
||||
* `@return Type` annotation. Skips `attribute_list` nodes (PHP 8 attributes).
|
||||
*/
|
||||
function extractPhpDocReturnType(node: SyntaxNode): string | undefined {
|
||||
let sibling = node.previousSibling;
|
||||
while (sibling) {
|
||||
if (sibling.type === 'comment') {
|
||||
const match = PHPDOC_RETURN_RE.exec(sibling.text);
|
||||
if (match) return normalizePhpReturnType(match[1]);
|
||||
} else if (sibling.isNamed && !PHPDOC_SKIP_NODE_TYPES.has(sibling.type)) {
|
||||
break;
|
||||
}
|
||||
sibling = sibling.previousSibling;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const PHP_VIS = new Set<MethodVisibility>(['public', 'private', 'protected']);
|
||||
|
||||
/**
|
||||
* Find the visibility keyword from a visibility_modifier named child.
|
||||
* PHP tree-sitter emits `visibility_modifier` as a named node with text
|
||||
* "public", "private", or "protected".
|
||||
*/
|
||||
function findPhpVisibility(node: SyntaxNode): MethodVisibility {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === 'visibility_modifier') {
|
||||
const text = child.text.trim() as MethodVisibility;
|
||||
if (PHP_VIS.has(text)) return text;
|
||||
}
|
||||
}
|
||||
return 'public'; // PHP methods are public by default
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a named modifier child of a specific type.
|
||||
* PHP tree-sitter uses distinct node types: abstract_modifier, final_modifier,
|
||||
* static_modifier — rather than a wrapper `modifiers` node with keyword children.
|
||||
*/
|
||||
function hasModifierNode(node: SyntaxNode, modifierType: string): boolean {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === modifierType) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the return type from a PHP method_declaration node.
|
||||
*
|
||||
* In tree-sitter-php, the return type is not exposed via a named field.
|
||||
* It appears as a type node (primitive_type, named_type, union_type,
|
||||
* optional_type, nullable_type, intersection_type) after the formal_parameters
|
||||
* and a `:` token separator.
|
||||
*
|
||||
* When the AST return type is missing or uninformative (`array` / `iterable`),
|
||||
* falls back to parsing PHPDoc `@return Type` from preceding doc comments.
|
||||
*/
|
||||
function extractPhpReturnType(node: SyntaxNode): string | undefined {
|
||||
const TYPE_NODE_TYPES = new Set([
|
||||
'primitive_type',
|
||||
'named_type',
|
||||
'union_type',
|
||||
'optional_type',
|
||||
'nullable_type',
|
||||
'intersection_type',
|
||||
]);
|
||||
|
||||
let astType: string | undefined;
|
||||
let seenParams = false;
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
if (!child) continue;
|
||||
if (child.type === 'formal_parameters') {
|
||||
seenParams = true;
|
||||
continue;
|
||||
}
|
||||
// After the parameters node, look for the colon and then the type
|
||||
if (seenParams && child.isNamed && TYPE_NODE_TYPES.has(child.type)) {
|
||||
astType = child.text?.trim();
|
||||
break;
|
||||
}
|
||||
// Stop at body or semicolon
|
||||
if (child.type === 'compound_statement' || (!child.isNamed && child.text === ';')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If AST type is missing or uninformative, try PHPDoc @return fallback
|
||||
if (!astType || astType === 'array' || astType === 'iterable') {
|
||||
const docType = extractPhpDocReturnType(node);
|
||||
if (docType) return docType;
|
||||
}
|
||||
|
||||
return astType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from a PHP method_declaration node.
|
||||
*
|
||||
* PHP parameter types in tree-sitter-php:
|
||||
* - `simple_parameter`: regular parameter with optional type and default
|
||||
* - `variadic_parameter`: `...$param` with optional type
|
||||
* - `property_promotion_parameter`: constructor promotion `private string $name`
|
||||
* (may also be variadic via an ERROR node containing `...`)
|
||||
*/
|
||||
function extractPhpParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
if (param.type === 'simple_parameter') {
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (!nameNode) continue;
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const typeName = typeNode ? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim()) : null;
|
||||
|
||||
// Detect optional: '=' token among children indicates a default value
|
||||
let isOptional = false;
|
||||
for (let j = 0; j < param.childCount; j++) {
|
||||
const c = param.child(j);
|
||||
if (c && !c.isNamed && c.text === '=') {
|
||||
isOptional = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
params.push({
|
||||
name: stripDollar(nameNode.text),
|
||||
type: typeName ?? null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional,
|
||||
isVariadic: false,
|
||||
});
|
||||
} else if (param.type === 'variadic_parameter') {
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (!nameNode) continue;
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const typeName = typeNode ? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim()) : null;
|
||||
|
||||
params.push({
|
||||
name: stripDollar(nameNode.text),
|
||||
type: typeName ?? null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
} else if (param.type === 'property_promotion_parameter') {
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (!nameNode) continue;
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const typeName = typeNode ? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim()) : null;
|
||||
|
||||
// Detect variadic: an ERROR child containing "..." indicates variadic promotion
|
||||
let isVariadic = false;
|
||||
for (let j = 0; j < param.childCount; j++) {
|
||||
const c = param.child(j);
|
||||
if (c && (c.text === '...' || (c.type === 'ERROR' && c.text === '...'))) {
|
||||
isVariadic = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
params.push({
|
||||
name: stripDollar(nameNode.text),
|
||||
type: typeName ?? null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/** Strip leading $ from PHP variable names. */
|
||||
function stripDollar(name: string): string {
|
||||
return name.startsWith('$') ? name.slice(1) : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract PHP 8 attributes (#[...]) from a method_declaration node.
|
||||
*
|
||||
* AST structure: attribute_list → attribute_group → attribute → name child.
|
||||
* Names are prefixed with '#' to distinguish from Java/Kotlin @ annotations.
|
||||
*/
|
||||
function extractPhpAnnotations(node: SyntaxNode): string[] {
|
||||
const annotations: string[] = [];
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (!child || child.type !== 'attribute_list') continue;
|
||||
for (let j = 0; j < child.namedChildCount; j++) {
|
||||
const group = child.namedChild(j);
|
||||
if (!group || group.type !== 'attribute_group') continue;
|
||||
for (let k = 0; k < group.namedChildCount; k++) {
|
||||
const attr = group.namedChild(k);
|
||||
if (!attr || attr.type !== 'attribute') continue;
|
||||
const nameNode = attr.firstNamedChild;
|
||||
if (nameNode && nameNode.type === 'name') {
|
||||
annotations.push('#' + nameNode.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return annotations;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PHP config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const phpMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.PHP,
|
||||
typeDeclarationNodes: [
|
||||
'class_declaration',
|
||||
'interface_declaration',
|
||||
'trait_declaration',
|
||||
'enum_declaration',
|
||||
],
|
||||
methodNodeTypes: ['method_declaration', 'function_definition'],
|
||||
bodyNodeTypes: ['declaration_list'],
|
||||
|
||||
extractName(node) {
|
||||
return node.childForFieldName('name')?.text;
|
||||
},
|
||||
|
||||
extractReturnType: extractPhpReturnType,
|
||||
|
||||
extractParameters: extractPhpParameters,
|
||||
|
||||
extractVisibility: findPhpVisibility,
|
||||
|
||||
isStatic(node) {
|
||||
return hasModifierNode(node, 'static_modifier');
|
||||
},
|
||||
|
||||
isAbstract(node, ownerNode) {
|
||||
if (hasModifierNode(node, 'abstract_modifier')) return true;
|
||||
// Interface methods are implicitly abstract when they have no body.
|
||||
// Check ownerNode first, then fall back to walking the parent chain
|
||||
// (needed when called from extractFromNode where ownerNode === node).
|
||||
let isInterface = ownerNode.type === 'interface_declaration';
|
||||
if (!isInterface) {
|
||||
let p = node.parent;
|
||||
while (p) {
|
||||
if (p.type === 'interface_declaration') {
|
||||
isInterface = true;
|
||||
break;
|
||||
}
|
||||
p = p.parent;
|
||||
}
|
||||
}
|
||||
if (isInterface) {
|
||||
const body = node.childForFieldName('body');
|
||||
if (body) return false;
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
if (node.namedChild(i)?.type === 'compound_statement') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
isFinal(node) {
|
||||
return hasModifierNode(node, 'final_modifier');
|
||||
},
|
||||
|
||||
extractAnnotations: extractPhpAnnotations,
|
||||
};
|
||||
@@ -0,0 +1,325 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/python.ts
|
||||
// Verified against tree-sitter-python 0.23.4
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { hasKeyword } from '../../field-extractors/configs/helpers.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Python helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Names that represent the instance/class receiver — not real parameters. */
|
||||
const SELF_NAMES = new Set(['self', 'cls']);
|
||||
|
||||
/**
|
||||
* Unwrap a decorated_definition to its inner function_definition.
|
||||
*
|
||||
* tree-sitter-python wraps decorated functions/methods in a `decorated_definition`
|
||||
* node that contains the decorators as children followed by the function_definition.
|
||||
* This is different from TS/JS where decorators are siblings.
|
||||
*/
|
||||
function unwrapDecorated(node: SyntaxNode): SyntaxNode {
|
||||
if (node.type === 'decorated_definition') {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child && child.type === 'function_definition') return child;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect decorator names from a decorated_definition wrapper.
|
||||
*
|
||||
* Returns decorator names prefixed with '@'. If the node is a plain
|
||||
* function_definition (no decorators), check if its parent is a
|
||||
* decorated_definition and collect from there.
|
||||
*/
|
||||
function collectDecorators(node: SyntaxNode): SyntaxNode[] {
|
||||
let wrapper: SyntaxNode | null = null;
|
||||
if (node.type === 'decorated_definition') {
|
||||
wrapper = node;
|
||||
} else if (node.parent?.type === 'decorated_definition') {
|
||||
wrapper = node.parent;
|
||||
}
|
||||
if (!wrapper) return [];
|
||||
|
||||
const decorators: SyntaxNode[] = [];
|
||||
for (let i = 0; i < wrapper.namedChildCount; i++) {
|
||||
const child = wrapper.namedChild(i);
|
||||
if (child && child.type === 'decorator') {
|
||||
decorators.push(child);
|
||||
}
|
||||
}
|
||||
return decorators;
|
||||
}
|
||||
|
||||
function extractDecoratorName(decorator: SyntaxNode): string | undefined {
|
||||
// decorator > identifier (simple)
|
||||
// decorator > call > identifier (call-style, e.g. @lru_cache())
|
||||
// decorator > attribute (dotted, e.g. @abc.abstractmethod)
|
||||
const expr = decorator.firstNamedChild;
|
||||
if (!expr) return undefined;
|
||||
|
||||
if (expr.type === 'identifier') return '@' + expr.text;
|
||||
if (expr.type === 'attribute') return '@' + expr.text;
|
||||
if (expr.type === 'call') {
|
||||
const fn = expr.childForFieldName('function');
|
||||
return fn ? '@' + fn.text : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function hasDecorator(node: SyntaxNode, name: string): boolean {
|
||||
const decorators = collectDecorators(node);
|
||||
for (const dec of decorators) {
|
||||
const decName = extractDecoratorName(dec);
|
||||
if (decName === '@' + name || decName?.endsWith('.' + name)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from a Python function_definition.
|
||||
*
|
||||
* Handles: identifier, default_parameter, typed_parameter, typed_default_parameter,
|
||||
* list_splat_pattern (*args), dictionary_splat_pattern (**kwargs), and typed variants.
|
||||
* Skips `self` and `cls` first parameters.
|
||||
*/
|
||||
function extractPythonParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const funcNode = unwrapDecorated(node);
|
||||
const paramList = funcNode.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
|
||||
const params: ParameterInfo[] = [];
|
||||
let isFirst = true;
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
switch (param.type) {
|
||||
case 'identifier': {
|
||||
// Bare parameter: `self`, `cls`, or untyped `x`
|
||||
if (isFirst && SELF_NAMES.has(param.text)) {
|
||||
isFirst = false;
|
||||
continue;
|
||||
}
|
||||
isFirst = false;
|
||||
params.push({
|
||||
name: param.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'default_parameter': {
|
||||
// `x = value` — untyped with default
|
||||
isFirst = false;
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: true,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'typed_parameter': {
|
||||
// `x: int` or `*args: str` or `**kwargs: int`
|
||||
// The first named child can be identifier, list_splat_pattern, or dictionary_splat_pattern
|
||||
const inner = param.firstNamedChild;
|
||||
if (!inner) break;
|
||||
|
||||
if (isFirst && inner.type === 'identifier' && SELF_NAMES.has(inner.text)) {
|
||||
isFirst = false;
|
||||
continue;
|
||||
}
|
||||
isFirst = false;
|
||||
|
||||
const typeNode = param.childForFieldName('type');
|
||||
const typeText = typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null;
|
||||
|
||||
const rawTypeText = typeNode?.text?.trim() ?? null;
|
||||
if (inner.type === 'list_splat_pattern') {
|
||||
const nameId = inner.firstNamedChild;
|
||||
if (nameId) {
|
||||
params.push({
|
||||
name: nameId.text,
|
||||
type: typeText,
|
||||
rawType: rawTypeText,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
} else if (inner.type === 'dictionary_splat_pattern') {
|
||||
const nameId = inner.firstNamedChild;
|
||||
if (nameId) {
|
||||
params.push({
|
||||
name: nameId.text,
|
||||
type: typeText,
|
||||
rawType: rawTypeText,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
params.push({
|
||||
name: inner.text,
|
||||
type: typeText,
|
||||
rawType: rawTypeText,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'typed_default_parameter': {
|
||||
// `x: int = 5` — typed with default
|
||||
isFirst = false;
|
||||
const nameNode = param.childForFieldName('name');
|
||||
const typeNode = param.childForFieldName('type');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: true,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'list_splat_pattern': {
|
||||
// `*args` (untyped)
|
||||
isFirst = false;
|
||||
const nameId = param.firstNamedChild;
|
||||
if (nameId) {
|
||||
params.push({
|
||||
name: nameId.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'dictionary_splat_pattern': {
|
||||
// `**kwargs` (untyped)
|
||||
isFirst = false;
|
||||
const nameId = param.firstNamedChild;
|
||||
if (nameId) {
|
||||
params.push({
|
||||
name: nameId.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
isFirst = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract return type from the `return_type` field.
|
||||
*
|
||||
* tree-sitter-python uses a `type` field on function_definition for the return
|
||||
* type annotation (e.g. `-> str`). The field contains a type node.
|
||||
*/
|
||||
function extractPythonReturnType(node: SyntaxNode): string | undefined {
|
||||
const funcNode = unwrapDecorated(node);
|
||||
const returnType = funcNode.childForFieldName('return_type');
|
||||
if (!returnType) return undefined;
|
||||
// Use .text to preserve full generic types (e.g. list[User], Dict[str, User])
|
||||
// that the call resolver needs for for-loop iterable and return-type inference.
|
||||
return returnType.text?.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract visibility based on Python name-mangling convention.
|
||||
* `__name` (not dunder) = private, `_name` = protected, else public.
|
||||
*/
|
||||
function extractPythonVisibility(node: SyntaxNode): MethodVisibility {
|
||||
const funcNode = unwrapDecorated(node);
|
||||
const nameNode = funcNode.childForFieldName('name');
|
||||
const name = nameNode?.text;
|
||||
if (!name) return 'public';
|
||||
if (name.startsWith('__') && !name.endsWith('__')) return 'private';
|
||||
if (name.startsWith('_') && !(name.startsWith('__') && name.endsWith('__'))) return 'protected';
|
||||
return 'public';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const pythonMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.Python,
|
||||
typeDeclarationNodes: ['class_definition'],
|
||||
// Both function_definition and decorated_definition must be listed:
|
||||
// decorated methods appear as decorated_definition in the class body block,
|
||||
// while undecorated methods appear as function_definition directly.
|
||||
methodNodeTypes: ['function_definition', 'decorated_definition'],
|
||||
bodyNodeTypes: ['block'],
|
||||
|
||||
extractName(node) {
|
||||
const funcNode = unwrapDecorated(node);
|
||||
const nameNode = funcNode.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
},
|
||||
|
||||
extractReturnType: extractPythonReturnType,
|
||||
extractParameters: extractPythonParameters,
|
||||
extractVisibility: extractPythonVisibility,
|
||||
|
||||
isStatic(node) {
|
||||
return hasDecorator(node, 'staticmethod') || hasDecorator(node, 'classmethod');
|
||||
},
|
||||
|
||||
isAbstract(node, _ownerNode) {
|
||||
return hasDecorator(node, 'abstractmethod');
|
||||
},
|
||||
|
||||
isFinal(_node) {
|
||||
return false; // @typing.final (PEP 591) is captured in annotations; isFinal not modeled
|
||||
},
|
||||
|
||||
extractAnnotations(node) {
|
||||
const decorators = collectDecorators(node);
|
||||
const annotations: string[] = [];
|
||||
for (const dec of decorators) {
|
||||
const name = extractDecoratorName(dec);
|
||||
if (name) annotations.push(name);
|
||||
}
|
||||
return annotations;
|
||||
},
|
||||
|
||||
isAsync(node) {
|
||||
const funcNode = unwrapDecorated(node);
|
||||
return hasKeyword(funcNode, 'async');
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,303 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/ruby.ts
|
||||
// Verified against tree-sitter-ruby 0.23.1
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ruby helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VISIBILITY_MODIFIERS = new Set(['private', 'protected', 'public']);
|
||||
|
||||
/** Regex to extract YARD `@return [Type]` annotations from comments. */
|
||||
const YARD_RETURN_RE = /@return\s+\[([^\]]+)\]/;
|
||||
|
||||
/**
|
||||
* Extract the simple type name from a YARD type string.
|
||||
* Handles qualified types ("Models::User" -> "User"), generics ("Array<User>"
|
||||
* -> "Array"), nullable ("String, nil" -> "String"), and rejects ambiguous
|
||||
* unions ("String, Integer" -> undefined).
|
||||
*/
|
||||
function extractYardTypeName(yardType: string): string | undefined {
|
||||
const trimmed = yardType.trim();
|
||||
|
||||
// Bracket-balanced split on commas to handle generics like Hash<Symbol, User>
|
||||
const parts: string[] = [];
|
||||
let depth = 0,
|
||||
start = 0;
|
||||
for (let i = 0; i < trimmed.length; i++) {
|
||||
if (trimmed[i] === '<') depth++;
|
||||
else if (trimmed[i] === '>') depth--;
|
||||
else if (trimmed[i] === ',' && depth === 0) {
|
||||
parts.push(trimmed.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
parts.push(trimmed.slice(start).trim());
|
||||
const filtered = parts.filter((p) => p !== '' && p !== 'nil');
|
||||
if (filtered.length !== 1) return undefined; // ambiguous union
|
||||
|
||||
const typePart = filtered[0];
|
||||
|
||||
// Qualified: "Models::User" -> "User"
|
||||
const segments = typePart.split('::');
|
||||
const last = segments[segments.length - 1];
|
||||
|
||||
// Generic: "Array<User>" -> "Array"
|
||||
const genericMatch = last.match(/^(\w+)\s*[<{(]/);
|
||||
if (genericMatch) return genericMatch[1];
|
||||
|
||||
// Simple identifier
|
||||
if (/^\w+$/.test(last)) return last;
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract visibility for a Ruby method by walking backwards through the
|
||||
* parent body_statement's named children from the method node's position.
|
||||
*
|
||||
* Ruby visibility modifiers (private, protected, public) appear as bare
|
||||
* `identifier` nodes in the body_statement. The most recent modifier
|
||||
* before the method determines its visibility. Default is public.
|
||||
*
|
||||
* Example AST for:
|
||||
* class Foo
|
||||
* private
|
||||
* def secret; end
|
||||
* end
|
||||
*
|
||||
* body_statement
|
||||
* identifier "private" ← index 0
|
||||
* method "def secret" ← index 1
|
||||
*/
|
||||
function extractRubyVisibility(node: SyntaxNode): MethodVisibility {
|
||||
const parent = node.parent;
|
||||
if (!parent) return 'public';
|
||||
|
||||
// Find the index of this method node in the parent's named children
|
||||
let methodIndex = -1;
|
||||
for (let i = 0; i < parent.namedChildCount; i++) {
|
||||
if (parent.namedChild(i) === node) {
|
||||
methodIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (methodIndex < 0) return 'public';
|
||||
|
||||
// Walk backwards from the method node looking for a visibility modifier
|
||||
for (let i = methodIndex - 1; i >= 0; i--) {
|
||||
const sibling = parent.namedChild(i);
|
||||
if (!sibling) continue;
|
||||
if (sibling.type === 'identifier' && VISIBILITY_MODIFIERS.has(sibling.text)) {
|
||||
return sibling.text as MethodVisibility;
|
||||
}
|
||||
// module_function makes instance methods private
|
||||
if (sibling.type === 'identifier' && sibling.text === 'module_function') {
|
||||
return 'private';
|
||||
}
|
||||
}
|
||||
return 'public';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from a Ruby method's method_parameters node.
|
||||
*
|
||||
* Handles: identifier, optional_parameter (default), splat_parameter (*args),
|
||||
* hash_splat_parameter (**kwargs), block_parameter (&block), keyword_parameter.
|
||||
*/
|
||||
function extractRubyParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
switch (param.type) {
|
||||
case 'identifier': {
|
||||
// Plain parameter: def foo(x)
|
||||
params.push({
|
||||
name: param.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'optional_parameter': {
|
||||
// Default parameter: def foo(x = 10)
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: true,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'splat_parameter': {
|
||||
// Splat: def foo(*args)
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'hash_splat_parameter': {
|
||||
// Double splat: def foo(**kwargs)
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'block_parameter': {
|
||||
// Block: def foo(&block)
|
||||
const nameNode = param.childForFieldName('name');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'keyword_parameter': {
|
||||
// Keyword: def foo(name:) or def foo(name: "default")
|
||||
const nameNode = param.childForFieldName('name');
|
||||
const valueNode = param.childForFieldName('value');
|
||||
if (nameNode) {
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: !!valueNode,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const rubyMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.Ruby,
|
||||
typeDeclarationNodes: ['class', 'module', 'singleton_class'],
|
||||
methodNodeTypes: ['method', 'singleton_method'],
|
||||
bodyNodeTypes: ['body_statement'],
|
||||
|
||||
extractOwnerName(node) {
|
||||
// singleton_class (class << self) inherits the enclosing class/module name
|
||||
if (node.type === 'singleton_class') {
|
||||
let ancestor = node.parent;
|
||||
while (ancestor) {
|
||||
if (ancestor.type === 'class' || ancestor.type === 'module') {
|
||||
const nameNode = ancestor.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
}
|
||||
ancestor = ancestor.parent;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
return undefined; // use default resolution for class/module
|
||||
},
|
||||
|
||||
extractName(node) {
|
||||
const nameNode = node.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
},
|
||||
|
||||
extractReturnType(node) {
|
||||
// Walk backwards through preceding siblings looking for YARD @return [Type].
|
||||
// Try direct siblings first, then fall back to parent (body_statement) siblings
|
||||
// for class methods where the comment may be a sibling of the body_statement.
|
||||
const search = (startNode: SyntaxNode): string | undefined => {
|
||||
let sibling = startNode.previousSibling;
|
||||
while (sibling) {
|
||||
if (sibling.type === 'comment') {
|
||||
const match = YARD_RETURN_RE.exec(sibling.text);
|
||||
if (match) return extractYardTypeName(match[1]);
|
||||
} else if (sibling.isNamed) {
|
||||
break;
|
||||
}
|
||||
sibling = sibling.previousSibling;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const result = search(node);
|
||||
if (result) return result;
|
||||
|
||||
if (node.parent?.type === 'body_statement') {
|
||||
return search(node.parent);
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
|
||||
extractParameters: extractRubyParameters,
|
||||
extractVisibility: extractRubyVisibility,
|
||||
|
||||
isStatic(node) {
|
||||
if (node.type === 'singleton_method') return true;
|
||||
// module_function makes following methods callable at module level (static)
|
||||
const parent = node.parent;
|
||||
if (!parent) return false;
|
||||
let methodIndex = -1;
|
||||
for (let i = 0; i < parent.namedChildCount; i++) {
|
||||
if (parent.namedChild(i) === node) {
|
||||
methodIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (let i = methodIndex - 1; i >= 0; i--) {
|
||||
const sibling = parent.namedChild(i);
|
||||
if (!sibling) continue;
|
||||
if (sibling.type === 'identifier' && sibling.text === 'module_function') return true;
|
||||
// Other visibility modifiers override module_function
|
||||
if (sibling.type === 'identifier' && VISIBILITY_MODIFIERS.has(sibling.text)) return false;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
isAbstract(_node, _ownerNode) {
|
||||
return false; // Ruby has no abstract methods
|
||||
},
|
||||
|
||||
isFinal(_node) {
|
||||
return false; // Ruby has no final methods
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,211 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/rust.ts
|
||||
// Verified against tree-sitter-rust 0.23.1
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rust helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Extract method name from function_item or function_signature_item.
|
||||
* Both use a `name` field containing an identifier.
|
||||
*/
|
||||
function extractRustMethodName(node: SyntaxNode): string | undefined {
|
||||
const nameNode = node.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract return type from the `return_type` field.
|
||||
* tree-sitter-rust puts the return type (after `->`) as the `return_type` field.
|
||||
*/
|
||||
function extractRustReturnType(node: SyntaxNode): string | undefined {
|
||||
const typeNode = node.childForFieldName('return_type');
|
||||
if (!typeNode) return undefined;
|
||||
return typeNode.text?.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters, skipping the self_parameter (handled by extractReceiverType).
|
||||
*
|
||||
* Rust parameters use `pattern` and `type` fields:
|
||||
* parameter { pattern: identifier, type: primitive_type }
|
||||
*/
|
||||
function extractRustParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
// Skip self_parameter — it is the receiver, not a regular parameter
|
||||
if (param.type === 'self_parameter') continue;
|
||||
|
||||
if (param.type === 'parameter') {
|
||||
const patternNode = param.childForFieldName('pattern');
|
||||
const typeNode = param.childForFieldName('type');
|
||||
params.push({
|
||||
name: patternNode?.text ?? '?',
|
||||
type: typeNode ? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null) : null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect visibility from visibility_modifier named child.
|
||||
* `pub`, `pub(crate)`, `pub(super)`, `pub(in path)` → public.
|
||||
* Absence → private (Rust default).
|
||||
*/
|
||||
function extractRustVisibility(node: SyntaxNode): MethodVisibility {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === 'visibility_modifier') return 'public';
|
||||
}
|
||||
return 'private';
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect receiver type from the first parameter if it is a self_parameter.
|
||||
*
|
||||
* Variants:
|
||||
* - `self` → "self"
|
||||
* - `&self` → "&self"
|
||||
* - `&mut self` → "&mut self"
|
||||
* - `mut self` → "mut self"
|
||||
* - `self: Box<Self>` → "Box<Self>" (explicit self type)
|
||||
*/
|
||||
function extractRustReceiverType(node: SyntaxNode): string | undefined {
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return undefined;
|
||||
const first = paramList.namedChild(0);
|
||||
if (!first || first.type !== 'self_parameter') return undefined;
|
||||
return first.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a function_item has the `async` keyword.
|
||||
* tree-sitter-rust wraps it in a `function_modifiers` named child.
|
||||
*/
|
||||
function isRustAsync(node: SyntaxNode): boolean {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === 'function_modifiers' && child.text.includes('async')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract attributes from preceding sibling attribute_item nodes.
|
||||
*
|
||||
* In tree-sitter-rust, `#[inline]` is an `attribute_item` sibling that precedes
|
||||
* the function_item in the declaration_list, not a child of the function_item.
|
||||
*/
|
||||
function extractRustAnnotations(node: SyntaxNode): string[] {
|
||||
const annotations: string[] = [];
|
||||
let sibling = node.previousNamedSibling;
|
||||
while (sibling) {
|
||||
if (sibling.type === 'attribute_item') {
|
||||
annotations.unshift(sibling.text);
|
||||
} else {
|
||||
// Stop at the first non-attribute sibling — attributes are contiguous
|
||||
break;
|
||||
}
|
||||
sibling = sibling.previousNamedSibling;
|
||||
}
|
||||
return annotations;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rust config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Rust methods live inside `impl` blocks (concrete implementations) or
|
||||
// `trait` blocks (trait definitions with required/default methods).
|
||||
//
|
||||
// `impl_item` body contains `function_item` nodes for concrete methods.
|
||||
// `trait_item` body contains `function_item` (default methods) and
|
||||
// `function_signature_item` (required/abstract methods without a body).
|
||||
//
|
||||
// ownerName resolution: `impl_item` has no `name` field — the generic
|
||||
// extractor falls back to the first `type_identifier` child, which is the
|
||||
// implementing type (e.g. `impl MyStruct { ... }` → "MyStruct").
|
||||
// `trait_item` uses the standard `name` field.
|
||||
//
|
||||
// Known gaps:
|
||||
// - Macro-generated methods (e.g. derive) are not visible in the AST.
|
||||
// - Unsafe methods are not distinguished (no isUnsafe field in schema).
|
||||
export const rustMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.Rust,
|
||||
typeDeclarationNodes: ['impl_item', 'trait_item'],
|
||||
methodNodeTypes: ['function_item', 'function_signature_item'],
|
||||
bodyNodeTypes: ['declaration_list'],
|
||||
|
||||
// For `impl Trait for Struct`, resolve owner to the concrete Struct (after `for`).
|
||||
// For plain `impl Struct`, resolve to Struct (first type_identifier).
|
||||
// For `trait Foo`, let the default name-field resolution handle it.
|
||||
extractOwnerName(node) {
|
||||
if (node.type !== 'impl_item') return undefined;
|
||||
const children = node.children ?? [];
|
||||
const forIdx = children.findIndex((c: SyntaxNode) => c.text === 'for');
|
||||
if (forIdx !== -1) {
|
||||
// impl Trait for Struct — pick the type after `for`
|
||||
const typeNode = children
|
||||
.slice(forIdx + 1)
|
||||
.find(
|
||||
(c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'scoped_type_identifier',
|
||||
);
|
||||
if (typeNode) return typeNode.text;
|
||||
}
|
||||
// Plain `impl Struct` — pick the first type_identifier
|
||||
const first = children.find((c: SyntaxNode) => c.type === 'type_identifier');
|
||||
return first?.text;
|
||||
},
|
||||
|
||||
extractName: extractRustMethodName,
|
||||
extractReturnType: extractRustReturnType,
|
||||
extractParameters: extractRustParameters,
|
||||
extractVisibility: extractRustVisibility,
|
||||
|
||||
isStatic(node) {
|
||||
// A Rust method is an "associated function" (static) if it lacks a
|
||||
// self_parameter as first parameter.
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return true;
|
||||
const first = paramList.namedChild(0);
|
||||
return !first || first.type !== 'self_parameter';
|
||||
},
|
||||
|
||||
isAbstract(node, ownerNode) {
|
||||
// Only trait methods without a body (function_signature_item) are abstract.
|
||||
// function_signature_item never has a body field.
|
||||
if (ownerNode.type === 'trait_item' && node.type === 'function_signature_item') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
isFinal() {
|
||||
// Rust has no `final` concept — all methods are effectively sealed
|
||||
// (traits cannot be "overridden" the way Java methods can).
|
||||
return false;
|
||||
},
|
||||
|
||||
extractAnnotations: extractRustAnnotations,
|
||||
extractReceiverType: extractRustReceiverType,
|
||||
isAsync: isRustAsync,
|
||||
};
|
||||
@@ -0,0 +1,311 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/swift.ts
|
||||
// Verified against tree-sitter-swift 0.6.0
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { findVisibility, hasKeyword, hasModifier } from '../../field-extractors/configs/helpers.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Swift helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SWIFT_VIS = new Set<MethodVisibility>([
|
||||
'public',
|
||||
'private',
|
||||
'fileprivate',
|
||||
'internal',
|
||||
'open',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Extract the method name from a function_declaration or protocol_function_declaration.
|
||||
*
|
||||
* In tree-sitter-swift, the name is stored in a `simple_identifier` child
|
||||
* (not a 'name' field) on both function_declaration and protocol_function_declaration.
|
||||
*/
|
||||
function extractSwiftName(node: SyntaxNode): string | undefined {
|
||||
// Try field-based name first
|
||||
const nameField = node.childForFieldName('name');
|
||||
if (nameField) return nameField.text;
|
||||
|
||||
// Walk named children for simple_identifier (the function name)
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === 'simple_identifier') return child.text;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the return type from a Swift function declaration.
|
||||
*
|
||||
* In tree-sitter-swift, the return type appears in a `type_annotation` child
|
||||
* that follows the parameter list (after `->` in source). It may also appear
|
||||
* as a direct type child (user_type, optional_type, tuple_type, array_type).
|
||||
*/
|
||||
function extractSwiftReturnType(node: SyntaxNode): string | undefined {
|
||||
// Look for the return type — typically the last type_annotation or a type node
|
||||
// that appears after the parameter list.
|
||||
// tree-sitter-swift places the return type inside a type child after '->'
|
||||
let seenParams = false;
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (!child) continue;
|
||||
if (child.type === 'parameter') {
|
||||
seenParams = true;
|
||||
continue;
|
||||
}
|
||||
// The parameter list may be unnamed children; track when we pass ')'
|
||||
if (seenParams || child.type === 'type_annotation') {
|
||||
if (child.type === 'type_annotation') {
|
||||
const inner = child.firstNamedChild;
|
||||
if (inner) return inner.text?.trim();
|
||||
}
|
||||
if (
|
||||
child.type === 'user_type' ||
|
||||
child.type === 'optional_type' ||
|
||||
child.type === 'tuple_type' ||
|
||||
child.type === 'array_type' ||
|
||||
child.type === 'dictionary_type' ||
|
||||
child.type === 'function_type'
|
||||
) {
|
||||
return child.text?.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: scan all children (named + unnamed) for '->' then grab the next named child
|
||||
let seenArrow = false;
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
if (!child) continue;
|
||||
if (!child.isNamed && child.text.trim() === '->') {
|
||||
seenArrow = true;
|
||||
continue;
|
||||
}
|
||||
if (seenArrow && child.isNamed) {
|
||||
return child.text?.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract parameters from a Swift function declaration.
|
||||
*
|
||||
* In tree-sitter-swift, parameters are `parameter` named children directly on
|
||||
* the function_declaration node. Each parameter has:
|
||||
* - An external name (label) and/or internal name as simple_identifier children
|
||||
* - A type_annotation child containing the type
|
||||
* - An optional default value after '='
|
||||
* - A possible `...` for variadic parameters
|
||||
*/
|
||||
function extractSwiftParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
// In tree-sitter-swift 0.6.0, parameters are direct children of function_declaration.
|
||||
// Default value tokens ('=', literal) are siblings of the parameter node at the
|
||||
// function_declaration level, not children of the parameter node.
|
||||
for (let i = 0; i < node.childCount; i++) {
|
||||
const child = node.child(i);
|
||||
if (!child?.isNamed || child.type !== 'parameter') continue;
|
||||
|
||||
// Extract parameter name — the last simple_identifier is the internal name
|
||||
let paramName: string | undefined;
|
||||
for (let j = 0; j < child.namedChildCount; j++) {
|
||||
const part = child.namedChild(j);
|
||||
if (part?.type === 'simple_identifier') {
|
||||
paramName = part.text;
|
||||
}
|
||||
}
|
||||
if (!paramName) continue;
|
||||
|
||||
// Extract type — tree-sitter-swift uses user_type (not type_annotation)
|
||||
let typeName: string | null = null;
|
||||
let rawTypeName: string | null = null;
|
||||
for (let j = 0; j < child.namedChildCount; j++) {
|
||||
const part = child.namedChild(j);
|
||||
if (part?.type === 'user_type' || part?.type === 'type_annotation') {
|
||||
rawTypeName = part.text?.trim() ?? null;
|
||||
const inner = part.firstNamedChild;
|
||||
if (inner) {
|
||||
typeName = extractSimpleTypeName(inner) ?? inner.text?.trim() ?? null;
|
||||
} else {
|
||||
typeName = rawTypeName;
|
||||
}
|
||||
break;
|
||||
}
|
||||
// Handle built-in types (array_type, dictionary_type, optional_type, tuple_type)
|
||||
if (part?.type.endsWith('_type') && part.type !== 'simple_identifier') {
|
||||
rawTypeName = part.text?.trim() ?? null;
|
||||
typeName = extractSimpleTypeName(part) ?? rawTypeName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for default value: '=' token appears as a sibling after the parameter node
|
||||
let isOptional = false;
|
||||
const nextSibling = node.child(i + 1);
|
||||
if (nextSibling && !nextSibling.isNamed && nextSibling.text.trim() === '=') {
|
||||
isOptional = true;
|
||||
}
|
||||
|
||||
// Check for variadic: '...' token among parameter children
|
||||
let isVariadic = false;
|
||||
for (let j = 0; j < child.childCount; j++) {
|
||||
const c = child.child(j);
|
||||
if (c && c.text.trim() === '...') {
|
||||
isVariadic = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
params.push({
|
||||
name: paramName,
|
||||
type: typeName,
|
||||
rawType: rawTypeName,
|
||||
isOptional,
|
||||
isVariadic,
|
||||
});
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a method is inside a protocol.
|
||||
*
|
||||
* A protocol_function_declaration is always abstract. For function_declaration
|
||||
* inside a protocol_body (if it appears there), it's also abstract when it has
|
||||
* no body.
|
||||
*/
|
||||
function isSwiftAbstract(node: SyntaxNode, ownerNode: SyntaxNode): boolean {
|
||||
// protocol_function_declaration nodes are inherently abstract
|
||||
if (node.type === 'protocol_function_declaration') return true;
|
||||
|
||||
// function_declaration inside a protocol is abstract if it has no body
|
||||
if (ownerNode.type === 'protocol_declaration') {
|
||||
const body = node.childForFieldName('body');
|
||||
if (!body) {
|
||||
// Also check for function_body named child
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child?.type === 'function_body') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect attribute nodes from a Swift function declaration.
|
||||
*
|
||||
* In tree-sitter-swift, attributes appear as `attribute` named children
|
||||
* directly on the function_declaration node, or inside a `modifiers` wrapper.
|
||||
* Each attribute node text starts with '@'.
|
||||
*/
|
||||
function extractSwiftAnnotations(node: SyntaxNode): string[] {
|
||||
const annotations: string[] = [];
|
||||
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (!child) continue;
|
||||
|
||||
if (child.type === 'attribute') {
|
||||
const text = child.text?.trim();
|
||||
if (text) {
|
||||
// Normalize: strip arguments, keep just the name
|
||||
// e.g. "@objc(myMethod)" -> "@objc", "@available(iOS 13, *)" -> "@available"
|
||||
const match = text.match(/^@(\w+)/);
|
||||
if (match) {
|
||||
annotations.push('@' + match[1]);
|
||||
} else {
|
||||
annotations.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also check inside modifiers wrapper
|
||||
if (child.type === 'modifiers') {
|
||||
for (let j = 0; j < child.namedChildCount; j++) {
|
||||
const mod = child.namedChild(j);
|
||||
if (mod?.type === 'attribute') {
|
||||
const text = mod.text?.trim();
|
||||
if (text) {
|
||||
const match = text.match(/^@(\w+)/);
|
||||
if (match) {
|
||||
annotations.push('@' + match[1]);
|
||||
} else {
|
||||
annotations.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return annotations;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Swift config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const swiftMethodConfig: MethodExtractionConfig = {
|
||||
language: SupportedLanguages.Swift,
|
||||
|
||||
// tree-sitter-swift 0.6.0 may use class_declaration for classes, structs, enums, extensions,
|
||||
// and actors — but this cannot be verified until the grammar installs on Node 22+.
|
||||
// TODO: Verify struct_declaration, enum_declaration, extension_declaration, actor_declaration
|
||||
// node types once tree-sitter-swift loads on Node 22, and add them here if they are distinct.
|
||||
// protocol_declaration is a separate, confirmed node type.
|
||||
typeDeclarationNodes: ['class_declaration', 'protocol_declaration'],
|
||||
|
||||
// function_declaration for class/struct methods, protocol_function_declaration for protocol methods
|
||||
methodNodeTypes: ['function_declaration', 'protocol_function_declaration'],
|
||||
|
||||
bodyNodeTypes: ['class_body', 'protocol_body'],
|
||||
|
||||
extractName: extractSwiftName,
|
||||
extractReturnType: extractSwiftReturnType,
|
||||
extractParameters: extractSwiftParameters,
|
||||
|
||||
extractVisibility(node) {
|
||||
return findVisibility(node, SWIFT_VIS, 'internal', 'modifiers');
|
||||
},
|
||||
|
||||
isStatic(node) {
|
||||
return (
|
||||
hasKeyword(node, 'static') ||
|
||||
hasKeyword(node, 'class') ||
|
||||
hasModifier(node, 'modifiers', 'static') ||
|
||||
hasModifier(node, 'modifiers', 'class')
|
||||
);
|
||||
},
|
||||
|
||||
isAbstract: isSwiftAbstract,
|
||||
|
||||
isFinal(node) {
|
||||
return hasKeyword(node, 'final') || hasModifier(node, 'modifiers', 'final');
|
||||
},
|
||||
|
||||
isAsync(node) {
|
||||
return hasKeyword(node, 'async') || hasModifier(node, 'modifiers', 'async');
|
||||
},
|
||||
|
||||
isOverride(node) {
|
||||
return hasKeyword(node, 'override') || hasModifier(node, 'modifiers', 'override');
|
||||
},
|
||||
|
||||
extractAnnotations: extractSwiftAnnotations,
|
||||
};
|
||||
@@ -0,0 +1,351 @@
|
||||
// gitnexus/src/core/ingestion/method-extractors/configs/typescript-javascript.ts
|
||||
// Verified against tree-sitter-typescript ^0.23.2, tree-sitter-javascript ^0.23.0
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type {
|
||||
MethodExtractionConfig,
|
||||
ParameterInfo,
|
||||
MethodVisibility,
|
||||
} from '../../method-types.js';
|
||||
import { hasKeyword } from '../../field-extractors/configs/helpers.js';
|
||||
import { extractSimpleTypeName } from '../../type-extractors/shared.js';
|
||||
import type { SyntaxNode } from '../../utils/ast-helpers.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TS/JS helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VISIBILITY_KEYWORDS = new Set<MethodVisibility>(['public', 'private', 'protected']);
|
||||
|
||||
/**
|
||||
* Extract parameters from formal_parameters.
|
||||
*
|
||||
* Handles both TS node types (required_parameter, optional_parameter, rest_parameter)
|
||||
* and JS node types (identifier, assignment_pattern, rest_pattern), plus destructured
|
||||
* parameters (object_pattern, array_pattern) in both grammars.
|
||||
*/
|
||||
function extractTsJsParameters(node: SyntaxNode): ParameterInfo[] {
|
||||
const paramList = node.childForFieldName('parameters');
|
||||
if (!paramList) return [];
|
||||
const params: ParameterInfo[] = [];
|
||||
|
||||
for (let i = 0; i < paramList.namedChildCount; i++) {
|
||||
const param = paramList.namedChild(i);
|
||||
if (!param) continue;
|
||||
|
||||
switch (param.type) {
|
||||
case 'required_parameter': {
|
||||
const patternNode = param.childForFieldName('pattern');
|
||||
if (!patternNode) break;
|
||||
|
||||
// Skip TS `this` parameter — it's a compile-time type constraint, not a real param
|
||||
if (patternNode.type === 'this') break;
|
||||
|
||||
// Rest parameter: pattern is a rest_pattern (...args) — extract inner identifier
|
||||
const isRest = patternNode.type === 'rest_pattern';
|
||||
const nameNode = isRest ? patternNode.firstNamedChild : patternNode;
|
||||
if (!nameNode) break;
|
||||
|
||||
// type field is a type_annotation — unwrap to get the inner type node
|
||||
const typeAnnotation = param.childForFieldName('type');
|
||||
const typeNode = typeAnnotation?.firstNamedChild;
|
||||
|
||||
// Default value: presence of a 'value' field means isOptional
|
||||
const hasDefault = !!param.childForFieldName('value');
|
||||
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: hasDefault,
|
||||
isVariadic: isRest,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'optional_parameter': {
|
||||
const nameNode = param.childForFieldName('pattern');
|
||||
if (!nameNode) break;
|
||||
const typeAnnotation = param.childForFieldName('type');
|
||||
const typeNode = typeAnnotation?.firstNamedChild;
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: true,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'rest_parameter': {
|
||||
const nameNode = param.childForFieldName('pattern');
|
||||
if (!nameNode) break;
|
||||
const typeAnnotation = param.childForFieldName('type');
|
||||
const typeNode = typeAnnotation?.firstNamedChild;
|
||||
params.push({
|
||||
name: nameNode.text,
|
||||
type: typeNode
|
||||
? (extractSimpleTypeName(typeNode) ?? typeNode.text?.trim() ?? null)
|
||||
: null,
|
||||
rawType: typeNode?.text?.trim() ?? null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'identifier': {
|
||||
// JS: bare parameter name, no type info
|
||||
params.push({
|
||||
name: param.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'assignment_pattern': {
|
||||
// JS: param = defaultValue — the left side is the name, isOptional = true
|
||||
const left = param.childForFieldName('left');
|
||||
if (left) {
|
||||
params.push({
|
||||
name: left.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: true,
|
||||
isVariadic: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'rest_pattern': {
|
||||
// JS: ...args
|
||||
const inner = param.firstNamedChild;
|
||||
if (inner) {
|
||||
params.push({
|
||||
name: inner.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: true,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'object_pattern':
|
||||
case 'array_pattern': {
|
||||
// Destructured parameter — use full text as name
|
||||
params.push({
|
||||
name: param.text,
|
||||
type: null,
|
||||
rawType: null,
|
||||
isOptional: false,
|
||||
isVariadic: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/** Regex to extract @returns or @return from JSDoc comments: `@returns {Type}` */
|
||||
const JSDOC_RETURN_RE = /@returns?\s*\{([^}]+)\}/;
|
||||
|
||||
/**
|
||||
* Minimal sanitization for JSDoc return types — preserves generic wrappers
|
||||
* (e.g. `Promise<User>`) so that extractReturnTypeName in call-processor
|
||||
* can apply WRAPPER_GENERICS unwrapping. Only strips JSDoc-specific syntax markers.
|
||||
*/
|
||||
function sanitizeJsDocReturnType(raw: string): string | undefined {
|
||||
let type = raw.trim();
|
||||
// Strip JSDoc nullable/non-nullable prefixes: ?User → User, !User → User
|
||||
if (type.startsWith('?') || type.startsWith('!')) type = type.slice(1);
|
||||
// Strip module: prefix — module:models.User → models.User
|
||||
if (type.startsWith('module:')) type = type.slice(7);
|
||||
// Reject unions (ambiguous)
|
||||
if (type.includes('|')) return undefined;
|
||||
if (!type) return undefined;
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk backwards through preceding siblings looking for a JSDoc comment containing
|
||||
* `@returns {Type}` or `@return {Type}`. Stops at the first non-comment named node
|
||||
* (excluding decorators, which precede methods in TS/JS).
|
||||
*/
|
||||
function extractJsDocReturnType(node: SyntaxNode): string | undefined {
|
||||
let sibling = node.previousSibling;
|
||||
while (sibling) {
|
||||
if (sibling.type === 'comment') {
|
||||
const match = JSDOC_RETURN_RE.exec(sibling.text);
|
||||
if (match) return sanitizeJsDocReturnType(match[1]);
|
||||
} else if (sibling.isNamed && sibling.type !== 'decorator') break;
|
||||
sibling = sibling.previousSibling;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract return type from return_type field, unwrapping type_annotation.
|
||||
* Falls back to JSDoc `@returns {Type}` when the AST has no return type annotation.
|
||||
*
|
||||
* tree-sitter-typescript uses `return_type` as the field name (not `type` like JVM).
|
||||
* The return_type field points to a type_annotation node that must be unwrapped.
|
||||
*/
|
||||
function extractTsJsReturnType(node: SyntaxNode): string | undefined {
|
||||
const returnType = node.childForFieldName('return_type');
|
||||
if (returnType) {
|
||||
if (returnType.type === 'type_annotation') {
|
||||
const inner = returnType.firstNamedChild;
|
||||
if (inner) return inner.text?.trim();
|
||||
}
|
||||
return returnType.text?.trim();
|
||||
}
|
||||
// AST has no return type annotation — try JSDoc fallback
|
||||
return extractJsDocReturnType(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract visibility from accessibility_modifier or #private name.
|
||||
*
|
||||
* tree-sitter-typescript emits accessibility_modifier as a named child of method nodes
|
||||
* (not as a modifiers wrapper like JVM). Pass 1 scans for that child; pass 2 checks for
|
||||
* ES2022 private_property_identifier (#name). Default: public.
|
||||
*/
|
||||
function extractTsJsVisibility(node: SyntaxNode): MethodVisibility {
|
||||
// Pass 1: check for accessibility_modifier named child (TS-specific)
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child && child.type === 'accessibility_modifier') {
|
||||
const t = child.text.trim();
|
||||
if (VISIBILITY_KEYWORDS.has(t as MethodVisibility)) return t as MethodVisibility;
|
||||
}
|
||||
}
|
||||
// Pass 2: ES2022 private methods (#name) are inherently private
|
||||
const nameNode = node.childForFieldName('name');
|
||||
if (nameNode && nameNode.type === 'private_property_identifier') return 'private';
|
||||
// No accessibility_modifier found — default to public.
|
||||
// Note: tree-sitter-typescript does not wrap modifiers in a 'modifiers' node
|
||||
// (unlike JVM), so there is no wrapper to scan.
|
||||
return 'public';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract decorator names, prefixed with '@'.
|
||||
*
|
||||
* In tree-sitter-typescript, decorators are **siblings** of the method_definition in the
|
||||
* class_body — they are NOT children of the method node. We find them by walking backwards
|
||||
* from the method node through its preceding siblings in the parent body.
|
||||
*/
|
||||
function extractTsJsDecorators(node: SyntaxNode): string[] {
|
||||
const decorators: string[] = [];
|
||||
// Walk backwards via previousNamedSibling to collect consecutive decorator siblings.
|
||||
// This avoids the O(N) index-finding scan through the parent's children.
|
||||
let sibling = node.previousNamedSibling;
|
||||
while (sibling && sibling.type === 'decorator') {
|
||||
const name = extractDecoratorName(sibling);
|
||||
if (name) decorators.unshift(name);
|
||||
sibling = sibling.previousNamedSibling;
|
||||
}
|
||||
return decorators;
|
||||
}
|
||||
|
||||
function extractDecoratorName(decorator: SyntaxNode): string | undefined {
|
||||
const expr = decorator.firstNamedChild;
|
||||
if (!expr) return undefined;
|
||||
if (expr.type === 'call_expression') {
|
||||
const fn = expr.childForFieldName('function');
|
||||
return fn ? '@' + fn.text : undefined;
|
||||
}
|
||||
if (expr.type === 'identifier') return '@' + expr.text;
|
||||
if (expr.type === 'member_expression') return '@' + expr.text;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// TS and JS share the same config base. TS-only node types (abstract_class_declaration,
|
||||
// interface_declaration, abstract_method_signature, method_signature, interface_body) are
|
||||
// included because the JS grammar never produces these nodes — they are harmless no-ops.
|
||||
// This mirrors the field extractor's typescript-javascript.ts shared pattern.
|
||||
//
|
||||
// Note: TS and JS share a method config but NOT a field extractor because the TS field
|
||||
// extractor needs a hand-written class for type_alias_declaration object literals and
|
||||
// nested type discovery. Methods have no such requirement.
|
||||
const shared: Omit<MethodExtractionConfig, 'language'> = {
|
||||
typeDeclarationNodes: [
|
||||
'class_declaration',
|
||||
'abstract_class_declaration',
|
||||
'interface_declaration',
|
||||
],
|
||||
// Note: TS constructors are method_definition nodes (name = 'constructor'), so no
|
||||
// explicit constructor_declaration entry is needed (unlike JVM/C# configs).
|
||||
// Known gaps:
|
||||
// - call_signature and construct_signature (e.g., interface Fn { (x: string): void; })
|
||||
// are not extracted — they have no name field and are uncommon in practice.
|
||||
// - class_expression (const Foo = class { ... }) — methods inside class expressions
|
||||
// are not discovered because class_expression is not in typeDeclarationNodes.
|
||||
// - declare module / declare global augmentations — methods inside ambient_module_declaration
|
||||
// wrappers are not surfaced because the top-level walker doesn't descend into them.
|
||||
methodNodeTypes: [
|
||||
'method_definition',
|
||||
'method_signature',
|
||||
'abstract_method_signature',
|
||||
'function_declaration',
|
||||
'generator_function_declaration',
|
||||
'function_signature',
|
||||
],
|
||||
bodyNodeTypes: ['class_body', 'interface_body'],
|
||||
|
||||
extractName(node) {
|
||||
const nameNode = node.childForFieldName('name');
|
||||
return nameNode?.text;
|
||||
},
|
||||
|
||||
extractReturnType: extractTsJsReturnType,
|
||||
extractParameters: extractTsJsParameters,
|
||||
extractVisibility: extractTsJsVisibility,
|
||||
|
||||
isStatic(node) {
|
||||
return hasKeyword(node, 'static');
|
||||
},
|
||||
|
||||
isAbstract(node, ownerNode) {
|
||||
// Explicit abstract keyword on the method itself
|
||||
if (hasKeyword(node, 'abstract')) return true;
|
||||
// Interface methods are implicitly abstract — TS interfaces never have method bodies
|
||||
// (unlike Java default methods), so no !body check needed
|
||||
if (ownerNode.type === 'interface_declaration') return true;
|
||||
return false;
|
||||
},
|
||||
|
||||
isFinal(_node) {
|
||||
return false; // TS/JS has no final/sealed methods
|
||||
},
|
||||
|
||||
extractAnnotations: extractTsJsDecorators,
|
||||
|
||||
isAsync(node) {
|
||||
return hasKeyword(node, 'async');
|
||||
},
|
||||
|
||||
isOverride(node) {
|
||||
return hasKeyword(node, 'override');
|
||||
},
|
||||
};
|
||||
|
||||
export const typescriptMethodConfig: MethodExtractionConfig = {
|
||||
...shared,
|
||||
language: SupportedLanguages.TypeScript,
|
||||
};
|
||||
|
||||
export const javascriptMethodConfig: MethodExtractionConfig = {
|
||||
...shared,
|
||||
language: SupportedLanguages.JavaScript,
|
||||
};
|
||||
@@ -16,8 +16,8 @@ import type {
|
||||
MethodInfo,
|
||||
} from '../method-types.js';
|
||||
|
||||
/** Owner node types where member functions are effectively static (JVM semantics). */
|
||||
const STATIC_OWNER_TYPES = new Set(['companion_object', 'object_declaration']);
|
||||
/** Owner node types where member functions are effectively static (JVM/Ruby semantics). */
|
||||
const STATIC_OWNER_TYPES = new Set(['companion_object', 'object_declaration', 'singleton_class']);
|
||||
|
||||
/**
|
||||
* Create a MethodExtractor from a declarative config.
|
||||
@@ -37,17 +37,27 @@ export function createMethodExtractor(config: MethodExtractionConfig): MethodExt
|
||||
extract(node: SyntaxNode, context: MethodExtractorContext): ExtractedMethods | null {
|
||||
if (!typeDeclarationSet.has(node.type)) return null;
|
||||
|
||||
// Resolve owner name: field-based → type_identifier → simple_identifier → "Companion"
|
||||
// Resolve owner name: config hook → field-based → type_identifier → simple_identifier → "Companion"
|
||||
let ownerName: string | undefined;
|
||||
const nameField = node.childForFieldName('name');
|
||||
if (nameField) {
|
||||
ownerName = nameField.text;
|
||||
} else {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (child && (child.type === 'type_identifier' || child.type === 'simple_identifier')) {
|
||||
ownerName = child.text;
|
||||
break;
|
||||
if (config.extractOwnerName) {
|
||||
ownerName = config.extractOwnerName(node);
|
||||
}
|
||||
if (!ownerName) {
|
||||
const nameField = node.childForFieldName('name');
|
||||
if (nameField) {
|
||||
ownerName = nameField.text;
|
||||
} else {
|
||||
for (let i = 0; i < node.namedChildCount; i++) {
|
||||
const child = node.namedChild(i);
|
||||
if (
|
||||
child &&
|
||||
(child.type === 'type_identifier' ||
|
||||
child.type === 'simple_identifier' ||
|
||||
child.type === 'identifier')
|
||||
) {
|
||||
ownerName = child.text;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,6 +81,13 @@ export function createMethodExtractor(config: MethodExtractionConfig): MethodExt
|
||||
|
||||
return { ownerName, methods };
|
||||
},
|
||||
|
||||
extractFromNode(node: SyntaxNode, context: MethodExtractorContext): MethodInfo | null {
|
||||
if (!methodNodeSet.has(node.type)) return null;
|
||||
return buildMethod(node, node, context, config);
|
||||
},
|
||||
|
||||
...(config.extractFunctionName ? { extractFunctionName: config.extractFunctionName } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -102,10 +119,17 @@ function findBodies(node: SyntaxNode, bodyNodeSet: Set<string>): SyntaxNode[] {
|
||||
return result;
|
||||
}
|
||||
|
||||
function addNestedBodies(parent: SyntaxNode, bodyNodeSet: Set<string>, out: SyntaxNode[]): void {
|
||||
function addNestedBodies(
|
||||
parent: SyntaxNode,
|
||||
bodyNodeSet: Set<string>,
|
||||
out: SyntaxNode[],
|
||||
seen?: Set<SyntaxNode>,
|
||||
): void {
|
||||
const visited = seen ?? new Set(out);
|
||||
for (let i = 0; i < parent.namedChildCount; i++) {
|
||||
const child = parent.namedChild(i);
|
||||
if (child && bodyNodeSet.has(child.type) && !out.includes(child)) {
|
||||
if (child && bodyNodeSet.has(child.type) && !visited.has(child)) {
|
||||
visited.add(child);
|
||||
out.push(child);
|
||||
}
|
||||
}
|
||||
@@ -120,9 +144,15 @@ function extractMethodsFromBody(
|
||||
out: MethodInfo[],
|
||||
): void {
|
||||
for (let i = 0; i < body.namedChildCount; i++) {
|
||||
const child = body.namedChild(i);
|
||||
let child = body.namedChild(i);
|
||||
if (!child) continue;
|
||||
|
||||
// C++ template methods are wrapped in template_declaration — unwrap to the inner node
|
||||
if (child.type === 'template_declaration') {
|
||||
const inner = child.namedChildren.find((c) => methodNodeSet.has(c.type));
|
||||
if (inner) child = inner;
|
||||
}
|
||||
|
||||
if (methodNodeSet.has(child.type)) {
|
||||
const method = buildMethod(child, ownerNode, context, config);
|
||||
if (method) out.push(method);
|
||||
@@ -170,6 +200,7 @@ function buildMethod(
|
||||
...(config.isOverride?.(node) ? { isOverride: true } : {}),
|
||||
...(config.isAsync?.(node) ? { isAsync: true } : {}),
|
||||
...(config.isPartial?.(node) ? { isPartial: true } : {}),
|
||||
...(config.isConst?.(node) ? { isConst: true } : {}),
|
||||
annotations: config.extractAnnotations?.(node) ?? [],
|
||||
sourceFile: context.filePath,
|
||||
line: node.startPosition.row + 1,
|
||||
|
||||
@@ -10,6 +10,10 @@ export type MethodVisibility = FieldVisibility;
|
||||
export interface ParameterInfo {
|
||||
name: string;
|
||||
type: string | null;
|
||||
/** Full type text including generic/template args (e.g. 'vector<int>', 'List<String>').
|
||||
* Used by typeTagForId for overload disambiguation where generic args matter.
|
||||
* Falls back to `type` when not set. */
|
||||
rawType?: string | null;
|
||||
isOptional: boolean;
|
||||
isVariadic: boolean;
|
||||
}
|
||||
@@ -27,6 +31,7 @@ export interface MethodInfo {
|
||||
isOverride?: boolean;
|
||||
isAsync?: boolean;
|
||||
isPartial?: boolean;
|
||||
isConst?: boolean;
|
||||
annotations: string[];
|
||||
sourceFile: string;
|
||||
line: number;
|
||||
@@ -46,6 +51,16 @@ export interface MethodExtractor {
|
||||
language: SupportedLanguages;
|
||||
extract(node: SyntaxNode, context: MethodExtractorContext): ExtractedMethods | null;
|
||||
isTypeDeclaration(node: SyntaxNode): boolean;
|
||||
/** Extract method info from a standalone method node (e.g. Go top-level method_declaration). */
|
||||
extractFromNode?(node: SyntaxNode, context: MethodExtractorContext): MethodInfo | null;
|
||||
/** Extract function name + label from an AST node during parent-walk.
|
||||
* Languages with non-standard AST structures (e.g. C/C++ declarator
|
||||
* unwrapping, Swift init/deinit, Rust impl_item) provide this hook
|
||||
* to replace the generic name-field lookup.
|
||||
* Return null to fall through to the generic extractor. */
|
||||
extractFunctionName?(
|
||||
node: SyntaxNode,
|
||||
): { funcName: string | null; label: import('gitnexus-shared').NodeLabel } | null;
|
||||
}
|
||||
|
||||
export interface MethodExtractionConfig {
|
||||
@@ -66,9 +81,17 @@ export interface MethodExtractionConfig {
|
||||
isOverride?: (node: SyntaxNode) => boolean;
|
||||
isAsync?: (node: SyntaxNode) => boolean;
|
||||
isPartial?: (node: SyntaxNode) => boolean;
|
||||
isConst?: (node: SyntaxNode) => boolean;
|
||||
/** Resolve the owner name from a standalone method node (e.g. Go receiver type). */
|
||||
extractOwnerName?: (node: SyntaxNode) => string | undefined;
|
||||
/** Extract a primary constructor from the owner node itself (e.g. C# 12 class Point(int x, int y)). */
|
||||
extractPrimaryConstructor?: (
|
||||
ownerNode: SyntaxNode,
|
||||
context: MethodExtractorContext,
|
||||
) => MethodInfo | null;
|
||||
/** Extract function name + label from an AST node during parent-walk.
|
||||
* Passed through to the MethodExtractor by createMethodExtractor. */
|
||||
extractFunctionName?: (
|
||||
node: SyntaxNode,
|
||||
) => { funcName: string | null; label: import('gitnexus-shared').NodeLabel } | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Field Registry
|
||||
*
|
||||
* Owner-scoped field/property index extracted from SymbolTable.
|
||||
* Stores Property symbols keyed by `ownerNodeId\0fieldName` for O(1) lookup.
|
||||
*/
|
||||
|
||||
import type { SymbolDefinition } from './symbol-table.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public read-only interface
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface FieldRegistry {
|
||||
/** Look up a field/property by its owning class nodeId and field name. */
|
||||
lookupFieldByOwner(ownerNodeId: string, fieldName: string): SymbolDefinition | undefined;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mutable interface (used internally by SymbolTable.add / clear)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface MutableFieldRegistry extends FieldRegistry {
|
||||
/** Register a field/property under its owner. */
|
||||
register(ownerNodeId: string, fieldName: string, def: SymbolDefinition): void;
|
||||
/** Clear all entries. */
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const createFieldRegistry = (): MutableFieldRegistry => {
|
||||
const fieldByOwner = new Map<string, SymbolDefinition>();
|
||||
|
||||
const lookupFieldByOwner = (
|
||||
ownerNodeId: string,
|
||||
fieldName: string,
|
||||
): SymbolDefinition | undefined => {
|
||||
return fieldByOwner.get(`${ownerNodeId}\0${fieldName}`);
|
||||
};
|
||||
|
||||
const register = (ownerNodeId: string, fieldName: string, def: SymbolDefinition): void => {
|
||||
fieldByOwner.set(`${ownerNodeId}\0${fieldName}`, def);
|
||||
};
|
||||
|
||||
const clear = (): void => {
|
||||
fieldByOwner.clear();
|
||||
};
|
||||
|
||||
return { lookupFieldByOwner, register, clear };
|
||||
};
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Heritage Map
|
||||
*
|
||||
* Unified inheritance data structure built from accumulated
|
||||
* {@link ExtractedHeritage} records **after all chunks complete** (between
|
||||
* chunk processing and call resolution). Consumes `ExtractedHeritage[]` and
|
||||
* resolves type names to nodeIds via `lookupClassByName`, NOT graph-edge
|
||||
* queries.
|
||||
*
|
||||
* Combines two concerns:
|
||||
* 1. **Parent/ancestor lookup** (MRO-aware method resolution)
|
||||
* 2. **Implementor lookup** (interface dispatch — which files contain
|
||||
* classes implementing a given interface)
|
||||
*/
|
||||
|
||||
import type { ResolutionContext } from './resolution-context.js';
|
||||
import { getLanguageFromFilename, type SupportedLanguages } from 'gitnexus-shared';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ExtractedHeritage — the shape produced by the parse worker / heritage
|
||||
// extractor. Defined here so `model/` has no upward imports; consumers
|
||||
// import this type from the model module.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ExtractedHeritage {
|
||||
filePath: string;
|
||||
className: string;
|
||||
parentName: string;
|
||||
/** 'extends' | 'implements' | 'trait-impl' | 'include' | 'extend' | 'prepend' */
|
||||
kind: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Heritage resolution strategy (the per-language knobs that drive
|
||||
// `resolveExtendsType` below). Pulled out as an explicit strategy object so
|
||||
// the model layer depends on a plain data shape rather than on the language
|
||||
// provider registry.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface HeritageResolutionStrategy {
|
||||
/** If set and the parent name matches, force IMPLEMENTS even when the
|
||||
* symbol is unresolved (e.g. `/^I[A-Z]/` for C# / Java). */
|
||||
readonly interfaceNamePattern?: RegExp;
|
||||
/** Fallback edge for unresolved parents when the name pattern doesn't
|
||||
* match (Swift uses 'IMPLEMENTS' for protocol conformance). */
|
||||
readonly defaultEdge: 'EXTENDS' | 'IMPLEMENTS';
|
||||
}
|
||||
|
||||
/** Callback used by `buildHeritageMap` to look up the resolution strategy
|
||||
* for a given language. Injected by callers so the model module doesn't
|
||||
* depend on `../languages/index.js`. */
|
||||
export type HeritageStrategyLookup = (lang: SupportedLanguages) => HeritageResolutionStrategy;
|
||||
|
||||
/**
|
||||
* Determine whether a heritage.extends capture is actually an IMPLEMENTS
|
||||
* relationship. Consults the symbol table first (authoritative — Tier 1 /
|
||||
* Tier 2 resolution); falls back to the injected {@link HeritageResolutionStrategy}
|
||||
* heuristics for external symbols not present in the graph.
|
||||
*/
|
||||
export const resolveExtendsType = (
|
||||
parentName: string,
|
||||
currentFilePath: string,
|
||||
ctx: ResolutionContext,
|
||||
strategy: HeritageResolutionStrategy,
|
||||
): { type: 'EXTENDS' | 'IMPLEMENTS'; idPrefix: string } => {
|
||||
const resolved = ctx.resolve(parentName, currentFilePath);
|
||||
if (resolved && resolved.candidates.length > 0) {
|
||||
const isInterface = resolved.candidates[0].type === 'Interface';
|
||||
return isInterface
|
||||
? { type: 'IMPLEMENTS', idPrefix: 'Interface' }
|
||||
: { type: 'EXTENDS', idPrefix: 'Class' };
|
||||
}
|
||||
// Unresolved symbol — fall back to strategy heuristics.
|
||||
if (strategy.interfaceNamePattern?.test(parentName)) {
|
||||
return { type: 'IMPLEMENTS', idPrefix: 'Interface' };
|
||||
}
|
||||
if (strategy.defaultEdge === 'IMPLEMENTS') {
|
||||
return { type: 'IMPLEMENTS', idPrefix: 'Interface' };
|
||||
}
|
||||
return { type: 'EXTENDS', idPrefix: 'Class' };
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Maximum ancestor chain depth to prevent runaway traversal. */
|
||||
const MAX_ANCESTOR_DEPTH = 32;
|
||||
|
||||
export interface HeritageMap {
|
||||
/** Direct parents of `childNodeId` (extends + implements + trait-impl). */
|
||||
getParents(childNodeId: string): string[];
|
||||
/** Full ancestor chain (BFS, bounded depth, cycle-safe). */
|
||||
getAncestors(childNodeId: string): string[];
|
||||
/**
|
||||
* File paths of classes that directly implement or extend-as-interface the
|
||||
* given interface/abstract-class **name**. Replaces the standalone
|
||||
* `ImplementorMap` — used by interface-dispatch in call resolution.
|
||||
*/
|
||||
getImplementorFiles(interfaceName: string): ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/** Shared empty set returned when no implementors are found. */
|
||||
const EMPTY_SET: ReadonlySet<string> = new Set();
|
||||
|
||||
/** Default strategy used when `buildHeritageMap` is called without an
|
||||
* explicit `getHeritageStrategy` callback — the fallback for a language
|
||||
* whose provider sets no interface-name pattern and no non-default
|
||||
* `heritageDefaultEdge`. */
|
||||
const DEFAULT_HERITAGE_STRATEGY: HeritageResolutionStrategy = { defaultEdge: 'EXTENDS' };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Builder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build a HeritageMap from accumulated ExtractedHeritage records.
|
||||
*
|
||||
* Resolves class/interface/struct/trait names to nodeIds via
|
||||
* `ctx.model.types.lookupClassByName`. When a name resolves to multiple
|
||||
* candidates, all are recorded (partial-class / cross-file scenario).
|
||||
* Unresolvable names are silently skipped — a missing parent is better
|
||||
* than a wrong edge.
|
||||
*
|
||||
* Also builds the implementor index (interface name → implementing file
|
||||
* paths) used by interface-dispatch in call resolution.
|
||||
*/
|
||||
export const buildHeritageMap = (
|
||||
heritage: readonly ExtractedHeritage[],
|
||||
ctx: ResolutionContext,
|
||||
getHeritageStrategy?: HeritageStrategyLookup,
|
||||
): HeritageMap => {
|
||||
// childNodeId → Set<parentNodeId> (Set to deduplicate cross-chunk duplicates)
|
||||
const directParents = new Map<string, Set<string>>();
|
||||
|
||||
// interfaceName → Set<filePath> (implementor lookup for interface dispatch)
|
||||
const implementorFiles = new Map<string, Set<string>>();
|
||||
|
||||
for (const h of heritage) {
|
||||
// ── Parent lookup (nodeId-based) ────────────────────────────────
|
||||
const childDefs = ctx.model.types.lookupClassByName(h.className);
|
||||
const parentDefs = ctx.model.types.lookupClassByName(h.parentName);
|
||||
|
||||
if (childDefs.length > 0 && parentDefs.length > 0) {
|
||||
for (const child of childDefs) {
|
||||
for (const parent of parentDefs) {
|
||||
// Skip self-references
|
||||
if (child.nodeId === parent.nodeId) continue;
|
||||
|
||||
let parents = directParents.get(child.nodeId);
|
||||
if (!parents) {
|
||||
parents = new Set();
|
||||
directParents.set(child.nodeId, parents);
|
||||
}
|
||||
parents.add(parent.nodeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Implementor index (name-based) ──────────────────────────────
|
||||
//
|
||||
// Known limitation: Rust `kind: 'trait-impl'` entries are intentionally NOT
|
||||
// added to the implementor index. Interface dispatch resolution currently
|
||||
// does not traverse Rust trait objects, so recording them here would
|
||||
// inflate the index without a consumer. Revisit if/when trait-object
|
||||
// dispatch is added.
|
||||
//
|
||||
// Known limitation: `getImplementorFiles` is keyed by interface **name**
|
||||
// (string), so two interfaces with the same unqualified name in different
|
||||
// packages (e.g. `pkgA.IRepository` vs `pkgB.IRepository`) collide.
|
||||
let isImpl = false;
|
||||
if (h.kind === 'implements') {
|
||||
isImpl = true;
|
||||
} else if (h.kind === 'extends') {
|
||||
const lang = getLanguageFromFilename(h.filePath);
|
||||
if (lang) {
|
||||
const strategy = getHeritageStrategy?.(lang) ?? DEFAULT_HERITAGE_STRATEGY;
|
||||
const { type } = resolveExtendsType(h.parentName, h.filePath, ctx, strategy);
|
||||
isImpl = type === 'IMPLEMENTS';
|
||||
}
|
||||
}
|
||||
if (isImpl) {
|
||||
let files = implementorFiles.get(h.parentName);
|
||||
if (!files) {
|
||||
files = new Set();
|
||||
implementorFiles.set(h.parentName, files);
|
||||
}
|
||||
files.add(h.filePath);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Public API ---------------------------------------------------
|
||||
|
||||
const getParents = (childNodeId: string): string[] => {
|
||||
const parents = directParents.get(childNodeId);
|
||||
return parents ? [...parents] : [];
|
||||
};
|
||||
|
||||
const getAncestors = (childNodeId: string): string[] => {
|
||||
const result: string[] = [];
|
||||
const visited = new Set<string>();
|
||||
visited.add(childNodeId); // prevent cycles through the start node
|
||||
|
||||
// BFS with bounded depth
|
||||
let frontier = getParents(childNodeId);
|
||||
let depth = 0;
|
||||
|
||||
while (frontier.length > 0 && depth < MAX_ANCESTOR_DEPTH) {
|
||||
const nextFrontier: string[] = [];
|
||||
for (const parentId of frontier) {
|
||||
if (visited.has(parentId)) continue;
|
||||
visited.add(parentId);
|
||||
result.push(parentId);
|
||||
// Expand parent's own parents for next level
|
||||
const grandparents = directParents.get(parentId);
|
||||
if (grandparents) {
|
||||
for (const gp of grandparents) {
|
||||
if (!visited.has(gp)) nextFrontier.push(gp);
|
||||
}
|
||||
}
|
||||
}
|
||||
frontier = nextFrontier;
|
||||
depth++;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const getImplementorFiles = (interfaceName: string): ReadonlySet<string> => {
|
||||
return implementorFiles.get(interfaceName) ?? EMPTY_SET;
|
||||
};
|
||||
|
||||
return { getParents, getAncestors, getImplementorFiles };
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user