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/cli.py
ADDED
|
@@ -0,0 +1,1862 @@
|
|
|
1
|
+
"""Kata CLI — Karpathy Development Cycle + Fable Method.
|
|
2
|
+
|
|
3
|
+
Modos:
|
|
4
|
+
--init <task> Cria .kata/<task>.yaml com template
|
|
5
|
+
(sem args) Ciclo: FIT, THINK, SIMPLIFY, INTENT, SURGICAL, VERIFY, ARTIFACT, REPORT
|
|
6
|
+
--check-only Roda só o passo 4 (lint + test + coverage)
|
|
7
|
+
--plan Modo planejamento (FIT → THINK, para)
|
|
8
|
+
--task <name> Retoma tarefa específica
|
|
9
|
+
--judge Modo adversarial verification (caça fraudes em tarefa concluída)
|
|
10
|
+
--task <name> --judge Verifica tarefa específica adversarialmente
|
|
11
|
+
--report Gera relatório outcome-first de tarefa concluída (usa --task ou branch)
|
|
12
|
+
--audit Gradua as fases da tarefa: followed/skipped/faked/degraded
|
|
13
|
+
(usa --task ou branch)
|
|
14
|
+
--doctor Confere se as skills de fase estão instaladas em cada frontend
|
|
15
|
+
|
|
16
|
+
Port do `scripts/karpathy_cycle.py` do mushin, usando `.kata/` e
|
|
17
|
+
lógica de verificação modularizada em `kata.verify` e `kata.fit`.
|
|
18
|
+
|
|
19
|
+
Inspirado no Karpathy Development Cycle e no The Fable Method
|
|
20
|
+
(https://github.com/Sahir619/fable-method).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import json
|
|
27
|
+
import logging
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import subprocess
|
|
31
|
+
import sys
|
|
32
|
+
import tempfile
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from kata import __version__
|
|
37
|
+
from kata.config import (
|
|
38
|
+
DEFAULT_GATE,
|
|
39
|
+
ConfigError,
|
|
40
|
+
VerifyConfig,
|
|
41
|
+
config_path,
|
|
42
|
+
load_verify_config,
|
|
43
|
+
)
|
|
44
|
+
from kata.fit import diff_stats, is_trivial, untracked_stats
|
|
45
|
+
from kata.install import FRONTENDS_VALIDOS, config_dir_de, run_install, run_uninstall
|
|
46
|
+
from kata.judge import (
|
|
47
|
+
is_debris_file,
|
|
48
|
+
judge_task,
|
|
49
|
+
record_baseline_ref,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# S7-refactor: I/O de relatório/auditoria vive em report.py. O cli re-exporta
|
|
53
|
+
# os nomes para que testes que patcham `kata.cli._print_header` etc.
|
|
54
|
+
# continuem a funcionar — o import também garante que as referências abaixo
|
|
55
|
+
# (main, _step_report, _step_artifact) resolvam os mesmos objetos.
|
|
56
|
+
from kata.report import ( # noqa: E402
|
|
57
|
+
_audit_task,
|
|
58
|
+
_format_auth_line,
|
|
59
|
+
_format_intent_line,
|
|
60
|
+
_format_pending_line,
|
|
61
|
+
_format_twins_line,
|
|
62
|
+
_print_audit,
|
|
63
|
+
_print_doctor,
|
|
64
|
+
_print_header,
|
|
65
|
+
_print_judge_verdict,
|
|
66
|
+
)
|
|
67
|
+
from kata.skills import DOMAIN_SKILLS, doctor
|
|
68
|
+
from kata.verify import VerifyResult, run_all, search_pattern, untracked_files
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
import yaml
|
|
72
|
+
|
|
73
|
+
_HAS_YAML = True
|
|
74
|
+
_YAML_ERRORS: tuple[type[BaseException], ...] = (yaml.YAMLError,)
|
|
75
|
+
except ImportError:
|
|
76
|
+
_HAS_YAML = False
|
|
77
|
+
_YAML_ERRORS = ()
|
|
78
|
+
|
|
79
|
+
# ── helpers ──────────────────────────────────────────────────────────────
|
|
80
|
+
|
|
81
|
+
_TASK_WHITESPACE = re.compile(r"\s")
|
|
82
|
+
|
|
83
|
+
# Hard bound (Fable Step 5): após este número de tentativas de verificação
|
|
84
|
+
# falhas, o ciclo devolve a tarefa ao usuário em vez de continuar o loop
|
|
85
|
+
# fix-verify indefinidamente.
|
|
86
|
+
MAX_VERIFY_ATTEMPTS = 3
|
|
87
|
+
|
|
88
|
+
# Versão do schema de .kata/<task>.yaml (CR-014/S5). O --init grava no topo
|
|
89
|
+
# do template; a leitura tolera ausência (YAMLs antigos) tratando como 1.
|
|
90
|
+
# Quando uma mudança obrigatória for necessária, incremente e falhe com
|
|
91
|
+
# mensagem clara em vez de .get() silencioso. A leitura vive em
|
|
92
|
+
# _deserialize — sem ela, o mecanismo era write-only (K-14).
|
|
93
|
+
SCHEMA_VERSION = 1
|
|
94
|
+
|
|
95
|
+
# Extensões que _task_path pode concatenar, conforme PyYAML esteja
|
|
96
|
+
# presente ou não. A validação rejeita as duas independentemente.
|
|
97
|
+
_SERIALIZATION_EXTS = (".yaml", ".yml", ".json")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _cwd() -> Path:
|
|
101
|
+
"""Retorna o diretório de trabalho atual."""
|
|
102
|
+
return Path.cwd()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _kata_dir() -> Path:
|
|
106
|
+
"""Retorna o diretório .kata/ no CWD."""
|
|
107
|
+
return _cwd() / ".kata"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _serialize(data: dict[str, Any]) -> str:
|
|
111
|
+
if _HAS_YAML:
|
|
112
|
+
return yaml.dump(data, allow_unicode=True, sort_keys=False, default_flow_style=False)
|
|
113
|
+
return json.dumps(data, ensure_ascii=False, indent=2)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _save_task(path: Path, data: dict[str, Any]) -> None:
|
|
117
|
+
"""Persiste a tarefa com replace atômico para permitir retomada segura."""
|
|
118
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
119
|
+
fd, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
|
|
120
|
+
temporary = Path(temporary_name)
|
|
121
|
+
try:
|
|
122
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
123
|
+
handle.write(_serialize(data))
|
|
124
|
+
handle.flush()
|
|
125
|
+
os.fsync(handle.fileno())
|
|
126
|
+
temporary.replace(path)
|
|
127
|
+
finally:
|
|
128
|
+
if temporary.exists():
|
|
129
|
+
temporary.unlink()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _deserialize(text: str) -> dict[str, Any]:
|
|
133
|
+
"""Lê o YAML/JSON da tarefa, levantando ValueError nomeado se ilegível.
|
|
134
|
+
|
|
135
|
+
Doutrina R11-1: arquivo malformado não pode virar traceback — traceback
|
|
136
|
+
sai com código 1, o mesmo de REFUTED, tornando arquivo quebrado
|
|
137
|
+
indistinguível de fraude encontrada para quem lê o exit code no CI.
|
|
138
|
+
Os call sites capturam ValueError e imprimem mensagem clara.
|
|
139
|
+
|
|
140
|
+
K-10: o topo precisa ser um mapa. `yaml.safe_load` devolve lista para
|
|
141
|
+
um arquivo `- a\n- b` (lista é truthy, o `or {}` não converte) e o
|
|
142
|
+
ciclo morria com `AttributeError: 'list' object has no attribute 'get'`
|
|
143
|
+
— exatamente o traceback que esta doutrina proíbe.
|
|
144
|
+
|
|
145
|
+
K-14: valida a versão do schema na leitura (ver SCHEMA_VERSION).
|
|
146
|
+
"""
|
|
147
|
+
try:
|
|
148
|
+
if _HAS_YAML:
|
|
149
|
+
dados = yaml.safe_load(text) or {}
|
|
150
|
+
else:
|
|
151
|
+
dados = json.loads(text)
|
|
152
|
+
except (*_YAML_ERRORS, json.JSONDecodeError) as exc:
|
|
153
|
+
raise ValueError(f"arquivo de tarefa ilegível: {exc}") from exc
|
|
154
|
+
if not isinstance(dados, dict):
|
|
155
|
+
raise ValueError(
|
|
156
|
+
f"arquivo de tarefa deve ter um mapa no topo (veio {type(dados).__name__})"
|
|
157
|
+
)
|
|
158
|
+
# K-14: valida a versão do schema na LEITURA. Antes, o mecanismo era
|
|
159
|
+
# write-only (o --init gravava, ninguém lia) e a promessa do comentário
|
|
160
|
+
# de SCHEMA_VERSION ("quando uma mudança obrigatória for necessária,
|
|
161
|
+
# incremente e falhe com mensagem clara") não existia no código. Ausência
|
|
162
|
+
# (YAMLs antigos) tolerada como 1.
|
|
163
|
+
try:
|
|
164
|
+
versao = int(dados.get("schema_version", SCHEMA_VERSION))
|
|
165
|
+
except (TypeError, ValueError):
|
|
166
|
+
raise ValueError(
|
|
167
|
+
f"schema_version inválido: {dados.get('schema_version')!r} (esperava um inteiro)"
|
|
168
|
+
) from None
|
|
169
|
+
if versao > SCHEMA_VERSION:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"tarefa usa schema_version {versao}, mas este kata suporta até "
|
|
172
|
+
f"{SCHEMA_VERSION} — atualize a ferramenta (pip install -U kata)"
|
|
173
|
+
)
|
|
174
|
+
return dados
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _load_task_or_exit(path: Path) -> dict[str, Any]:
|
|
178
|
+
"""Lê e desserializa a tarefa, saindo com mensagem clara se ilegível.
|
|
179
|
+
|
|
180
|
+
R11-1: arquivo malformado não pode virar traceback (exit 1 = mesmo de
|
|
181
|
+
REFUTED). Mensagem nomeada + exit 1, sem stack trace.
|
|
182
|
+
"""
|
|
183
|
+
try:
|
|
184
|
+
return _deserialize(path.read_text(encoding="utf-8"))
|
|
185
|
+
except ValueError as exc:
|
|
186
|
+
print(f"⚠ {path.name}: {exc}")
|
|
187
|
+
sys.exit(1)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _ext() -> str:
|
|
191
|
+
return ".yaml" if _HAS_YAML else ".json"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _detect_cov_source() -> str | list[str]:
|
|
195
|
+
"""Detecta o(s) pacote(s) fonte de coverage a partir de pyproject.toml.
|
|
196
|
+
|
|
197
|
+
Lê `[tool.coverage.run] source` e retorna o primeiro item quando há um
|
|
198
|
+
só, ou a lista completa quando há vários — o `--cov` do pytest-cov aceita
|
|
199
|
+
múltiplas fontes via flags repetidas, e medir apenas a primeira (como
|
|
200
|
+
antes) reportava um gate baseado num subconjunto do que o projeto
|
|
201
|
+
declarou. Se não encontrar, cai no fallback "src".
|
|
202
|
+
"""
|
|
203
|
+
pyproject = _cwd() / "pyproject.toml"
|
|
204
|
+
if pyproject.exists():
|
|
205
|
+
try:
|
|
206
|
+
import tomllib
|
|
207
|
+
|
|
208
|
+
text = pyproject.read_text(encoding="utf-8")
|
|
209
|
+
config = tomllib.loads(text)
|
|
210
|
+
sources = config.get("tool", {}).get("coverage", {}).get("run", {}).get("source", [])
|
|
211
|
+
if isinstance(sources, str):
|
|
212
|
+
return sources
|
|
213
|
+
if len(sources) == 1:
|
|
214
|
+
return sources[0]
|
|
215
|
+
if sources:
|
|
216
|
+
return list(sources)
|
|
217
|
+
except (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError) as exc:
|
|
218
|
+
# CR-009/S4: pyproject malformado ou ilegível não pode ser
|
|
219
|
+
# engolido em silêncio — o --cov rodaria contra um source que o
|
|
220
|
+
# projeto não declarou. Avisa e degrada para o fallback.
|
|
221
|
+
logging.warning("pyproject.toml ilegível (%s); usando 'src' como fallback", exc)
|
|
222
|
+
return "src"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _is_invalid_task_name(task: str) -> bool:
|
|
226
|
+
"""Predicado de nome de tarefa, compartilhado entre CLI (--task/--init/...)
|
|
227
|
+
e o prompt interativo de _pick_task — um único lugar para a regra em si.
|
|
228
|
+
|
|
229
|
+
Rejeita, além de path traversal: espaços em branco (que produziriam
|
|
230
|
+
`.kata/my task.yaml`), nomes iniciados por ponto (arquivo oculto, e
|
|
231
|
+
cobre "." e "..") e nomes que já trazem a extensão de serialização
|
|
232
|
+
(`--init foo.yaml` produziria `.kata/foo.yaml.yaml`, porque _task_path
|
|
233
|
+
concatena a extensão).
|
|
234
|
+
|
|
235
|
+
Ambas as extensões são rejeitadas sempre, e não só a de _ext(): amarrar a
|
|
236
|
+
regra ao formato ativo fazia `--init foo.yaml` passar quando PyYAML está
|
|
237
|
+
ausente, criando `.kata/foo.yaml.json`. Nome de tarefa é escolha do
|
|
238
|
+
usuário e não deve depender de qual biblioteca está instalada.
|
|
239
|
+
|
|
240
|
+
K-16: "check-only" também é rejeitado — o VERIFY usa o nome da tarefa
|
|
241
|
+
como magic string para pular a confirmação do critério de sucesso
|
|
242
|
+
(task == "check-only"); uma tarefa legítima com esse nome teria o
|
|
243
|
+
sucesso assumido silenciosamente, a classe de "sucesso afirmado sem
|
|
244
|
+
confirmação" que o audit caça.
|
|
245
|
+
"""
|
|
246
|
+
if not task or not task.strip():
|
|
247
|
+
return True
|
|
248
|
+
if _TASK_WHITESPACE.search(task):
|
|
249
|
+
return True
|
|
250
|
+
if task.startswith("."):
|
|
251
|
+
return True
|
|
252
|
+
if task.endswith(_SERIALIZATION_EXTS):
|
|
253
|
+
return True
|
|
254
|
+
if task == "config" or task == "check-only":
|
|
255
|
+
return True
|
|
256
|
+
return "/" in task or "\\" in task or ".." in task
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _validate_task_name(task: str) -> None:
|
|
260
|
+
"""Impede path traversal via nome de tarefa (--task/--init/--judge/--report).
|
|
261
|
+
|
|
262
|
+
Sem isso, um nome como '../../etc/foo' escreve/lê fora de .kata/, já que
|
|
263
|
+
_task_path só concatena o nome ao diretório sem checar separadores.
|
|
264
|
+
"""
|
|
265
|
+
if _is_invalid_task_name(task):
|
|
266
|
+
print(
|
|
267
|
+
f"⚠ Nome de tarefa inválido: '{task}'. "
|
|
268
|
+
"Não pode ser vazio, conter espaços, começar com '.', "
|
|
269
|
+
f"terminar em {' ou '.join(_SERIALIZATION_EXTS)}, "
|
|
270
|
+
"nem ser 'config', 'check-only' ou conter '/', '\\' ou '..'."
|
|
271
|
+
)
|
|
272
|
+
sys.exit(1)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _task_path(task: str) -> Path:
|
|
276
|
+
_validate_task_name(task)
|
|
277
|
+
return _kata_dir() / f"{task}{_ext()}"
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _detect_task_from_branch() -> str | None:
|
|
281
|
+
"""Detecta o nome da tarefa a partir do branch git atual."""
|
|
282
|
+
try:
|
|
283
|
+
result = subprocess.run(
|
|
284
|
+
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
|
285
|
+
capture_output=True,
|
|
286
|
+
text=True,
|
|
287
|
+
check=True,
|
|
288
|
+
cwd=_cwd(),
|
|
289
|
+
)
|
|
290
|
+
branch = result.stdout.strip()
|
|
291
|
+
if branch and branch != "HEAD":
|
|
292
|
+
return branch.replace("/", "-").replace("_", "-")
|
|
293
|
+
except subprocess.CalledProcessError:
|
|
294
|
+
pass
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _pick_task() -> str:
|
|
299
|
+
"""Escolhe a tarefa interativamente (branch, menu existente, ou nova)."""
|
|
300
|
+
if not sys.stdin.isatty():
|
|
301
|
+
return "untitled"
|
|
302
|
+
branch_task = _detect_task_from_branch()
|
|
303
|
+
existing = sorted(p.stem for p in _kata_dir().glob(f"*{_ext()}") if p.stem != "config")
|
|
304
|
+
if branch_task and branch_task in existing:
|
|
305
|
+
return branch_task
|
|
306
|
+
if existing:
|
|
307
|
+
print("Tarefas existentes em .kata/:")
|
|
308
|
+
for i, name in enumerate(existing, 1):
|
|
309
|
+
print(f" {i}. {name}")
|
|
310
|
+
print(f" {len(existing) + 1}. [Nova tarefa]")
|
|
311
|
+
choice = _ask_text("\nEscolha (número ou nome): ")
|
|
312
|
+
if choice.isdigit():
|
|
313
|
+
idx = int(choice) - 1
|
|
314
|
+
if 0 <= idx < len(existing):
|
|
315
|
+
return existing[idx]
|
|
316
|
+
elif choice in existing:
|
|
317
|
+
return choice
|
|
318
|
+
name = _ask_text("Nome da tarefa: ").replace(" ", "-") or "untitled"
|
|
319
|
+
if _is_invalid_task_name(name):
|
|
320
|
+
print("⚠ Nome de tarefa inválido. Usando 'untitled'")
|
|
321
|
+
return "untitled"
|
|
322
|
+
return name
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _resolve_task_or_suggest(task: str) -> Path | None:
|
|
326
|
+
"""Resolve o caminho da task ou imprime mensagem específica e retorna None.
|
|
327
|
+
|
|
328
|
+
CR-004 (S1): três call sites (--report, --judge, --audit) caíam na mesma
|
|
329
|
+
mensagem vaga "não encontrado. Execute o ciclo primeiro" para casos
|
|
330
|
+
distintos. Esta função distingue:
|
|
331
|
+
|
|
332
|
+
a) repo sem nenhuma task em .kata/ → sugere `kata --init <nome>`
|
|
333
|
+
b) há tasks mas `task` (vindo de _pick_task ou --task) não bate →
|
|
334
|
+
lista as existentes
|
|
335
|
+
c) a task existe mas o YAML não (improvável; corrida) →
|
|
336
|
+
mensagem original
|
|
337
|
+
|
|
338
|
+
Retorna o Path se a task existe, None se não existe (já tendo imprimido
|
|
339
|
+
a mensagem de erro adequada). O caller decide se faz sys.exit(1).
|
|
340
|
+
"""
|
|
341
|
+
path = _task_path(task)
|
|
342
|
+
if path.exists():
|
|
343
|
+
return path
|
|
344
|
+
existentes = sorted(p.stem for p in _kata_dir().glob(f"*{_ext()}") if p.stem != "config")
|
|
345
|
+
if not existentes:
|
|
346
|
+
print(f"⚠ Nenhuma tarefa em {_kata_dir()}. Rode `kata --init <nome>` primeiro.")
|
|
347
|
+
return None
|
|
348
|
+
print(f"⚠ {path.name} não encontrado. Tarefas existentes em {_kata_dir()}:")
|
|
349
|
+
for i, name in enumerate(existentes, 1):
|
|
350
|
+
print(f" {i}. {name}")
|
|
351
|
+
print("Rode `kata --task <nome>`, ou crie uma nova com `kata --init <nome>`.")
|
|
352
|
+
return None
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _run_git(cmd: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
|
|
356
|
+
"""Executa um comando git capturando saída, com defaults sobrescreíveis.
|
|
357
|
+
|
|
358
|
+
Nome distinto de kata.verify._run de propósito: são helpers diferentes,
|
|
359
|
+
com assinaturas diferentes, e judge.py importa o de verify. Dois `_run`
|
|
360
|
+
homônimos no mesmo projeto é convite a erro de manutenção.
|
|
361
|
+
|
|
362
|
+
Defaults (capture_output, text, cwd) podem ser sobrescritos via kwargs
|
|
363
|
+
sem causar colisão de argumentos.
|
|
364
|
+
"""
|
|
365
|
+
defaults: dict[str, Any] = {"capture_output": True, "text": True, "cwd": _cwd()}
|
|
366
|
+
defaults.update(kwargs)
|
|
367
|
+
return subprocess.run(cmd, **defaults)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _changed_paths() -> list[str]:
|
|
371
|
+
"""Arquivos que a tarefa alterou, segundo o git.
|
|
372
|
+
|
|
373
|
+
Usa diff contra HEAD para incluir staged e unstaged, com fallback para
|
|
374
|
+
repositórios sem commit. Untracked são somados sempre, porque arquivos
|
|
375
|
+
novos nunca aparecem em `git diff`.
|
|
376
|
+
"""
|
|
377
|
+
result = _run_git(["git", "diff", "HEAD", "--name-only"])
|
|
378
|
+
if result.returncode == 0:
|
|
379
|
+
rastreados = [f for f in result.stdout.strip().split("\n") if f.strip()]
|
|
380
|
+
else:
|
|
381
|
+
result = _run_git(["git", "diff", "--name-only"])
|
|
382
|
+
rastreados = [f for f in result.stdout.strip().split("\n") if f.strip()]
|
|
383
|
+
if result.returncode != 0 or not rastreados:
|
|
384
|
+
rastreados = [
|
|
385
|
+
f
|
|
386
|
+
for f in _run_git(["git", "diff", "--cached", "--name-only"]).stdout.strip().split("\n")
|
|
387
|
+
if f.strip()
|
|
388
|
+
]
|
|
389
|
+
novos = untracked_files()
|
|
390
|
+
vistos = set(rastreados)
|
|
391
|
+
return rastreados + [f for f in novos if f not in vistos]
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _confirm(prompt: str, default: bool = True) -> bool:
|
|
395
|
+
if not sys.stdin.isatty():
|
|
396
|
+
return default
|
|
397
|
+
opts = " [S/n]" if default else " [s/N]"
|
|
398
|
+
try:
|
|
399
|
+
answer = input(f"{prompt}{opts}: ").strip().lower()
|
|
400
|
+
except (EOFError, KeyboardInterrupt):
|
|
401
|
+
return default
|
|
402
|
+
if not answer:
|
|
403
|
+
return default
|
|
404
|
+
return answer in ("s", "sim", "y", "yes")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _ask_text(prompt: str, default: str = "") -> str:
|
|
408
|
+
"""Pergunta em texto livre tratando EOF/Ctrl-C (K-17).
|
|
409
|
+
|
|
410
|
+
Os input() crus das fases (rota, THINK, INTENT, TWIN, observações)
|
|
411
|
+
morriam com traceback em Ctrl-D — _confirm já tratava, os demais não.
|
|
412
|
+
EOF/Ctrl-C devolve o default (ou ""), nunca traceback.
|
|
413
|
+
"""
|
|
414
|
+
try:
|
|
415
|
+
return input(prompt).strip()
|
|
416
|
+
except (EOFError, KeyboardInterrupt):
|
|
417
|
+
return default
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ── step implementations ────────────────────────────────────────────────
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _resolve_trusted_base(ref: str) -> str | None:
|
|
424
|
+
"""merge-base entre a base confiável e o HEAD, ou None.
|
|
425
|
+
|
|
426
|
+
A ref resolver não basta: é o merge-base que vira o piso do JUDGE. Num
|
|
427
|
+
clone raso (o default do actions/checkout) ou numa história sem
|
|
428
|
+
ancestral comum ele falha, e o juiz cairia de volta na janela do YAML.
|
|
429
|
+
"""
|
|
430
|
+
result = _run_git(["git", "merge-base", ref, "HEAD"])
|
|
431
|
+
sha = result.stdout.strip()
|
|
432
|
+
return sha if result.returncode == 0 and sha else None
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _capture_base_commit(data: dict[str, Any], task: str | None = None) -> dict[str, Any]:
|
|
436
|
+
"""Registra o HEAD do git no início da tarefa, uma única vez.
|
|
437
|
+
|
|
438
|
+
O JUDGE usa esse commit como ponto de comparação. Sem ele, o JUDGE só
|
|
439
|
+
enxerga o diff não commitado (unstaged/staged) e fica cego assim que
|
|
440
|
+
a tarefa é commitada — exatamente o estado de uma tarefa "concluída",
|
|
441
|
+
que é o caso que o JUDGE existe para verificar.
|
|
442
|
+
"""
|
|
443
|
+
if data.get("base_commit"):
|
|
444
|
+
return data
|
|
445
|
+
result = _run_git(["git", "rev-parse", "HEAD"])
|
|
446
|
+
sha = result.stdout.strip()
|
|
447
|
+
if result.returncode == 0 and sha:
|
|
448
|
+
data["base_commit"] = sha
|
|
449
|
+
if task:
|
|
450
|
+
record_baseline_ref(task, sha, cwd=_cwd())
|
|
451
|
+
return data
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _avisa_domain_desconhecido(data: dict[str, Any]) -> None:
|
|
455
|
+
"""Avisa quando a tarefa declara um domínio sem adapter conhecido.
|
|
456
|
+
|
|
457
|
+
O orquestrador só carrega adapters por nome `kata-<domínio>`; um valor
|
|
458
|
+
fora da lista (typo, domínio futuro) roda o ciclo inteiro sem o adapter,
|
|
459
|
+
em silêncio — exatamente o modo de falha que a Fase 0.5 manda não
|
|
460
|
+
improvisar (R10-21). Aviso, não erro: o ciclo continua em `coding`.
|
|
461
|
+
"""
|
|
462
|
+
domain = data.get("domain", "coding")
|
|
463
|
+
if domain == "coding":
|
|
464
|
+
return
|
|
465
|
+
adapters = {d.removeprefix("kata-") for d in DOMAIN_SKILLS}
|
|
466
|
+
if domain not in adapters:
|
|
467
|
+
conhecidos = ", ".join(sorted(adapters | {"coding"}))
|
|
468
|
+
print(
|
|
469
|
+
f" ⚠ Domínio '{domain}' não tem adapter conhecido "
|
|
470
|
+
f"(disponíveis: {conhecidos}) — o ciclo roda sem ele."
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _secao(data: dict[str, Any], nome: str) -> dict[str, Any]:
|
|
475
|
+
"""Seção da tarefa em forma de mapa, ou {} se ausente ou não-mapa.
|
|
476
|
+
|
|
477
|
+
K-11: YAML escrito à mão pode ter `fit: true`, `verify: "x"`, etc. As
|
|
478
|
+
fases do ciclo morriam com AttributeError (mesma classe que o R11-1
|
|
479
|
+
fechou para --audit/--judge). O que não pôde ser lido vira seção
|
|
480
|
+
vazia — a fase re-pergunta ou aplica o default, nunca traceback.
|
|
481
|
+
"""
|
|
482
|
+
secao = data.get(nome)
|
|
483
|
+
if isinstance(secao, dict):
|
|
484
|
+
return secao
|
|
485
|
+
return {}
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _step_fit(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
489
|
+
"""Fase 0: FIT — triviality gate + classificação da tarefa antes do THINK.
|
|
490
|
+
|
|
491
|
+
Inspirado no fit gate do fable-method (think → act → prove → grow)
|
|
492
|
+
e no Karpathy Development Cycle.
|
|
493
|
+
"""
|
|
494
|
+
fit = _secao(data, "fit")
|
|
495
|
+
if fit.get("answered"):
|
|
496
|
+
print("(fit gate já respondido)")
|
|
497
|
+
return data
|
|
498
|
+
|
|
499
|
+
if not sys.stdin.isatty():
|
|
500
|
+
print("(modo não-interativo — assumindo code-loop)")
|
|
501
|
+
# `skipped`, não `answered`: nenhum humano respondeu nada aqui. Marcar
|
|
502
|
+
# como respondido fazia esta fase ser saltada para sempre, inclusive
|
|
503
|
+
# num ciclo interativo posterior na mesma tarefa.
|
|
504
|
+
data["fit"] = {
|
|
505
|
+
"trivial": False,
|
|
506
|
+
"route": "code-loop",
|
|
507
|
+
"reason": "non-interactive mode",
|
|
508
|
+
"answered": False,
|
|
509
|
+
"skipped": True,
|
|
510
|
+
}
|
|
511
|
+
return data
|
|
512
|
+
|
|
513
|
+
_print_header("0. FIT — Classificação da tarefa")
|
|
514
|
+
|
|
515
|
+
files, lines = diff_stats()
|
|
516
|
+
trivial = is_trivial(files, lines)
|
|
517
|
+
|
|
518
|
+
print(f" diff: {len(files)} arquivo(s), {lines} linha(s) alteradas")
|
|
519
|
+
if trivial:
|
|
520
|
+
print(" ↳ tarefa parece trivial (<=1 arquivo, <10 linhas)")
|
|
521
|
+
trivial = _confirm(
|
|
522
|
+
" A mudança não altera comportamento e não exige pesquisa?",
|
|
523
|
+
default=False,
|
|
524
|
+
)
|
|
525
|
+
if not trivial:
|
|
526
|
+
print(" ↳ gates completos serão mantidos por segurança")
|
|
527
|
+
else:
|
|
528
|
+
print(" ↳ tarefa não-trivial")
|
|
529
|
+
|
|
530
|
+
print()
|
|
531
|
+
print(" Rotas disponíveis:")
|
|
532
|
+
print(" [1] code-loop — ciclo completo (THINK → SIMPLIFY → SURGICAL → VERIFY)")
|
|
533
|
+
print(" [2] plan-first — só planejamento (para e entrega um plano)")
|
|
534
|
+
print(" [3] question — só diagnóstico, sem alterar código")
|
|
535
|
+
print(" [4] research — precisa pesquisar antes de agir")
|
|
536
|
+
print(" [5] inference — baseado só em inferência (baixa confiança)")
|
|
537
|
+
|
|
538
|
+
choice = _ask_text("\n Rota escolhida [1]: ") or "1"
|
|
539
|
+
route_map = {
|
|
540
|
+
"1": "code-loop",
|
|
541
|
+
"2": "plan-first",
|
|
542
|
+
"3": "question",
|
|
543
|
+
"4": "research",
|
|
544
|
+
"5": "inference",
|
|
545
|
+
}
|
|
546
|
+
route = route_map.get(choice, "code-loop")
|
|
547
|
+
reason = _ask_text(" Justificativa breve (opcional): ")
|
|
548
|
+
|
|
549
|
+
# `answered` fecha o guard no topo desta função: sem gravá-la, FIT
|
|
550
|
+
# repergunta a cada retomada da tarefa. think e intent já gravavam a sua.
|
|
551
|
+
data["fit"] = {
|
|
552
|
+
"trivial": trivial,
|
|
553
|
+
"route": route,
|
|
554
|
+
"reason": reason or f"Rota {choice} escolhida pelo usuário",
|
|
555
|
+
"answered": True,
|
|
556
|
+
}
|
|
557
|
+
return data
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _step_think(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
561
|
+
"""Fase 1: THINK — declarar assumptions antes de codar.
|
|
562
|
+
|
|
563
|
+
O parâmetro `task` é mantido por simetria com as demais fases e para
|
|
564
|
+
identificação no YAML, mas não é usado na lógica desta fase.
|
|
565
|
+
"""
|
|
566
|
+
_print_header("1. THINK — Antes de codificar, declare suas assumptions")
|
|
567
|
+
think = data.get("think", {})
|
|
568
|
+
if think.get("answered"):
|
|
569
|
+
print("(já respondido — recarregue para reabrir)")
|
|
570
|
+
return data
|
|
571
|
+
|
|
572
|
+
if not sys.stdin.isatty():
|
|
573
|
+
print("(modo não-interativo — pulando THINK)")
|
|
574
|
+
# `skipped`, não `answered`: nenhum humano respondeu nada aqui. Marcar
|
|
575
|
+
# como respondido fazia esta fase ser saltada para sempre, inclusive
|
|
576
|
+
# num ciclo interativo posterior na mesma tarefa.
|
|
577
|
+
data["think"] = {
|
|
578
|
+
"problem": "",
|
|
579
|
+
"assumptions": [],
|
|
580
|
+
"alternatives": [],
|
|
581
|
+
"unknowns": "",
|
|
582
|
+
"answered": False,
|
|
583
|
+
"skipped": True,
|
|
584
|
+
}
|
|
585
|
+
data["done"] = ""
|
|
586
|
+
return data
|
|
587
|
+
|
|
588
|
+
print("Pergunte-se:")
|
|
589
|
+
problem = _ask_text(" Qual o problema exato que estou resolvendo? ")
|
|
590
|
+
assumptions_raw = _ask_text(" Quais assumptions estou fazendo? (separadas por ;) ")
|
|
591
|
+
alternatives_raw = _ask_text(" Quais alternativas considerei? (separadas por ;) ")
|
|
592
|
+
unknowns = _ask_text(" O que NÃO sei? (preciso perguntar antes?) ")
|
|
593
|
+
# Fable Step 1: definir "pronto" ANTES da evidência, com verificação
|
|
594
|
+
# nomeada ("done = este teste passa, o build fica verde, esta página
|
|
595
|
+
# renderiza"). O VERIFY confronta este critério declarado com o resultado
|
|
596
|
+
# final — sem isso, o critério só existe depois que tudo já foi feito.
|
|
597
|
+
done = _ask_text(" O que é 'pronto'? (critério de sucesso + como vou verificar) ")
|
|
598
|
+
|
|
599
|
+
data["think"] = {
|
|
600
|
+
"problem": problem,
|
|
601
|
+
"assumptions": [a.strip() for a in assumptions_raw.split(";") if a.strip()],
|
|
602
|
+
"alternatives": [a.strip() for a in alternatives_raw.split(";") if a.strip()],
|
|
603
|
+
"unknowns": unknowns,
|
|
604
|
+
"answered": True,
|
|
605
|
+
}
|
|
606
|
+
data["done"] = done
|
|
607
|
+
data["status"] = "think-complete"
|
|
608
|
+
return data
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def _step_simplify(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
612
|
+
"""Fase 2: SIMPLIFY — o código é mínimo?
|
|
613
|
+
|
|
614
|
+
O parâmetro `task` é mantido por simetria com as demais fases e para
|
|
615
|
+
identificação no YAML, mas não é usado na lógica desta fase.
|
|
616
|
+
"""
|
|
617
|
+
_print_header("2. SIMPLIFY — O código é mínimo?")
|
|
618
|
+
|
|
619
|
+
# K-12: guard de retomada, no mesmo contrato de FIT/THINK/INTENT/TWIN.
|
|
620
|
+
# Antes, SIMPLIFY e SURGICAL re-perguntavam tudo a cada retomada de
|
|
621
|
+
# tarefa rejeitada enquanto as irmãs pulavam — e o `answered: True`
|
|
622
|
+
# gravado era dead code para o ciclo (só o audit o lia).
|
|
623
|
+
if _secao(data, "simplify").get("answered"):
|
|
624
|
+
print("(simplify já respondido)")
|
|
625
|
+
return data
|
|
626
|
+
|
|
627
|
+
if not sys.stdin.isatty():
|
|
628
|
+
print("(modo não-interativo — pulando SIMPLIFY)")
|
|
629
|
+
# `skipped`, não `answered`: nenhum humano respondeu nada aqui. Marcar
|
|
630
|
+
# como respondido fazia a fase ser saltada para sempre, inclusive num
|
|
631
|
+
# ciclo interativo posterior na mesma tarefa (mesmo padrão do R7-1
|
|
632
|
+
# para FIT/THINK/INTENT).
|
|
633
|
+
data["simplify"] = {
|
|
634
|
+
"minimum_code": True,
|
|
635
|
+
"no_single_use_abstractions": True,
|
|
636
|
+
"no_speculative_config": True,
|
|
637
|
+
"answered": False,
|
|
638
|
+
"skipped": True,
|
|
639
|
+
}
|
|
640
|
+
return data
|
|
641
|
+
|
|
642
|
+
# Mostra diff stat
|
|
643
|
+
has_changes = False
|
|
644
|
+
result = _run_git(["git", "diff", "HEAD", "--stat"])
|
|
645
|
+
if result.returncode == 0 and result.stdout.strip():
|
|
646
|
+
print("git diff --stat:")
|
|
647
|
+
print(result.stdout)
|
|
648
|
+
has_changes = True
|
|
649
|
+
elif result.returncode != 0:
|
|
650
|
+
result = _run_git(["git", "diff", "--stat"])
|
|
651
|
+
if result.stdout.strip():
|
|
652
|
+
print("git diff --stat:")
|
|
653
|
+
print(result.stdout)
|
|
654
|
+
has_changes = True
|
|
655
|
+
if not has_changes:
|
|
656
|
+
result = _run_git(["git", "diff", "--cached", "--stat"])
|
|
657
|
+
if result.stdout.strip():
|
|
658
|
+
print("git diff --cached --stat (staged):")
|
|
659
|
+
print(result.stdout)
|
|
660
|
+
has_changes = True
|
|
661
|
+
|
|
662
|
+
# Arquivos novos não aparecem em nenhum `git diff`. Sem listá-los, uma
|
|
663
|
+
# tarefa que só cria arquivos passava por SIMPLIFY sem uma pergunta
|
|
664
|
+
# sequer, e o YAML registrava o checklist como aprovado.
|
|
665
|
+
novos, linhas_novas = untracked_stats()
|
|
666
|
+
if novos:
|
|
667
|
+
print(f"arquivos novos (untracked) — {linhas_novas} linha(s):")
|
|
668
|
+
for f in novos:
|
|
669
|
+
print(f" {f}")
|
|
670
|
+
print()
|
|
671
|
+
has_changes = True
|
|
672
|
+
|
|
673
|
+
if not has_changes:
|
|
674
|
+
print("(nenhuma alteração detectada — pulando confirmações)")
|
|
675
|
+
|
|
676
|
+
simplify = _secao(data, "simplify")
|
|
677
|
+
if has_changes:
|
|
678
|
+
simplify["minimum_code"] = _confirm(" O código mínimo resolve o problema?")
|
|
679
|
+
simplify["no_single_use_abstractions"] = _confirm(
|
|
680
|
+
" Código livre de abstrações para uso único?", default=True
|
|
681
|
+
)
|
|
682
|
+
simplify["no_speculative_config"] = _confirm(
|
|
683
|
+
" Código livre de configurabilidade não solicitada?", default=True
|
|
684
|
+
)
|
|
685
|
+
notes = _ask_text(" Observações (opcional): ")
|
|
686
|
+
if notes:
|
|
687
|
+
simplify["notes"] = notes
|
|
688
|
+
else:
|
|
689
|
+
simplify["minimum_code"] = True
|
|
690
|
+
simplify["no_single_use_abstractions"] = True
|
|
691
|
+
simplify["no_speculative_config"] = True
|
|
692
|
+
# Interativo: alguém respondeu — o audit pode graduar como followed.
|
|
693
|
+
simplify["answered"] = True
|
|
694
|
+
simplify["skipped"] = False
|
|
695
|
+
data["simplify"] = simplify
|
|
696
|
+
return data
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _step_intent(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
700
|
+
"""Fase 2.5: INTENT — verificar intenção antes de mudar comportamento.
|
|
701
|
+
|
|
702
|
+
Inspirado no intent gate do fable-method: antes de qualquer mudança
|
|
703
|
+
de comportamento, registrar o que o código faz, o que o teste espera,
|
|
704
|
+
e o que a especificação diz.
|
|
705
|
+
"""
|
|
706
|
+
intent = _secao(data, "intent")
|
|
707
|
+
if intent.get("answered"):
|
|
708
|
+
print("(intent gate já respondido)")
|
|
709
|
+
return data
|
|
710
|
+
|
|
711
|
+
if not sys.stdin.isatty():
|
|
712
|
+
print("(modo não-interativo — assumindo intenção alinhada)")
|
|
713
|
+
# `skipped`, não `answered`: nenhum humano respondeu nada aqui. Marcar
|
|
714
|
+
# como respondido fazia esta fase ser saltada para sempre, inclusive
|
|
715
|
+
# num ciclo interativo posterior na mesma tarefa.
|
|
716
|
+
data["intent"] = {
|
|
717
|
+
"code_does": "",
|
|
718
|
+
"check_expects": "",
|
|
719
|
+
"spec_says": "",
|
|
720
|
+
"all_agree": True,
|
|
721
|
+
"answered": False,
|
|
722
|
+
"skipped": True,
|
|
723
|
+
}
|
|
724
|
+
return data
|
|
725
|
+
|
|
726
|
+
_print_header("2.5 INTENT — Antes de mudar, verifique a intenção")
|
|
727
|
+
|
|
728
|
+
print(" Se esta tarefa muda comportamento, responda:")
|
|
729
|
+
code_does = _ask_text(" O que o código FAZ hoje? ")
|
|
730
|
+
check_expects = _ask_text(" O que o teste/check ESPERA? ")
|
|
731
|
+
spec_says = _ask_text(" O que a especificação/README DIZ? ")
|
|
732
|
+
|
|
733
|
+
all_agree = _confirm(" Código, teste e especificação concordam?", default=True)
|
|
734
|
+
if not all_agree:
|
|
735
|
+
print(" ⚠ Conflito detectado! A ordem de autoridade é:")
|
|
736
|
+
print(" declaração do usuário > spec > testes > código")
|
|
737
|
+
resolve = _ask_text(" Como resolver o conflito? ")
|
|
738
|
+
else:
|
|
739
|
+
resolve = ""
|
|
740
|
+
|
|
741
|
+
data["intent"] = {
|
|
742
|
+
"code_does": code_does,
|
|
743
|
+
"check_expects": check_expects,
|
|
744
|
+
"spec_says": spec_says,
|
|
745
|
+
"all_agree": all_agree,
|
|
746
|
+
"conflict_resolution": resolve,
|
|
747
|
+
"answered": True,
|
|
748
|
+
}
|
|
749
|
+
return data
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _step_surgical(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
753
|
+
"""Fase 3: SURGICAL — cada linha toca só o necessário.
|
|
754
|
+
|
|
755
|
+
O parâmetro `task` é mantido por simetria com as demais fases e para
|
|
756
|
+
identificação no YAML, mas não é usado na lógica desta fase.
|
|
757
|
+
"""
|
|
758
|
+
_print_header("3. SURGICAL — Cada linha toca só o necessário")
|
|
759
|
+
|
|
760
|
+
# K-12: guard de retomada (mesmo contrato de FIT/THINK/INTENT/TWIN).
|
|
761
|
+
if _secao(data, "surgical").get("answered"):
|
|
762
|
+
print("(surgical já respondido)")
|
|
763
|
+
return data
|
|
764
|
+
|
|
765
|
+
if not sys.stdin.isatty():
|
|
766
|
+
print("(modo não-interativo — pulando SURGICAL)")
|
|
767
|
+
data["surgical"] = {
|
|
768
|
+
"files": [],
|
|
769
|
+
"removed_imports_clean": True,
|
|
770
|
+
"answered": False,
|
|
771
|
+
"skipped": True,
|
|
772
|
+
}
|
|
773
|
+
return data
|
|
774
|
+
|
|
775
|
+
files = _changed_paths()
|
|
776
|
+
|
|
777
|
+
surgical = _secao(data, "surgical")
|
|
778
|
+
file_checks: list[dict[str, Any]] = []
|
|
779
|
+
|
|
780
|
+
if files:
|
|
781
|
+
print("Arquivos alterados:")
|
|
782
|
+
for f in files:
|
|
783
|
+
necessary = _confirm(f" {f} — necessário para esta tarefa?", default=True)
|
|
784
|
+
file_checks.append({"path": f, "necessary": necessary})
|
|
785
|
+
surgical["removed_imports_clean"] = _confirm(
|
|
786
|
+
" Imports removidos são só os que sua mudança tornou inúteis?"
|
|
787
|
+
)
|
|
788
|
+
else:
|
|
789
|
+
print("(nenhum arquivo alterado detectado — pulando confirmações)")
|
|
790
|
+
surgical["removed_imports_clean"] = True
|
|
791
|
+
|
|
792
|
+
surgical["files"] = file_checks
|
|
793
|
+
# Interativo: alguém respondeu — o audit pode graduar como followed.
|
|
794
|
+
surgical["answered"] = True
|
|
795
|
+
surgical["skipped"] = False
|
|
796
|
+
data["surgical"] = surgical
|
|
797
|
+
return data
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def _step_verify(
|
|
801
|
+
task: str,
|
|
802
|
+
data: dict[str, Any],
|
|
803
|
+
ruff_paths: list[str] | None = None,
|
|
804
|
+
test_paths: list[str] | None = None,
|
|
805
|
+
ignore: list[str] | None = None,
|
|
806
|
+
cov_source: str | list[str] = "src",
|
|
807
|
+
gate: float = 70.0,
|
|
808
|
+
config: VerifyConfig | None = None,
|
|
809
|
+
) -> dict[str, Any]:
|
|
810
|
+
"""Fase 4: GOAL-DRIVEN — verificação de qualidade (lint + teste + coverage)."""
|
|
811
|
+
_print_header("4. GOAL-DRIVEN — Verificação de qualidade")
|
|
812
|
+
# Parte do verify existente (ex.: attempts de uma execução anterior) para
|
|
813
|
+
# que o contador de tentativas sobreviva entre retomadas da tarefa.
|
|
814
|
+
# K-11: seção não-mapa (YAML à mão) vira {} — nunca AttributeError.
|
|
815
|
+
verify: dict[str, Any] = dict(_secao(data, "verify"))
|
|
816
|
+
all_ok = True
|
|
817
|
+
|
|
818
|
+
results = run_all(
|
|
819
|
+
ruff_paths=ruff_paths,
|
|
820
|
+
test_paths=test_paths,
|
|
821
|
+
ignore=ignore,
|
|
822
|
+
cov_source=cov_source,
|
|
823
|
+
gate=gate,
|
|
824
|
+
config=config,
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
# ── lint ──
|
|
828
|
+
ruff_res: VerifyResult = results["ruff"]
|
|
829
|
+
print(f"▶ {ruff_res.details.get('command', 'lint')}")
|
|
830
|
+
verify["ruff_clean"] = ruff_res.ok
|
|
831
|
+
if ruff_res.ok:
|
|
832
|
+
print(" ✅ limpo")
|
|
833
|
+
else:
|
|
834
|
+
all_ok = False
|
|
835
|
+
print(" ❌ falhou — saída:")
|
|
836
|
+
for line in ruff_res.output.split("\n"):
|
|
837
|
+
print(f" {line}")
|
|
838
|
+
|
|
839
|
+
# ── teste ──
|
|
840
|
+
pytest_res: VerifyResult = results["pytest"]
|
|
841
|
+
print(f"\n▶ {pytest_res.details.get('command', 'test')}")
|
|
842
|
+
verify["tests_pass"] = pytest_res.ok
|
|
843
|
+
if pytest_res.ok:
|
|
844
|
+
print(" ✅ passou")
|
|
845
|
+
else:
|
|
846
|
+
all_ok = False
|
|
847
|
+
print(" ❌ falhou — últimas linhas:")
|
|
848
|
+
for line in pytest_res.output.split("\n"):
|
|
849
|
+
print(f" {line}")
|
|
850
|
+
|
|
851
|
+
# ── coverage ──
|
|
852
|
+
cov_res: VerifyResult = results["coverage"]
|
|
853
|
+
cov_pct = cov_res.details.get("coverage_pct", 0.0)
|
|
854
|
+
print(f"\n▶ coverage (gate ≥ {gate:.0f}%)")
|
|
855
|
+
verify["coverage_pct"] = cov_pct
|
|
856
|
+
verify["coverage_pass"] = cov_res.ok
|
|
857
|
+
if cov_res.ok:
|
|
858
|
+
print(f" ✅ passou ({cov_pct:.1f}%)")
|
|
859
|
+
else:
|
|
860
|
+
all_ok = False
|
|
861
|
+
print(f" ❌ falhou ({cov_pct:.1f}% — gate: {gate:.0f}%)")
|
|
862
|
+
for line in cov_res.output.split("\n"):
|
|
863
|
+
print(f" {line}")
|
|
864
|
+
|
|
865
|
+
# ── success criteria ──
|
|
866
|
+
print("\n▶ Critério de sucesso da tarefa")
|
|
867
|
+
# Fable Step 1: o critério foi declarado no THINK, antes da evidência.
|
|
868
|
+
# O VERIFY confronta o declarado com o resultado final em vez de apenas
|
|
869
|
+
# perguntar "está satisfeito?" a um critério que só existe agora.
|
|
870
|
+
done = data.get("done", "")
|
|
871
|
+
if done:
|
|
872
|
+
print(f" (declarado no THINK: {done})")
|
|
873
|
+
if task == "check-only":
|
|
874
|
+
success_met = True
|
|
875
|
+
print(" (modo check-only — assumido satisfeito)")
|
|
876
|
+
else:
|
|
877
|
+
success_met = _confirm(" O critério de sucesso da tarefa está satisfeito?")
|
|
878
|
+
verify["success_criteria_met"] = success_met
|
|
879
|
+
if not success_met:
|
|
880
|
+
all_ok = False
|
|
881
|
+
|
|
882
|
+
# Hard bound (Fable Step 5): contador de tentativas FALHAS de verificação
|
|
883
|
+
# persistido na tarefa. Após MAX_VERIFY_ATTEMPTS falhas, o ciclo devolve
|
|
884
|
+
# a tarefa ao usuário com o que foi tentado, o output real e a hipótese
|
|
885
|
+
# atual — não fica repetindo o mesmo fix-verify indefinidamente.
|
|
886
|
+
# K-11: attempts não-numérico (YAML à mão) não pode derrubar o ciclo.
|
|
887
|
+
try:
|
|
888
|
+
attempts_base = int(verify.get("attempts") or 0)
|
|
889
|
+
except (TypeError, ValueError):
|
|
890
|
+
attempts_base = 0
|
|
891
|
+
# K-13: o contador mede FALHAS, não execuções. Antes, toda execução
|
|
892
|
+
# incrementava e o relatório dizia "N tentativa(s) falharam" quando uma
|
|
893
|
+
# tinha passado — tarefa aprovada (1) + 2 falhas disparava hand_back
|
|
894
|
+
# com apenas 2 falhas reais.
|
|
895
|
+
if not all_ok:
|
|
896
|
+
attempts = attempts_base + 1
|
|
897
|
+
else:
|
|
898
|
+
attempts = attempts_base
|
|
899
|
+
verify["attempts"] = attempts
|
|
900
|
+
verify["hand_back"] = not all_ok and attempts >= MAX_VERIFY_ATTEMPTS
|
|
901
|
+
if verify["hand_back"]:
|
|
902
|
+
print(
|
|
903
|
+
f" ⚠ {attempts} tentativas de verificação falharam — devolvendo a tarefa ao usuário."
|
|
904
|
+
)
|
|
905
|
+
|
|
906
|
+
data["verify"] = verify
|
|
907
|
+
data["status"] = "approved" if all_ok else "rejected"
|
|
908
|
+
if all_ok:
|
|
909
|
+
# R14: approved_commit marca o FIM do trabalho da tarefa — o HEAD no
|
|
910
|
+
# momento da aprovação. O JUDGE diffa base_commit..approved_commit
|
|
911
|
+
# (em vez de base_commit..HEAD), então arquivos alterados por tasks
|
|
912
|
+
# POSTERIORES não contam como "não declarados" para esta.
|
|
913
|
+
#
|
|
914
|
+
# Com o HEAD ainda no base_commit a mudança não está em commit nenhum:
|
|
915
|
+
# gravar o HEAD daria teto == piso, uma janela de diff vazia que o
|
|
916
|
+
# JUDGE não tem como inspecionar (artigo JSERD §6.4). Sem teto, o
|
|
917
|
+
# juiz difa contra a árvore de trabalho enquanto nada for commitado.
|
|
918
|
+
result = _run_git(["git", "rev-parse", "HEAD"])
|
|
919
|
+
sha = result.stdout.strip()
|
|
920
|
+
base = data.get("base_commit")
|
|
921
|
+
mesmo_que_base = (
|
|
922
|
+
bool(base)
|
|
923
|
+
and _run_git(["git", "rev-parse", "--verify", str(base)]).stdout.strip() == sha
|
|
924
|
+
)
|
|
925
|
+
if result.returncode == 0 and sha and not mesmo_que_base:
|
|
926
|
+
data["approved_commit"] = sha
|
|
927
|
+
|
|
928
|
+
# Resumo
|
|
929
|
+
print()
|
|
930
|
+
if all_ok:
|
|
931
|
+
print("┌" + "─" * 58 + "┐")
|
|
932
|
+
print("│ ✅ KATA CYCLE — APROVADO │")
|
|
933
|
+
print("└" + "─" * 58 + "┘")
|
|
934
|
+
else:
|
|
935
|
+
print("┌" + "─" * 58 + "┐")
|
|
936
|
+
print("│ ❌ KATA CYCLE — REJEITADO │")
|
|
937
|
+
print("│ Corrija os problemas e rode novamente. │")
|
|
938
|
+
print("└" + "─" * 58 + "┘")
|
|
939
|
+
|
|
940
|
+
return data
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _step_twin(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
944
|
+
"""Fase pós-VERIFY: TWIN CHECK — busca automática de padrão recorrente.
|
|
945
|
+
|
|
946
|
+
Inspirado no twin check do fable-method: quando um defeito é corrigido,
|
|
947
|
+
busca o mesmo padrão no projeto inteiro para evitar recorrências.
|
|
948
|
+
"""
|
|
949
|
+
if data.get("status") != "approved":
|
|
950
|
+
return data
|
|
951
|
+
|
|
952
|
+
twins = _secao(data, "twins")
|
|
953
|
+
if twins.get("searched"):
|
|
954
|
+
return data
|
|
955
|
+
|
|
956
|
+
intent = _secao(data, "intent")
|
|
957
|
+
defect_fixed = not intent.get("all_agree", True) or _confirm(
|
|
958
|
+
" Um defeito foi corrigido? Deseja buscar padrão similar?", default=False
|
|
959
|
+
)
|
|
960
|
+
|
|
961
|
+
# `defect_fixed` é gravado porque é a única evidência de que um defeito
|
|
962
|
+
# foi corrigido: sem ele, _detect_twins_owed não tem como distinguir uma
|
|
963
|
+
# correção de defeito de uma tarefa aprovada qualquer.
|
|
964
|
+
if not defect_fixed:
|
|
965
|
+
data["twins"] = {
|
|
966
|
+
"searched": False,
|
|
967
|
+
"pattern": "",
|
|
968
|
+
"result": "",
|
|
969
|
+
"defect_fixed": False,
|
|
970
|
+
}
|
|
971
|
+
return data
|
|
972
|
+
|
|
973
|
+
if not sys.stdin.isatty():
|
|
974
|
+
# Mesmo contrato dos ramos de erro e padrão vazio (R10-13): nada foi
|
|
975
|
+
# confirmado — `defect_fixed: True` aqui faria o audit graduar a
|
|
976
|
+
# tarefa como faked por uma busca que ninguém pôde fazer.
|
|
977
|
+
data["twins"] = {
|
|
978
|
+
"searched": False,
|
|
979
|
+
"pattern": "",
|
|
980
|
+
"result": "",
|
|
981
|
+
"defect_fixed": False,
|
|
982
|
+
}
|
|
983
|
+
return data
|
|
984
|
+
|
|
985
|
+
_print_header("TWIN CHECK — Busca de padrão recorrente")
|
|
986
|
+
|
|
987
|
+
pattern = _ask_text(" Padrão a buscar (regex): ")
|
|
988
|
+
if not pattern:
|
|
989
|
+
data["twins"] = {
|
|
990
|
+
"searched": False,
|
|
991
|
+
"pattern": "",
|
|
992
|
+
"result": "",
|
|
993
|
+
"defect_fixed": False,
|
|
994
|
+
}
|
|
995
|
+
return data
|
|
996
|
+
|
|
997
|
+
print(f"\n Buscando '{pattern}' no projeto...")
|
|
998
|
+
search_result = search_pattern(pattern, cwd=_cwd())
|
|
999
|
+
|
|
1000
|
+
if search_result.error:
|
|
1001
|
+
print(f" ❌ Busca inválida ou interrompida: {search_result.error}")
|
|
1002
|
+
# `defect_fixed` fica False: a busca falhou, nada foi confirmado.
|
|
1003
|
+
# Com True, o audit graduaria "faked" (defeito declarado corrigido
|
|
1004
|
+
# sem busca) por uma falha de ferramenta (R10-13).
|
|
1005
|
+
data["twins"] = {
|
|
1006
|
+
"pattern": pattern,
|
|
1007
|
+
"result": search_result.error,
|
|
1008
|
+
"searched": False,
|
|
1009
|
+
"defect_fixed": False,
|
|
1010
|
+
"matches_count": 0,
|
|
1011
|
+
"files_count": 0,
|
|
1012
|
+
"fix_applied": False,
|
|
1013
|
+
}
|
|
1014
|
+
return data
|
|
1015
|
+
|
|
1016
|
+
if search_result.matches:
|
|
1017
|
+
print(f"\n ✅ Encontrado em {search_result.total_files} arquivo(s):")
|
|
1018
|
+
for match in search_result.matches[:20]:
|
|
1019
|
+
print(f" {match.file}:{match.line} {match.content[:80]}")
|
|
1020
|
+
if len(search_result.matches) > 20:
|
|
1021
|
+
print(f" ... e mais {len(search_result.matches) - 20} ocorrência(s)")
|
|
1022
|
+
else:
|
|
1023
|
+
print(" Nenhuma ocorrência encontrada.")
|
|
1024
|
+
|
|
1025
|
+
fix_others = False
|
|
1026
|
+
if search_result.matches:
|
|
1027
|
+
fix_others = _confirm(" Corrigir as demais ocorrências agora?", default=False)
|
|
1028
|
+
if fix_others:
|
|
1029
|
+
print(" ⚠ O CLI não edita ocorrências; a correção não foi aplicada.")
|
|
1030
|
+
fix_others = False
|
|
1031
|
+
|
|
1032
|
+
result_str = (
|
|
1033
|
+
f"{search_result.total_files} arquivo(s), {len(search_result.matches)} ocorrência(s)"
|
|
1034
|
+
)
|
|
1035
|
+
data["twins"] = {
|
|
1036
|
+
"pattern": pattern,
|
|
1037
|
+
"result": result_str,
|
|
1038
|
+
"searched": True,
|
|
1039
|
+
"defect_fixed": True,
|
|
1040
|
+
"matches_count": len(search_result.matches),
|
|
1041
|
+
"files_count": search_result.total_files,
|
|
1042
|
+
"fix_applied": fix_others,
|
|
1043
|
+
}
|
|
1044
|
+
return data
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
def _has_deploy_docs() -> bool:
|
|
1048
|
+
"""Detecta se README menciona passos de deploy."""
|
|
1049
|
+
readme = _cwd() / "README.md"
|
|
1050
|
+
if not readme.exists():
|
|
1051
|
+
return False
|
|
1052
|
+
deploy_keywords = ["deploy", "docker", "push", "publish", "rollout", "release"]
|
|
1053
|
+
try:
|
|
1054
|
+
text = readme.read_text(encoding="utf-8").lower()
|
|
1055
|
+
return any(kw in text for kw in deploy_keywords)
|
|
1056
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
1057
|
+
# K-28: gêmeo do CR-009 — `except Exception` engolia bugs reais e
|
|
1058
|
+
# fazia a heurística de deploy falhar em silêncio. README ilegível
|
|
1059
|
+
# vira warning, não silêncio.
|
|
1060
|
+
logging.warning("README.md ilegível (%s); assumindo sem docs de deploy", exc)
|
|
1061
|
+
return False
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
_DOC_SUFFIXES = frozenset({".md", ".rst", ".txt"})
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def _detect_intent_owed(data: dict[str, Any]) -> bool:
|
|
1068
|
+
"""Detecta se INTENT line é devida (comportamento mudou).
|
|
1069
|
+
|
|
1070
|
+
Devida quando pelo menos um arquivo alterado não é documentação. Antes
|
|
1071
|
+
bastava VERIFY ter rodado, o que tornava INTENT devida em toda tarefa —
|
|
1072
|
+
inclusive numa mudança só de docs, onde não há "o que o código FAZ" a
|
|
1073
|
+
declarar.
|
|
1074
|
+
|
|
1075
|
+
A fonte preferida é surgical.files, porque SURGICAL é a fase que
|
|
1076
|
+
estabelece o que mudou. Mas em modo não-interativo SURGICAL grava uma
|
|
1077
|
+
lista vazia, e olhar só para ela fazia INTENT nunca ser devida em
|
|
1078
|
+
execuções headless — o caveat "INTENT não documentada" sumia
|
|
1079
|
+
justamente onde não há ninguém para notar a ausência. Sem declaração,
|
|
1080
|
+
cai para o git.
|
|
1081
|
+
"""
|
|
1082
|
+
declared = [f.get("path", "") for f in _secao(data, "surgical").get("files", [])]
|
|
1083
|
+
paths = [p for p in declared if p] or _changed_paths()
|
|
1084
|
+
return any(Path(p).suffix.lower() not in _DOC_SUFFIXES for p in paths)
|
|
1085
|
+
|
|
1086
|
+
|
|
1087
|
+
def _detect_auth_owed(data: dict[str, Any]) -> bool:
|
|
1088
|
+
"""Detecta se AUTH line é devida (ação irreversível realizada).
|
|
1089
|
+
|
|
1090
|
+
Não há como inferir de forma confiável, só a partir do estado local do
|
|
1091
|
+
git, que uma ação irreversível (push, deploy, publish) foi tomada:
|
|
1092
|
+
commits locais não enviados ao remote são o estado normal e reversível
|
|
1093
|
+
de qualquer branch em progresso, não evidência de uma ação irreversível.
|
|
1094
|
+
Por isso a detecção depende de quem executou a ação (o agente ou o
|
|
1095
|
+
usuário) registrar `auth.action_taken` explicitamente.
|
|
1096
|
+
"""
|
|
1097
|
+
auth = _secao(data, "auth")
|
|
1098
|
+
return bool(auth.get("action_taken"))
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _detect_pending_owed(data: dict[str, Any]) -> bool:
|
|
1102
|
+
"""Detecta se PENDING line é devida (follow-up prescrito não tomado)."""
|
|
1103
|
+
# Heurística 1: README tem instruções de deploy e tarefa está aprovada
|
|
1104
|
+
if data.get("status") == "approved" and _has_deploy_docs():
|
|
1105
|
+
return True
|
|
1106
|
+
# Heurística 2: dados de pending já existentes
|
|
1107
|
+
pending = _secao(data, "pending")
|
|
1108
|
+
if pending.get("action"):
|
|
1109
|
+
return True
|
|
1110
|
+
return False
|
|
1111
|
+
|
|
1112
|
+
|
|
1113
|
+
def _detect_twins_owed(data: dict[str, Any]) -> bool:
|
|
1114
|
+
"""Detecta se TWINS line é devida (defeito corrigido, padrão pode se repetir).
|
|
1115
|
+
|
|
1116
|
+
"Testes e coverage passaram" era um dos sinais, o que tornava TWINS
|
|
1117
|
+
devida em toda tarefa aprovada — passar nas verificações é o estado
|
|
1118
|
+
normal de uma tarefa concluída, não evidência de defeito corrigido.
|
|
1119
|
+
Sobram os sinais que de fato indicam correção de defeito.
|
|
1120
|
+
"""
|
|
1121
|
+
# Sinal 1: intent registrou conflito código/teste/spec (resolvido ou não)
|
|
1122
|
+
intent = _secao(data, "intent")
|
|
1123
|
+
if intent.get("answered") and not intent.get("all_agree"):
|
|
1124
|
+
return True
|
|
1125
|
+
# Sinal 2: o TWIN CHECK registrou que um defeito foi corrigido
|
|
1126
|
+
twins = _secao(data, "twins")
|
|
1127
|
+
return bool(twins.get("defect_fixed") or twins.get("pattern"))
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _step_artifact(task: str, data: dict[str, Any]) -> dict[str, Any]:
|
|
1131
|
+
"""Fase 4.5: ARTIFACT — verificar linhas devidas no relatório.
|
|
1132
|
+
|
|
1133
|
+
Inspirado no artifact gate do fable-method: antes de finalizar, verificar
|
|
1134
|
+
se INTENT, AUTH, PENDING e TWINS estão presentes quando devidos.
|
|
1135
|
+
"""
|
|
1136
|
+
_print_header("4.5 ARTIFACT — Verificação de linhas devidas")
|
|
1137
|
+
|
|
1138
|
+
intent = _secao(data, "intent")
|
|
1139
|
+
|
|
1140
|
+
# INTENT: devida se a tarefa alterou algum arquivo que não é documentação
|
|
1141
|
+
intent_owed = _detect_intent_owed(data)
|
|
1142
|
+
intent_present = bool(_format_intent_line(intent))
|
|
1143
|
+
|
|
1144
|
+
# AUTH: devida se ação irreversível foi tomada
|
|
1145
|
+
auth_owed = _detect_auth_owed(data)
|
|
1146
|
+
auth_present = bool(_format_auth_line(_secao(data, "auth")))
|
|
1147
|
+
|
|
1148
|
+
# PENDING: devida se docs prescrevem follow-up e não foi tomado
|
|
1149
|
+
pending_owed = _detect_pending_owed(data)
|
|
1150
|
+
pending_present = bool(_format_pending_line(_secao(data, "pending")))
|
|
1151
|
+
|
|
1152
|
+
# TWINS: devida se defeito foi corrigido
|
|
1153
|
+
twins_owed = _detect_twins_owed(data)
|
|
1154
|
+
twins_present = bool(_format_twins_line(_secao(data, "twins")))
|
|
1155
|
+
|
|
1156
|
+
checks: dict[str, Any] = {
|
|
1157
|
+
"intent_owed": intent_owed,
|
|
1158
|
+
"intent_present": intent_present,
|
|
1159
|
+
"auth_owed": auth_owed,
|
|
1160
|
+
"auth_present": auth_present,
|
|
1161
|
+
"pending_owed": pending_owed,
|
|
1162
|
+
"pending_present": pending_present,
|
|
1163
|
+
"twins_owed": twins_owed,
|
|
1164
|
+
"twins_present": twins_present,
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
missing = []
|
|
1168
|
+
if intent_owed and not intent_present:
|
|
1169
|
+
missing.append("INTENT: código/teste/spec não documentados")
|
|
1170
|
+
if auth_owed and not auth_present:
|
|
1171
|
+
missing.append("AUTH: ação externa sem autorização documentada")
|
|
1172
|
+
if pending_owed and not pending_present:
|
|
1173
|
+
missing.append("PENDING: follow-up não documentado")
|
|
1174
|
+
if twins_owed and not twins_present:
|
|
1175
|
+
missing.append("TWINS: busca de padrão recorrente não realizada")
|
|
1176
|
+
|
|
1177
|
+
if missing:
|
|
1178
|
+
print(" ⚠ Linhas devidas ausentes:")
|
|
1179
|
+
for msg in missing:
|
|
1180
|
+
print(f" • {msg}")
|
|
1181
|
+
if sys.stdin.isatty():
|
|
1182
|
+
print()
|
|
1183
|
+
for msg in missing:
|
|
1184
|
+
if msg.startswith("AUTH"):
|
|
1185
|
+
action = _ask_text(" Ação realizada: ")
|
|
1186
|
+
auth_line = _ask_text(" Citação exata da autorização: ")
|
|
1187
|
+
data["auth"] = {
|
|
1188
|
+
"action_taken": True,
|
|
1189
|
+
"authorized": True,
|
|
1190
|
+
"action": action,
|
|
1191
|
+
"quote": auth_line,
|
|
1192
|
+
}
|
|
1193
|
+
elif msg.startswith("PENDING"):
|
|
1194
|
+
action = input(" Ação pendente: ").strip()
|
|
1195
|
+
data["pending"] = {"action": action, "documented": True}
|
|
1196
|
+
elif msg.startswith("TWINS"):
|
|
1197
|
+
pattern = input(" Padrão buscado: ").strip()
|
|
1198
|
+
result = input(" Resultado: ").strip()
|
|
1199
|
+
data["twins"] = {"pattern": pattern, "result": result, "searched": True}
|
|
1200
|
+
elif msg.startswith("INTENT"):
|
|
1201
|
+
code = input(" O que o código FAZ hoje? ").strip()
|
|
1202
|
+
check = input(" O que o teste/check ESPERA? ").strip()
|
|
1203
|
+
spec = input(" O que a especificação DIZ? ").strip()
|
|
1204
|
+
data["intent"] = {
|
|
1205
|
+
"code_does": code,
|
|
1206
|
+
"check_expects": check,
|
|
1207
|
+
"spec_says": spec,
|
|
1208
|
+
"all_agree": True,
|
|
1209
|
+
"answered": True,
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
# Recompute present flags after user input so YAML reflects reality.
|
|
1213
|
+
intent = _secao(data, "intent")
|
|
1214
|
+
checks["intent_present"] = bool(_format_intent_line(intent))
|
|
1215
|
+
checks["auth_present"] = bool(_format_auth_line(_secao(data, "auth")))
|
|
1216
|
+
checks["pending_present"] = bool(_format_pending_line(_secao(data, "pending")))
|
|
1217
|
+
checks["twins_present"] = bool(_format_twins_line(_secao(data, "twins")))
|
|
1218
|
+
else:
|
|
1219
|
+
print(" ✅ Todas as linhas devidas estão presentes")
|
|
1220
|
+
|
|
1221
|
+
data["artifact"] = checks
|
|
1222
|
+
return data
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
def _detect_scratch_files() -> list[str]:
|
|
1226
|
+
"""Detecta arquivos temporários/de lixo no diff.
|
|
1227
|
+
|
|
1228
|
+
Usa is_debris_file (kata.judge) para que CLI e JUDGE apliquem a mesma
|
|
1229
|
+
regra. A cópia que existia aqui casava a substring "temp" e marcava
|
|
1230
|
+
`templates/`, `temperature.py` e `attempt_parser.py` como detrito.
|
|
1231
|
+
|
|
1232
|
+
A lista vem de _changed_paths, que inclui untracked: detrito recém-criado
|
|
1233
|
+
e ainda não adicionado ao índice é justamente o caso mais comum.
|
|
1234
|
+
"""
|
|
1235
|
+
return [f for f in _changed_paths() if is_debris_file(f)]
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def _step_report(task: str, data: dict[str, Any]) -> None:
|
|
1239
|
+
"""Fase 5: REPORT — relatório outcome-first.
|
|
1240
|
+
|
|
1241
|
+
Inspirado no Step 6 do fable-method: primeira frase = resultado,
|
|
1242
|
+
detalhes depois, sem números de passo, com linhas INTENT/AUTH/PENDING/TWINS.
|
|
1243
|
+
"""
|
|
1244
|
+
status = data.get("status", "unknown")
|
|
1245
|
+
icon = "✅" if status == "approved" else "❌"
|
|
1246
|
+
verify = _secao(data, "verify")
|
|
1247
|
+
|
|
1248
|
+
# Outcome first
|
|
1249
|
+
print()
|
|
1250
|
+
if status == "approved":
|
|
1251
|
+
print(f"{icon} KATA CYCLE — APROVADO: critério de sucesso satisfeito")
|
|
1252
|
+
elif status == "rejected":
|
|
1253
|
+
print(f"{icon} KATA CYCLE — REJEITADO: verifique os problemas abaixo")
|
|
1254
|
+
else:
|
|
1255
|
+
print(f" ⏳ Tarefa '{task}' está em andamento (status: {status})")
|
|
1256
|
+
return
|
|
1257
|
+
|
|
1258
|
+
# O que foi feito
|
|
1259
|
+
intent = _secao(data, "intent")
|
|
1260
|
+
surgical = _secao(data, "surgical")
|
|
1261
|
+
think = data.get("think", {})
|
|
1262
|
+
|
|
1263
|
+
print()
|
|
1264
|
+
domain = data.get("domain", "coding")
|
|
1265
|
+
if domain != "coding":
|
|
1266
|
+
print(f" Domínio: {domain}")
|
|
1267
|
+
|
|
1268
|
+
if think.get("problem"):
|
|
1269
|
+
print(f" Problema: {think['problem']}")
|
|
1270
|
+
|
|
1271
|
+
# Fable Step 1: o critério de sucesso declarado no THINK aparece no
|
|
1272
|
+
# relatório — o leitor vê o que era "pronto" e pode confrontar com o
|
|
1273
|
+
# resultado.
|
|
1274
|
+
done = data.get("done", "")
|
|
1275
|
+
if done:
|
|
1276
|
+
print(f" Critério declarado: {done}")
|
|
1277
|
+
|
|
1278
|
+
files = surgical.get("files", [])
|
|
1279
|
+
if files:
|
|
1280
|
+
# Aceita {"path": ...} e {"file": ...} — o schema do orquestrador
|
|
1281
|
+
# OpenCode grava "file"; o CLI esperava "path" e quebrava no NoneType.
|
|
1282
|
+
needed = [f.get("path") or f.get("file") for f in files if f.get("necessary")]
|
|
1283
|
+
needed = [f for f in needed if f]
|
|
1284
|
+
if needed:
|
|
1285
|
+
print(f" Arquivos alterados: {', '.join(needed)}")
|
|
1286
|
+
|
|
1287
|
+
# INTENT line
|
|
1288
|
+
intent_line = _format_intent_line(intent)
|
|
1289
|
+
if intent_line:
|
|
1290
|
+
print(f" {intent_line}")
|
|
1291
|
+
|
|
1292
|
+
# Verificações
|
|
1293
|
+
print()
|
|
1294
|
+
checks = []
|
|
1295
|
+
ruff = verify.get("ruff_clean")
|
|
1296
|
+
if ruff is not None:
|
|
1297
|
+
checks.append(f" {'✅' if ruff else '❌'} ruff check {'limpo' if ruff else 'com erros'}")
|
|
1298
|
+
tests = verify.get("tests_pass")
|
|
1299
|
+
if tests is not None:
|
|
1300
|
+
checks.append(f" {'✅' if tests else '❌'} pytest {'passou' if tests else 'falhou'}")
|
|
1301
|
+
cov = verify.get("coverage_pass")
|
|
1302
|
+
# `or 0.0` e não `get(..., 0)`: a chave existe com valor None no template
|
|
1303
|
+
# de --init e nos YAMLs escritos à mão pelas skills, então o default do
|
|
1304
|
+
# get nunca entra e o format de None levanta TypeError.
|
|
1305
|
+
cov_pct = verify.get("coverage_pct") or 0.0
|
|
1306
|
+
if cov is not None:
|
|
1307
|
+
label = f" {'✅' if cov else '❌'} coverage {cov_pct:.1f}% {'≥' if cov else '<'} gate"
|
|
1308
|
+
checks.append(label)
|
|
1309
|
+
success = verify.get("success_criteria_met")
|
|
1310
|
+
if success is not None:
|
|
1311
|
+
checks.append(f" {'✅' if success else '❌'} critério de sucesso satisfeito")
|
|
1312
|
+
if checks:
|
|
1313
|
+
print(" Verificações:")
|
|
1314
|
+
for c in checks:
|
|
1315
|
+
print(c)
|
|
1316
|
+
|
|
1317
|
+
# Caveats
|
|
1318
|
+
caveats: list[str] = []
|
|
1319
|
+
if status == "rejected":
|
|
1320
|
+
caveats.append("Ciclo rejeitado — problemas de qualidade pendentes")
|
|
1321
|
+
# Hard bound (Fable Step 5): estourado o limite de tentativas, o relatório
|
|
1322
|
+
# diz explicitamente que a tarefa foi devolvida ao usuário — com o que foi
|
|
1323
|
+
# tentado, o output real e a hipótese atual — em vez de um "rejeitado"
|
|
1324
|
+
# genérico que convida a mais um ciclo fix-verify.
|
|
1325
|
+
if verify.get("hand_back"):
|
|
1326
|
+
caveats.append(
|
|
1327
|
+
f"hand back: {verify.get('attempts', 0)} tentativa(s) de verificação "
|
|
1328
|
+
"falharam — devolvendo ao usuário com o que foi tentado, o output "
|
|
1329
|
+
"real e a hipótese atual"
|
|
1330
|
+
)
|
|
1331
|
+
# Fase preenchida com default em modo não-interativo não foi verificada por
|
|
1332
|
+
# ninguém. Um relatório que não diz isso apresenta como cumprido um gate
|
|
1333
|
+
# que só foi contornado. As cinco fases com default headless: FIT, THINK,
|
|
1334
|
+
# INTENT (R7-1) e SIMPLIFY, SURGICAL (R9-2).
|
|
1335
|
+
puladas = [
|
|
1336
|
+
nome.upper()
|
|
1337
|
+
for nome in ("fit", "think", "intent", "simplify", "surgical")
|
|
1338
|
+
if data.get(nome, {}).get("skipped")
|
|
1339
|
+
]
|
|
1340
|
+
if puladas:
|
|
1341
|
+
caveats.append(
|
|
1342
|
+
f"{', '.join(puladas)} preenchida(s) com default em modo não-interativo — "
|
|
1343
|
+
"ninguém respondeu"
|
|
1344
|
+
)
|
|
1345
|
+
scratch = _detect_scratch_files()
|
|
1346
|
+
if scratch:
|
|
1347
|
+
caveats.append(f"Arquivos temporários detectados: {', '.join(scratch)}")
|
|
1348
|
+
artifact = _secao(data, "artifact")
|
|
1349
|
+
if artifact.get("intent_owed") and not artifact.get("intent_present"):
|
|
1350
|
+
caveats.append("INTENT não documentada — comportamento alterado sem registro de intenção")
|
|
1351
|
+
if artifact.get("auth_owed") and not artifact.get("auth_present"):
|
|
1352
|
+
caveats.append("AÇÃO EXTERNA sem autorização documentada (AUTH ausente)")
|
|
1353
|
+
if artifact.get("pending_owed") and not artifact.get("pending_present"):
|
|
1354
|
+
caveats.append("PENDING não documentada — follow-up prescrito sem registro")
|
|
1355
|
+
if artifact.get("twins_owed") and not artifact.get("twins_present"):
|
|
1356
|
+
caveats.append("TWINS não documentada — busca de recorrência ausente")
|
|
1357
|
+
|
|
1358
|
+
if caveats:
|
|
1359
|
+
print()
|
|
1360
|
+
print(" Caveats:")
|
|
1361
|
+
for c in caveats:
|
|
1362
|
+
print(f" ⚠ {c}")
|
|
1363
|
+
|
|
1364
|
+
# Forced artifact lines
|
|
1365
|
+
lines: list[str] = []
|
|
1366
|
+
auth_line = _format_auth_line(_secao(data, "auth"))
|
|
1367
|
+
if auth_line:
|
|
1368
|
+
lines.append(auth_line)
|
|
1369
|
+
pending_line = _format_pending_line(_secao(data, "pending"))
|
|
1370
|
+
if pending_line:
|
|
1371
|
+
lines.append(pending_line)
|
|
1372
|
+
twins_line = _format_twins_line(_secao(data, "twins"))
|
|
1373
|
+
if twins_line:
|
|
1374
|
+
lines.append(twins_line)
|
|
1375
|
+
if lines:
|
|
1376
|
+
print()
|
|
1377
|
+
for line in lines:
|
|
1378
|
+
print(f" {line}")
|
|
1379
|
+
|
|
1380
|
+
print()
|
|
1381
|
+
print("─" * 58)
|
|
1382
|
+
|
|
1383
|
+
|
|
1384
|
+
# ── init ────────────────────────────────────────────────────────────────
|
|
1385
|
+
|
|
1386
|
+
|
|
1387
|
+
def _init_task(task: str) -> bool:
|
|
1388
|
+
"""Cria template .kata/<task>.yaml para uma nova tarefa."""
|
|
1389
|
+
path = _task_path(task)
|
|
1390
|
+
if path.exists():
|
|
1391
|
+
print(f"⚠ {path} já existe. Use o modo interativo para continuar.")
|
|
1392
|
+
return False
|
|
1393
|
+
|
|
1394
|
+
template: dict[str, Any] = {
|
|
1395
|
+
"schema_version": SCHEMA_VERSION,
|
|
1396
|
+
"task": task,
|
|
1397
|
+
"status": "draft",
|
|
1398
|
+
"domain": "coding",
|
|
1399
|
+
# Fable Step 1: critério de sucesso declarado no THINK, antes da
|
|
1400
|
+
# evidência; exibido no VERIFY e no relatório.
|
|
1401
|
+
"done": "",
|
|
1402
|
+
"fit": {
|
|
1403
|
+
"trivial": False,
|
|
1404
|
+
"route": "code-loop",
|
|
1405
|
+
"reason": "",
|
|
1406
|
+
"answered": False,
|
|
1407
|
+
"skipped": False,
|
|
1408
|
+
},
|
|
1409
|
+
"think": {
|
|
1410
|
+
"problem": "",
|
|
1411
|
+
"assumptions": [],
|
|
1412
|
+
"alternatives": [],
|
|
1413
|
+
"unknowns": "",
|
|
1414
|
+
"answered": False,
|
|
1415
|
+
"skipped": False,
|
|
1416
|
+
},
|
|
1417
|
+
"simplify": {
|
|
1418
|
+
"minimum_code": True,
|
|
1419
|
+
"no_single_use_abstractions": True,
|
|
1420
|
+
"no_speculative_config": True,
|
|
1421
|
+
"notes": "",
|
|
1422
|
+
"answered": False,
|
|
1423
|
+
"skipped": False,
|
|
1424
|
+
},
|
|
1425
|
+
"intent": {
|
|
1426
|
+
"code_does": "",
|
|
1427
|
+
"check_expects": "",
|
|
1428
|
+
"spec_says": "",
|
|
1429
|
+
"all_agree": True,
|
|
1430
|
+
"conflict_resolution": "",
|
|
1431
|
+
"answered": False,
|
|
1432
|
+
"skipped": False,
|
|
1433
|
+
},
|
|
1434
|
+
"surgical": {
|
|
1435
|
+
"files": [],
|
|
1436
|
+
"removed_imports_clean": True,
|
|
1437
|
+
"answered": False,
|
|
1438
|
+
"skipped": False,
|
|
1439
|
+
},
|
|
1440
|
+
"verify": {
|
|
1441
|
+
"ruff_clean": None,
|
|
1442
|
+
"tests_pass": None,
|
|
1443
|
+
"coverage_pct": None,
|
|
1444
|
+
"coverage_pass": None,
|
|
1445
|
+
"success_criteria_met": None,
|
|
1446
|
+
# Fable Step 5: hard bounds. attempts conta execuções do VERIFY;
|
|
1447
|
+
# hand_back é true quando o limite foi estourado com falha e a
|
|
1448
|
+
# tarefa foi devolvida ao usuário.
|
|
1449
|
+
"attempts": 0,
|
|
1450
|
+
"hand_back": False,
|
|
1451
|
+
},
|
|
1452
|
+
"auth": {"action_taken": False, "authorized": False, "action": "", "quote": ""},
|
|
1453
|
+
"pending": {"action": "", "documented": False},
|
|
1454
|
+
"twins": {
|
|
1455
|
+
"searched": False,
|
|
1456
|
+
"pattern": "",
|
|
1457
|
+
"result": "",
|
|
1458
|
+
"defect_fixed": False,
|
|
1459
|
+
"matches_count": 0,
|
|
1460
|
+
"files_count": 0,
|
|
1461
|
+
"fix_applied": False,
|
|
1462
|
+
},
|
|
1463
|
+
"preflight": {"skills_missing": []},
|
|
1464
|
+
"artifact": {
|
|
1465
|
+
"intent_owed": False,
|
|
1466
|
+
"intent_present": False,
|
|
1467
|
+
"auth_owed": False,
|
|
1468
|
+
"auth_present": False,
|
|
1469
|
+
"pending_owed": False,
|
|
1470
|
+
"pending_present": False,
|
|
1471
|
+
"twins_owed": False,
|
|
1472
|
+
"twins_present": False,
|
|
1473
|
+
},
|
|
1474
|
+
}
|
|
1475
|
+
template = _capture_base_commit(template, task=task)
|
|
1476
|
+
_save_task(path, template)
|
|
1477
|
+
print(f"✅ {path} criado. Preencha as respostas com o modo interativo.")
|
|
1478
|
+
return True
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
# ── audit ────────────────────────────────────────────────────────────────
|
|
1482
|
+
|
|
1483
|
+
|
|
1484
|
+
# Risco concreto que cada fase faked/skipped cria, no estilo do
|
|
1485
|
+
# `/fable-method audit` do The Fable Method: cada skip/fake nomeia o que
|
|
1486
|
+
# deixou de ser observado e o que isso permite que aconteça.
|
|
1487
|
+
def main() -> None:
|
|
1488
|
+
"""Entry point do CLI kata."""
|
|
1489
|
+
parser = argparse.ArgumentParser(
|
|
1490
|
+
description="Kata (型) — Karpathy Development Cycle",
|
|
1491
|
+
)
|
|
1492
|
+
parser.add_argument("--version", action="version", version=f"kata {__version__}")
|
|
1493
|
+
parser.add_argument("--init", metavar="TASK", help="Cria checklist para nova tarefa")
|
|
1494
|
+
parser.add_argument(
|
|
1495
|
+
"--check-only",
|
|
1496
|
+
action="store_true",
|
|
1497
|
+
help="Roda só o passo 4 (lint + test + coverage)",
|
|
1498
|
+
)
|
|
1499
|
+
parser.add_argument(
|
|
1500
|
+
"--plan",
|
|
1501
|
+
action="store_true",
|
|
1502
|
+
help="Modo planejamento: executa THINK e para (não modifica código)",
|
|
1503
|
+
)
|
|
1504
|
+
parser.add_argument(
|
|
1505
|
+
"--task",
|
|
1506
|
+
metavar="NAME",
|
|
1507
|
+
help="Retoma tarefa específica existente",
|
|
1508
|
+
)
|
|
1509
|
+
parser.add_argument(
|
|
1510
|
+
"--ruff-paths",
|
|
1511
|
+
nargs="*",
|
|
1512
|
+
default=None,
|
|
1513
|
+
help="Caminhos para ruff check (default: src/ tests/)",
|
|
1514
|
+
)
|
|
1515
|
+
parser.add_argument(
|
|
1516
|
+
"--test-paths",
|
|
1517
|
+
nargs="*",
|
|
1518
|
+
default=None,
|
|
1519
|
+
help="Caminhos para pytest (default: tests/)",
|
|
1520
|
+
)
|
|
1521
|
+
parser.add_argument(
|
|
1522
|
+
"--ignore",
|
|
1523
|
+
nargs="*",
|
|
1524
|
+
default=None,
|
|
1525
|
+
help="Caminhos para ignorar no pytest (--ignore)",
|
|
1526
|
+
)
|
|
1527
|
+
parser.add_argument(
|
|
1528
|
+
"--cov-source",
|
|
1529
|
+
nargs="*",
|
|
1530
|
+
default=None,
|
|
1531
|
+
help=(
|
|
1532
|
+
"Pacote(s) fonte para coverage (default: %(default)s; lê "
|
|
1533
|
+
"[tool.coverage.run] source do pyproject.toml — uma entrada por "
|
|
1534
|
+
"fonte quando há várias)"
|
|
1535
|
+
),
|
|
1536
|
+
)
|
|
1537
|
+
parser.add_argument(
|
|
1538
|
+
"--gate",
|
|
1539
|
+
type=float,
|
|
1540
|
+
default=None,
|
|
1541
|
+
help=(
|
|
1542
|
+
"Gate mínimo de coverage, em %%. Default: o `verify.gate` de "
|
|
1543
|
+
f".kata/config.yaml, ou {DEFAULT_GATE:.0f}"
|
|
1544
|
+
),
|
|
1545
|
+
)
|
|
1546
|
+
parser.add_argument(
|
|
1547
|
+
"--doctor",
|
|
1548
|
+
action="store_true",
|
|
1549
|
+
help="Confere se as skills de fase estão instaladas em cada frontend",
|
|
1550
|
+
)
|
|
1551
|
+
parser.add_argument(
|
|
1552
|
+
"--install",
|
|
1553
|
+
metavar="FRONTEND",
|
|
1554
|
+
default=None,
|
|
1555
|
+
choices=[*FRONTENDS_VALIDOS, "all"],
|
|
1556
|
+
help=(
|
|
1557
|
+
"Instala as skills empacotadas (copia, sem exigir clone do repo). "
|
|
1558
|
+
"FRONTEND: opencode, claude-code ou all"
|
|
1559
|
+
),
|
|
1560
|
+
)
|
|
1561
|
+
parser.add_argument(
|
|
1562
|
+
"--uninstall",
|
|
1563
|
+
metavar="FRONTEND",
|
|
1564
|
+
default=None,
|
|
1565
|
+
choices=[*FRONTENDS_VALIDOS, "all"],
|
|
1566
|
+
help="Remove as skills instaladas por --install (só o que o Kata criou)",
|
|
1567
|
+
)
|
|
1568
|
+
parser.add_argument(
|
|
1569
|
+
"--force",
|
|
1570
|
+
action="store_true",
|
|
1571
|
+
help="Com --install: guarda personalização existente em .bak e substitui",
|
|
1572
|
+
)
|
|
1573
|
+
parser.add_argument(
|
|
1574
|
+
"--judge",
|
|
1575
|
+
action="store_true",
|
|
1576
|
+
help="Modo adversarial verification — re-executa verificações e caça fraudes",
|
|
1577
|
+
)
|
|
1578
|
+
parser.add_argument(
|
|
1579
|
+
"--trusted-base",
|
|
1580
|
+
metavar="REF",
|
|
1581
|
+
default=None,
|
|
1582
|
+
help=(
|
|
1583
|
+
"Com --judge: ref que o agente não controla (ex.: origin/main no CI). O "
|
|
1584
|
+
"piso da janela vira merge-base(REF, HEAD) e o teto do YAML é ignorado"
|
|
1585
|
+
),
|
|
1586
|
+
)
|
|
1587
|
+
parser.add_argument(
|
|
1588
|
+
"--report",
|
|
1589
|
+
action="store_true",
|
|
1590
|
+
help="Gera relatório outcome-first de tarefa concluída",
|
|
1591
|
+
)
|
|
1592
|
+
parser.add_argument(
|
|
1593
|
+
"--audit",
|
|
1594
|
+
action="store_true",
|
|
1595
|
+
help=(
|
|
1596
|
+
"Gradua as fases da tarefa: followed / skipped / faked / degraded (com risco concreto)"
|
|
1597
|
+
),
|
|
1598
|
+
)
|
|
1599
|
+
args = parser.parse_args()
|
|
1600
|
+
|
|
1601
|
+
if args.plan and args.check_only:
|
|
1602
|
+
parser.error("--plan e --check-only são mutuamente exclusivos")
|
|
1603
|
+
if args.trusted_base and not args.judge:
|
|
1604
|
+
parser.error("--trusted-base só vale com --judge")
|
|
1605
|
+
if args.judge and (args.plan or args.check_only):
|
|
1606
|
+
parser.error("--judge é mutuamente exclusivo com --plan e --check-only")
|
|
1607
|
+
if args.report and args.judge:
|
|
1608
|
+
parser.error("--report e --judge são mutuamente exclusivos")
|
|
1609
|
+
if args.report and (args.plan or args.check_only):
|
|
1610
|
+
parser.error("--report é mutuamente exclusivo com --plan e --check-only")
|
|
1611
|
+
if args.audit and (args.init or args.plan or args.check_only or args.judge or args.report):
|
|
1612
|
+
parser.error(
|
|
1613
|
+
"--audit é mutuamente exclusivo com --init, --plan, --check-only, --judge e --report"
|
|
1614
|
+
)
|
|
1615
|
+
# K-17: --init/--check-only com os modos de tarefa eram descartados em
|
|
1616
|
+
# silêncio (o branch do --init roda primeiro). `--init foo --judge`
|
|
1617
|
+
# parecia julgar e ganhava um init; `--task x --check-only` rodava o
|
|
1618
|
+
# check-only sobre a task resolvida de outro jeito. Agora é erro nomeado.
|
|
1619
|
+
if args.init and (args.judge or args.report or args.plan or args.check_only):
|
|
1620
|
+
parser.error("--init é mutuamente exclusivo com --judge, --report, --plan e --check-only")
|
|
1621
|
+
if args.task and args.check_only:
|
|
1622
|
+
parser.error("--task é mutuamente exclusivo com --check-only")
|
|
1623
|
+
if args.install and args.uninstall:
|
|
1624
|
+
parser.error("--install e --uninstall são mutuamente exclusivos")
|
|
1625
|
+
if args.force and not args.install:
|
|
1626
|
+
parser.error("--force só vale com --install")
|
|
1627
|
+
if (args.install or args.uninstall) and (
|
|
1628
|
+
args.init or args.plan or args.check_only or args.judge or args.report or args.audit
|
|
1629
|
+
):
|
|
1630
|
+
parser.error("--install/--uninstall são mutuamente exclusivos com os outros modos")
|
|
1631
|
+
if (args.install or args.uninstall) and args.task:
|
|
1632
|
+
parser.error("--install/--uninstall não usam --task (são globais por frontend)")
|
|
1633
|
+
|
|
1634
|
+
# --install/--uninstall não tocam em tarefa nem precisam de .kata/: são
|
|
1635
|
+
# sobre a instalação das skills, e têm de funcionar de qualquer diretório.
|
|
1636
|
+
if args.install or args.uninstall:
|
|
1637
|
+
_print_header(
|
|
1638
|
+
"INSTALL — Skills empacotadas" if args.install else "UNINSTALL — Skills empacotadas"
|
|
1639
|
+
)
|
|
1640
|
+
if args.install:
|
|
1641
|
+
reports, code = run_install(args.install, force=args.force)
|
|
1642
|
+
else:
|
|
1643
|
+
reports, code = run_uninstall(args.uninstall)
|
|
1644
|
+
for rep in reports:
|
|
1645
|
+
print(f" {rep.frontend}: destino {config_dir_de(rep.frontend)}")
|
|
1646
|
+
for nome in rep.instaladas:
|
|
1647
|
+
print(f" ✅ {nome}")
|
|
1648
|
+
for nome in rep.removidas:
|
|
1649
|
+
print(f" 🗑 {nome}")
|
|
1650
|
+
for nome in rep.backups:
|
|
1651
|
+
print(f" 💾 backup em {nome}")
|
|
1652
|
+
for msg in rep.recusadas:
|
|
1653
|
+
print(f" ❌ {msg}")
|
|
1654
|
+
for msg in rep.erros:
|
|
1655
|
+
print(f" ⚠ {msg}")
|
|
1656
|
+
print()
|
|
1657
|
+
sys.exit(code)
|
|
1658
|
+
|
|
1659
|
+
# --doctor não toca em tarefa nem precisa de .kata/: é sobre a
|
|
1660
|
+
# instalação das skills, e tem de funcionar de qualquer diretório.
|
|
1661
|
+
if args.doctor:
|
|
1662
|
+
_print_header("DOCTOR — Instalação das skills de fase")
|
|
1663
|
+
sys.exit(_print_doctor(doctor()))
|
|
1664
|
+
|
|
1665
|
+
_kata_dir().mkdir(parents=True, exist_ok=True)
|
|
1666
|
+
|
|
1667
|
+
# Comandos de verificação declarados pelo projeto alvo. Config quebrada
|
|
1668
|
+
# aborta em vez de cair no default: quem escreveu .kata/config.yaml quis
|
|
1669
|
+
# verificar de um jeito específico, e verificar de outro calado seria
|
|
1670
|
+
# reportar sucesso de algo que o projeto nunca pediu.
|
|
1671
|
+
try:
|
|
1672
|
+
config = load_verify_config()
|
|
1673
|
+
except ConfigError as exc:
|
|
1674
|
+
print(f"⚠ {exc}")
|
|
1675
|
+
sys.exit(1)
|
|
1676
|
+
|
|
1677
|
+
# Precedência do gate: flag explícita > config do projeto > 70%.
|
|
1678
|
+
gate = args.gate if args.gate is not None else config.gate
|
|
1679
|
+
if gate is None:
|
|
1680
|
+
gate = DEFAULT_GATE
|
|
1681
|
+
|
|
1682
|
+
# R12-02: --cov-source aceita várias fontes (uma flag por source). Sem a
|
|
1683
|
+
# flag, o default sai do pyproject.toml — string com 1 source, lista com
|
|
1684
|
+
# várias — e cai na mesma resolução do gate (nargs="*" com default None
|
|
1685
|
+
# não pode rodar _detect_cov_source() no próprio argumento, que é avaliado
|
|
1686
|
+
# no parse, quando o pyproject ainda é do CWD de quem invoca).
|
|
1687
|
+
cov_source = args.cov_source if args.cov_source is not None else _detect_cov_source()
|
|
1688
|
+
|
|
1689
|
+
if config.customizado:
|
|
1690
|
+
print(f"▶ verificações de {config_path()} (declaradas pelo projeto)")
|
|
1691
|
+
|
|
1692
|
+
# Modo --init
|
|
1693
|
+
if args.init:
|
|
1694
|
+
created = _init_task(args.init)
|
|
1695
|
+
path = _task_path(args.init)
|
|
1696
|
+
if not created or not path.exists():
|
|
1697
|
+
return
|
|
1698
|
+
data = _load_task_or_exit(path)
|
|
1699
|
+
data = _capture_base_commit(data, task=args.init)
|
|
1700
|
+
_avisa_domain_desconhecido(data)
|
|
1701
|
+
_save_task(path, data)
|
|
1702
|
+
data = _step_fit(args.init, data)
|
|
1703
|
+
_save_task(path, data)
|
|
1704
|
+
data = _step_think(args.init, data)
|
|
1705
|
+
_save_task(path, data)
|
|
1706
|
+
print(f"\n📝 FIT + THINK salvos em {path}")
|
|
1707
|
+
return
|
|
1708
|
+
|
|
1709
|
+
# Modo --report (outcome-first)
|
|
1710
|
+
if args.report:
|
|
1711
|
+
task = args.task or _pick_task()
|
|
1712
|
+
path = _resolve_task_or_suggest(task)
|
|
1713
|
+
if path is None:
|
|
1714
|
+
sys.exit(1)
|
|
1715
|
+
data = _load_task_or_exit(path)
|
|
1716
|
+
_step_report(task, data)
|
|
1717
|
+
# Só `rejected` é falha. Uma tarefa em andamento (draft,
|
|
1718
|
+
# think-complete — o estado normal de `--plan`) está funcionando como
|
|
1719
|
+
# esperado; sair 1 ao consultar seu relatório equipara planejar a
|
|
1720
|
+
# falhar.
|
|
1721
|
+
sys.exit(1 if data.get("status") == "rejected" else 0)
|
|
1722
|
+
|
|
1723
|
+
# Modo --judge (adversarial verification)
|
|
1724
|
+
if args.judge:
|
|
1725
|
+
task = args.task or _pick_task()
|
|
1726
|
+
path = _resolve_task_or_suggest(task)
|
|
1727
|
+
if path is None:
|
|
1728
|
+
sys.exit(1)
|
|
1729
|
+
data = _load_task_or_exit(path)
|
|
1730
|
+
if args.trusted_base and _resolve_trusted_base(args.trusted_base) is None:
|
|
1731
|
+
# Cair de volta na janela do YAML seria julgar exatamente o que
|
|
1732
|
+
# a base confiável existe para não confiar.
|
|
1733
|
+
print(
|
|
1734
|
+
f"❌ base confiável '{args.trusted_base}' não resolve ou não tem merge-base "
|
|
1735
|
+
"com o HEAD (clone raso? use fetch-depth: 0)"
|
|
1736
|
+
)
|
|
1737
|
+
sys.exit(1)
|
|
1738
|
+
_print_header(f"JUDGE — Verificação adversarial de '{task}'")
|
|
1739
|
+
result = judge_task(
|
|
1740
|
+
data,
|
|
1741
|
+
ruff_paths=args.ruff_paths,
|
|
1742
|
+
test_paths=args.test_paths,
|
|
1743
|
+
ignore=args.ignore,
|
|
1744
|
+
cov_source=cov_source,
|
|
1745
|
+
gate=gate,
|
|
1746
|
+
config=config,
|
|
1747
|
+
trusted_base=args.trusted_base,
|
|
1748
|
+
)
|
|
1749
|
+
_print_judge_verdict(result)
|
|
1750
|
+
# Só REFUTED é falha. "VERIFIED WITH CAVEATS" significa que o juiz
|
|
1751
|
+
# verificou e aprovou com ressalvas de severidade baixa/média;
|
|
1752
|
+
# tratá-lo como falha equipara ressalva a fraude grave e leva o CI
|
|
1753
|
+
# a ignorar o exit code por inútil.
|
|
1754
|
+
#
|
|
1755
|
+
# UNVERIFIABLE também sai 0, e a escolha é deliberada: o juiz não
|
|
1756
|
+
# encontrou nada errado, apenas não teve como olhar. Reprovar por
|
|
1757
|
+
# isso quebraria o `--judge` de todo projeto não-Python — que é
|
|
1758
|
+
# justamente quem mais o recebe — antes que houvesse alternativa a
|
|
1759
|
+
# oferecer. O veredito e a seção de pontos cegos dizem em voz alta
|
|
1760
|
+
# o que não foi observado; quem quiser barrar no CI lê o veredito.
|
|
1761
|
+
sys.exit(1 if result.verdict == "REFUTED" else 0)
|
|
1762
|
+
|
|
1763
|
+
# Modo --audit (graduação followed/skipped/faked)
|
|
1764
|
+
if args.audit:
|
|
1765
|
+
task = args.task or _pick_task()
|
|
1766
|
+
path = _resolve_task_or_suggest(task)
|
|
1767
|
+
if path is None:
|
|
1768
|
+
sys.exit(1)
|
|
1769
|
+
data = _load_task_or_exit(path)
|
|
1770
|
+
_print_header(f"AUDIT — Graduação das fases de '{task}'")
|
|
1771
|
+
achados = _audit_task(data)
|
|
1772
|
+
_print_audit(achados)
|
|
1773
|
+
# 0 = audit limpo (nenhum fake/skip); 1 = há fakes/skips.
|
|
1774
|
+
sys.exit(1 if any(a["status"] != "followed" for a in achados) else 0)
|
|
1775
|
+
|
|
1776
|
+
# Modo --check-only (CI)
|
|
1777
|
+
if args.check_only:
|
|
1778
|
+
data: dict[str, Any] = {"task": "check-only", "status": "draft"}
|
|
1779
|
+
data = _step_verify(
|
|
1780
|
+
"check-only",
|
|
1781
|
+
data,
|
|
1782
|
+
ruff_paths=args.ruff_paths,
|
|
1783
|
+
test_paths=args.test_paths,
|
|
1784
|
+
ignore=args.ignore,
|
|
1785
|
+
cov_source=cov_source,
|
|
1786
|
+
gate=gate,
|
|
1787
|
+
config=config,
|
|
1788
|
+
)
|
|
1789
|
+
sys.exit(0 if data.get("status") == "approved" else 1)
|
|
1790
|
+
|
|
1791
|
+
# Modo interativo: escolher ou criar tarefa
|
|
1792
|
+
if args.task:
|
|
1793
|
+
task = args.task
|
|
1794
|
+
else:
|
|
1795
|
+
task = _pick_task()
|
|
1796
|
+
|
|
1797
|
+
path = _task_path(task)
|
|
1798
|
+
|
|
1799
|
+
if not path.exists():
|
|
1800
|
+
_init_task(task)
|
|
1801
|
+
|
|
1802
|
+
data = _load_task_or_exit(path) if path.exists() else {"task": task, "status": "draft"}
|
|
1803
|
+
data = _capture_base_commit(data, task=task)
|
|
1804
|
+
_avisa_domain_desconhecido(data)
|
|
1805
|
+
_save_task(path, data)
|
|
1806
|
+
|
|
1807
|
+
data = _step_fit(task, data)
|
|
1808
|
+
_save_task(path, data)
|
|
1809
|
+
|
|
1810
|
+
fit_route = _secao(data, "fit").get("route", "code-loop")
|
|
1811
|
+
fit_trivial = _secao(data, "fit").get("trivial", False)
|
|
1812
|
+
|
|
1813
|
+
if not fit_trivial or args.plan or fit_route in {"question", "plan-first"}:
|
|
1814
|
+
data = _step_think(task, data)
|
|
1815
|
+
_save_task(path, data)
|
|
1816
|
+
|
|
1817
|
+
if fit_route == "question":
|
|
1818
|
+
_save_task(path, data)
|
|
1819
|
+
print(f"\n📝 Resultado salvo em {path}")
|
|
1820
|
+
return
|
|
1821
|
+
|
|
1822
|
+
if args.plan or fit_route == "plan-first":
|
|
1823
|
+
_save_task(path, data)
|
|
1824
|
+
print(f"\n📝 Plano salvo em {path}")
|
|
1825
|
+
print(" Próximas fases: SIMPLIFY → SURGICAL → VERIFY")
|
|
1826
|
+
return
|
|
1827
|
+
|
|
1828
|
+
if not fit_trivial:
|
|
1829
|
+
data = _step_simplify(task, data)
|
|
1830
|
+
_save_task(path, data)
|
|
1831
|
+
data = _step_intent(task, data)
|
|
1832
|
+
_save_task(path, data)
|
|
1833
|
+
data = _step_surgical(task, data)
|
|
1834
|
+
_save_task(path, data)
|
|
1835
|
+
|
|
1836
|
+
data = _step_verify(
|
|
1837
|
+
task,
|
|
1838
|
+
data,
|
|
1839
|
+
ruff_paths=args.ruff_paths,
|
|
1840
|
+
test_paths=args.test_paths,
|
|
1841
|
+
ignore=args.ignore,
|
|
1842
|
+
cov_source=cov_source,
|
|
1843
|
+
gate=gate,
|
|
1844
|
+
config=config,
|
|
1845
|
+
)
|
|
1846
|
+
_save_task(path, data)
|
|
1847
|
+
if not fit_trivial:
|
|
1848
|
+
data = _step_twin(task, data)
|
|
1849
|
+
_save_task(path, data)
|
|
1850
|
+
data = _step_artifact(task, data)
|
|
1851
|
+
_save_task(path, data)
|
|
1852
|
+
_step_report(task, data)
|
|
1853
|
+
|
|
1854
|
+
_save_task(path, data)
|
|
1855
|
+
print(f"\n📝 Resultado salvo em {path}")
|
|
1856
|
+
|
|
1857
|
+
if data.get("status") == "rejected":
|
|
1858
|
+
sys.exit(1)
|
|
1859
|
+
|
|
1860
|
+
|
|
1861
|
+
if __name__ == "__main__":
|
|
1862
|
+
main()
|