@andespindola/crow-skills 0.10.0 → 0.11.0

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.
@@ -0,0 +1,720 @@
1
+ """Machine-wide flows: ``setup`` (configure every agent CLI found) and ``upgrade``.
2
+
3
+ setup detects the agent CLIs on this machine (binary on PATH and/or config
4
+ dir, version probed with a short timeout, fail-open) and, for each one, in the
5
+ user scope, runs the same code paths as ``install --global``: all catalog
6
+ skills (or --skills), the guide, the interface integrations, the crow-mode
7
+ hooks and their approval in each CLI (``integrations.sync(trust=...)``). Then
8
+ machine-level defaults: crow mode written as on unless the user already chose,
9
+ autoupdate on (unless --no-autoupdate), broadcast and resources reported
10
+ only. Every safety rule of install still holds (backups, refusal of symlinks
11
+ and unmanaged files, transactions); a refusal for one agent never stops the
12
+ others and is reported with the flag or command that resolves it. Re-running
13
+ is idempotent: what is already configured is reported as such.
14
+
15
+ upgrade is ``autoupdate run`` started by hand: same implementation
16
+ (autoupdate.run / autoupdate.preview).
17
+ """
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ import os
20
+ from pathlib import Path
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+
25
+ from . import __version__
26
+ from . import autoupdate
27
+ from . import broadcast
28
+ from . import guide
29
+ from . import hook
30
+ from . import integrations
31
+ from . import resources
32
+ from . import ui
33
+ from .agents import destinations, uniflow_config_dir
34
+ from .source import CrowError, Source
35
+ from .storage import Store
36
+
37
+ # id, label, binary, version flag, config dir (relative to home or a function), installer agent,
38
+ # integrations that belong to this CLI (hooks first).
39
+ CLIS = (
40
+ {"id": "claude", "label": "Claude Code", "binary": "claude", "config": lambda h: h / ".claude", "agent": "claude",
41
+ "integrations": ("claude-hooks", "claude-statusline", "claude-command")},
42
+ {"id": "codex", "label": "Codex CLI", "binary": "codex", "config": lambda h: h / ".codex", "agent": "codex",
43
+ "integrations": ("codex-hooks", "codex-hooks-trust", "codex-statusline")},
44
+ {"id": "gemini", "label": "Gemini CLI", "binary": "gemini", "config": lambda h: h / ".gemini" / "settings.json",
45
+ "agent": "gemini", "integrations": ("gemini-hooks", "gemini-command")},
46
+ {"id": "agy", "label": "Antigravity (agy)", "binary": "agy", "config": lambda h: h / ".gemini" / "antigravity-cli",
47
+ "agent": "gemini", "integrations": ("agy-hooks", "agy-statusline")},
48
+ {"id": "devin", "label": "Devin CLI", "binary": "devin",
49
+ "config": lambda h: Path(destinations("devin", h)[0]["path"]).parent, "agent": "devin", "integrations": ("devin-hooks",)},
50
+ {"id": "uniflow", "label": "Uniflow", "binary": "uniflow", "config": uniflow_config_dir, "agent": "uniflow",
51
+ "integrations": ()},
52
+ {"id": "tmux", "label": "tmux", "binary": "tmux", "flag": "-V", "config": None, "agent": None,
53
+ "integrations": ("tmux-status",)},
54
+ )
55
+ AGENT_ORDER = ("claude", "codex", "gemini", "devin", "uniflow") # natives first: the uniflow notice sees them
56
+ GUIDE_WORDS = {"install": "aplicado", "update": "atualizado", "replace": "atualizado", "unchanged": "já em dia",
57
+ "uninstall": "removido", "remove": "removido"}
58
+ BAD_SKILL = ("modified", "missing", "unsafe", "external_link")
59
+ BAD_GUIDE = ("modified", "missing", "unsafe")
60
+ BAD_HOOKS = ("untrusted", "modified", "missing", "feature_off")
61
+ VERSION_TIMEOUT = 3
62
+
63
+
64
+ # --- detection -----------------------------------------------------------------------------
65
+
66
+ def probe_version(path, flag="--version"):
67
+ """First line of `<bin> --version`; None on any failure or timeout (fail-open)."""
68
+ try:
69
+ done = subprocess.run([path, flag], capture_output=True, text=True, timeout=VERSION_TIMEOUT,
70
+ stdin=subprocess.DEVNULL, errors="replace")
71
+ except (OSError, subprocess.SubprocessError, ValueError):
72
+ return None
73
+ for line in (done.stdout or "").splitlines() + (done.stderr or "").splitlines():
74
+ if line.strip():
75
+ return ui.clean(line.strip())[:80] if done.returncode == 0 else None
76
+ return None
77
+
78
+
79
+ def detect(home, probe=True):
80
+ home = Path(home)
81
+ rows = []
82
+ for cli in CLIS:
83
+ binary = shutil.which(cli["binary"])
84
+ config = cli["config"](home) if cli["config"] else None
85
+ try:
86
+ config_found = bool(config and config.exists())
87
+ except OSError:
88
+ config_found = False
89
+ rows.append({"id": cli["id"], "label": cli["label"], "agent": cli["agent"], "binary": binary,
90
+ "config": str(config) if config else None, "config_found": config_found,
91
+ "detected": bool(binary) or config_found, "version": None})
92
+ if probe:
93
+ found = [(r, CLIS[i].get("flag", "--version")) for i, r in enumerate(rows) if r["binary"]]
94
+ if found:
95
+ with ThreadPoolExecutor(max_workers=min(4, len(found))) as pool:
96
+ for row, version in zip([r for r, _ in found], pool.map(lambda p: probe_version(p[0]["binary"], p[1]), found)):
97
+ row["version"] = version
98
+ return rows
99
+
100
+
101
+ def wanted_agents(rows, only=None):
102
+ """Installer agents for the detected CLIs, optionally limited by --agents (CLI ids or installer agents)."""
103
+ allowed = None
104
+ if only:
105
+ allowed = set()
106
+ valid = {c["id"] for c in CLIS if c["agent"]} | set(AGENT_ORDER)
107
+ for name in (n.strip() for n in only.split(",") if n.strip()):
108
+ if name not in valid:
109
+ raise CrowError("unknown_agent", "Agente desconhecido para setup: " + name + ". Use: " +
110
+ ",".join(c["id"] for c in CLIS if c["agent"]) + ".")
111
+ allowed.add("gemini" if name == "agy" else name)
112
+ agents = {r["agent"] for r in rows if r["detected"] and r["agent"]}
113
+ return [a for a in AGENT_ORDER if a in agents and (allowed is None or a in allowed)]
114
+
115
+
116
+ # --- setup ---------------------------------------------------------------------------------
117
+
118
+ def catalog_names(args):
119
+ source = Source(getattr(args, "source", None) or _cli().DEFAULT_SOURCE, getattr(args, "ref", "HEAD"))
120
+ names = list(source.catalog)
121
+ group = getattr(args, "group", None)
122
+ if group is not None:
123
+ from . import groups as groups_mod
124
+ names = groups_mod.resolve(source, group)
125
+ if getattr(args, "skills", None) and group is not None:
126
+ chosen = [n.strip() for n in args.skills.split(",") if n.strip()]
127
+ for name in chosen:
128
+ source.require(name)
129
+ return source, list(dict.fromkeys(names + chosen))
130
+ if getattr(args, "skills", None):
131
+ chosen = [n.strip() for n in args.skills.split(",") if n.strip()]
132
+ for name in chosen:
133
+ source.require(name)
134
+ names = list(dict.fromkeys(chosen))
135
+ return source, names
136
+
137
+
138
+ def _cli():
139
+ from . import cli
140
+ return cli
141
+
142
+
143
+ def fix_for(code, agent):
144
+ hint = ui.FIXES.get(code)
145
+ if code == "local_changes":
146
+ return "crow-skills setup --agents " + agent + " --overwrite-modified --yes (substitui com backup)"
147
+ if code in ("unmanaged_conflict", "unmanaged_link"):
148
+ return "crow-skills setup --agents " + agent + " --replace --yes (substitui com backup)"
149
+ return hint
150
+
151
+
152
+ DISABLED_REASON = "desabilitada no Uniflow (SKILL.md.disabled no store); não conta como ativa"
153
+
154
+
155
+ def store_disabled(home, store):
156
+ """Names managed by crow-skills in the Uniflow store that Uniflow disabled (SKILL.md.disabled)."""
157
+ try:
158
+ return {r["name"] for r in store.status(destinations("uniflow", home), ()) if r["status"] == "disabled"}
159
+ except (CrowError, OSError):
160
+ return set()
161
+
162
+
163
+ def classify(store, target, names, agent, replace, overwrite, store_names=()):
164
+ """Split the requested skills into (to install, kept with the reason and fix, projected by Uniflow).
165
+
166
+ A skill Uniflow projects into this CLI (a link to its store) is installed for the CLI: its source of
167
+ truth is the store (--agents uniflow); the link is never followed, replaced or reported as an error."""
168
+ rows = {r["name"]: r for r in store.status([target], names) if r["name"]}
169
+ install, kept, via, waiting = [], [], [], []
170
+ # Uniflow already projects into this dir: what goes into its store arrives by the same projection on the
171
+ # CLI's next start; a native copy would shadow it. crow-behaviour stays native when absent (guide, hooks).
172
+ projected = any(r["status"] == "uniflow_link" for r in store.status([target], ()))
173
+ pending = set(store_names) if projected else set()
174
+ store_ok = guide.store_managed(store.home, store) if projected else set()
175
+ disabled = store_disabled(store.home, store) if projected else set()
176
+ for name in names:
177
+ row = rows.get(name) or {"status": "absent"}
178
+ status = row["status"]
179
+ if status == "uniflow_link" and name in store_ok:
180
+ via.append(name)
181
+ elif status == "uniflow_link" and name in disabled:
182
+ kept.append({"name": name, "status": "uniflow_link_disabled", "reason": DISABLED_REASON,
183
+ "fix": "reabilite a skill no Uniflow; o crow-skills mantém a desabilitação"})
184
+ elif status == "uniflow_link":
185
+ kept.append({"name": name, "status": "uniflow_link_unmanaged",
186
+ "reason": "link do Uniflow para um pacote do store que o crow-skills não gerencia; não conta como instalada",
187
+ "fix": "revise o store e, para gerenciá-lo com backup: crow-skills setup --agents uniflow --replace --yes"})
188
+ elif status == "absent" and name in pending and name != "crow-behaviour":
189
+ via.append(name)
190
+ waiting.append(name)
191
+ elif status in ("modified", "missing") and not overwrite:
192
+ kept.append({"name": name, "status": status, "reason": "editada localmente" if status == "modified" else "arquivos removidos",
193
+ "fix": "crow-skills setup --agents " + agent + " --overwrite-modified --yes"})
194
+ elif status == "unmanaged" and not replace:
195
+ kept.append({"name": name, "status": status, "reason": "já existe e não é gerenciada pelo crow-skills",
196
+ "fix": "crow-skills setup --agents " + agent + " --replace --yes"})
197
+ elif status == "external_link" and not replace and not store.managed_target(
198
+ os.path.realpath(Path(target["path"]) / name), name):
199
+ kept.append({"name": name, "status": status, "reason": "link do Uniflow para uma cópia não gerenciada",
200
+ "fix": "crow-skills setup --agents uniflow --replace --yes"})
201
+ elif status == "unsafe":
202
+ path = Path(target["path"]) / name
203
+ what = "é um link para " + os.path.realpath(path) if path.is_symlink() else "não é um diretório regular"
204
+ kept.append({"name": name, "status": status, "reason": str(path) + " " + what + "; não é lido nem substituído",
205
+ "fix": "remova ou troque você mesmo " + str(path) + " e rode crow-skills setup --yes de novo"})
206
+ else:
207
+ install.append(name)
208
+ return install, kept, via, waiting
209
+
210
+
211
+ def refresh_extras(agent, home, dry_run, trust=True, source=None, ref=None, replace=False, overwrite=False):
212
+ """Guide, integrations and hooks of an agent when no skill is (re)installed there, e.g. every crow
213
+ skill comes from Uniflow's projection. Same commands as guide/integrations install --global."""
214
+ cli = _cli()
215
+ out = {"guides": None, "integrations": None}
216
+ if agent not in guide.MECHANISMS or "crow-behaviour" not in guide.managed_skills(agent, home, Store(home)):
217
+ return out
218
+ mode = "--dry-run" if dry_run else "--yes"
219
+ argv = ["guide", "install", "--agents", agent, "--global", "--json", "--home", str(home), mode]
220
+ for flag, on in (("--replace", replace), ("--overwrite-modified", overwrite)):
221
+ if on:
222
+ argv.append(flag)
223
+ for flag, value in (("--source", source), ("--ref", ref)):
224
+ if value:
225
+ argv += [flag, value]
226
+ out["guides"] = cli.run(cli.parser().parse_args(argv))
227
+ argv = ["integrations", "install", "--agents", agent, "--global", "--json", "--home", str(home), mode]
228
+ if not trust:
229
+ argv.append("--no-trust")
230
+ out["integrations"] = cli.run(cli.parser().parse_args(argv))
231
+ return out
232
+
233
+
234
+ def configure_agent(args, home, store, agent, names, dry_run, store_names=()):
235
+ cli = _cli()
236
+ target = destinations(agent, home)[0]
237
+ entry = {"agent": agent, "target": target["path"], "changed": [], "unchanged": [], "kept": [], "via_uniflow": [],
238
+ "error": None, "guides": None, "integrations": None}
239
+ replace, overwrite = bool(getattr(args, "replace", False)), bool(getattr(args, "overwrite_modified", False))
240
+ try:
241
+ install, entry["kept"], entry["via_uniflow"], waiting = classify(store, target, names, agent, replace, overwrite,
242
+ store_names if agent != "uniflow" else ())
243
+ if waiting:
244
+ entry["via_uniflow_pending"] = waiting
245
+ if not install:
246
+ entry.update(refresh_extras(agent, home, dry_run, not getattr(args, "no_trust", False), getattr(args, "source", None),
247
+ getattr(args, "ref", None), replace, overwrite))
248
+ return entry
249
+ argv = ["install", *install, "--agents", agent, "--global", "--json", "--home", str(home),
250
+ "--dry-run" if dry_run else "--yes"]
251
+ for flag, on in (("--replace", replace), ("--overwrite-modified", overwrite), ("--no-trust", getattr(args, "no_trust", False))):
252
+ if on:
253
+ argv.append(flag)
254
+ for flag in ("source", "ref"):
255
+ if getattr(args, flag, None):
256
+ argv += ["--" + flag, getattr(args, flag)]
257
+ data = cli.run(cli.parser().parse_args(argv))
258
+ except CrowError as exc:
259
+ entry["error"] = {"code": exc.code, "message": str(exc), "fix": fix_for(exc.code, agent)}
260
+ return entry
261
+ except (OSError, ValueError, KeyError, TypeError):
262
+ entry["error"] = {"code": "io_error", "message": "Falha de leitura/gravação; nada concluído para este agente.",
263
+ "fix": "crow-skills doctor"}
264
+ return entry
265
+ for change in data["changes"]:
266
+ (entry["unchanged"] if change["action"] == "unchanged" else entry["changed"]).append(change["name"])
267
+ entry["guides"] = data.get("guides")
268
+ entry["integrations"] = data.get("integrations")
269
+ entry["transaction"] = data.get("transaction")
270
+ if data.get("uniflow"):
271
+ entry["uniflow"] = data["uniflow"]
272
+ return entry
273
+
274
+
275
+ def machine_steps(args, home, store, dry_run):
276
+ steps = {}
277
+ # Crow mode: written as on only when the user never chose (no mode file).
278
+ current = hook.read_mode(home)
279
+ if current["source"] == "file":
280
+ steps["mode"] = {"state": "ok", "action": "unchanged", "mode": current["mode"],
281
+ "note": "modo já escolhido (" + current["mode"] + "); mantido"}
282
+ elif dry_run:
283
+ steps["mode"] = {"state": "plan", "action": "install", "mode": "on", "note": "gravar modo crow on"}
284
+ else:
285
+ hook.write_mode(home, "on", "setup")
286
+ steps["mode"] = {"state": "ok", "action": "install", "mode": "on", "note": "modo crow on gravado"}
287
+ # Autoupdate.
288
+ if getattr(args, "no_autoupdate", False):
289
+ steps["autoupdate"] = {"state": "skip", "action": "skip", "note": "--no-autoupdate: não alterado"}
290
+ else:
291
+ try:
292
+ status = autoupdate.status(store, home)
293
+ if status["enabled"] and all(f["status"] == "installed" for f in status["files"]):
294
+ steps["autoupdate"] = {"state": "ok", "action": "unchanged", "note": "já ligado"}
295
+ else:
296
+ preview = autoupdate.turn_on(store, home, dry_run=True)
297
+ if dry_run:
298
+ steps["autoupdate"] = {"state": "plan", "action": "install", "note": "ligar (diário e no login)",
299
+ "changes": preview["changes"]}
300
+ else:
301
+ done = autoupdate.turn_on(store, home)
302
+ steps["autoupdate"] = {"state": "ok" if done.get("activated") or not autoupdate.real_home(home) else "warn",
303
+ "action": "install", "note": done.get("note") or "ligado (diário e no login)",
304
+ "changes": done["changes"]}
305
+ except CrowError as exc:
306
+ steps["autoupdate"] = {"state": "warn", "action": "skip", "note": str(exc), "code": exc.code,
307
+ "fix": ui.FIXES.get(exc.code) or "crow-skills autoupdate on --yes"}
308
+ # Broadcast is on by default; a user's broadcast.json is never rewritten.
309
+ cfg = broadcast.config(home)
310
+ if cfg["enabled"]:
311
+ steps["broadcast"] = {"state": "ok", "action": "unchanged",
312
+ "note": "ligado (padrão)" if not broadcast.config_path(home).exists() else "ligado (broadcast.json)"}
313
+ else:
314
+ steps["broadcast"] = {"state": "warn", "action": "unchanged",
315
+ "note": "desligado em " + str(broadcast.config_path(home)) + " (escolha do usuário; mantido)"}
316
+ # Resources: report only; nothing to write when the defaults apply.
317
+ config = resources.load_config(home)
318
+ errors = config.get("errors") if isinstance(config, dict) else None
319
+ steps["resources"] = {"state": "warn" if errors else "ok", "action": "unchanged",
320
+ "note": ("; ".join(errors) if errors else
321
+ "padrões" if not resources.config_path(home).exists() else "resources.json do usuário")}
322
+ return steps
323
+
324
+
325
+ def integration_rows(store, home, probe):
326
+ try:
327
+ return {r["integration"]: r for r in integrations.status(store, home, probe=probe)}
328
+ except (CrowError, OSError):
329
+ return {}
330
+
331
+
332
+ NO_TRUST_FIX = ("hooks gravados sem aprovação (--no-trust); aprove no próprio CLI (no Codex: /hooks) "
333
+ "ou rode crow-skills setup --yes sem --no-trust")
334
+
335
+
336
+ def hooks_state(cli, rows, trust=True):
337
+ """(state, text, fix) of this CLI's crow hooks. With --no-trust an unapproved hook is expected: a warning."""
338
+ for name in cli["integrations"]:
339
+ if not name.endswith("-hooks"):
340
+ continue
341
+ row = rows.get(name)
342
+ if not row or row.get("status") != "installed":
343
+ return "absent", "não instalados", None
344
+ enabled = row.get("enabled") or {}
345
+ state = enabled.get("state")
346
+ if state in (None, "trusted", "not_required"):
347
+ return "ok", "sim", None
348
+ reason = ui.word(state)
349
+ if not trust and state == "untrusted":
350
+ return "warn", "não (" + reason + ")", NO_TRUST_FIX
351
+ return ("fail" if state in BAD_HOOKS else "warn"), "não (" + reason + ")", enabled.get("fix")
352
+ return "none", "—", None
353
+
354
+
355
+ def agent_health(store, home, agent):
356
+ """Doctor-level problems of one installer agent, after the fact."""
357
+ problems = []
358
+ target = destinations(agent, home)[0]
359
+ try:
360
+ for row in store.status([target]):
361
+ if row["status"] in BAD_SKILL:
362
+ problems.append((row["name"] or target["path"]) + ": " + row["status"])
363
+ except (CrowError, OSError) as exc:
364
+ problems.append(str(exc) or "destino ilegível")
365
+ if agent in guide.MECHANISMS:
366
+ for row in guide.status(store, home, [agent]):
367
+ if row["status"] in BAD_GUIDE:
368
+ problems.append("guia: " + row["status"])
369
+ return problems
370
+
371
+
372
+ def real_changes(report):
373
+ """Change entries that change something (sync and guide plans also list "unchanged" ones)."""
374
+ return [c for c in ((report or {}).get("changes") or []) if c.get("action") != "unchanged"]
375
+
376
+
377
+ def summarize(detected, entries, store, home, probe, dry_run, trust=True):
378
+ rows = integration_rows(store, home, probe)
379
+ by_agent = {e["agent"]: e for e in entries}
380
+ summary = []
381
+ for row in detected:
382
+ cli = next(c for c in CLIS if c["id"] == row["id"])
383
+ item = {"cli": row["id"], "label": row["label"], "version": row["version"], "detected": row["detected"], "notes": []}
384
+ if not row["detected"]:
385
+ item.update(state="skip", skills="—", guide="—", hooks="—")
386
+ item["notes"].append("não encontrado (nem binário no PATH nem configuração)")
387
+ summary.append(item)
388
+ continue
389
+ if cli["agent"] is None: # tmux
390
+ tmux = rows.get("tmux-status") or {}
391
+ item.update(state="ok" if tmux.get("status") == "installed" else "warn", skills="—", guide="—",
392
+ hooks="segmento " + ("instalado" if tmux.get("status") == "installed" else "não instalado"))
393
+ if tmux.get("status") != "installed":
394
+ item["notes"].append("o segmento entra quando o tmux tem ~/.tmux.conf e algum agente tem a crow-behaviour")
395
+ summary.append(item)
396
+ continue
397
+ entry = by_agent.get(cli["agent"])
398
+ if entry is None:
399
+ item.update(state="skip", skills="—", guide="—", hooks="—")
400
+ item["notes"].append("fora do filtro --agents")
401
+ summary.append(item)
402
+ continue
403
+ changed, unchanged, kept = len(entry["changed"]), len(entry["unchanged"]), entry["kept"]
404
+ verb = "a instalar/atualizar" if dry_run else "instaladas/atualizadas"
405
+ parts = []
406
+ if changed:
407
+ parts.append(str(changed) + " " + verb)
408
+ if unchanged:
409
+ parts.append(str(unchanged) + " já em dia")
410
+ if entry.get("via_uniflow"):
411
+ parts.append(str(len(entry["via_uniflow"])) + " via uniflow")
412
+ if kept:
413
+ parts.append(str(len(kept)) + " mantidas")
414
+ item["skills"] = ", ".join(parts) or "—"
415
+ guides = entry.get("guides") or {}
416
+ guide_change = next((c for c in guides.get("changes", []) if c.get("agent") == cli["agent"]), None)
417
+ guide_skip = next((s for s in guides.get("skipped", []) if s.get("agent") == cli["agent"]), None)
418
+ if cli["agent"] == "uniflow":
419
+ item["guide"] = "não se aplica"
420
+ elif guide_change:
421
+ item["guide"] = GUIDE_WORDS.get(guide_change.get("action"), guide_change.get("action", "?"))
422
+ elif guide_skip:
423
+ item["guide"] = "não aplicado"
424
+ item["notes"].append("guia: " + guide_skip["reason"])
425
+ elif cli["agent"] not in guide.MECHANISMS:
426
+ item["guide"] = "—"
427
+ else:
428
+ try:
429
+ current = guide.status(store, home, [cli["agent"]])[0]["status"]
430
+ except (CrowError, OSError, IndexError):
431
+ current = "unsafe"
432
+ item["guide"] = {"installed": "já em dia", "absent": "—"}.get(current, ui.word(current))
433
+ state, hooks_text, fix = hooks_state(cli, rows, trust) if not dry_run else ("none", "—", None)
434
+ if dry_run and cli["integrations"]:
435
+ planned = [c["integration"] for c in real_changes(entry.get("integrations"))
436
+ if c["integration"] in cli["integrations"]]
437
+ hooks_text = ("a aplicar: " + ", ".join(planned)) if planned else "sem mudança"
438
+ item["hooks"] = hooks_text
439
+ for skip in (entry.get("integrations") or {}).get("skipped", []):
440
+ if skip.get("integration") in cli["integrations"] and not ((fix or not trust) and skip["integration"].endswith("-trust")):
441
+ item["notes"].append(skip["integration"] + ": " + skip["reason"])
442
+ if fix:
443
+ item["notes"].append("hooks: " + fix)
444
+ for k in kept:
445
+ item["notes"].append(k["name"] + " mantida (" + k["reason"] + "): " + k["fix"])
446
+ if entry.get("via_uniflow_pending"):
447
+ item["notes"].append(", ".join(entry["via_uniflow_pending"]) + ": vai para o store do Uniflow e aparece neste CLI no "
448
+ "próximo início pelo Uniflow (sem cópia nativa, para não sombrear o store)")
449
+ for dup in (entry.get("uniflow") or {}).get("native_duplicates") or []:
450
+ names_ = ", ".join(sk["name"] for sk in dup["skills"])
451
+ effect = ("o Codex vê as duas cópias" if dup.get("effect") == "both" else
452
+ "o Uniflow não liga esse nome e a cópia nativa vale ali")
453
+ item["notes"].append("cópia física em " + ",".join(dup["agents"]) + " (" + dup["target"] + ") de " + names_ +
454
+ ", que o store também tem: " + effect + " (links do Uniflow não contam)")
455
+ for command in (entry.get("uniflow") or {}).get("suggested_commands") or []:
456
+ item["notes"].append("para usar só o store: " + command + " --yes" +
457
+ (" (sem a cópia nativa da crow-behaviour, o guia daquele agente sai até o Uniflow ligar o store)"
458
+ if " crow-behaviour " in command else ""))
459
+ problems = [] if dry_run else agent_health(store, home, cli["agent"])
460
+ if entry["error"]:
461
+ item["state"] = "fail"
462
+ item["notes"].insert(0, entry["error"]["message"] + (" Para corrigir: " + entry["error"]["fix"] if entry["error"].get("fix") else ""))
463
+ elif problems or state == "fail":
464
+ item["state"] = "fail"
465
+ item["notes"] += problems
466
+ elif kept or state in ("warn", "absent"):
467
+ item["state"] = "warn"
468
+ else:
469
+ item["state"] = "plan" if dry_run and (entry["changed"] or real_changes(entry.get("integrations"))) else "ok"
470
+ summary.append(item)
471
+ return summary
472
+
473
+
474
+ def setup(args, home, store, interactive):
475
+ if getattr(args, "project", None) or getattr(args, "dest", None):
476
+ raise CrowError("usage", "setup configura só o escopo do usuário; não use --project nem --dest.")
477
+ dry_run = bool(getattr(args, "dry_run", False))
478
+ detected = detect(home, probe=not getattr(args, "no_probe", False))
479
+ agents = wanted_agents(detected, getattr(args, "agents", None))
480
+ source, names = catalog_names(args)
481
+
482
+ def build(dry):
483
+ # The Uniflow store goes first: a name is left to its projection only if the store really has it
484
+ # (installed, updated or already there); kept or failed names are installed natively.
485
+ entries = {}
486
+ store_names = ()
487
+ if "uniflow" in agents:
488
+ entries["uniflow"] = configure_agent(args, home, store, "uniflow", names, dry)
489
+ if not entries["uniflow"]["error"]:
490
+ store_names = tuple(entries["uniflow"]["changed"]) + tuple(entries["uniflow"]["unchanged"])
491
+ for agent in agents:
492
+ if agent != "uniflow":
493
+ entries[agent] = configure_agent(args, home, store, agent, names, dry, store_names)
494
+ entries = [entries[a] for a in agents]
495
+ return entries, machine_steps(args, home, store, dry)
496
+
497
+ entries, steps = build(True)
498
+ result = {"version": __version__, "revision": source.revision, "skills": names, "detected": detected, "agents": agents,
499
+ "absent": [r["id"] for r in detected if not r["detected"]], "trust": not getattr(args, "no_trust", False)}
500
+ pending = any(e["changed"] or real_changes(e.get("integrations")) or real_changes(e.get("guides"))
501
+ for e in entries) or any(s["state"] == "plan" for s in steps.values())
502
+ if dry_run or not agents:
503
+ summary = summarize(detected, entries, store, home, False, True)
504
+ return dict(result, entries=entries, machine=steps if agents else {}, summary=summary, dry_run=dry_run, applied=False,
505
+ healthy=not any(e["error"] for e in entries), nothing_detected=not agents)
506
+ if pending and not getattr(args, "yes", False):
507
+ if not interactive:
508
+ raise CrowError("confirmation_required", "setup altera a configuração dos CLIs; use --yes para aplicar ou --dry-run para ver o plano.")
509
+ print(render_setup(dict(result, entries=entries, machine=steps, dry_run=True,
510
+ summary=summarize(detected, entries, store, home, False, True)), sys.stderr), file=sys.stderr)
511
+ if _cli().prompt("Aplicar este plano? [s/N]").lower() not in ("s", "sim", "y", "yes"):
512
+ raise CrowError("cancelled", "Setup cancelado; nada foi alterado.")
513
+ entries, steps = build(False)
514
+ trust = not getattr(args, "no_trust", False)
515
+ summary = summarize(detected, entries, store, home, not getattr(args, "no_probe", False), False, trust)
516
+ try:
517
+ doctor = _cli().run(_cli().parser().parse_args(["doctor", "--json", "--home", str(home)]))
518
+ reasons = doctor_reasons(doctor, trust)
519
+ doctor_view = {"healthy": doctor.get("healthy"), "pending_transactions": doctor.get("pending_transactions"),
520
+ "reasons": reasons}
521
+ except (CrowError, OSError, ValueError, KeyError, TypeError) as exc:
522
+ reasons = [str(exc) or "doctor falhou"]
523
+ doctor_view = {"healthy": False, "error": reasons[0], "reasons": reasons}
524
+ healthy = all(s["state"] != "fail" for s in summary) and not reasons
525
+ return dict(result, entries=entries, machine=steps, summary=summary, doctor=doctor_view, dry_run=False, applied=True,
526
+ healthy=healthy)
527
+
528
+
529
+ def doctor_reasons(doctor, trust=True):
530
+ """Why the doctor is unhealthy, in the doctor's own terms. With --no-trust, unapproved hooks are expected."""
531
+ reasons = []
532
+ if doctor.get("pending_transactions"):
533
+ reasons.append("transação pendente: crow-skills recover --yes")
534
+ for row in doctor.get("installations") or []:
535
+ if row.get("status") in BAD_SKILL:
536
+ reasons.append(",".join(row.get("agents") or []) + ": " + str(row.get("name") or row.get("target")) + " " +
537
+ ui.word(row["status"]))
538
+ for row in doctor.get("guides") or []:
539
+ if row.get("status") in BAD_GUIDE:
540
+ reasons.append("guia " + str(row.get("agent")) + ": " + ui.word(row["status"]))
541
+ auto = doctor.get("autoupdate") or {}
542
+ if auto.get("healthy") is False:
543
+ last = auto.get("lastRun") or {}
544
+ reasons.append("autoupdate: " + ("a última execução falhou (crow-skills autoupdate status)" if last and not last.get("ok")
545
+ else "agendador alterado ou removido (crow-skills autoupdate on --yes)"))
546
+ for hook_row in doctor.get("hooks") or []:
547
+ if hook_row.get("state") in BAD_HOOKS and not (not trust and hook_row["state"] == "untrusted"):
548
+ reasons.append(hook_row["integration"] + ": " + ui.word(hook_row["state"]) +
549
+ (" (" + hook_row["fix"] + ")" if hook_row.get("fix") else ""))
550
+ if doctor.get("healthy") is False and not reasons and trust:
551
+ reasons.append("doctor não saudável (crow-skills doctor)")
552
+ return reasons
553
+
554
+
555
+ # --- upgrade -------------------------------------------------------------------------------
556
+
557
+ AGENT_LABELS = {"claude": "Claude Code", "codex": "Codex CLI", "gemini": "Gemini CLI / Antigravity", "devin": "Devin CLI",
558
+ "uniflow": "Uniflow"}
559
+
560
+
561
+ def upgrade_summary(skills, dry_run):
562
+ rows = []
563
+ for s in skills:
564
+ agent = s["agent"]
565
+ item = {"agent": agent, "label": AGENT_LABELS.get(agent, agent), "changed": s.get("updated") or [],
566
+ "unchanged": s.get("unchanged", 0), "kept": s.get("kept") or [], "via_uniflow": len(s.get("via_uniflow") or []),
567
+ "needs_user": []}
568
+ for k in item["kept"]:
569
+ if k["status"] in ("modified", "missing"):
570
+ item["needs_user"].append(k["name"] + " editada localmente; para substituir com backup: crow-skills update " +
571
+ k["name"] + " --agents " + agent + " --global --overwrite-modified --yes")
572
+ elif k["status"] == "other_origin":
573
+ item["needs_user"].append(k["name"] + " instalada de outra origem; para trocar: crow-skills install " +
574
+ k["name"] + " --agents " + agent + " --global --yes")
575
+ else:
576
+ item["needs_user"].append(k["name"] + ": " + k["status"])
577
+ if s.get("error"):
578
+ item["needs_user"].insert(0, s["error"]["message"])
579
+ item["state"] = "fail" if s.get("error") else ("warn" if item["needs_user"] else ("plan" if dry_run and item["changed"] else "ok"))
580
+ rows.append(item)
581
+ return rows
582
+
583
+
584
+ def upgrade(args, home, store, interactive):
585
+ self_step = not (getattr(args, "skills_only", False) or getattr(args, "no_self", False))
586
+ trust = not getattr(args, "no_trust", False)
587
+ git_pull = True if getattr(args, "git_pull", False) else None
588
+ preview = autoupdate.preview(store, home, self_step=self_step, trust=trust, git_pull=git_pull)
589
+ if getattr(args, "dry_run", False):
590
+ return dict(preview, summary=upgrade_summary(preview.get("skills", []), True), healthy=True)
591
+ if not getattr(args, "yes", False):
592
+ if not interactive:
593
+ raise CrowError("confirmation_required", "upgrade atualiza o crow-skills e a configuração dos CLIs; use --yes para aplicar "
594
+ "ou --dry-run para ver o plano.")
595
+ print(render_upgrade(dict(preview, summary=upgrade_summary(preview.get("skills", []), True)), sys.stderr), file=sys.stderr)
596
+ if _cli().prompt("Aplicar? [s/N]").lower() not in ("s", "sim", "y", "yes"):
597
+ raise CrowError("cancelled", "Upgrade cancelado; nada foi alterado.")
598
+ done = autoupdate.run(store, home, self_step=self_step, trust=trust, git_pull=git_pull, trigger="upgrade")
599
+ last = done["lastRun"]
600
+ return dict(done, summary=upgrade_summary(last.get("skills", []), False), healthy=bool(last.get("ok")), dry_run=False)
601
+
602
+
603
+ # --- bare invocation -----------------------------------------------------------------------
604
+
605
+ def configured_agents(home):
606
+ store = Store(home)
607
+ found = []
608
+ for agent in AGENT_ORDER:
609
+ try:
610
+ if store.state(destinations(agent, home)[0]["path"])["installed"]:
611
+ found.append(agent)
612
+ except (CrowError, OSError, ValueError, KeyError):
613
+ continue
614
+ return found
615
+
616
+
617
+ def status_line(home, stream=None):
618
+ try:
619
+ mode = hook.read_mode(home)["mode"]
620
+ except (OSError, ValueError):
621
+ mode = "?"
622
+ agents = configured_agents(home)
623
+ text = hook.indicator(mode, ui.unicode_on(stream)) + " · "
624
+ if agents:
625
+ text += str(len(agents)) + " agente(s) configurado(s): " + ", ".join(agents)
626
+ else:
627
+ text += "nenhum agente configurado; comece com: crow-skills setup --yes"
628
+ return text, {"mode": mode, "agents": agents, "version": __version__}
629
+
630
+
631
+ # --- rendering -----------------------------------------------------------------------------
632
+
633
+ STATE_MARK = {"ok": "ok", "fail": "fail", "warn": "warn", "skip": "skip", "plan": "plan"}
634
+
635
+
636
+ def render_setup(data, stream=None):
637
+ stream = stream or sys.stdout
638
+ lines = []
639
+ title = "crow-skills setup" + (" (prévia; nada gravado)" if data.get("dry_run") else "")
640
+ lines.append(ui.paint(title, "bold", stream) + " · " + str(len(data["skills"])) + " skills · revisão " +
641
+ str(data.get("revision", ""))[:12])
642
+ lines.append("")
643
+ rows = []
644
+ for item in data["summary"]:
645
+ rows.append([ui.mark(STATE_MARK[item["state"]], stream), item["label"], item.get("version") or "—", item["skills"],
646
+ item["guide"], item["hooks"]])
647
+ lines += ui.table(rows, ["", "CLI", "versão", "skills", "guia", "integrações" if data.get("dry_run") else "hooks habilitados"], stream)
648
+ notes = [(i["label"], n) for i in data["summary"] for n in i["notes"] if i["detected"] or i["state"] != "skip"]
649
+ if notes:
650
+ lines.append("")
651
+ for label, note in notes:
652
+ lines.append(" " + ui.mark("warn", stream) + " " + label + ": " + ui.clean(note))
653
+ machine = data.get("machine") or {}
654
+ if machine:
655
+ lines.append("")
656
+ names = {"mode": "modo crow", "autoupdate": "autoupdate", "broadcast": "broadcast", "resources": "recursos"}
657
+ lines += ui.table([[ui.mark(STATE_MARK.get(s["state"], "ok"), stream), names[k], ui.clean(s["note"]) +
658
+ (" — " + s["fix"] if s.get("fix") else "")] for k, s in machine.items()], stream=stream)
659
+ doctor_reasons_ = (data.get("doctor") or {}).get("reasons") or []
660
+ if doctor_reasons_:
661
+ lines += ["", ui.mark("fail", stream) + " doctor:"]
662
+ lines += [" " + ui.clean(r) for r in doctor_reasons_]
663
+ absent = [i["label"] for i in data["summary"] if not i["detected"]]
664
+ if absent:
665
+ lines += ["", " Não encontrados (pulados): " + ", ".join(absent)]
666
+ lines.append("")
667
+ if data.get("nothing_detected"):
668
+ lines.append(ui.mark("warn", stream) + " Nenhum CLI de agente encontrado. Instale um (claude, codex, gemini, agy, devin, "
669
+ "uniflow) e rode crow-skills setup de novo.")
670
+ elif data.get("dry_run"):
671
+ lines.append("Para aplicar: crow-skills setup --yes")
672
+ elif data.get("healthy"):
673
+ lines.append(ui.mark("ok", stream) + " Tudo configurado. Abra uma sessão nova de cada CLI para carregar.")
674
+ else:
675
+ lines.append(ui.mark("fail", stream) + " Algum CLI precisa de atenção (veja acima); depois rode crow-skills setup --yes de novo.")
676
+ return "\n".join(lines)
677
+
678
+
679
+ def render_upgrade(data, stream=None):
680
+ stream = stream or sys.stdout
681
+ dry = data.get("dry_run")
682
+ last = data.get("lastRun") or {}
683
+ lines = [ui.paint("crow-skills upgrade" + (" (prévia; nada executado)" if dry else ""), "bold", stream), ""]
684
+ me = data.get("self") if dry else last.get("self")
685
+ if me:
686
+ result = me.get("result")
687
+ if result == "would_run":
688
+ lines.append(" " + ui.mark("plan", stream) + " crow-skills " + __version__ + ": rodaria " + " ".join(me.get("command") or []))
689
+ elif result == "ok":
690
+ after = me.get("after")
691
+ lines.append(" " + ui.mark("ok", stream) + " crow-skills " + str(me.get("before")) +
692
+ (" → " + str(after) if after and after != me.get("before") else " (já na versão mais nova)"))
693
+ elif result == "failed":
694
+ lines.append(" " + ui.mark("fail", stream) + " self-upgrade falhou (" + me.get("kind", "?") + ", código " +
695
+ str(me.get("exitCode")) + "); tente de novo ou atualize pelo gerenciador de pacotes")
696
+ else:
697
+ lines.append(" " + ui.mark("skip", stream) + " self-upgrade pulado: " + str(me.get("reason")))
698
+ rows = []
699
+ for item in data.get("summary", []):
700
+ changed = ", ".join(item["changed"]) if len(item["changed"]) <= 3 else str(len(item["changed"])) + " skills"
701
+ rows.append([ui.mark(STATE_MARK[item["state"]], stream), item["label"],
702
+ (("a atualizar: " if dry else "atualizadas: ") + changed) if changed else "sem mudanças",
703
+ str(item["unchanged"]), str(item.get("via_uniflow", 0)), str(len(item["kept"]))])
704
+ if rows:
705
+ lines.append("")
706
+ lines += ui.table(rows, ["", "CLI", "mudanças", "em dia", "via uniflow", "mantidas"], stream)
707
+ elif not data.get("handoff"):
708
+ lines += ["", " Nenhum agente com skills gerenciadas; comece com: crow-skills setup --yes"]
709
+ needs = [(i["label"], n) for i in data.get("summary", []) for n in i["needs_user"]]
710
+ if needs:
711
+ lines += ["", "Precisa de você:"]
712
+ lines += [" " + ui.mark("warn", stream) + " " + label + ": " + ui.clean(n) for label, n in needs]
713
+ lines.append("")
714
+ if dry:
715
+ lines.append("Para aplicar: crow-skills upgrade --yes")
716
+ elif data.get("healthy"):
717
+ lines.append(ui.mark("ok", stream) + " Atualizado. Sessões abertas carregam as mudanças ao reiniciar.")
718
+ else:
719
+ lines.append(ui.mark("fail", stream) + " Upgrade com falhas (veja acima). Detalhes: crow-skills autoupdate status")
720
+ return "\n".join(lines)