@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.
Files changed (83) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +243 -2
  4. package/bin/harness.js +21 -0
  5. package/install +108 -0
  6. package/package.json +27 -4
  7. package/plugin/.claude-plugin/plugin.json +9 -0
  8. package/plugin/agents/implementador.md +55 -0
  9. package/plugin/agents/orquestrador.md +59 -0
  10. package/plugin/agents/qualidade.md +44 -0
  11. package/plugin/agents/revisor-ambiente.md +86 -0
  12. package/plugin/agents/revisor-bugs.md +153 -0
  13. package/plugin/agents/revisor-spec.md +49 -0
  14. package/plugin/agents/revisor.md +96 -0
  15. package/plugin/agents/seguranca.md +62 -0
  16. package/plugin/bin/sync +322 -0
  17. package/plugin/map.json +387 -0
  18. package/plugin/payload/agents-clean +77 -0
  19. package/plugin/payload/approve +34 -0
  20. package/plugin/payload/arch_check.py +94 -0
  21. package/plugin/payload/compose_check.py +186 -0
  22. package/plugin/payload/conf-apply +22 -0
  23. package/plugin/payload/destroy +21 -0
  24. package/plugin/payload/dev +24 -0
  25. package/plugin/payload/down +20 -0
  26. package/plugin/payload/entrega/despacho.md +186 -0
  27. package/plugin/payload/entrega/fechamento.md +179 -0
  28. package/plugin/payload/entrega/tickets.md +154 -0
  29. package/plugin/payload/env-common.sh +64 -0
  30. package/plugin/payload/fetch +10 -0
  31. package/plugin/payload/gate-check +159 -0
  32. package/plugin/payload/git-hooks/commit-msg +32 -0
  33. package/plugin/payload/git-hooks/pre-commit +19 -0
  34. package/plugin/payload/git-hooks/pre-push +15 -0
  35. package/plugin/payload/hooks/__pycache__/common.cpython-313.pyc +0 -0
  36. package/plugin/payload/hooks/__pycache__/gate_stamp.cpython-313.pyc +0 -0
  37. package/plugin/payload/hooks/common.py +274 -0
  38. package/plugin/payload/hooks/dispatch_guard.py +290 -0
  39. package/plugin/payload/hooks/gate_stamp.py +242 -0
  40. package/plugin/payload/hooks/managed_guard.py +95 -0
  41. package/plugin/payload/hooks/service_guard.py +178 -0
  42. package/plugin/payload/hooks/session_context.py +68 -0
  43. package/plugin/payload/hooks/subagent_context.py +49 -0
  44. package/plugin/payload/integrate +110 -0
  45. package/plugin/payload/learn +7 -0
  46. package/plugin/payload/learn.py +282 -0
  47. package/plugin/payload/manifest_check.py +68 -0
  48. package/plugin/payload/memory +7 -0
  49. package/plugin/payload/memory.py +521 -0
  50. package/plugin/payload/pendings +7 -0
  51. package/plugin/payload/ports-free +55 -0
  52. package/plugin/payload/pr +52 -0
  53. package/plugin/payload/prepare +10 -0
  54. package/plugin/payload/push +44 -0
  55. package/plugin/payload/setup-worktree +61 -0
  56. package/plugin/payload/skills-add +20 -0
  57. package/plugin/payload/skills-search +6 -0
  58. package/plugin/payload/skills-show +6 -0
  59. package/plugin/payload/skills_remote.py +111 -0
  60. package/plugin/payload/subagent-rules.md +14 -0
  61. package/plugin/payload/ticket +67 -0
  62. package/plugin/payload/tickets_check.py +206 -0
  63. package/plugin/payload/up +45 -0
  64. package/plugin/payload/update +45 -0
  65. package/plugin/payload/validate +90 -0
  66. package/plugin/payload/worktree-env +128 -0
  67. package/plugin/skills/aprender/SKILL.md +62 -0
  68. package/plugin/skills/buscar-skills/SKILL.md +73 -0
  69. package/plugin/skills/dream/SKILL.md +92 -0
  70. package/plugin/skills/entregar/SKILL.md +110 -0
  71. package/plugin/skills/entregar/references/spec.md +84 -0
  72. package/plugin/skills/mapear/SKILL.md +85 -0
  73. package/plugin/skills/setup/SKILL.md +66 -0
  74. package/plugin/templates/AGENTS.managed.md +173 -0
  75. package/plugin/templates/AGENTS.project.md +3 -0
  76. package/plugin/templates/CLAUDE.md +10 -0
  77. package/plugin/templates/conductor.toml +16 -0
  78. package/plugin/templates/docs/agents/domain.md +15 -0
  79. package/plugin/templates/docs/agents/issue-tracker.md +23 -0
  80. package/plugin/templates/docs/agents/stack.md +132 -0
  81. package/plugin/templates/harness.conf +61 -0
  82. package/plugin/templates/orca.yaml +10 -0
  83. package/plugin/templates/settings.json +210 -0
