kata-dev 0.7.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.
- kata/__init__.py +9 -0
- kata/__main__.py +8 -0
- kata/assets/claude-code/skills/kata/SKILL.md +562 -0
- kata/assets/claude-code/skills/kata-artifact/SKILL.md +81 -0
- kata/assets/claude-code/skills/kata-data-analysis/SKILL.md +183 -0
- kata/assets/claude-code/skills/kata-devops/SKILL.md +220 -0
- kata/assets/claude-code/skills/kata-docs/SKILL.md +119 -0
- kata/assets/claude-code/skills/kata-fit/SKILL.md +116 -0
- kata/assets/claude-code/skills/kata-intent/SKILL.md +85 -0
- kata/assets/claude-code/skills/kata-judge/SKILL.md +177 -0
- kata/assets/claude-code/skills/kata-question/SKILL.md +129 -0
- kata/assets/claude-code/skills/kata-report/SKILL.md +112 -0
- kata/assets/claude-code/skills/kata-research/SKILL.md +131 -0
- kata/assets/claude-code/skills/kata-simplify/SKILL.md +133 -0
- kata/assets/claude-code/skills/kata-surgical/SKILL.md +142 -0
- kata/assets/claude-code/skills/kata-think/SKILL.md +149 -0
- kata/assets/claude-code/skills/kata-verify/SKILL.md +210 -0
- kata/assets/opencode/agent/kata.md +562 -0
- kata/assets/opencode/skills/kata-artifact/SKILL.md +81 -0
- kata/assets/opencode/skills/kata-data-analysis/SKILL.md +183 -0
- kata/assets/opencode/skills/kata-devops/SKILL.md +220 -0
- kata/assets/opencode/skills/kata-docs/SKILL.md +119 -0
- kata/assets/opencode/skills/kata-fit/SKILL.md +112 -0
- kata/assets/opencode/skills/kata-intent/SKILL.md +84 -0
- kata/assets/opencode/skills/kata-judge/SKILL.md +177 -0
- kata/assets/opencode/skills/kata-question/SKILL.md +113 -0
- kata/assets/opencode/skills/kata-report/SKILL.md +112 -0
- kata/assets/opencode/skills/kata-research/SKILL.md +131 -0
- kata/assets/opencode/skills/kata-simplify/SKILL.md +132 -0
- kata/assets/opencode/skills/kata-surgical/SKILL.md +142 -0
- kata/assets/opencode/skills/kata-think/SKILL.md +146 -0
- kata/assets/opencode/skills/kata-verify/SKILL.md +210 -0
- kata/cli.py +1862 -0
- kata/config.py +182 -0
- kata/fit.py +105 -0
- kata/install.py +226 -0
- kata/judge.py +1681 -0
- kata/report.py +328 -0
- kata/skills.py +175 -0
- kata/verify.py +485 -0
- kata_dev-0.7.0.dist-info/METADATA +388 -0
- kata_dev-0.7.0.dist-info/RECORD +46 -0
- kata_dev-0.7.0.dist-info/WHEEL +5 -0
- kata_dev-0.7.0.dist-info/entry_points.txt +2 -0
- kata_dev-0.7.0.dist-info/licenses/LICENSE +21 -0
- kata_dev-0.7.0.dist-info/top_level.txt +1 -0
kata/config.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Configuração do projeto alvo — quais comandos verificam este repositório.
|
|
2
|
+
|
|
3
|
+
O kata nasceu presumindo ruff + pytest + coverage. A presunção estava no lugar
|
|
4
|
+
errado: quem sabe verificar um projeto é o projeto, não a ferramenta. Sem
|
|
5
|
+
isto, num repositório que não é Python o VERIFY não tinha o que rodar e o
|
|
6
|
+
JUDGE não re-executava nada — e `UNVERIFIABLE` (ver `kata.judge`) era a única
|
|
7
|
+
resposta honesta que sobrava.
|
|
8
|
+
|
|
9
|
+
O arquivo é `.kata/config.yaml` (ou `.kata/config.json` onde não houver
|
|
10
|
+
PyYAML), ao lado dos arquivos de tarefa. Ausente, os defaults reproduzem
|
|
11
|
+
exatamente o comportamento anterior — nenhum projeto Python existente muda.
|
|
12
|
+
|
|
13
|
+
```yaml
|
|
14
|
+
verify:
|
|
15
|
+
lint: npx eslint src tests
|
|
16
|
+
test: npx vitest run
|
|
17
|
+
coverage: npx vitest run --coverage
|
|
18
|
+
coverage_pattern: 'All files\\s+\\|\\s+([\\d.]+)'
|
|
19
|
+
gate: 80
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Cada comando aceita string (dividida como o shell dividiria) ou lista já
|
|
23
|
+
dividida. Um papel não declarado cai no default Python daquele papel.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import math
|
|
30
|
+
import re
|
|
31
|
+
import shlex
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
import yaml
|
|
38
|
+
|
|
39
|
+
_HAS_YAML = True
|
|
40
|
+
except ImportError:
|
|
41
|
+
_HAS_YAML = False
|
|
42
|
+
|
|
43
|
+
# Percentual na linha TOTAL do `coverage report` — o formato que pytest-cov
|
|
44
|
+
# emite. É o default porque é o que o kata sempre leu; projetos com outro
|
|
45
|
+
# formato declaram o seu em `verify.coverage_pattern`.
|
|
46
|
+
DEFAULT_COVERAGE_PATTERN = r"^TOTAL\s+.*?(\d+(?:\.\d+)?)%"
|
|
47
|
+
|
|
48
|
+
DEFAULT_GATE = 70.0
|
|
49
|
+
|
|
50
|
+
_ROLES = ("lint", "test", "coverage")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ConfigError(ValueError):
|
|
54
|
+
"""Configuração presente porém inválida.
|
|
55
|
+
|
|
56
|
+
É erro, e não default silencioso, de propósito: quem escreveu
|
|
57
|
+
`.kata/config.yaml` quis verificar de um jeito específico. Cair no ruff
|
|
58
|
+
calado faria o kata reportar sucesso de uma verificação que o projeto
|
|
59
|
+
nunca pediu — a mesma classe de mentira que o JUDGE existe para caçar.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class VerifyConfig:
|
|
65
|
+
"""Comandos de verificação declarados pelo projeto alvo.
|
|
66
|
+
|
|
67
|
+
`None` em um papel significa "não declarado": o papel cai no default
|
|
68
|
+
Python e continua obedecendo às flags de caminho (`--ruff-paths`,
|
|
69
|
+
`--test-paths`, `--cov-source`). Um papel declarado é usado verbatim, e
|
|
70
|
+
as flags de caminho daquele papel deixam de valer — o projeto já disse
|
|
71
|
+
o comando inteiro.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
lint: list[str] | None = None
|
|
75
|
+
test: list[str] | None = None
|
|
76
|
+
coverage: list[str] | None = None
|
|
77
|
+
coverage_pattern: str = DEFAULT_COVERAGE_PATTERN
|
|
78
|
+
gate: float | None = None
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def customizado(self) -> bool:
|
|
82
|
+
"""Algum papel foi declarado pelo projeto."""
|
|
83
|
+
return any(getattr(self, role) is not None for role in _ROLES)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _parse_command(value: Any, role: str) -> list[str] | None:
|
|
87
|
+
"""Aceita string ("npx eslint src") ou lista (["npx", "eslint", "src"]).
|
|
88
|
+
|
|
89
|
+
K-09: aspas não fechadas ("npx eslint 'src") levantam ValueError do
|
|
90
|
+
shlex — antes escapavam do `except ConfigError` do main e viravam
|
|
91
|
+
traceback. Config ilegível é erro nomeado, nunca traceback (mesma
|
|
92
|
+
doutrina do docstring de ConfigError).
|
|
93
|
+
"""
|
|
94
|
+
if value is None:
|
|
95
|
+
return None
|
|
96
|
+
if isinstance(value, str):
|
|
97
|
+
try:
|
|
98
|
+
cmd = shlex.split(value)
|
|
99
|
+
except ValueError as exc:
|
|
100
|
+
raise ConfigError(f"verify.{role}: comando inválido ({exc})") from exc
|
|
101
|
+
if not cmd:
|
|
102
|
+
raise ConfigError(f"verify.{role}: comando vazio")
|
|
103
|
+
return cmd
|
|
104
|
+
if isinstance(value, list):
|
|
105
|
+
if not value:
|
|
106
|
+
raise ConfigError(f"verify.{role}: comando vazio")
|
|
107
|
+
if not all(isinstance(part, str) for part in value):
|
|
108
|
+
raise ConfigError(f"verify.{role}: a lista deve conter só strings")
|
|
109
|
+
return list(value)
|
|
110
|
+
raise ConfigError(f"verify.{role}: esperava string ou lista, veio {type(value).__name__}")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def config_path(cwd: Path | None = None) -> Path | None:
|
|
114
|
+
"""Caminho do arquivo de config existente, ou None."""
|
|
115
|
+
base = (cwd or Path.cwd()) / ".kata"
|
|
116
|
+
for nome in ("config.yaml", "config.yml", "config.json"):
|
|
117
|
+
caminho = base / nome
|
|
118
|
+
if caminho.is_file():
|
|
119
|
+
return caminho
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def load_verify_config(cwd: Path | None = None) -> VerifyConfig:
|
|
124
|
+
"""Lê `.kata/config.yaml`. Sem arquivo, devolve os defaults Python."""
|
|
125
|
+
caminho = config_path(cwd)
|
|
126
|
+
if caminho is None:
|
|
127
|
+
return VerifyConfig()
|
|
128
|
+
|
|
129
|
+
texto = ""
|
|
130
|
+
try:
|
|
131
|
+
texto = caminho.read_text(encoding="utf-8")
|
|
132
|
+
if caminho.suffix == ".json" or not _HAS_YAML:
|
|
133
|
+
dados = json.loads(texto)
|
|
134
|
+
else:
|
|
135
|
+
dados = yaml.safe_load(texto)
|
|
136
|
+
except Exception as exc:
|
|
137
|
+
# YAML, JSON e OSError levantam exceções de famílias diferentes; o
|
|
138
|
+
# que importa é que config ilegível vire erro nomeado, nunca default
|
|
139
|
+
# silencioso. O read_text fora do try deixava OSError (permissão,
|
|
140
|
+
# diretório quebrado) escapar como traceback (K-09).
|
|
141
|
+
raise ConfigError(f"{caminho}: não foi possível ler ({exc})") from exc
|
|
142
|
+
|
|
143
|
+
if dados is None:
|
|
144
|
+
return VerifyConfig()
|
|
145
|
+
if not isinstance(dados, dict):
|
|
146
|
+
raise ConfigError(f"{caminho}: esperava um mapa no topo")
|
|
147
|
+
|
|
148
|
+
verify = dados.get("verify")
|
|
149
|
+
if verify is None:
|
|
150
|
+
verify = {}
|
|
151
|
+
if not isinstance(verify, dict):
|
|
152
|
+
raise ConfigError(f"{caminho}: `verify` deve ser um mapa")
|
|
153
|
+
|
|
154
|
+
gate = verify.get("gate")
|
|
155
|
+
if gate is not None and (isinstance(gate, bool) or not isinstance(gate, (int, float))):
|
|
156
|
+
raise ConfigError(f"{caminho}: `verify.gate` deve ser número")
|
|
157
|
+
if gate is not None and (not math.isfinite(float(gate)) or not 0 <= gate <= 100):
|
|
158
|
+
raise ConfigError(f"{caminho}: `verify.gate` deve estar entre 0 e 100")
|
|
159
|
+
|
|
160
|
+
pattern = verify.get("coverage_pattern", DEFAULT_COVERAGE_PATTERN)
|
|
161
|
+
if not isinstance(pattern, str):
|
|
162
|
+
raise ConfigError(f"{caminho}: `verify.coverage_pattern` deve ser string")
|
|
163
|
+
try:
|
|
164
|
+
compiled = re.compile(pattern)
|
|
165
|
+
except re.error as exc:
|
|
166
|
+
raise ConfigError(f"{caminho}: `verify.coverage_pattern` inválido ({exc})") from exc
|
|
167
|
+
# O percentual é extraído do grupo 1; um padrão válido sem grupo faz
|
|
168
|
+
# run_command_coverage casar sem conseguir medir (R10-1). Erro nomeado no
|
|
169
|
+
# carregamento, não crash em tempo de verificação.
|
|
170
|
+
if compiled.groups < 1:
|
|
171
|
+
raise ConfigError(
|
|
172
|
+
f"{caminho}: `verify.coverage_pattern` deve ter ao menos um grupo "
|
|
173
|
+
"de captura para o percentual"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
return VerifyConfig(
|
|
177
|
+
lint=_parse_command(verify.get("lint"), "lint"),
|
|
178
|
+
test=_parse_command(verify.get("test"), "test"),
|
|
179
|
+
coverage=_parse_command(verify.get("coverage"), "coverage"),
|
|
180
|
+
coverage_pattern=pattern,
|
|
181
|
+
gate=float(gate) if gate is not None else None,
|
|
182
|
+
)
|
kata/fit.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Fit gate — classificação e roteamento de tarefas antes do THINK.
|
|
2
|
+
|
|
3
|
+
Implementa os conceitos de triviality gate e fit gate do fable-method:
|
|
4
|
+
1. Identificar tarefas triviais (<=1 arquivo, <10 linhas, sem busca)
|
|
5
|
+
2. Classificar a rota da tarefa (code-loop, plan-first, question, research, inference)
|
|
6
|
+
|
|
7
|
+
Referência: The Fable Method (https://github.com/Sahir619/fable-method),
|
|
8
|
+
Karpathy Development Cycle (https://github.com/karpathy).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from kata.verify import _run, is_inspectable, untracked_files
|
|
17
|
+
|
|
18
|
+
# Limite de linhas do triviality gate. Nomeado porque untracked_stats
|
|
19
|
+
# precisa dele para tratar arquivo ilegível como não-trivial.
|
|
20
|
+
TRIVIAL_MAX_LINES = 10
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def untracked_stats(cwd: Path | None = None) -> tuple[list[str], int]:
|
|
24
|
+
"""Arquivos novos ainda não rastreados, e quantas linhas trazem.
|
|
25
|
+
|
|
26
|
+
`git diff` — unstaged, staged, contra commit, qualquer forma — é cego a
|
|
27
|
+
arquivos que nunca entraram no índice. Sem isto, uma tarefa que só cria
|
|
28
|
+
arquivos aparecia como diff vazio e o triviality gate a classificava
|
|
29
|
+
como trivial, pulando SIMPLIFY, INTENT e SURGICAL.
|
|
30
|
+
|
|
31
|
+
As linhas são contadas sem carregar o arquivo inteiro na memória.
|
|
32
|
+
|
|
33
|
+
Arquivo que não pode ser lido — grande demais (ver
|
|
34
|
+
verify.MAX_UNTRACKED_FILE_BYTES) ou binário — conta como TRIVIAL_MAX_LINES,
|
|
35
|
+
o suficiente para reprovar o triviality gate. Contar zero, que é o que
|
|
36
|
+
acontecia antes, faria "não consegui olhar" virar "mudança trivial" e o
|
|
37
|
+
ciclo pularia SIMPLIFY, INTENT e SURGICAL exatamente onde há menos
|
|
38
|
+
evidência para confiar.
|
|
39
|
+
"""
|
|
40
|
+
base = cwd or Path.cwd()
|
|
41
|
+
files = untracked_files(cwd=cwd)
|
|
42
|
+
|
|
43
|
+
total = 0
|
|
44
|
+
for f in files:
|
|
45
|
+
caminho = base / f
|
|
46
|
+
if not is_inspectable(caminho):
|
|
47
|
+
total += TRIVIAL_MAX_LINES
|
|
48
|
+
continue
|
|
49
|
+
try:
|
|
50
|
+
with caminho.open(encoding="utf-8") as fh:
|
|
51
|
+
total += sum(1 for _ in fh)
|
|
52
|
+
except (OSError, UnicodeDecodeError):
|
|
53
|
+
total += TRIVIAL_MAX_LINES
|
|
54
|
+
return files, total
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def diff_stats(cwd: Path | None = None) -> tuple[list[str], int]:
|
|
58
|
+
"""Analisa o diff git atual e retorna (lista de arquivos, linhas totais).
|
|
59
|
+
|
|
60
|
+
Tenta o diff contra HEAD para incluir alterações staged e unstaged de uma
|
|
61
|
+
vez. Em repositório sem commit, cai para unstaged e staged. Arquivos
|
|
62
|
+
untracked são somados sempre, e não como último fallback.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
cwd: Diretório de execução. Default: CWD atual.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
Tupla (lista de paths de arquivos alterados, total de linhas alteradas).
|
|
69
|
+
"""
|
|
70
|
+
result = _run(["git", "diff", "HEAD", "--name-only"], cwd=cwd)
|
|
71
|
+
files_text = result.stdout.strip()
|
|
72
|
+
cmd_stat = ["git", "diff", "HEAD", "--stat"]
|
|
73
|
+
|
|
74
|
+
if result.returncode != 0:
|
|
75
|
+
result = _run(["git", "diff", "--name-only"], cwd=cwd)
|
|
76
|
+
files_text = result.stdout.strip()
|
|
77
|
+
cmd_stat = ["git", "diff", "--stat"]
|
|
78
|
+
|
|
79
|
+
if result.returncode != 0 or not files_text:
|
|
80
|
+
result = _run(["git", "diff", "--cached", "--name-only"], cwd=cwd)
|
|
81
|
+
files_text = result.stdout.strip()
|
|
82
|
+
cmd_stat = ["git", "diff", "--cached", "--stat"]
|
|
83
|
+
|
|
84
|
+
files = [f for f in files_text.split("\n") if f.strip()]
|
|
85
|
+
|
|
86
|
+
result = _run(cmd_stat, cwd=cwd)
|
|
87
|
+
total_lines = 0
|
|
88
|
+
for line in result.stdout.split("\n"):
|
|
89
|
+
m = re.search(r"\|\s*(\d+)", line)
|
|
90
|
+
if m:
|
|
91
|
+
total_lines += int(m.group(1))
|
|
92
|
+
|
|
93
|
+
novos, linhas_novas = untracked_stats(cwd=cwd)
|
|
94
|
+
vistos = set(files)
|
|
95
|
+
files += [f for f in novos if f not in vistos]
|
|
96
|
+
|
|
97
|
+
return files, total_lines + linhas_novas
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def is_trivial(files: list[str], lines: int) -> bool:
|
|
101
|
+
"""Retorna True se a tarefa é trivial: <=1 arquivo e menos de 10 linhas.
|
|
102
|
+
|
|
103
|
+
Corresponde ao triviality gate do fable-method.
|
|
104
|
+
"""
|
|
105
|
+
return len(files) <= 1 and lines < TRIVIAL_MAX_LINES
|
kata/install.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Instala as skills empacotadas a partir do wheel, sem exigir clone do repo.
|
|
2
|
+
|
|
3
|
+
Os scripts `scripts/install*.sh` criam symlinks apontando para o checkout —
|
|
4
|
+
que não existe para quem instalou via `pipx install kata-dev`. Este módulo
|
|
5
|
+
copia o gerado embarcado em `src/kata/assets/` para `~/.config/opencode` ou
|
|
6
|
+
`~/.claude`, com as mesmas travas dos instaladores shell: nada que o Kata
|
|
7
|
+
não criou é sobrescrito sem `--force`, e o uninstall remove só o que criou.
|
|
8
|
+
|
|
9
|
+
A prova de "criado pelo Kata" é um marcador `.kata-managed` dentro de cada
|
|
10
|
+
diretório de skill (e ao lado do arquivo do agente): reinstalar por cima de
|
|
11
|
+
conteúdo nosso é upgrade seguro; por cima de personalização do usuário,
|
|
12
|
+
recusa — a menos de `force=True`, que guarda o original em `<nome>.bak`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import shutil
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from importlib import resources
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from kata import __version__
|
|
23
|
+
from kata.skills import FRONTENDS, Frontend
|
|
24
|
+
|
|
25
|
+
MARKER = ".kata-managed"
|
|
26
|
+
AGENT_MARKER = ".kata-managed-kata.md"
|
|
27
|
+
|
|
28
|
+
FRONTENDS_VALIDOS: tuple[str, ...] = tuple(f.nome for f in FRONTENDS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class InstallReport:
|
|
33
|
+
"""Resultado de um install/uninstall, para o CLI imprimir."""
|
|
34
|
+
|
|
35
|
+
frontend: str
|
|
36
|
+
instaladas: list[str] = field(default_factory=list)
|
|
37
|
+
removidas: list[str] = field(default_factory=list)
|
|
38
|
+
backups: list[str] = field(default_factory=list)
|
|
39
|
+
recusadas: list[str] = field(default_factory=list)
|
|
40
|
+
erros: list[str] = field(default_factory=list)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def ok(self) -> bool:
|
|
44
|
+
return not self.erros and not self.recusadas
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def bundled_root() -> Path:
|
|
48
|
+
"""Raiz dos assets embarcados (`src/kata/assets/` no wheel ou no repo)."""
|
|
49
|
+
try:
|
|
50
|
+
raiz = resources.files("kata") / "assets"
|
|
51
|
+
if raiz.is_dir():
|
|
52
|
+
return Path(str(raiz))
|
|
53
|
+
except (ModuleNotFoundError, TypeError, OSError):
|
|
54
|
+
pass
|
|
55
|
+
return Path(__file__).resolve().parent / "assets"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _frontend(nome: str) -> Frontend:
|
|
59
|
+
for f in FRONTENDS:
|
|
60
|
+
if f.nome == nome:
|
|
61
|
+
return f
|
|
62
|
+
raise ValueError(f"frontend desconhecido: {nome!r} (use: {', '.join(FRONTENDS_VALIDOS)})")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _origens(frontend: Frontend) -> tuple[Path, Path | None]:
|
|
66
|
+
"""Diretórios de origem (skills, agent?) dentro do pacote embarcado."""
|
|
67
|
+
raiz = bundled_root()
|
|
68
|
+
if frontend.nome == "opencode":
|
|
69
|
+
return raiz / "opencode" / "skills", raiz / "opencode" / "agent"
|
|
70
|
+
return raiz / "claude-code" / "skills", None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _e_nosso_skill(destino: Path) -> bool:
|
|
74
|
+
return (destino / MARKER).is_file()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _e_nosso_agent(marcador: Path, destino: Path, origem: Path) -> bool:
|
|
78
|
+
if marcador.is_file():
|
|
79
|
+
return True
|
|
80
|
+
# Sem marcador mas conteúdo idêntico ao embarcado: intacto, é nosso.
|
|
81
|
+
return destino.is_file() and destino.read_bytes() == origem.read_bytes()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _backup(caminho: Path) -> Path:
|
|
85
|
+
"""Move o existente para `<nome>.bak`, removendo backup anterior."""
|
|
86
|
+
backup = caminho.with_name(caminho.name + ".bak")
|
|
87
|
+
if backup.exists():
|
|
88
|
+
if backup.is_dir() and not backup.is_symlink():
|
|
89
|
+
shutil.rmtree(backup)
|
|
90
|
+
else:
|
|
91
|
+
backup.unlink()
|
|
92
|
+
caminho.rename(backup)
|
|
93
|
+
return backup
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _escrever_marcador(destino: Path) -> None:
|
|
97
|
+
(destino / MARKER).write_text(f"kata-dev {__version__}\n", encoding="utf-8")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def install_frontend(nome: str, force: bool = False) -> InstallReport:
|
|
101
|
+
"""Copia skills (+ agente, no OpenCode) do pacote para o config dir."""
|
|
102
|
+
frontend = _frontend(nome)
|
|
103
|
+
report = InstallReport(frontend=nome)
|
|
104
|
+
skills_src, agent_src = _origens(frontend)
|
|
105
|
+
if not skills_src.is_dir():
|
|
106
|
+
report.erros.append(f"assets não encontrados em {skills_src}")
|
|
107
|
+
return report
|
|
108
|
+
|
|
109
|
+
config = frontend.config_dir()
|
|
110
|
+
skills_dir = config / "skills"
|
|
111
|
+
skills_dir.mkdir(parents=True, exist_ok=True)
|
|
112
|
+
|
|
113
|
+
for origem in sorted(p for p in skills_src.iterdir() if p.is_dir()):
|
|
114
|
+
destino = skills_dir / origem.name
|
|
115
|
+
if destino.is_symlink() or destino.exists():
|
|
116
|
+
if _e_nosso_skill(destino):
|
|
117
|
+
if destino.is_symlink():
|
|
118
|
+
destino.unlink()
|
|
119
|
+
else:
|
|
120
|
+
shutil.rmtree(destino)
|
|
121
|
+
elif force:
|
|
122
|
+
report.backups.append(str(_backup(destino)))
|
|
123
|
+
else:
|
|
124
|
+
report.recusadas.append(
|
|
125
|
+
f"{destino} já existe e não foi criado pelo Kata "
|
|
126
|
+
"(use --force para guardar .bak e substituir)"
|
|
127
|
+
)
|
|
128
|
+
continue
|
|
129
|
+
shutil.copytree(origem, destino)
|
|
130
|
+
_escrever_marcador(destino)
|
|
131
|
+
report.instaladas.append(origem.name)
|
|
132
|
+
|
|
133
|
+
if agent_src is not None:
|
|
134
|
+
origem_agent = agent_src / "kata.md"
|
|
135
|
+
agent_dir = config / "agent"
|
|
136
|
+
agent_dir.mkdir(parents=True, exist_ok=True)
|
|
137
|
+
destino_agent = agent_dir / "kata.md"
|
|
138
|
+
marcador = agent_dir / AGENT_MARKER
|
|
139
|
+
if destino_agent.is_symlink() or destino_agent.exists():
|
|
140
|
+
if _e_nosso_agent(marcador, destino_agent, origem_agent):
|
|
141
|
+
destino_agent.unlink()
|
|
142
|
+
elif force:
|
|
143
|
+
report.backups.append(str(_backup(destino_agent)))
|
|
144
|
+
else:
|
|
145
|
+
report.recusadas.append(
|
|
146
|
+
f"{destino_agent} já existe e não foi criado pelo Kata "
|
|
147
|
+
"(use --force para guardar .bak e substituir)"
|
|
148
|
+
)
|
|
149
|
+
return report
|
|
150
|
+
shutil.copy2(origem_agent, destino_agent)
|
|
151
|
+
marcador.write_text(f"kata-dev {__version__}\n", encoding="utf-8")
|
|
152
|
+
report.instaladas.append("agent/kata.md")
|
|
153
|
+
|
|
154
|
+
return report
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def uninstall_frontend(nome: str) -> InstallReport:
|
|
158
|
+
"""Remove só o que o install copiou; personalização do usuário fica."""
|
|
159
|
+
frontend = _frontend(nome)
|
|
160
|
+
report = InstallReport(frontend=nome)
|
|
161
|
+
config = frontend.config_dir()
|
|
162
|
+
skills_dir = config / "skills"
|
|
163
|
+
|
|
164
|
+
if skills_dir.is_dir():
|
|
165
|
+
for filho in sorted(skills_dir.iterdir()):
|
|
166
|
+
if filho.is_dir() and _e_nosso_skill(filho):
|
|
167
|
+
shutil.rmtree(filho)
|
|
168
|
+
report.removidas.append(filho.name)
|
|
169
|
+
|
|
170
|
+
if frontend.nome == "opencode":
|
|
171
|
+
agent_dir = config / "agent"
|
|
172
|
+
destino_agent = agent_dir / "kata.md"
|
|
173
|
+
marcador = agent_dir / AGENT_MARKER
|
|
174
|
+
skills_src, agent_src = _origens(frontend)
|
|
175
|
+
origem_agent = agent_src / "kata.md" if agent_src else None
|
|
176
|
+
if marcador.is_file() or (
|
|
177
|
+
origem_agent is not None
|
|
178
|
+
and origem_agent.is_file()
|
|
179
|
+
and _e_nosso_agent(marcador, destino_agent, origem_agent)
|
|
180
|
+
):
|
|
181
|
+
if destino_agent.is_symlink() or destino_agent.is_file():
|
|
182
|
+
destino_agent.unlink()
|
|
183
|
+
report.removidas.append("agent/kata.md")
|
|
184
|
+
if marcador.is_file():
|
|
185
|
+
marcador.unlink()
|
|
186
|
+
|
|
187
|
+
return report
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def config_dir_de(nome: str) -> Path:
|
|
191
|
+
"""Diretório de destino de um frontend (respeita *_CONFIG_DIR)."""
|
|
192
|
+
return _frontend(nome).config_dir()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _resolver_nomes(selecao: str | None) -> list[str]:
|
|
196
|
+
if selecao in (None, "all"):
|
|
197
|
+
return list(FRONTENDS_VALIDOS)
|
|
198
|
+
return [selecao]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def run_install(selecao: str | None, force: bool = False) -> tuple[list[InstallReport], int]:
|
|
202
|
+
"""Executa o install para a seleção; retorna (reports, exit_code)."""
|
|
203
|
+
reports = [install_frontend(nome, force=force) for nome in _resolver_nomes(selecao)]
|
|
204
|
+
code = 0 if all(r.ok for r in reports) else 1
|
|
205
|
+
return reports, code
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def run_uninstall(selecao: str | None) -> tuple[list[InstallReport], int]:
|
|
209
|
+
"""Executa o uninstall para a seleção; retorna (reports, exit_code)."""
|
|
210
|
+
reports = [uninstall_frontend(nome) for nome in _resolver_nomes(selecao)]
|
|
211
|
+
code = 0 if all(r.ok for r in reports) else 1
|
|
212
|
+
return reports, code
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
__all__ = [
|
|
216
|
+
"AGENT_MARKER",
|
|
217
|
+
"FRONTENDS_VALIDOS",
|
|
218
|
+
"MARKER",
|
|
219
|
+
"InstallReport",
|
|
220
|
+
"bundled_root",
|
|
221
|
+
"config_dir_de",
|
|
222
|
+
"install_frontend",
|
|
223
|
+
"run_install",
|
|
224
|
+
"run_uninstall",
|
|
225
|
+
"uninstall_frontend",
|
|
226
|
+
]
|