@fullchico/harness 0.0.0-stage → 0.1.3
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.
- package/.claude-plugin/marketplace.json +14 -0
- package/LICENSE +21 -0
- package/README.md +243 -2
- package/bin/harness.js +21 -0
- package/install +108 -0
- package/package.json +27 -4
- package/plugin/.claude-plugin/plugin.json +9 -0
- package/plugin/agents/implementador.md +55 -0
- package/plugin/agents/orquestrador.md +59 -0
- package/plugin/agents/qualidade.md +44 -0
- package/plugin/agents/revisor-ambiente.md +86 -0
- package/plugin/agents/revisor-bugs.md +153 -0
- package/plugin/agents/revisor-spec.md +49 -0
- package/plugin/agents/revisor.md +96 -0
- package/plugin/agents/seguranca.md +62 -0
- package/plugin/bin/sync +322 -0
- package/plugin/map.json +387 -0
- package/plugin/payload/agents-clean +77 -0
- package/plugin/payload/approve +34 -0
- package/plugin/payload/arch_check.py +94 -0
- package/plugin/payload/compose_check.py +186 -0
- package/plugin/payload/conf-apply +22 -0
- package/plugin/payload/destroy +21 -0
- package/plugin/payload/dev +24 -0
- package/plugin/payload/down +20 -0
- package/plugin/payload/entrega/despacho.md +186 -0
- package/plugin/payload/entrega/fechamento.md +179 -0
- package/plugin/payload/entrega/tickets.md +154 -0
- package/plugin/payload/env-common.sh +64 -0
- package/plugin/payload/fetch +10 -0
- package/plugin/payload/gate-check +159 -0
- package/plugin/payload/git-hooks/commit-msg +32 -0
- package/plugin/payload/git-hooks/pre-commit +19 -0
- package/plugin/payload/git-hooks/pre-push +15 -0
- package/plugin/payload/hooks/__pycache__/common.cpython-313.pyc +0 -0
- package/plugin/payload/hooks/__pycache__/gate_stamp.cpython-313.pyc +0 -0
- package/plugin/payload/hooks/common.py +274 -0
- package/plugin/payload/hooks/dispatch_guard.py +290 -0
- package/plugin/payload/hooks/gate_stamp.py +242 -0
- package/plugin/payload/hooks/managed_guard.py +95 -0
- package/plugin/payload/hooks/service_guard.py +178 -0
- package/plugin/payload/hooks/session_context.py +68 -0
- package/plugin/payload/hooks/subagent_context.py +49 -0
- package/plugin/payload/integrate +110 -0
- package/plugin/payload/learn +7 -0
- package/plugin/payload/learn.py +282 -0
- package/plugin/payload/manifest_check.py +68 -0
- package/plugin/payload/memory +7 -0
- package/plugin/payload/memory.py +521 -0
- package/plugin/payload/pendings +7 -0
- package/plugin/payload/ports-free +55 -0
- package/plugin/payload/pr +52 -0
- package/plugin/payload/prepare +10 -0
- package/plugin/payload/push +44 -0
- package/plugin/payload/setup-worktree +61 -0
- package/plugin/payload/skills-add +20 -0
- package/plugin/payload/skills-search +6 -0
- package/plugin/payload/skills-show +6 -0
- package/plugin/payload/skills_remote.py +111 -0
- package/plugin/payload/subagent-rules.md +14 -0
- package/plugin/payload/ticket +67 -0
- package/plugin/payload/tickets_check.py +206 -0
- package/plugin/payload/up +45 -0
- package/plugin/payload/update +45 -0
- package/plugin/payload/validate +90 -0
- package/plugin/payload/worktree-env +128 -0
- package/plugin/skills/aprender/SKILL.md +62 -0
- package/plugin/skills/buscar-skills/SKILL.md +73 -0
- package/plugin/skills/dream/SKILL.md +92 -0
- package/plugin/skills/entregar/SKILL.md +110 -0
- package/plugin/skills/entregar/references/spec.md +84 -0
- package/plugin/skills/mapear/SKILL.md +85 -0
- package/plugin/skills/setup/SKILL.md +66 -0
- package/plugin/templates/AGENTS.managed.md +173 -0
- package/plugin/templates/AGENTS.project.md +3 -0
- package/plugin/templates/CLAUDE.md +10 -0
- package/plugin/templates/conductor.toml +16 -0
- package/plugin/templates/docs/agents/domain.md +15 -0
- package/plugin/templates/docs/agents/issue-tracker.md +23 -0
- package/plugin/templates/docs/agents/stack.md +132 -0
- package/plugin/templates/harness.conf +61 -0
- package/plugin/templates/orca.yaml +10 -0
- package/plugin/templates/settings.json +210 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Base dos hooks do harness: leitura de entrada, estado dos portões e configuração."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import pwd
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
sys.dont_write_bytecode = True
|
|
11
|
+
|
|
12
|
+
GATES = ("seguranca", "revisao", "qualidade", "bugs", "ambiente")
|
|
13
|
+
_CONF_LINE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_payload() -> dict:
|
|
17
|
+
try:
|
|
18
|
+
data = json.load(sys.stdin)
|
|
19
|
+
except Exception:
|
|
20
|
+
return {}
|
|
21
|
+
return data if isinstance(data, dict) else {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def deny(reason: str):
|
|
25
|
+
sys.stderr.write(reason.rstrip() + "\n")
|
|
26
|
+
sys.exit(2)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _git(cwd, *args):
|
|
30
|
+
if not cwd or not os.path.isdir(cwd):
|
|
31
|
+
return None
|
|
32
|
+
try:
|
|
33
|
+
r = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
|
|
34
|
+
except OSError:
|
|
35
|
+
return None
|
|
36
|
+
return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def repo_root(cwd):
|
|
40
|
+
return _git(cwd, "rev-parse", "--show-toplevel")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def home() -> str:
|
|
44
|
+
"""Pasta do usuário, pelo sistema e não pela variável HOME, que um comando pode trocar."""
|
|
45
|
+
return pwd.getpwuid(os.getuid()).pw_dir
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def state_root() -> str:
|
|
49
|
+
return os.path.join(home(), ".claude", "harness")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def state_dir(cwd):
|
|
53
|
+
"""Onde ficam as aprovações e os hooks de git deste repositório.
|
|
54
|
+
|
|
55
|
+
Fica em ~/.claude, que o sandbox do Bash não deixa o agente gravar, e não dentro
|
|
56
|
+
do .git, que uma sessão num worktree consegue alterar. Um diretório por
|
|
57
|
+
repositório, igual para todos os worktrees.
|
|
58
|
+
"""
|
|
59
|
+
common_dir = _git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
|
60
|
+
if not common_dir:
|
|
61
|
+
return None
|
|
62
|
+
repo_id = hashlib.sha256(os.path.realpath(common_dir).encode("utf-8")).hexdigest()[:16]
|
|
63
|
+
return os.path.join(state_root(), repo_id)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def memory_dir(cwd):
|
|
67
|
+
"""Onde fica a memória derivada do repositório: o mapa do código e as âncoras.
|
|
68
|
+
|
|
69
|
+
Dentro do diretório git comum: local, fora dos arquivos versionados, igual para
|
|
70
|
+
todos os worktrees, e gravável pelo agente (ao contrário de ~/.claude).
|
|
71
|
+
"""
|
|
72
|
+
common_dir = _git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
|
73
|
+
return os.path.join(common_dir, "harness-memory") if common_dir else None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def request_path(state: str, gate: str, sha: str) -> str:
|
|
77
|
+
return os.path.join(state, "requests", gate, sha + ".json")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def head_sha(cwd):
|
|
81
|
+
return _git(cwd, "rev-parse", "HEAD")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def git_dirs(cwd):
|
|
85
|
+
"""Diretórios git deste checkout: o comum a todos os worktrees e o do próprio worktree."""
|
|
86
|
+
found = []
|
|
87
|
+
for flag in ("--git-common-dir", "--absolute-git-dir"):
|
|
88
|
+
args = ("rev-parse", "--path-format=absolute", flag) if flag == "--git-common-dir" else ("rev-parse", flag)
|
|
89
|
+
value = _git(cwd, *args)
|
|
90
|
+
if value:
|
|
91
|
+
found.append(os.path.realpath(value))
|
|
92
|
+
return found
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
DEFAULT_REFS = ("refs/remotes/origin/HEAD", "refs/remotes/origin/main", "refs/remotes/origin/master",
|
|
96
|
+
"refs/heads/main", "refs/heads/master")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _remote_head(cwd):
|
|
100
|
+
"""Commit para o qual aponta o HEAD do remoto `origin`, perguntando ao remoto. None se não der."""
|
|
101
|
+
try:
|
|
102
|
+
r = subprocess.run(["git", "ls-remote", "--symref", "origin", "HEAD"], cwd=cwd,
|
|
103
|
+
capture_output=True, text=True, timeout=15)
|
|
104
|
+
except (OSError, subprocess.SubprocessError):
|
|
105
|
+
return None
|
|
106
|
+
if r.returncode != 0:
|
|
107
|
+
return None
|
|
108
|
+
for line in r.stdout.splitlines():
|
|
109
|
+
parts = line.split()
|
|
110
|
+
if len(parts) == 2 and parts[1] == "HEAD" and parts[0] != "ref:":
|
|
111
|
+
return parts[0]
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def branch_base(cwd, sha):
|
|
116
|
+
"""Commit em que a branch de `sha` saiu da branch padrão; None se não der para saber.
|
|
117
|
+
|
|
118
|
+
A branch padrão é a que o remoto anuncia agora. As referências locais só são
|
|
119
|
+
usadas quando o remoto não responde (sem rede): elas podem ser movidas por
|
|
120
|
+
qualquer comando, e por isso o push confere de novo, sempre contra o remoto.
|
|
121
|
+
"""
|
|
122
|
+
remote = _remote_head(cwd)
|
|
123
|
+
if remote and _exists(cwd, remote):
|
|
124
|
+
return _git(cwd, "merge-base", sha, remote)
|
|
125
|
+
root = repo_root(cwd)
|
|
126
|
+
refs = []
|
|
127
|
+
declared = read_conf(os.path.join(root, "harness.conf")).get("DEFAULT_BRANCH") if root else None
|
|
128
|
+
if declared:
|
|
129
|
+
refs += ["refs/remotes/origin/" + declared, "refs/heads/" + declared]
|
|
130
|
+
refs += DEFAULT_REFS
|
|
131
|
+
for ref in refs:
|
|
132
|
+
if _git(cwd, "rev-parse", "-q", "--verify", ref + "^{commit}"):
|
|
133
|
+
return _git(cwd, "merge-base", sha, ref)
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _exists(cwd, sha) -> bool:
|
|
138
|
+
try:
|
|
139
|
+
return subprocess.run(["git", "cat-file", "-e", sha + "^{commit}"], cwd=cwd,
|
|
140
|
+
capture_output=True).returncode == 0
|
|
141
|
+
except OSError:
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def approval_path(state: str, gate: str, sha: str) -> str:
|
|
146
|
+
return os.path.join(state, "approvals", gate, sha + ".json")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def pendings_dir(cwd):
|
|
150
|
+
"""Onde ficam as pendências da feature deste worktree: achados simples do caçador de bugs,
|
|
151
|
+
que não bloquearam o ticket mas precisam ser conferidos antes do push."""
|
|
152
|
+
state, root = state_dir(cwd), repo_root(cwd)
|
|
153
|
+
if not state or not root:
|
|
154
|
+
return None
|
|
155
|
+
feature = os.path.realpath(feature_root(root))
|
|
156
|
+
return os.path.join(state, "pendings", hashlib.sha256(feature.encode("utf-8")).hexdigest()[:16])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def pendings(cwd) -> list:
|
|
160
|
+
"""Todas as pendências da feature, abertas e resolvidas, em ordem de criação."""
|
|
161
|
+
folder = pendings_dir(cwd)
|
|
162
|
+
found = []
|
|
163
|
+
try:
|
|
164
|
+
names = sorted(os.listdir(folder), key=lambda n: int(n[1:-5]) if n[1:-5].isdigit() else 0)
|
|
165
|
+
except (OSError, TypeError):
|
|
166
|
+
return found
|
|
167
|
+
for name in names:
|
|
168
|
+
try:
|
|
169
|
+
with open(os.path.join(folder, name), encoding="utf-8") as f:
|
|
170
|
+
found.append(json.load(f))
|
|
171
|
+
except (OSError, ValueError):
|
|
172
|
+
continue
|
|
173
|
+
return found
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def read_conf(path: str) -> dict:
|
|
177
|
+
conf = {}
|
|
178
|
+
try:
|
|
179
|
+
with open(path, encoding="utf-8") as f:
|
|
180
|
+
lines = f.read().splitlines()
|
|
181
|
+
except OSError:
|
|
182
|
+
return conf
|
|
183
|
+
for line in lines:
|
|
184
|
+
m = _CONF_LINE.match(line.strip())
|
|
185
|
+
if not m:
|
|
186
|
+
continue
|
|
187
|
+
value = m.group(2).strip()
|
|
188
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
|
189
|
+
value = value[1:-1]
|
|
190
|
+
conf[m.group(1)] = value
|
|
191
|
+
return conf
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
AGENT_MARK = "/.claude/worktrees/"
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def feature_root(root: str) -> str:
|
|
198
|
+
"""O worktree da feature a que este worktree pertence; ele mesmo, se não for de agente.
|
|
199
|
+
|
|
200
|
+
O Claude Code cria os worktrees de agente sob o checkout principal, mesmo quando a
|
|
201
|
+
sessão está no worktree de uma feature. A pasta não diz de quem ele é; o git diz: a
|
|
202
|
+
feature é o worktree de cujo histórico o agente mais recentemente saiu.
|
|
203
|
+
"""
|
|
204
|
+
if AGENT_MARK not in root:
|
|
205
|
+
return root
|
|
206
|
+
listed = _git(root, "worktree", "list", "--porcelain") or ""
|
|
207
|
+
trees, path = [], None
|
|
208
|
+
for line in listed.splitlines():
|
|
209
|
+
if line.startswith("worktree "):
|
|
210
|
+
path = line[len("worktree "):]
|
|
211
|
+
elif line.startswith("HEAD ") and path and AGENT_MARK not in path:
|
|
212
|
+
trees.append((path, line[len("HEAD "):]))
|
|
213
|
+
parent = root.split(AGENT_MARK)[0]
|
|
214
|
+
main = trees[0][0] if trees else parent
|
|
215
|
+
if os.path.realpath(parent) != os.path.realpath(main):
|
|
216
|
+
return parent # agente criado dentro da pasta da própria feature
|
|
217
|
+
best = None
|
|
218
|
+
for index, (path, tip) in enumerate(trees):
|
|
219
|
+
base = _git(root, "merge-base", tip, "HEAD")
|
|
220
|
+
ahead = _git(root, "rev-list", "--count", f"{base}..HEAD") if base else None
|
|
221
|
+
if ahead is None or not ahead.isdigit():
|
|
222
|
+
continue
|
|
223
|
+
# Menos commits fora do histórico do candidato ganha; no empate, a feature e não o principal.
|
|
224
|
+
rank = (int(ahead), index == 0, index)
|
|
225
|
+
if best is None or rank < best[0]:
|
|
226
|
+
best = (rank, path)
|
|
227
|
+
return best[1] if best else parent
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def file_digest(rel: str, data: bytes) -> str:
|
|
231
|
+
"""Impressão digital de um arquivo gerenciado.
|
|
232
|
+
|
|
233
|
+
Arquivo JSON é comparado pelo conteúdo, não pelos bytes: o `claude plugin install`
|
|
234
|
+
regrava o settings.json com as chaves em outra ordem, e isso não é alteração.
|
|
235
|
+
"""
|
|
236
|
+
import hashlib
|
|
237
|
+
if rel.endswith(".json"):
|
|
238
|
+
try:
|
|
239
|
+
data = json.dumps(json.loads(data.decode("utf-8")), sort_keys=True, ensure_ascii=False).encode("utf-8")
|
|
240
|
+
except ValueError:
|
|
241
|
+
pass
|
|
242
|
+
return hashlib.sha256(data).hexdigest()
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def conf_approval_path(root):
|
|
246
|
+
"""Onde fica a proposta de harness.conf que o dono acabou de ver, para este worktree."""
|
|
247
|
+
import hashlib
|
|
248
|
+
state = state_dir(root)
|
|
249
|
+
if not state:
|
|
250
|
+
return None
|
|
251
|
+
key = hashlib.sha256(os.path.realpath(root).encode("utf-8")).hexdigest()[:16]
|
|
252
|
+
return os.path.join(state, "conf", key)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
if __name__ == "__main__":
|
|
256
|
+
# Uso pelos scripts de shell: common.py state-dir | common.py branch-base <sha> | common.py conf-approval <raiz>
|
|
257
|
+
out = None
|
|
258
|
+
if len(sys.argv) == 3 and sys.argv[1] == "feature-root":
|
|
259
|
+
out = feature_root(sys.argv[2])
|
|
260
|
+
elif len(sys.argv) == 3 and sys.argv[1] == "conf-approval":
|
|
261
|
+
out = conf_approval_path(sys.argv[2])
|
|
262
|
+
if sys.argv[1:] == ["pendings"]:
|
|
263
|
+
for item in pendings(os.getcwd()):
|
|
264
|
+
if item.get("status") == "open":
|
|
265
|
+
print(f"{item['id']}: {item['text']} (commit {item['commit'][:7]})")
|
|
266
|
+
sys.exit(0)
|
|
267
|
+
if sys.argv[1:] == ["state-dir"]:
|
|
268
|
+
out = state_dir(os.getcwd())
|
|
269
|
+
elif len(sys.argv) == 3 and sys.argv[1] == "branch-base":
|
|
270
|
+
out = branch_base(os.getcwd(), sys.argv[2])
|
|
271
|
+
if out:
|
|
272
|
+
print(out)
|
|
273
|
+
sys.exit(0)
|
|
274
|
+
sys.exit(1)
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""PreToolUse (Agent): o pedido a um revisor do harness só aponta, não narra.
|
|
3
|
+
|
|
4
|
+
O documento é a única interface entre quem escreveu e quem revisa. Para os
|
|
5
|
+
revisores do harness, cada linha do pedido é `chave: valor`, com chaves fixas.
|
|
6
|
+
Os demais agentes não são afetados. Erro do hook vira negação.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
sys.dont_write_bytecode = True # não deixa __pycache__ dentro de .harness/ do projeto
|
|
14
|
+
|
|
15
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
16
|
+
import common # noqa: E402
|
|
17
|
+
|
|
18
|
+
REQUIRED = {
|
|
19
|
+
"harness:seguranca": ("diff", "commit"),
|
|
20
|
+
"harness:revisor": ("diff", "commit"),
|
|
21
|
+
"harness:revisor-spec": ("spec",),
|
|
22
|
+
"harness:implementador": ("spec", "ticket"),
|
|
23
|
+
"harness:orquestrador": ("spec",),
|
|
24
|
+
"harness:qualidade": ("commit",),
|
|
25
|
+
"harness:revisor-bugs": ("diff", "commit"),
|
|
26
|
+
"harness:revisor-ambiente": ("spec", "ticket", "diff", "commit"),
|
|
27
|
+
}
|
|
28
|
+
# O que cada um pode receber. O implementador recebe a spec e o ticket, e numa rodada
|
|
29
|
+
# de correção o arquivo com o achado; quem revisa recebe o que vai ler, e mais nada.
|
|
30
|
+
ALLOWED = {
|
|
31
|
+
"harness:seguranca": ("diff", "commit", "spec", "leitura"),
|
|
32
|
+
"harness:revisor": ("diff", "commit", "spec", "leitura"),
|
|
33
|
+
"harness:revisor-spec": ("spec", "leitura"),
|
|
34
|
+
"harness:implementador": ("spec", "ticket", "leitura", "achado"),
|
|
35
|
+
# Quem executa a entrega recebe a spec aprovada e nada da conversa de quem a desenhou.
|
|
36
|
+
"harness:orquestrador": ("spec", "leitura"),
|
|
37
|
+
# Quem atesta a qualidade recebe o commit e mais nada: nenhuma explicação muda o resultado da checagem.
|
|
38
|
+
"harness:qualidade": ("commit",),
|
|
39
|
+
# Quem caça bug recebe o que vai ler: o intervalo, o commit, e a spec e o ticket que dizem
|
|
40
|
+
# o que o código deveria fazer. Com `ticket`, revisa a branch de um implementador.
|
|
41
|
+
# Numa rodada de correção recebe também o achado: confere a correção, não relê o ticket inteiro.
|
|
42
|
+
"harness:revisor-bugs": ("diff", "commit", "spec", "ticket", "leitura", "achado"),
|
|
43
|
+
# Só no ticket de contrato: confere que o que ele monta funciona fora da máquina de quem escreveu.
|
|
44
|
+
"harness:revisor-ambiente": ("diff", "commit", "spec", "ticket", "leitura", "achado"),
|
|
45
|
+
}
|
|
46
|
+
_LINE = re.compile(r"^(spec|ticket|diff|commit|leitura|achado): (\S.*)$")
|
|
47
|
+
_SHA = re.compile(r"^[0-9a-f]{40}$")
|
|
48
|
+
# Revisões do git: nomes, caminhos de ref, ~N, ^, @{N}. Nada de espaço, opção ou shell.
|
|
49
|
+
_REV = r"[\w./~^@{}-]+"
|
|
50
|
+
_DIFF = re.compile(rf"^(?!-){_REV}\.\.\.?(?!-){_REV}$")
|
|
51
|
+
FORMAT = ("Pedido a revisor do harness tem formato fixo, uma chave por linha: "
|
|
52
|
+
"`spec: <caminho>`, `ticket: <caminho>`, `diff: <base>...<topo>`, "
|
|
53
|
+
"`commit: <hash de 40 dígitos>`, `leitura: <caminho>, <caminho>`, `achado: <caminho>`. "
|
|
54
|
+
"Sem narrativa nem opinião: o revisor lê os documentos por conta própria.")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _inside(root: str, value: str) -> bool:
|
|
58
|
+
if os.path.isabs(value) or ".." in value.split("/"):
|
|
59
|
+
return False
|
|
60
|
+
full = os.path.realpath(os.path.join(root, value))
|
|
61
|
+
return full.startswith(os.path.realpath(root) + os.sep) and os.path.exists(full)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _committed(root: str, value: str) -> bool:
|
|
65
|
+
"""O arquivo existe no commit atual, com o mesmo conteúdo que está no disco?"""
|
|
66
|
+
if common._git(root, "cat-file", "-t", "HEAD:" + value) != "blob":
|
|
67
|
+
return False
|
|
68
|
+
import subprocess
|
|
69
|
+
return subprocess.run(["git", "diff", "--quiet", "HEAD", "--", value], cwd=root).returncode == 0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def check(agent: str, prompt, root):
|
|
73
|
+
required = REQUIRED.get(agent)
|
|
74
|
+
if required is None:
|
|
75
|
+
return None
|
|
76
|
+
if not isinstance(prompt, str) or not root:
|
|
77
|
+
return FORMAT
|
|
78
|
+
seen = {}
|
|
79
|
+
for raw in prompt.splitlines():
|
|
80
|
+
line = raw.strip()
|
|
81
|
+
if not line:
|
|
82
|
+
continue
|
|
83
|
+
m = _LINE.match(line)
|
|
84
|
+
if not m or m.group(1) in seen:
|
|
85
|
+
return FORMAT
|
|
86
|
+
seen[m.group(1)] = m.group(2).strip()
|
|
87
|
+
extra = [key for key in seen if key not in ALLOWED[agent]]
|
|
88
|
+
if extra:
|
|
89
|
+
return f"{FORMAT} Este agente não recebe: {', '.join(extra)}."
|
|
90
|
+
missing = [key for key in required if key not in seen]
|
|
91
|
+
if missing:
|
|
92
|
+
return f"{FORMAT} Falta: {', '.join(missing)}."
|
|
93
|
+
for key in ("spec", "ticket", "achado"):
|
|
94
|
+
if key in seen and not _inside(root, seen[key]):
|
|
95
|
+
return f"{FORMAT} `{key}` precisa ser um caminho relativo existente no repositório."
|
|
96
|
+
if agent == "harness:implementador":
|
|
97
|
+
# Ele trabalha num worktree próprio, que só tem o que está em commit.
|
|
98
|
+
for key in ("spec", "ticket", "achado"):
|
|
99
|
+
if key in seen and not _committed(root, seen[key]):
|
|
100
|
+
return (f"`{key}` aponta para um arquivo que ainda não está em commit ({seen[key]}). "
|
|
101
|
+
"O implementador trabalha num worktree próprio e só enxerga o que foi commitado.")
|
|
102
|
+
if "ticket" in seen:
|
|
103
|
+
issues = os.path.realpath(os.path.join(root, os.path.dirname(seen["spec"]), "issues"))
|
|
104
|
+
if not os.path.realpath(os.path.join(root, seen["ticket"])).startswith(issues + os.sep):
|
|
105
|
+
return f"{FORMAT} `ticket` precisa ser um ticket da mesma spec (na pasta issues/ ao lado dela)."
|
|
106
|
+
if "leitura" in seen:
|
|
107
|
+
for item in seen["leitura"].split(","):
|
|
108
|
+
if not _inside(root, item.strip()):
|
|
109
|
+
return f"{FORMAT} `leitura` aponta para um caminho que não existe: {item.strip()}"
|
|
110
|
+
if "commit" in seen and not _SHA.match(seen["commit"]):
|
|
111
|
+
return f"{FORMAT} `commit` precisa ser o hash completo."
|
|
112
|
+
if "diff" in seen and not _DIFF.match(seen["diff"]):
|
|
113
|
+
return f"{FORMAT} `diff` precisa ser um intervalo, como main...HEAD."
|
|
114
|
+
if agent in ("harness:revisor-bugs", "harness:revisor-ambiente") and "ticket" in seen:
|
|
115
|
+
return ticket_range(seen["diff"], seen["commit"], root)
|
|
116
|
+
if "commit" in seen and "diff" in seen:
|
|
117
|
+
return bound(seen["diff"], seen["commit"], root)
|
|
118
|
+
if agent == "harness:qualidade" and seen["commit"] != common.head_sha(root):
|
|
119
|
+
return "`commit` precisa ser o commit atual (HEAD): é nele que a checagem roda."
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def ticket_range(diff: str, commit: str, root: str):
|
|
124
|
+
"""Caça a bugs num ticket: o commit é a ponta da branch do implementador, e o intervalo termina nele."""
|
|
125
|
+
if common._git(root, "cat-file", "-t", commit) != "commit":
|
|
126
|
+
return "`commit` precisa ser um commit deste repositório: a ponta da branch do implementador."
|
|
127
|
+
right = re.split(r"\.\.\.?", diff, maxsplit=1)[1]
|
|
128
|
+
if common._git(root, "rev-parse", "-q", "--verify", right + "^{commit}") != commit:
|
|
129
|
+
return "`diff` precisa terminar no commit revisado (a ponta da branch do implementador)."
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def bound(diff: str, commit: str, root: str):
|
|
134
|
+
"""O revisor vê a branch inteira, e é o commit do topo que ele aprova.
|
|
135
|
+
|
|
136
|
+
Sem isso, um diff vazio ou parcial renderia uma aprovação que o push lê
|
|
137
|
+
como sendo de tudo o que a branch acrescenta.
|
|
138
|
+
"""
|
|
139
|
+
if commit != common.head_sha(root):
|
|
140
|
+
return "`commit` precisa ser o commit atual (HEAD): é ele que a aprovação assina."
|
|
141
|
+
left, right = re.split(r"\.\.\.?", diff, maxsplit=1)
|
|
142
|
+
resolve = lambda rev: common._git(root, "rev-parse", "-q", "--verify", rev + "^{commit}")
|
|
143
|
+
base = common.branch_base(root, commit)
|
|
144
|
+
if not base or base == commit:
|
|
145
|
+
return ("Não há o que revisar: a branch não tem commits além da branch padrão, ou a "
|
|
146
|
+
"branch padrão não foi encontrada (defina DEFAULT_BRANCH no harness.conf).")
|
|
147
|
+
if resolve(right) != commit:
|
|
148
|
+
return "`diff` precisa terminar no commit atual (HEAD)."
|
|
149
|
+
if common._git(root, "merge-base", resolve(left) or "", commit) != base:
|
|
150
|
+
return ("`diff` precisa cobrir a branch inteira, a partir da branch padrão "
|
|
151
|
+
f"(por exemplo {base[:12]}...HEAD).")
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
ONLY_ORCHESTRATOR = ("Quem despacha implementador é o `harness:orquestrador`. A sessão do dono desenha "
|
|
156
|
+
"(entrevista e spec) e entrega a execução a ele, só com o caminho da spec: o modelo "
|
|
157
|
+
"caro não fatia, não despacha e não integra.")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def chain(agent, caller):
|
|
161
|
+
"""Quem pode despachar quem. É o que mantém o modelo caro no desenho e o barato na execução."""
|
|
162
|
+
if agent == "harness:implementador" and caller != "harness:orquestrador":
|
|
163
|
+
return ONLY_ORCHESTRATOR
|
|
164
|
+
if agent == "harness:orquestrador" and caller:
|
|
165
|
+
return "O `harness:orquestrador` é despachado pela sessão do dono, não por um subagente."
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def isolated(agent, tool_input):
|
|
170
|
+
"""Cada implementador trabalha na própria cópia: no worktree da feature ele atropelaria os outros."""
|
|
171
|
+
if agent == "harness:implementador" and tool_input.get("isolation") != "worktree":
|
|
172
|
+
return "Implementador é despachado com `isolation: worktree`, mesmo quando a rodada tem um ticket só."
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def foreground(caller, tool_input):
|
|
177
|
+
"""O orquestrador espera os subagentes que dispara.
|
|
178
|
+
|
|
179
|
+
Subagente em segundo plano avisa a sessão do dono, e não quem o despachou. O modelo caro
|
|
180
|
+
passava a receber cada término e a repassar, por mensagem, ao orquestrador.
|
|
181
|
+
"""
|
|
182
|
+
if caller == "harness:orquestrador" and tool_input.get("run_in_background") is not False:
|
|
183
|
+
return ("O orquestrador despacha em primeiro plano: passe `run_in_background: false`. Dispare os "
|
|
184
|
+
"tickets da rodada na mesma mensagem, que eles rodam juntos, e espere todos voltarem.")
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def ready_for_execution(prompt, root):
|
|
189
|
+
"""O orquestrador não tem a quem perguntar: o que ele precisa tem de estar na spec, em commit."""
|
|
190
|
+
fields = dict(m.groups() for m in map(_LINE.match, (l.strip() for l in prompt.splitlines())) if m)
|
|
191
|
+
spec = fields["spec"]
|
|
192
|
+
if not _committed(root, spec):
|
|
193
|
+
return (f"A spec ({spec}) precisa estar em commit, igual ao que está no disco: o orquestrador "
|
|
194
|
+
"trabalha só com o que foi commitado.")
|
|
195
|
+
if not common.read_conf(os.path.join(root, "harness.conf")).get("PROJECT"):
|
|
196
|
+
with open(os.path.join(root, spec), encoding="utf-8", errors="replace") as f:
|
|
197
|
+
if "harness.conf" not in f.read():
|
|
198
|
+
return ("Este projeto ainda não tem `harness.conf` preenchido, e a spec não diz o conteúdo dele. "
|
|
199
|
+
"Acrescente à spec uma seção `harness.conf` com as chaves (PROJECT, SERVICES, COMPOSE_FILE, "
|
|
200
|
+
"INSTALL_CMD, AFTER_UP, DEV_CMD, VALIDATE_PUSH, VALIDATE_MERGE, VALIDATE_ARCH, CONTRACT_PATHS, MODULE_ROOTS, "
|
|
201
|
+
"ENV_*) e faça o commit.")
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def main():
|
|
206
|
+
try:
|
|
207
|
+
payload = json.load(sys.stdin)
|
|
208
|
+
except Exception:
|
|
209
|
+
common.deny("dispatch-guard: entrada do hook inválida; chamada negada.")
|
|
210
|
+
if not isinstance(payload, dict):
|
|
211
|
+
common.deny("dispatch-guard: entrada do hook inválida; chamada negada.")
|
|
212
|
+
if payload.get("tool_name") not in ("Agent", "Task"):
|
|
213
|
+
return
|
|
214
|
+
tool_input = payload.get("tool_input") or {}
|
|
215
|
+
cwd = payload.get("cwd")
|
|
216
|
+
root = common.repo_root(cwd) if isinstance(cwd, str) else None
|
|
217
|
+
agent = tool_input.get("subagent_type")
|
|
218
|
+
reason = (chain(agent, payload.get("agent_type"))
|
|
219
|
+
or foreground(payload.get("agent_type"), tool_input)
|
|
220
|
+
or isolated(agent, tool_input)
|
|
221
|
+
or check(agent, tool_input.get("prompt"), root))
|
|
222
|
+
if not reason:
|
|
223
|
+
reason = claimed(agent, tool_input.get("prompt"), root)
|
|
224
|
+
if not reason and agent == "harness:orquestrador":
|
|
225
|
+
reason = ready_for_execution(tool_input.get("prompt"), root)
|
|
226
|
+
if reason:
|
|
227
|
+
common.deny(reason)
|
|
228
|
+
record_request(agent, tool_input.get("prompt"), root)
|
|
229
|
+
record_ticket(agent, tool_input.get("prompt"), root)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
TICKET_GATE = {"harness:revisor-bugs": "bugs", "harness:revisor-ambiente": "ambiente"}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def record_ticket(agent, prompt, root):
|
|
236
|
+
"""Guarda de que ticket é a revisão: o teto de pendências é do ticket, não de cada resposta."""
|
|
237
|
+
gate = TICKET_GATE.get(agent)
|
|
238
|
+
if not gate or not isinstance(prompt, str) or not root:
|
|
239
|
+
return
|
|
240
|
+
fields = dict(m.groups() for m in map(_LINE.match, (l.strip() for l in prompt.splitlines())) if m)
|
|
241
|
+
path = common.request_path(common.state_dir(root), gate, fields["commit"])
|
|
242
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
243
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
244
|
+
json.dump({"gate": gate, "commit": fields["commit"], "ticket": fields.get("ticket")}, f)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def claimed(agent, prompt, root):
|
|
248
|
+
"""Só se despacha ticket que o orquestrador pegou com `.harness/ticket claim`, e em commit."""
|
|
249
|
+
if agent != "harness:implementador" or not isinstance(prompt, str) or not root:
|
|
250
|
+
return None
|
|
251
|
+
fields = dict(m.groups() for m in map(_LINE.match, (l.strip() for l in prompt.splitlines())) if m)
|
|
252
|
+
ticket = fields.get("ticket")
|
|
253
|
+
text = common._git(root, "show", f"HEAD:{ticket}") if ticket else None
|
|
254
|
+
if text is None or not re.search(r"(?m)^Status: claimed\s*$", text):
|
|
255
|
+
return (f"O ticket {ticket} não está `Status: claimed` no commit atual. Pegue-o antes com "
|
|
256
|
+
"`.harness/ticket claim <pasta da spec> <NN>`, que também faz o commit.")
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
GATE = {"harness:seguranca": "seguranca", "harness:revisor": "revisao"}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def record_request(agent, prompt, root):
|
|
264
|
+
"""Guarda a base do intervalo que o revisor vai ler.
|
|
265
|
+
|
|
266
|
+
O push compara essa base com a que o remoto de verdade informa. Assim, mexer
|
|
267
|
+
nas referências locais para mostrar ao revisor só parte da branch não rende
|
|
268
|
+
uma aprovação da branch inteira.
|
|
269
|
+
"""
|
|
270
|
+
gate = GATE.get(agent)
|
|
271
|
+
if not gate or not isinstance(prompt, str):
|
|
272
|
+
return
|
|
273
|
+
fields = dict(m.groups() for m in map(_LINE.match, (l.strip() for l in prompt.splitlines())) if m)
|
|
274
|
+
left = re.split(r"\.\.\.?", fields["diff"], maxsplit=1)[0]
|
|
275
|
+
commit = fields["commit"]
|
|
276
|
+
left_sha = common._git(root, "rev-parse", "-q", "--verify", left + "^{commit}")
|
|
277
|
+
base = common._git(root, "merge-base", left_sha, commit)
|
|
278
|
+
path = common.request_path(common.state_dir(root), gate, commit)
|
|
279
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
280
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
281
|
+
json.dump({"gate": gate, "commit": commit, "base": base, "diff": fields["diff"]}, f)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
if __name__ == "__main__":
|
|
285
|
+
try:
|
|
286
|
+
main()
|
|
287
|
+
except SystemExit:
|
|
288
|
+
raise
|
|
289
|
+
except Exception as exc:
|
|
290
|
+
common.deny(f"dispatch-guard: erro interno ({exc}); chamada negada.")
|