@@ -0,0 +1,322 @@
1
+ #!/usr/bin/env python3
2
+ """Instala ou atualiza o harness num projeto.
3
+
4
+ Uso: sync <raiz do projeto> --version <tag> [--force]
5
+
6
+ Copia o payload para .harness/, gera os arquivos gerenciados a partir dos
7
+ templates e grava .harness/MANIFEST. Nunca toca no que é do projeto.
8
+
9
+ Saída: 0 ok; 1 se um arquivo gerenciado foi alterado à mão (ou já existia com
10
+ outro conteúdo) e --force não foi passado, sem escrever nada; 2 uso inválido.
11
+ """
12
+ import argparse
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import subprocess
18
+ import sys
19
+
20
+ PLUGIN = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ PAYLOAD = os.path.join(PLUGIN, "payload")
22
+ TEMPLATES = os.path.join(PLUGIN, "templates")
23
+ sys.path.insert(0, os.path.join(PAYLOAD, "hooks"))
24
+ import common # noqa: E402
25
+ from managed_guard import BEGIN, END, region # noqa: E402
26
+
27
+
28
+ def sha256(data: bytes) -> str:
29
+ return hashlib.sha256(data).hexdigest()
30
+
31
+
32
+ def read(path: str) -> bytes:
33
+ with open(path, "rb") as f:
34
+ return f.read()
35
+
36
+
37
+ def merge(base, extra):
38
+ """Soma o fragmento do projeto ao que o harness gera. Em conflito, o harness vence."""
39
+ if isinstance(base, dict) and isinstance(extra, dict):
40
+ out = dict(base)
41
+ for key, value in extra.items():
42
+ out[key] = merge(base[key], value) if key in base else value
43
+ return out
44
+ if isinstance(base, list) and isinstance(extra, list):
45
+ return base + [item for item in extra if item not in base]
46
+ return base
47
+
48
+
49
+ def write_atomic(path: str, content: bytes, executable: bool) -> None:
50
+ """Grava num arquivo novo e troca de uma vez.
51
+
52
+ O `update` em execução é um desses arquivos: escrever por cima dele faria o
53
+ shell continuar lendo, do meio, um conteúdo que mudou.
54
+ """
55
+ os.makedirs(os.path.dirname(path), exist_ok=True)
56
+ tmp = path + ".harness-tmp"
57
+ with open(tmp, "wb") as f:
58
+ f.write(content)
59
+ os.chmod(tmp, 0o755 if executable else 0o644)
60
+ os.replace(tmp, path)
61
+
62
+
63
+ DISPATCHER = """#!/bin/sh
64
+ # Despachante do harness. O hook de verdade mora em .harness/git-hooks do checkout em uso.
65
+ ROOT="$(git rev-parse --show-toplevel 2>/dev/null)" || ROOT=""
66
+ HOOK="$ROOT/.harness/git-hooks/{name}"
67
+ if [ -n "$ROOT" ] && [ -x "$HOOK" ]; then
68
+ exec "$HOOK" "$@"
69
+ fi
70
+ {missing}
71
+ """
72
+ MISSING = {
73
+ "pre-push": ('echo "push negado: este checkout não tem .harness/git-hooks/pre-push." >&2\n'
74
+ 'echo " O repositório usa o harness; traga a branch para um commit que o tenha." >&2\n'
75
+ "exit 1"),
76
+ "commit-msg": "exit 0",
77
+ "pre-commit": "exit 0",
78
+ }
79
+
80
+
81
+ def install_hook_dispatchers(root: str) -> None:
82
+ """Aponta o git para hooks num caminho absoluto, no estado do harness em ~/.claude.
83
+
84
+ Um core.hooksPath relativo vale para todos os worktrees, e num checkout sem
85
+ .harness/ o git simplesmente não roda hook nenhum, em silêncio. O despachante
86
+ existe sempre e nega o push quando o hook de verdade não está lá.
87
+ """
88
+ target = os.path.join(common.state_dir(root), "git-hooks")
89
+ for name, missing in MISSING.items():
90
+ script = DISPATCHER.format(name=name, missing=missing)
91
+ write_atomic(os.path.join(target, name), script.encode("utf-8"), True)
92
+ subprocess.run(["git", "config", "core.hooksPath", target], cwd=root, check=True)
93
+
94
+
95
+ def remote_host(root: str):
96
+ """Servidor do remoto origin, ou None para remoto local ou ausente."""
97
+ url = subprocess.run(["git", "remote", "get-url", "origin"], cwd=root, capture_output=True, text=True).stdout.strip()
98
+ url = url.lower()
99
+ if not url or url.startswith(("/", ".", "~", "file:")):
100
+ return None
101
+ m = re.match(r"^[a-z0-9+.-]+://(?:[^@/]+@)?(\[[0-9a-f:]+\]|[^/:]+)", url) or re.match(r"^(?:[^@/]+@)?([^/:]+):", url)
102
+ return m.group(1).strip("[]").rstrip(".") if m else None
103
+
104
+
105
+ def close_git_host(settings: dict, root: str) -> None:
106
+ """Dentro do sandbox, o servidor de git não é alcançável.
107
+
108
+ O portão de push é um script do harness que roda fora do sandbox. Se o agente
109
+ alcançasse o servidor por conta própria, qualquer comando do git que não roda
110
+ hooks enviaria código sem revisão. Um fragmento do projeto não reabre isso.
111
+ """
112
+ network = settings["sandbox"]["network"]
113
+ denied = network["deniedDomains"]
114
+ host = remote_host(root)
115
+ for domain in ([host, "*." + host] if host else []):
116
+ if domain not in denied:
117
+ denied.append(domain)
118
+ bare = {d[2:] if d.startswith("*.") else d for d in denied}
119
+ network["allowedDomains"] = [d for d in network.get("allowedDomains", [])
120
+ if d not in denied and not any(d == b or d.endswith("." + b) for b in bare)]
121
+
122
+
123
+ IGNORED = (".claude/worktrees/", ".harness-run/", ".env")
124
+
125
+
126
+ def ignore_run_paths(root: str) -> None:
127
+ """Garante no .gitignore do projeto os caminhos que o harness cria ao trabalhar.
128
+
129
+ Os worktrees de agente ficam dentro da feature; sem isto, um `git add -A` os
130
+ adicionaria como repositórios embutidos. Só acrescenta linhas que faltam.
131
+ """
132
+ path = os.path.join(root, ".gitignore")
133
+ current = read(path).decode("utf-8") if os.path.exists(path) else ""
134
+ missing = [line for line in IGNORED if line not in current.splitlines()]
135
+ if missing:
136
+ with open(path, "w", encoding="utf-8") as f:
137
+ f.write(current + ("" if current.endswith("\n") or not current else "\n") + "\n".join(missing) + "\n")
138
+
139
+
140
+ def planned_files(root: str, version: str, profile: str) -> dict:
141
+ """Caminho relativo -> (conteúdo, executável) de tudo que é inteiramente gerenciado."""
142
+ plan = {}
143
+ for folder, dirs, files in os.walk(PAYLOAD):
144
+ dirs[:] = [d for d in dirs if d != "__pycache__"]
145
+ for name in files:
146
+ if name.endswith(".pyc"):
147
+ continue
148
+ src = os.path.join(folder, name)
149
+ rel = os.path.join(".harness", os.path.relpath(src, PAYLOAD))
150
+ plan[rel] = (read(src), os.access(src, os.X_OK))
151
+
152
+ with open(os.path.join(PLUGIN, "map.json"), encoding="utf-8") as f:
153
+ skill_map = json.load(f)
154
+ env = f"SPEC_GLOB={skill_map['spec_glob']}\nTICKETS_GLOB={skill_map['tickets_glob']}\n"
155
+ plan[os.path.join(".harness", "map.env")] = (env.encode("utf-8"), False)
156
+
157
+ settings = json.loads(read(os.path.join(TEMPLATES, "settings.json")).decode("utf-8")
158
+ .replace("__VERSION__", version))
159
+ fragment = os.path.join(root, "harness.d", "settings.json")
160
+ if os.path.exists(fragment):
161
+ try:
162
+ extra = json.loads(read(fragment).decode("utf-8"))
163
+ except ValueError as exc:
164
+ raise SystemExit(f"sync: harness.d/settings.json não é JSON válido: {exc}")
165
+ if not isinstance(extra, dict):
166
+ raise SystemExit("sync: harness.d/settings.json precisa ser um objeto JSON.")
167
+ settings = merge(settings, extra)
168
+ close_git_host(settings, root)
169
+ text = json.dumps(settings, indent=2, ensure_ascii=False) + "\n"
170
+ plan[os.path.join(".claude", "settings.json")] = (text.encode("utf-8"), False)
171
+
172
+ plan["CLAUDE.md"] = (read(os.path.join(TEMPLATES, "CLAUDE.md")), False)
173
+ plan["orca.yaml"] = (read(os.path.join(TEMPLATES, "orca.yaml")), False)
174
+ # O Conductor é secundário: só entra quando o dono pede, no harness.conf.
175
+ if common.read_conf(os.path.join(root, "harness.conf")).get("CONDUCTOR") == "1":
176
+ plan[os.path.join(".conductor", "settings.toml")] = (read(os.path.join(TEMPLATES, "conductor.toml")), False)
177
+ agents_docs = os.path.join(TEMPLATES, "docs", "agents")
178
+ for name in sorted(os.listdir(agents_docs)):
179
+ if name == "stack.md" and profile != "fullstack-typescript":
180
+ continue # a stack padrão só é descrita no perfil que a adota
181
+ plan[os.path.join("docs", "agents", name)] = (read(os.path.join(agents_docs, name)), False)
182
+ return plan
183
+
184
+
185
+ PROFILES = ("fullstack-typescript", "livre", "existente")
186
+ _PROFILE_BLOCK = re.compile(r"<!-- perfil: ([^>]*?) -->\n(.*?)<!-- /perfil -->\n", re.S)
187
+
188
+
189
+ def profile_of(root: str, asked=None) -> str:
190
+ """Perfil do projeto: o pedido na linha de comando, senão o PROFILE do harness.conf, senão o padrão."""
191
+ chosen = asked or common.read_conf(os.path.join(root, "harness.conf")).get("PROFILE") or PROFILES[0]
192
+ if chosen not in PROFILES:
193
+ raise SystemExit(f"sync: PROFILE `{chosen}` não existe. Os perfis são: {', '.join(PROFILES)}.")
194
+ return chosen
195
+
196
+
197
+ def for_profile(text: str, profile: str) -> str:
198
+ """Mantém os trechos marcados para o perfil e tira os marcadores."""
199
+ keep = lambda m: m.group(2) if profile in [p.strip() for p in m.group(1).split(",")] else ""
200
+ return _PROFILE_BLOCK.sub(keep, text)
201
+
202
+
203
+ def managed_region(profile: str) -> str:
204
+ body = for_profile(read(os.path.join(TEMPLATES, "AGENTS.managed.md")).decode("utf-8"), profile).strip()
205
+ return f"{BEGIN}\n{body}\n{END}"
206
+
207
+
208
+ def new_agents_md(current, managed: str) -> str:
209
+ if current is None:
210
+ project = read(os.path.join(TEMPLATES, "AGENTS.project.md")).decode("utf-8")
211
+ return f"# AGENTS.md\n\n{managed}\n\n{project}"
212
+ old = region(current)
213
+ if old is None:
214
+ return f"{managed}\n\n{current}"
215
+ return current.replace(old, managed, 1)
216
+
217
+
218
+ def load_manifest(root: str) -> dict:
219
+ try:
220
+ return json.loads(read(os.path.join(root, ".harness", "MANIFEST")).decode("utf-8"))
221
+ except (OSError, ValueError):
222
+ return {}
223
+
224
+
225
+ def conflicts(root: str, plan: dict, manifest: dict, current_agents) -> list:
226
+ """Arquivos que o dono alterou à mão, ou que já existiam antes do harness."""
227
+ found = []
228
+ known = manifest.get("files", {})
229
+ for rel, (content, _) in sorted(plan.items()):
230
+ path = os.path.join(root, rel)
231
+ if not os.path.exists(path):
232
+ continue
233
+ data = read(path)
234
+ actual = common.file_digest(rel, data)
235
+ # Manifesto antigo guardava os bytes; os dois valem.
236
+ if actual != common.file_digest(rel, content) and known.get(rel) not in (actual, sha256(data)):
237
+ found.append(rel)
238
+ expected_region = manifest.get("regions", {}).get("AGENTS.md")
239
+ if expected_region and current_agents is not None:
240
+ actual = region(current_agents)
241
+ if actual is None or sha256(actual.encode("utf-8")) != expected_region:
242
+ found.append("AGENTS.md")
243
+ return found
244
+
245
+
246
+ def main() -> int:
247
+ parser = argparse.ArgumentParser(prog="sync", add_help=True)
248
+ parser.add_argument("project")
249
+ parser.add_argument("--version", required=True)
250
+ parser.add_argument("--force", action="store_true")
251
+ parser.add_argument("--profile", choices=PROFILES)
252
+ try:
253
+ args = parser.parse_args()
254
+ except SystemExit:
255
+ return 2
256
+
257
+ top = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=args.project,
258
+ capture_output=True, text=True) if os.path.isdir(args.project) else None
259
+ if top is None or top.returncode != 0:
260
+ sys.stderr.write("sync: o projeto precisa ser um repositório git.\n")
261
+ return 2
262
+ root = top.stdout.strip()
263
+
264
+ profile = profile_of(root, args.profile)
265
+ plan = planned_files(root, args.version, profile)
266
+ manifest = load_manifest(root)
267
+ agents_path = os.path.join(root, "AGENTS.md")
268
+ current_agents = read(agents_path).decode("utf-8") if os.path.exists(agents_path) else None
269
+
270
+ changed = conflicts(root, plan, manifest, current_agents)
271
+ if changed and not args.force:
272
+ sys.stderr.write("sync: estes arquivos gerenciados têm conteúdo diferente do que o harness "
273
+ "gravou. Nada foi alterado. Confira e rode de novo com --force para "
274
+ "substituí-los:\n")
275
+ for rel in changed:
276
+ sys.stderr.write(f" {rel}\n")
277
+ return 1
278
+
279
+ # O que o harness gravou antes e deixou de gerar sai. Se o dono mexeu no arquivo,
280
+ # ele fica, com aviso: o harness não apaga o que não reconhece mais como seu.
281
+ for rel, known in manifest.get("files", {}).items():
282
+ stale = os.path.join(root, rel)
283
+ if rel in plan or not os.path.exists(stale):
284
+ continue
285
+ if known in (common.file_digest(rel, read(stale)), sha256(read(stale))):
286
+ os.remove(stale)
287
+ else:
288
+ sys.stderr.write(f"sync: {rel.replace(os.sep, '/')} não é mais gerado pelo harness, mas foi "
289
+ "alterado à mão; ficou como está.\n")
290
+
291
+ for rel, (content, executable) in plan.items():
292
+ write_atomic(os.path.join(root, rel), content, executable)
293
+
294
+ managed = managed_region(profile)
295
+ with open(agents_path, "w", encoding="utf-8") as f:
296
+ f.write(new_agents_md(current_agents, managed))
297
+
298
+ conf = os.path.join(root, "harness.conf")
299
+ if not os.path.exists(conf):
300
+ with open(conf, "wb") as f:
301
+ f.write(read(os.path.join(TEMPLATES, "harness.conf")))
302
+ # O perfil pedido na instalação fica escrito: as próximas sincronizações o leem dali.
303
+ if args.profile and not common.read_conf(conf).get("PROFILE"):
304
+ with open(conf, "a", encoding="utf-8") as f:
305
+ f.write(f"\nPROFILE={args.profile}\n")
306
+
307
+ install_hook_dispatchers(root)
308
+ ignore_run_paths(root)
309
+
310
+ record = {
311
+ "version": args.version,
312
+ "files": {rel: common.file_digest(rel, content) for rel, (content, _) in sorted(plan.items())},
313
+ "regions": {"AGENTS.md": sha256(managed.encode("utf-8"))},
314
+ }
315
+ with open(os.path.join(root, ".harness", "MANIFEST"), "w", encoding="utf-8") as f:
316
+ f.write(json.dumps(record, indent=2, ensure_ascii=False) + "\n")
317
+ print(f"harness {args.version} sincronizado em {root}")
318
+ return 0
319
+
320
+
321
+ if __name__ == "__main__":
322
+ sys.exit(main())