reponexia 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
reponexia/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
reponexia/ask.py ADDED
@@ -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)
reponexia/cache.py ADDED
@@ -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
+ )
reponexia/cli.py ADDED
@@ -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
reponexia/contract.py ADDED
@@ -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
@@ -0,0 +1,118 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://reponexia.dev/contract/graph.schema.json",
4
+ "title": "RepoNexia graph",
5
+ "description": "Contrato entre o motor Rust e o orquestrador Python. Versão 1.0.",
6
+ "type": "object",
7
+ "required": ["schema_version", "root", "files"],
8
+ "properties": {
9
+ "schema_version": {
10
+ "type": "string",
11
+ "pattern": "^1\\.[0-9]+$"
12
+ },
13
+ "root": {
14
+ "type": "string",
15
+ "description": "Raiz absoluta do repositório analisado."
16
+ },
17
+ "repo_hash": {
18
+ "type": "string",
19
+ "description": "Hash do hash de todos os arquivos. Permite cache O(1)."
20
+ },
21
+ "languages": {
22
+ "type": "array",
23
+ "items": { "type": "string" }
24
+ },
25
+ "files": {
26
+ "type": "array",
27
+ "items": {
28
+ "type": "object",
29
+ "required": ["path", "language", "loc", "hash"],
30
+ "properties": {
31
+ "path": {
32
+ "type": "string",
33
+ "description": "Caminho relativo à raiz, sempre com '/' como separador."
34
+ },
35
+ "language": { "type": "string" },
36
+ "loc": { "type": "integer", "minimum": 0 },
37
+ "hash": { "type": "string" },
38
+ "parse_errors": {
39
+ "type": "array",
40
+ "items": { "type": "string" }
41
+ }
42
+ },
43
+ "additionalProperties": false
44
+ }
45
+ },
46
+ "warnings": {
47
+ "type": "array",
48
+ "items": {
49
+ "type": "object",
50
+ "required": ["message"],
51
+ "properties": {
52
+ "path": { "type": "string" },
53
+ "message": { "type": "string" }
54
+ },
55
+ "additionalProperties": false
56
+ }
57
+ },
58
+ "symbols":{
59
+ "type": "array",
60
+ "items": {
61
+ "type": "object",
62
+ "required": ["id", "file", "name", "kind", "line", "exported"],
63
+ "properties": {
64
+ "id": { "type": "string" },
65
+ "file": { "type": "string" },
66
+ "name": { "type": "string" },
67
+ "kind": { "type": "string", "enum": ["function", "class", "method"] },
68
+ "line": { "type": "integer", "minimum": 1 },
69
+ "exported": { "type": "boolean" }
70
+ },
71
+ "additionalProperties": false
72
+ }
73
+ },
74
+ "edges":{
75
+ "type": "array",
76
+ "items": {
77
+ "type": "object",
78
+ "required": ["from", "to", "kind", "line"],
79
+ "properties": {
80
+ "from": { "type": "string" },
81
+ "to": { "type": "string" },
82
+ "kind": { "type": "string", "enum": ["import", "call", "extends", "implements"] },
83
+ "symbol": { "type": "string" },
84
+ "line": { "type": "integer", "minimum": 1 }
85
+ },
86
+ "additionalProperties": false
87
+ }
88
+ },
89
+ "metrics": {
90
+ "type": "array",
91
+ "items": {
92
+ "type": "object",
93
+ "required": ["path", "fan_in", "fan_out", "page_rank"],
94
+ "properties": {
95
+ "path": { "type": "string" },
96
+ "fan_in": { "type": "integer", "minimum": 0 },
97
+ "fan_out": { "type": "integer", "minimum": 0 },
98
+ "page_rank": { "type": "number", "minimum": 0 }
99
+ },
100
+ "additionalProperties": false
101
+ }
102
+ },
103
+ "entry_points": {
104
+ "type": "array",
105
+ "items": {
106
+ "type": "object",
107
+ "required": ["path", "kind", "evidence"],
108
+ "properties": {
109
+ "path": { "type": "string" },
110
+ "kind": { "type": "string", "enum": ["main", "bin", "console_script","package_main"] },
111
+ "evidence": { "type": "string" }
112
+ },
113
+ "additionalProperties": false
114
+ }
115
+ }
116
+ },
117
+ "additionalProperties": true
118
+ }
reponexia/guide.py ADDED
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ # Fonte única do guia: o comando `reponexia guia` e docs/USAGE.md saem daqui.
4
+ ORDER = ["instalacao", "comandos", "graph", "llm", "config", "problemas"]
5
+
6
+ TOPICS: dict[str, str] = {
7
+ "instalacao": """## Instalação
8
+
9
+ Via PyPI (pacote publicado):
10
+ pip install reponexia
11
+ pip install "reponexia[llm]" # para usar o LLM real
12
+
13
+ A partir do código-fonte (clone):
14
+ python -m venv .venv
15
+ .venv\\Scripts\\Activate.ps1 # Linux/macOS: source .venv/bin/activate
16
+
17
+ # Opção A (após publicar): usa o wheel do core, sem Rust
18
+ pip install -e .
19
+
20
+ # Opção B (testar o core local): compila o Rust
21
+ pip install ./core
22
+ pip install -e ".[llm]"
23
+
24
+ O binário do motor é procurado nesta ordem:
25
+ REPONEXIA_CORE -> Scripts do ambiente -> PATH -> core/target/{release,debug}""",
26
+ "comandos": """## Comandos
27
+
28
+ reponexia guia [topico] Este guia
29
+ reponexia map <path> Estrutura do repo (JSON, sem LLM)
30
+ reponexia graph <path> [--format] Exporta o grafo (json|mermaid)
31
+ reponexia explain <path> --dry-run Onboarding estrutural, sem LLM
32
+ reponexia explain <path> --model ... Onboarding com LLM
33
+ reponexia ask <path> "pergunta" Pergunta sobre o índice""",
34
+ "graph": """## Ver os dados do grafo
35
+
36
+ reponexia map . JSON no terminal
37
+ reponexia graph . --out graph.json salva JSON (UTF-8)
38
+ reponexia graph . --format mermaid --out architecture.mmd
39
+ reponexia explain . --dry-run gera .reponexia/{ONBOARDING.md,architecture.mmd,graph.json}
40
+ reponexia graph . | jq '.edges' filtra com jq (se instalado)
41
+
42
+ Visualizar o Mermaid: https://mermaid.live ou extensão do VS Code.
43
+ Atenção (PowerShell 5.1): `>` grava UTF-16; prefira `--out`.
44
+ O graph.json contém só metadados (arquivos, símbolos, arestas, métricas), sem código.""",
45
+ "llm": """## LLM
46
+
47
+ reponexia explain . --model openai/gpt-4o-mini
48
+ REPONEXIA_MODEL=... reponexia explain .
49
+ --max-tokens N teto de orçamento do run (estimativa)
50
+ Cache em .reponexia/cache.json: rodar sem mudança = 0 chamadas.
51
+
52
+ Providers via litellm: OpenAI, Anthropic, Ollama, etc.
53
+ Configure a env do provider (ex.: OPENAI_API_KEY, ANTHROPIC_API_KEY).
54
+ Ollama local: --model ollama/qwen2.5-coder""",
55
+ "config": """## Configuração
56
+
57
+ REPONEXIA_CORE caminho do binário do motor
58
+ REPONEXIA_MODEL modelo padrão (usado quando --model não é passado)
59
+ REPONEXIA_CONTRACT caminho alternativo do graph.schema.json
60
+ --out DIR diretório de saída (padrão: <path>/.reponexia)""",
61
+ "problemas": """## Problemas comuns
62
+
63
+ "reponexia-core não encontrado"
64
+ -> pip install ./core (ou cargo build --release em core/ e aponte REPONEXIA_CORE)
65
+
66
+ "defina --model ou REPONEXIA_MODEL"
67
+ -> passe --model ou use --dry-run
68
+
69
+ "graph.json invalido ... schema"
70
+ -> motor e orquestrador com versões diferentes; atualize os dois.
71
+
72
+ Mermaid vazio
73
+ -> não há dependências internas resolvidas; rode `reponexia map .` e veja `edges`.""",
74
+ }
75
+
76
+
77
+ def render(topic: str | None = None, *, markdown: bool = False) -> str:
78
+ if topic is None:
79
+ body = "\n\n".join(TOPICS[key] for key in ORDER)
80
+ else:
81
+ key = topic.strip().lower()
82
+ if key not in TOPICS:
83
+ raise KeyError(key)
84
+ body = TOPICS[key]
85
+
86
+ if markdown:
87
+ return f"# RepoNexia — Guia de uso\n\n{body}"
88
+ return body
reponexia/modules.py ADDED
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+ from pathlib import PurePosixPath
5
+
6
+
7
+ # Modulo = pai do arquivo, ou "(raiz)" se o arquivo estiver na raiz
8
+ def module_of(path: str) -> str:
9
+ # Retorna o módulo pai do arquivo, ou "(raiz)" se o arquivo estiver na raiz
10
+ parent = str(PurePosixPath(path).parent)
11
+ return "(raiz)" if parent == "." else parent
12
+
13
+ # Agrupa os arquivos por módulo, retornando um dicionário {modulo: [arquivos]}
14
+ def group_files_by_module(files: list[dict]) -> dict[str,list[dict]]:
15
+ groups: dict[str, list[dict]] = defaultdict(list)
16
+ for file in files:
17
+ groups[module_of(file["path"])].append(file)
18
+ return {
19
+ name: sorted(members, key=lambda f: f["path"])
20
+ for name, members in groups.items()
21
+ }