reponexia 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- reponexia-0.1.0/LICENSE +21 -0
- reponexia-0.1.0/PKG-INFO +88 -0
- reponexia-0.1.0/README.md +65 -0
- reponexia-0.1.0/pyproject.toml +40 -0
- reponexia-0.1.0/setup.cfg +4 -0
- reponexia-0.1.0/src/reponexia/__init__.py +1 -0
- reponexia-0.1.0/src/reponexia/__main__.py +5 -0
- reponexia-0.1.0/src/reponexia/ask.py +50 -0
- reponexia-0.1.0/src/reponexia/cache.py +40 -0
- reponexia-0.1.0/src/reponexia/cli.py +178 -0
- reponexia-0.1.0/src/reponexia/contract.py +43 -0
- reponexia-0.1.0/src/reponexia/core_runner.py +61 -0
- reponexia-0.1.0/src/reponexia/graph.schema.json +118 -0
- reponexia-0.1.0/src/reponexia/guide.py +88 -0
- reponexia-0.1.0/src/reponexia/modules.py +21 -0
- reponexia-0.1.0/src/reponexia/pipeline.py +101 -0
- reponexia-0.1.0/src/reponexia/redact.py +28 -0
- reponexia-0.1.0/src/reponexia/render/__init__.py +4 -0
- reponexia-0.1.0/src/reponexia/render/markdown.py +144 -0
- reponexia-0.1.0/src/reponexia/render/mermaid.py +44 -0
- reponexia-0.1.0/src/reponexia/summarize/__init__.py +3 -0
- reponexia-0.1.0/src/reponexia/summarize/base.py +39 -0
- reponexia-0.1.0/src/reponexia/summarize/context.py +57 -0
- reponexia-0.1.0/src/reponexia/summarize/litellm_impl.py +112 -0
- reponexia-0.1.0/src/reponexia/summarize/skeleton.py +28 -0
- reponexia-0.1.0/src/reponexia.egg-info/PKG-INFO +88 -0
- reponexia-0.1.0/src/reponexia.egg-info/SOURCES.txt +42 -0
- reponexia-0.1.0/src/reponexia.egg-info/dependency_links.txt +1 -0
- reponexia-0.1.0/src/reponexia.egg-info/entry_points.txt +2 -0
- reponexia-0.1.0/src/reponexia.egg-info/requires.txt +8 -0
- reponexia-0.1.0/src/reponexia.egg-info/top_level.txt +1 -0
- reponexia-0.1.0/tests/test_ask.py +20 -0
- reponexia-0.1.0/tests/test_cache.py +26 -0
- reponexia-0.1.0/tests/test_cli.py +73 -0
- reponexia-0.1.0/tests/test_context.py +55 -0
- reponexia-0.1.0/tests/test_contract.py +40 -0
- reponexia-0.1.0/tests/test_core_runner.py +27 -0
- reponexia-0.1.0/tests/test_guide.py +30 -0
- reponexia-0.1.0/tests/test_litellm.py +89 -0
- reponexia-0.1.0/tests/test_mermaid.py +67 -0
- reponexia-0.1.0/tests/test_pipeline.py +65 -0
- reponexia-0.1.0/tests/test_redact.py +42 -0
- reponexia-0.1.0/tests/test_render.py +84 -0
- reponexia-0.1.0/tests/test_skeleton.py +21 -0
reponexia-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RepoNexia contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
reponexia-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: reponexia
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI que explica um repositório desconhecido
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/rhyan05/reponexia
|
|
7
|
+
Project-URL: Repository, https://github.com/rhyan05/reponexia
|
|
8
|
+
Project-URL: Issues, https://github.com/rhyan05/reponexia/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Topic :: Software Development :: Documentation
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: jsonschema>=4.0
|
|
17
|
+
Requires-Dist: reponexia-core==0.1.*
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Provides-Extra: llm
|
|
21
|
+
Requires-Dist: litellm; extra == "llm"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# RepoNexia
|
|
25
|
+
|
|
26
|
+
CLI que explica um repositório desconhecido: mapeia arquitetura, entry points e
|
|
27
|
+
dependências críticas, e gera um onboarding doc.
|
|
28
|
+
|
|
29
|
+
Motor em Rust (`reponexia-core`) faz o scan/parse e monta o grafo; o orquestrador
|
|
30
|
+
em Python chama o LLM e renderiza a documentação. A fronteira é um JSON
|
|
31
|
+
versionado (`src/reponexia/graph.schema.json`).
|
|
32
|
+
|
|
33
|
+
## Build e instalação
|
|
34
|
+
|
|
35
|
+
**Via PyPI** (após o release):
|
|
36
|
+
```bash
|
|
37
|
+
pip install reponexia
|
|
38
|
+
pip install "reponexia[llm]" # LLM real (litellm)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**A partir do código-fonte** (clone):
|
|
42
|
+
```bash
|
|
43
|
+
python -m venv .venv
|
|
44
|
+
# .venv\Scripts\Activate.ps1 (Windows) | source .venv/bin/activate (Unix)
|
|
45
|
+
|
|
46
|
+
pip install -e . # usa o wheel publicado do core (sem Rust)
|
|
47
|
+
# ou, para compilar/testar o core local:
|
|
48
|
+
pip install ./core
|
|
49
|
+
pip install -e ".[llm]"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
O Python descobre o binário nesta ordem: `REPONEXIA_CORE` → `Scripts/bin` do
|
|
53
|
+
ambiente → `PATH` → `core/target/{release,debug}`.
|
|
54
|
+
|
|
55
|
+
## Uso
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
reponexia guia # guia de uso no terminal
|
|
59
|
+
reponexia map <path> # só o core; imprime o graph.json
|
|
60
|
+
reponexia graph <path> --format mermaid # exporta o grafo (json|mermaid)
|
|
61
|
+
reponexia explain <path> --dry-run # esqueleto estrutural, sem LLM
|
|
62
|
+
reponexia explain <path> --model openai/gpt-4o-mini
|
|
63
|
+
reponexia ask <path> "onde fica a autenticação?"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
O mesmo guia está em [`docs/USAGE.md`](docs/USAGE.md) (gerado por
|
|
67
|
+
`reponexia guia --markdown`).
|
|
68
|
+
|
|
69
|
+
No modo real o modelo vem de `--model` ou `REPONEXIA_MODEL`. `--max-tokens`
|
|
70
|
+
limita o orçamento; sem mudança no repo, o cache evita novas chamadas LLM.
|
|
71
|
+
|
|
72
|
+
Saída padrão em `<path>/.reponexia/`: `graph.json`, `ONBOARDING.md` e
|
|
73
|
+
`architecture.mmd` (`--out` sobrescreve o diretório).
|
|
74
|
+
|
|
75
|
+
Exemplo de saída: [`examples/ONBOARDING.md`](examples/ONBOARDING.md).
|
|
76
|
+
|
|
77
|
+
## Segurança
|
|
78
|
+
|
|
79
|
+
Antes de qualquer chamada LLM, snippets passam por `redact.py` (AWS, OpenAI,
|
|
80
|
+
GitHub, Slack, chave privada e connection strings). O scan ignora `.gitignore`,
|
|
81
|
+
dotfiles e `.reponexia`.
|
|
82
|
+
|
|
83
|
+
## Testes
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
cargo test --manifest-path core/Cargo.toml
|
|
87
|
+
pytest
|
|
88
|
+
```
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# RepoNexia
|
|
2
|
+
|
|
3
|
+
CLI que explica um repositório desconhecido: mapeia arquitetura, entry points e
|
|
4
|
+
dependências críticas, e gera um onboarding doc.
|
|
5
|
+
|
|
6
|
+
Motor em Rust (`reponexia-core`) faz o scan/parse e monta o grafo; o orquestrador
|
|
7
|
+
em Python chama o LLM e renderiza a documentação. A fronteira é um JSON
|
|
8
|
+
versionado (`src/reponexia/graph.schema.json`).
|
|
9
|
+
|
|
10
|
+
## Build e instalação
|
|
11
|
+
|
|
12
|
+
**Via PyPI** (após o release):
|
|
13
|
+
```bash
|
|
14
|
+
pip install reponexia
|
|
15
|
+
pip install "reponexia[llm]" # LLM real (litellm)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
**A partir do código-fonte** (clone):
|
|
19
|
+
```bash
|
|
20
|
+
python -m venv .venv
|
|
21
|
+
# .venv\Scripts\Activate.ps1 (Windows) | source .venv/bin/activate (Unix)
|
|
22
|
+
|
|
23
|
+
pip install -e . # usa o wheel publicado do core (sem Rust)
|
|
24
|
+
# ou, para compilar/testar o core local:
|
|
25
|
+
pip install ./core
|
|
26
|
+
pip install -e ".[llm]"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
O Python descobre o binário nesta ordem: `REPONEXIA_CORE` → `Scripts/bin` do
|
|
30
|
+
ambiente → `PATH` → `core/target/{release,debug}`.
|
|
31
|
+
|
|
32
|
+
## Uso
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
reponexia guia # guia de uso no terminal
|
|
36
|
+
reponexia map <path> # só o core; imprime o graph.json
|
|
37
|
+
reponexia graph <path> --format mermaid # exporta o grafo (json|mermaid)
|
|
38
|
+
reponexia explain <path> --dry-run # esqueleto estrutural, sem LLM
|
|
39
|
+
reponexia explain <path> --model openai/gpt-4o-mini
|
|
40
|
+
reponexia ask <path> "onde fica a autenticação?"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
O mesmo guia está em [`docs/USAGE.md`](docs/USAGE.md) (gerado por
|
|
44
|
+
`reponexia guia --markdown`).
|
|
45
|
+
|
|
46
|
+
No modo real o modelo vem de `--model` ou `REPONEXIA_MODEL`. `--max-tokens`
|
|
47
|
+
limita o orçamento; sem mudança no repo, o cache evita novas chamadas LLM.
|
|
48
|
+
|
|
49
|
+
Saída padrão em `<path>/.reponexia/`: `graph.json`, `ONBOARDING.md` e
|
|
50
|
+
`architecture.mmd` (`--out` sobrescreve o diretório).
|
|
51
|
+
|
|
52
|
+
Exemplo de saída: [`examples/ONBOARDING.md`](examples/ONBOARDING.md).
|
|
53
|
+
|
|
54
|
+
## Segurança
|
|
55
|
+
|
|
56
|
+
Antes de qualquer chamada LLM, snippets passam por `redact.py` (AWS, OpenAI,
|
|
57
|
+
GitHub, Slack, chave privada e connection strings). O scan ignora `.gitignore`,
|
|
58
|
+
dotfiles e `.reponexia`.
|
|
59
|
+
|
|
60
|
+
## Testes
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
cargo test --manifest-path core/Cargo.toml
|
|
64
|
+
pytest
|
|
65
|
+
```
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "reponexia"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "CLI que explica um repositório desconhecido"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"jsonschema>=4.0",
|
|
15
|
+
"reponexia-core==0.1.*",
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Environment :: Console",
|
|
20
|
+
"Topic :: Software Development :: Documentation",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
reponexia = "reponexia.cli:main"
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/rhyan05/reponexia"
|
|
29
|
+
Repository = "https://github.com/rhyan05/reponexia"
|
|
30
|
+
Issues = "https://github.com/rhyan05/reponexia/issues"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["src"]
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.package-data]
|
|
36
|
+
reponexia = ["graph.schema.json"]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
dev = ["pytest"]
|
|
40
|
+
llm = ["litellm"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .render import render_markdown, render_mermaid
|
|
4
|
+
from .summarize.litellm_impl import LiteLLMSummarizer
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
# Contexto compacto do grafo para responder perguntas sem mandar código bruto.
|
|
8
|
+
def build_context(graph: dict) -> str:
|
|
9
|
+
lines = [f"Repositorio com {len(graph.get('files', []))} arquivos."]
|
|
10
|
+
languages = ", ".join(graph.get("languages", [])) or "nenhuma"
|
|
11
|
+
lines.append(f"Linguagens: {languages}")
|
|
12
|
+
|
|
13
|
+
entries = graph.get("entry_points", [])
|
|
14
|
+
if entries:
|
|
15
|
+
lines.append("Entry points: " + ", ".join(e["path"] for e in entries))
|
|
16
|
+
|
|
17
|
+
metrics = sorted(
|
|
18
|
+
graph.get("metrics", []), key=lambda m: (-m["page_rank"], m["path"])
|
|
19
|
+
)[:10]
|
|
20
|
+
if metrics:
|
|
21
|
+
lines.append(
|
|
22
|
+
"Arquivos centrais: "
|
|
23
|
+
+ ", ".join(f"{m['path']} (rank {m['page_rank']})" for m in metrics)
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
symbols = graph.get("symbols", [])[:50]
|
|
27
|
+
if symbols:
|
|
28
|
+
lines.append(
|
|
29
|
+
"Simbolos: "
|
|
30
|
+
+ ", ".join(f"{s['name']}@{s['file']}:{s['line']}" for s in symbols)
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
edges = graph.get("edges", [])[:50]
|
|
34
|
+
if edges:
|
|
35
|
+
lines.append(
|
|
36
|
+
"Dependencias: "
|
|
37
|
+
+ "; ".join(f"{e['from']} -> {e['to']}" for e in edges)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return "\n".join(lines)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ask(graph: dict, question: str, model: str, *, max_tokens: int = 1_000_000) -> str:
|
|
44
|
+
summarizer = LiteLLMSummarizer(model, max_tokens=max_tokens)
|
|
45
|
+
prompt = (
|
|
46
|
+
f"Contexto do repositorio:\n{build_context(graph)}\n\n"
|
|
47
|
+
f"Pergunta: {question}\n\n"
|
|
48
|
+
"Responda citando arquivo quando possivel. Nao invente fatos."
|
|
49
|
+
)
|
|
50
|
+
return summarizer._complete(prompt)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from hashlib import sha256
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def cache_key(*parts: str) -> str:
|
|
9
|
+
hasher = sha256()
|
|
10
|
+
for part in parts:
|
|
11
|
+
hasher.update(part.encode("utf-8"))
|
|
12
|
+
hasher.update(b"\x00") # separador evita colisão entre campos
|
|
13
|
+
return hasher.hexdigest()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# Cache local em JSON: map de chave -> resumo.
|
|
17
|
+
# Chave inclui repo/conteúdo do módulo + modelo, então rodar sem mudança = 0 chamadas.
|
|
18
|
+
class Cache:
|
|
19
|
+
def __init__(self, path: str | Path) -> None:
|
|
20
|
+
self.path = Path(path)
|
|
21
|
+
self._data = self._load()
|
|
22
|
+
|
|
23
|
+
def _load(self) -> dict[str, str]:
|
|
24
|
+
try:
|
|
25
|
+
return json.loads(self.path.read_text(encoding="utf-8"))
|
|
26
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
27
|
+
return {}
|
|
28
|
+
|
|
29
|
+
def get(self, key: str) -> str | None:
|
|
30
|
+
return self._data.get(key)
|
|
31
|
+
|
|
32
|
+
def set(self, key: str, value: str) -> None:
|
|
33
|
+
self._data[key] = value
|
|
34
|
+
|
|
35
|
+
def save(self) -> None:
|
|
36
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
self.path.write_text(
|
|
38
|
+
json.dumps(self._data, indent=2, sort_keys=True, ensure_ascii=False),
|
|
39
|
+
encoding="utf-8",
|
|
40
|
+
)
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .ask import ask
|
|
10
|
+
from .cache import Cache
|
|
11
|
+
from .contract import ContractError
|
|
12
|
+
from .core_runner import CoreNotFound, index
|
|
13
|
+
from .guide import ORDER, render as render_guide
|
|
14
|
+
from .pipeline import build_narrative
|
|
15
|
+
from .render import render_markdown, render_mermaid
|
|
16
|
+
from .summarize.litellm_impl import (
|
|
17
|
+
BudgetExceeded,
|
|
18
|
+
LiteLLMSummarizer,
|
|
19
|
+
SummarizerError,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _model_from(args) -> str | None:
|
|
24
|
+
# Sem hardcode de provider: flag ou variável de ambiente.
|
|
25
|
+
return args.model or os.environ.get("REPONEXIA_MODEL")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _write(path: Path, text: str) -> None:
|
|
29
|
+
# UTF-8 + LF fixo para o artefato ser idêntico em qualquer SO.
|
|
30
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
with path.open("w", encoding="utf-8", newline="\n") as file:
|
|
32
|
+
file.write(text)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _json(graph: dict) -> str:
|
|
36
|
+
return json.dumps(graph, indent=2, ensure_ascii=False) + "\n"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(argv: list[str] | None = None) -> int:
|
|
40
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
41
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
42
|
+
|
|
43
|
+
parser = argparse.ArgumentParser(prog="reponexia")
|
|
44
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
45
|
+
|
|
46
|
+
guia_cmd = sub.add_parser("guia", help="Guia de uso no terminal")
|
|
47
|
+
guia_cmd.add_argument(
|
|
48
|
+
"topico",
|
|
49
|
+
nargs="?",
|
|
50
|
+
help="instalacao | comandos | graph | llm | config | problemas",
|
|
51
|
+
)
|
|
52
|
+
guia_cmd.add_argument(
|
|
53
|
+
"--markdown", action="store_true", help="emite markdown (para docs/USAGE.md)"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
map_cmd = sub.add_parser("map", help="Mostra a estrutura do repositório (sem LLM)")
|
|
57
|
+
map_cmd.add_argument("path")
|
|
58
|
+
|
|
59
|
+
explain_cmd = sub.add_parser(
|
|
60
|
+
"explain", help="Gera o onboarding do repositório (--dry-run = sem LLM)"
|
|
61
|
+
)
|
|
62
|
+
explain_cmd.add_argument("path")
|
|
63
|
+
explain_cmd.add_argument(
|
|
64
|
+
"--dry-run",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="Roda só o core e gera o esqueleto estrutural, sem LLM",
|
|
67
|
+
)
|
|
68
|
+
explain_cmd.add_argument("--model", help="ex.: openai/gpt-4o-mini, ollama/qwen2.5-coder")
|
|
69
|
+
explain_cmd.add_argument(
|
|
70
|
+
"--max-tokens", type=int, default=1_000_000, help="orçamento de tokens do run"
|
|
71
|
+
)
|
|
72
|
+
explain_cmd.add_argument("--out", help="diretório de saída (padrão: <path>/.reponexia)")
|
|
73
|
+
explain_cmd.add_argument("--verbose", action="store_true")
|
|
74
|
+
|
|
75
|
+
graph_cmd = sub.add_parser("graph", help="Exporta o grafo do repositório")
|
|
76
|
+
graph_cmd.add_argument("path")
|
|
77
|
+
graph_cmd.add_argument("--format", choices=["json", "mermaid"], default="json")
|
|
78
|
+
graph_cmd.add_argument("--out", help="arquivo de saída (padrão: stdout)")
|
|
79
|
+
|
|
80
|
+
ask_cmd = sub.add_parser("ask", help="Pergunta sobre o índice do repositório")
|
|
81
|
+
ask_cmd.add_argument("path")
|
|
82
|
+
ask_cmd.add_argument("question")
|
|
83
|
+
ask_cmd.add_argument("--model")
|
|
84
|
+
ask_cmd.add_argument("--max-tokens", type=int, default=1_000_000)
|
|
85
|
+
|
|
86
|
+
args = parser.parse_args(argv)
|
|
87
|
+
|
|
88
|
+
# Guia não toca no core nem exige path: é o comando de quem está perdido.
|
|
89
|
+
if args.command == "guia":
|
|
90
|
+
try:
|
|
91
|
+
print(render_guide(args.topico, markdown=args.markdown))
|
|
92
|
+
except KeyError:
|
|
93
|
+
print(f"topico desconhecido: {args.topico}", file=sys.stderr)
|
|
94
|
+
print("disponiveis: " + ", ".join(ORDER), file=sys.stderr)
|
|
95
|
+
return 1
|
|
96
|
+
return 0
|
|
97
|
+
|
|
98
|
+
if args.command == "map":
|
|
99
|
+
try:
|
|
100
|
+
graph = index(args.path)
|
|
101
|
+
except (CoreNotFound, ContractError) as err:
|
|
102
|
+
print(err, file=sys.stderr)
|
|
103
|
+
return 1
|
|
104
|
+
print(json.dumps(graph, indent=2, ensure_ascii=False))
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
if args.command == "graph":
|
|
108
|
+
try:
|
|
109
|
+
graph = index(args.path)
|
|
110
|
+
except (CoreNotFound, ContractError) as err:
|
|
111
|
+
print(err, file=sys.stderr)
|
|
112
|
+
return 1
|
|
113
|
+
text = _json(graph) if args.format == "json" else render_mermaid(graph)
|
|
114
|
+
if args.out:
|
|
115
|
+
_write(Path(args.out), text)
|
|
116
|
+
else:
|
|
117
|
+
sys.stdout.write(text)
|
|
118
|
+
return 0
|
|
119
|
+
|
|
120
|
+
if args.command == "ask":
|
|
121
|
+
model = _model_from(args)
|
|
122
|
+
if not model:
|
|
123
|
+
print("defina --model ou REPONEXIA_MODEL", file=sys.stderr)
|
|
124
|
+
return 1
|
|
125
|
+
try:
|
|
126
|
+
graph = index(args.path)
|
|
127
|
+
print(ask(graph, args.question, model, max_tokens=args.max_tokens))
|
|
128
|
+
except (CoreNotFound, ContractError, SummarizerError) as err:
|
|
129
|
+
print(err, file=sys.stderr)
|
|
130
|
+
return 1
|
|
131
|
+
return 0
|
|
132
|
+
|
|
133
|
+
if args.command == "explain":
|
|
134
|
+
# No modo real exigimos modelo antes de tocar no core.
|
|
135
|
+
model = None
|
|
136
|
+
if not args.dry_run:
|
|
137
|
+
model = _model_from(args)
|
|
138
|
+
if not model:
|
|
139
|
+
print("defina --model ou REPONEXIA_MODEL (ou use --dry-run)", file=sys.stderr)
|
|
140
|
+
return 1
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
graph = index(args.path)
|
|
144
|
+
except (CoreNotFound, ContractError) as err:
|
|
145
|
+
print(err, file=sys.stderr)
|
|
146
|
+
return 1
|
|
147
|
+
|
|
148
|
+
out_dir = Path(args.out) if args.out else Path(args.path).resolve() / ".reponexia"
|
|
149
|
+
|
|
150
|
+
narrative = None
|
|
151
|
+
if not args.dry_run:
|
|
152
|
+
summarizer = LiteLLMSummarizer(model, max_tokens=args.max_tokens)
|
|
153
|
+
cache = Cache(out_dir / "cache.json")
|
|
154
|
+
try:
|
|
155
|
+
narrative = build_narrative(
|
|
156
|
+
graph, summarizer, cache=cache, verbose=args.verbose
|
|
157
|
+
)
|
|
158
|
+
except (SummarizerError, BudgetExceeded) as err:
|
|
159
|
+
print(err, file=sys.stderr)
|
|
160
|
+
return 1
|
|
161
|
+
cache.save()
|
|
162
|
+
if args.verbose:
|
|
163
|
+
print(
|
|
164
|
+
f"[verbose] ~{summarizer.spent} tokens gastos", file=sys.stderr
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
_write(out_dir / "graph.json", _json(graph))
|
|
168
|
+
onboarding = out_dir / "ONBOARDING.md"
|
|
169
|
+
_write(onboarding, render_markdown(graph, narrative))
|
|
170
|
+
architecture = out_dir / "architecture.mmd"
|
|
171
|
+
_write(architecture, render_mermaid(graph))
|
|
172
|
+
|
|
173
|
+
print(f"onboarding gerado em {onboarding}")
|
|
174
|
+
print(f"arquitetura gerada em {architecture}")
|
|
175
|
+
print(f"grafo gerado em {out_dir / 'graph.json'}")
|
|
176
|
+
return 0
|
|
177
|
+
|
|
178
|
+
return 1
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import jsonschema
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ContractError(ValueError):
|
|
12
|
+
"""O graph.json produzido pelo core viola o contrato."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@lru_cache(maxsize=1)
|
|
16
|
+
def load_schema() -> dict:
|
|
17
|
+
override = os.environ.get("REPONEXIA_CONTRACT")
|
|
18
|
+
if override:
|
|
19
|
+
path = Path(override)
|
|
20
|
+
else:
|
|
21
|
+
path = Path(__file__).with_name("graph.schema.json")
|
|
22
|
+
|
|
23
|
+
if not path.exists():
|
|
24
|
+
raise ContractError(f"schema do contrato nao encontrado em {path}")
|
|
25
|
+
|
|
26
|
+
with path.open(encoding="utf-8") as file:
|
|
27
|
+
try:
|
|
28
|
+
return json.load(file)
|
|
29
|
+
except json.JSONDecodeError as err:
|
|
30
|
+
raise ContractError(f"schema invalido em {path}: {err}") from err
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def validate(graph: dict) -> None:
|
|
34
|
+
schema = load_schema()
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
jsonschema.validate(instance=graph, schema=schema)
|
|
38
|
+
except jsonschema.ValidationError as err:
|
|
39
|
+
raise ContractError(
|
|
40
|
+
f"graph.json invalido em {err.json_path}: {err.message}"
|
|
41
|
+
) from err
|
|
42
|
+
except jsonschema.SchemaError as err:
|
|
43
|
+
raise ContractError(f"schema invalido: {err.message}") from err
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .contract import validate
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CoreNotFound(RuntimeError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def find_core() -> Path:
|
|
18
|
+
override = os.environ.get("REPONEXIA_CORE")
|
|
19
|
+
if override:
|
|
20
|
+
return Path(override)
|
|
21
|
+
|
|
22
|
+
exe = "reponexia-core.exe" if os.name == "nt" else "reponexia-core"
|
|
23
|
+
|
|
24
|
+
# 1. Binário instalado pelo pip no mesmo ambiente (Scripts/bin do venv).
|
|
25
|
+
# Não depende do PATH estar ativo, o que falha quando o comando é
|
|
26
|
+
# chamado por subprocess/serviço.
|
|
27
|
+
packaged = Path(sys.executable).parent / exe
|
|
28
|
+
if packaged.exists():
|
|
29
|
+
return packaged
|
|
30
|
+
|
|
31
|
+
# 2. Binário disponível no PATH.
|
|
32
|
+
on_path = shutil.which(exe)
|
|
33
|
+
if on_path:
|
|
34
|
+
return Path(on_path)
|
|
35
|
+
|
|
36
|
+
# 3. Build local a partir do código-fonte (modo desenvolvimento).
|
|
37
|
+
root = Path(__file__).resolve().parents[2]
|
|
38
|
+
for profile in ("release", "debug"):
|
|
39
|
+
candidate = root / "core" / "target" / profile / exe
|
|
40
|
+
if candidate.exists():
|
|
41
|
+
return candidate
|
|
42
|
+
|
|
43
|
+
raise CoreNotFound(
|
|
44
|
+
"reponexia-core não encontrado. Instale com `pip install ./core`, rode "
|
|
45
|
+
"`cargo build --release` em core/ ou defina a variável REPONEXIA_CORE."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Faz a indexação do path usando o core e retorna o grafo resultante
|
|
49
|
+
def index(path: str | Path) -> dict:
|
|
50
|
+
core = find_core()
|
|
51
|
+
proc = subprocess.run(
|
|
52
|
+
[str(core), "index", str(path)],
|
|
53
|
+
capture_output=True,
|
|
54
|
+
check=True,
|
|
55
|
+
)
|
|
56
|
+
stdout = proc.stdout.decode("utf-8", errors="replace")
|
|
57
|
+
graph = json.loads(stdout)
|
|
58
|
+
|
|
59
|
+
# Valida o grafo retornado pelo core contra o contrato
|
|
60
|
+
validate(graph)
|
|
61
|
+
return graph
|