@andespindola/crow-skills 0.10.1 → 0.11.1
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/README.md +16 -2
- package/catalog.json +24 -0
- package/crow_skills/__init__.py +1 -1
- package/crow_skills/autoupdate.py +144 -10
- package/crow_skills/cli.py +439 -62
- package/crow_skills/groups.py +76 -0
- package/crow_skills/guide.py +37 -2
- package/crow_skills/integrations.py +188 -13
- package/crow_skills/machine.py +795 -0
- package/crow_skills/projection.py +128 -0
- package/crow_skills/trust.py +437 -0
- package/crow_skills/ui.py +198 -0
- package/docs/cli.md +84 -8
- package/package.json +1 -1
- package/release.json +36 -11
package/crow_skills/cli.py
CHANGED
|
@@ -9,22 +9,100 @@ from . import __version__
|
|
|
9
9
|
from . import autoupdate
|
|
10
10
|
from . import broadcast
|
|
11
11
|
from . import events
|
|
12
|
+
from . import groups as groups_mod
|
|
12
13
|
from . import guide
|
|
13
14
|
from . import hook
|
|
14
15
|
from . import integrations
|
|
15
16
|
from . import progress
|
|
17
|
+
from . import projection
|
|
16
18
|
from . import resources
|
|
19
|
+
from . import machine
|
|
20
|
+
from . import ui
|
|
17
21
|
from .agents import AGENTS, destinations, inventory
|
|
18
22
|
from .source import CrowError, Source, valid_name
|
|
19
23
|
from .storage import Store, checked
|
|
20
24
|
|
|
21
25
|
DEFAULT_SOURCE = Path(__file__).resolve().parents[1]
|
|
22
|
-
MUTATIONS = {"install", "update", "uninstall", "rollback", "recover", "guide", "integrations", "mode", "autoupdate"}
|
|
26
|
+
MUTATIONS = {"install", "update", "uninstall", "rollback", "recover", "guide", "integrations", "mode", "autoupdate", "setup", "upgrade"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
TRUST_HELP = "Não habilitar/aprovar os hooks do crow-skills nos CLIs (padrão: habilita)"
|
|
30
|
+
|
|
31
|
+
# Per-command help: what it is for and real examples (crow-skills help <cmd> or <cmd> --help).
|
|
32
|
+
COMMANDS = {
|
|
33
|
+
"setup": ("Detecta os CLIs de agente desta máquina (Claude Code, Codex, Gemini CLI, Antigravity, Devin, Uniflow, tmux) e "
|
|
34
|
+
"configura cada um no escopo do usuário: todas as skills do catálogo, guia, integrações, hooks do modo crow "
|
|
35
|
+
"habilitados, modo crow e autoupdate. Rodar de novo só corrige o que mudou.",
|
|
36
|
+
["crow-skills setup --dry-run", "crow-skills setup --yes", "crow-skills setup --agents claude,codex --yes",
|
|
37
|
+
"crow-skills setup --skills crow-behaviour,crow-debug --no-autoupdate --yes"]),
|
|
38
|
+
"upgrade": ("Atualiza o próprio crow-skills (Homebrew, npm ou checkout git) e, em seguida, skills, guias, integrações e "
|
|
39
|
+
"hooks de todo agente configurado. Skills editadas localmente nunca são sobrescritas.",
|
|
40
|
+
["crow-skills upgrade --dry-run", "crow-skills upgrade --yes", "crow-skills upgrade --skills-only --yes"]),
|
|
41
|
+
"help": ("Ajuda curta, por tarefa; help <comando> detalha um comando e help flags lista as flags globais.",
|
|
42
|
+
["crow-skills help", "crow-skills help setup", "crow-skills help flags"]),
|
|
43
|
+
"list": ("Lista o catálogo de skills da fonte atual.", ["crow-skills list", "crow-skills list --json"]),
|
|
44
|
+
"groups": ("Grupos de skills pré-definidos no catálogo, para install --group e setup --group (todas = o catálogo inteiro; "
|
|
45
|
+
"a crow-behaviour entra com qualquer grupo).", ["crow-skills groups", "crow-skills groups --json"]),
|
|
46
|
+
"agents": ("Agentes detectados (PATH e diretórios); não prova que as skills carregam.", ["crow-skills agents --json"]),
|
|
47
|
+
"status": ("Instalações, guias, integrações, modo e autoupdate, por agente.", ["crow-skills status", "crow-skills status --agents claude"]),
|
|
48
|
+
"doctor": ("Como status, com healthy true/false: skills editadas/ausentes, guia alterado, hooks não aprovados, transação pendente.",
|
|
49
|
+
["crow-skills doctor", "crow-skills doctor --json"]),
|
|
50
|
+
"info": ("Detalhes de uma skill do catálogo.", ["crow-skills info crow-backend"]),
|
|
51
|
+
"related": ("Handoffs, overlays e disponibilidade de complementos de uma skill.", ["crow-skills related crow-backend --agents claude --global"]),
|
|
52
|
+
"install": ("Instala skills escolhidas em agentes e escopo explícitos, com preview, backup e transação.",
|
|
53
|
+
["crow-skills install crow-behaviour --agents claude,codex --global --dry-run",
|
|
54
|
+
"crow-skills install --group essencial --agents claude --global --yes",
|
|
55
|
+
"crow-skills install --group web,qualidade --agents codex --global --yes",
|
|
56
|
+
"crow-skills install --all --agents claude --global --yes",
|
|
57
|
+
"crow-skills install crow-debug --agents gemini --project . --yes"]),
|
|
58
|
+
"update": ("Atualiza skills gerenciadas para a revisão da fonte atual (sem self-upgrade; para tudo, use upgrade).",
|
|
59
|
+
["crow-skills update --all --agents claude --global --yes", "crow-skills update crow-debug --agents codex --global --dry-run"]),
|
|
60
|
+
"uninstall": ("Remove skills gerenciadas, com backup; edições locais exigem --overwrite-modified.",
|
|
61
|
+
["crow-skills uninstall crow-debug --agents claude --global --yes"]),
|
|
62
|
+
"guide": ("Instruções gerenciadas para o agente usar as skills (só --global).",
|
|
63
|
+
["crow-skills guide status", "crow-skills guide install --agents claude --global --yes"]),
|
|
64
|
+
"integrations": ("Status lines, hooks do modo crow, comando /crow e segmento tmux (só --global).",
|
|
65
|
+
["crow-skills integrations status", "crow-skills integrations install --global --yes"]),
|
|
66
|
+
"progress": ("Painel de progresso da execução crow-behaviour (ledger, barras, tokens).",
|
|
67
|
+
["crow-skills progress", "crow-skills progress --watch"]),
|
|
68
|
+
"mode": ("Liga/desliga a crow-behaviour em todas as sessões e CLIs, a partir do próximo prompt.",
|
|
69
|
+
["crow-skills mode", "crow-skills mode off", "crow-skills mode on"]),
|
|
70
|
+
"events": ("Barramento de eventos dos hooks (crow-event/1) para terminais.",
|
|
71
|
+
["crow-skills events", "crow-skills events tail --limit 20", "crow-skills events tail --follow"]),
|
|
72
|
+
"broadcast": ("Sessões vivas dos CLIs, arquivos em edição, conflitos e reservas.",
|
|
73
|
+
["crow-skills broadcast", "crow-skills broadcast claim src/api --ttl 30m", "crow-skills broadcast release --all"]),
|
|
74
|
+
"resources": ("Memória, pressão, agentes em execução e paralelismo recomendado (somente leitura).",
|
|
75
|
+
["crow-skills resources", "crow-skills resources --exec-prefix"]),
|
|
76
|
+
"autoupdate": ("Agenda a atualização diária e no login (o mesmo fluxo de upgrade) ou roda agora.",
|
|
77
|
+
["crow-skills autoupdate on --yes", "crow-skills autoupdate status", "crow-skills autoupdate run --yes"]),
|
|
78
|
+
"rollback": ("Desfaz uma transação concluída (skills e o guia ligado a ela).", ["crow-skills rollback --transaction <id> --yes"]),
|
|
79
|
+
"recover": ("Conclui ou desfaz uma transação interrompida.", ["crow-skills recover --dry-run", "crow-skills recover --yes"]),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Formatter(argparse.RawDescriptionHelpFormatter):
|
|
84
|
+
def add_usage(self, usage, actions, groups, prefix=None):
|
|
85
|
+
return super().add_usage(usage, actions, groups, "uso: " if prefix is None else prefix)
|
|
23
86
|
|
|
24
87
|
|
|
25
88
|
class Parser(argparse.ArgumentParser):
|
|
89
|
+
def __init__(self, *args, **kwargs):
|
|
90
|
+
kwargs.setdefault("formatter_class", Formatter)
|
|
91
|
+
super().__init__(*args, **kwargs)
|
|
92
|
+
self._positionals.title = "argumentos"
|
|
93
|
+
self._optionals.title = "opções"
|
|
94
|
+
for action in self._actions:
|
|
95
|
+
if isinstance(action, argparse._HelpAction):
|
|
96
|
+
action.help = "Mostra esta ajuda e sai"
|
|
97
|
+
|
|
26
98
|
def error(self, message):
|
|
27
|
-
raise CrowError("usage", message)
|
|
99
|
+
raise CrowError("usage", ui.translate_usage(message))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def command_parser(sub, name, parents, aliases=()):
|
|
103
|
+
text, examples = COMMANDS[name]
|
|
104
|
+
return sub.add_parser(name, parents=parents, aliases=list(aliases), help=text, description=text,
|
|
105
|
+
epilog="exemplos:\n" + "\n".join(" $ " + e for e in examples))
|
|
28
106
|
|
|
29
107
|
|
|
30
108
|
def parser():
|
|
@@ -38,24 +116,46 @@ def parser():
|
|
|
38
116
|
("--project", {"help": "Diretório físico do projeto"}),
|
|
39
117
|
("--dest", {"help": "Diretório de skills explícito, para outro host"}),
|
|
40
118
|
("--json", {"action": "store_true", "help": "Envelope JSON; nunca abre prompts"}),
|
|
41
|
-
("--non-interactive", {"action": "store_true"}),
|
|
119
|
+
("--non-interactive", {"action": "store_true", "help": "Nunca perguntar; sem --yes, mutações falham"}),
|
|
42
120
|
("--yes", {"action": "store_true", "help": "Aplicar o escopo explícito sem prompt"}),
|
|
43
121
|
("--dry-run", {"action": "store_true", "help": "Preview sem gravar estado ou instalar"}),
|
|
44
122
|
("--fetch", {"action": "store_true", "help": "Buscar origin explicitamente; não cria clone"}),
|
|
45
123
|
]:
|
|
46
124
|
common.add_argument(flag, default=argparse.SUPPRESS, **kwargs)
|
|
47
|
-
|
|
125
|
+
common._optionals.title = "flags globais (crow-skills help flags)"
|
|
126
|
+
p = Parser(prog="crow-skills", parents=[common], add_help=False,
|
|
127
|
+
description="Instale pacotes crow completos, por agente e revisão, sem executar scripts de skills.")
|
|
128
|
+
p.add_argument("-h", "--help", dest="show_help", action="store_true", default=argparse.SUPPRESS,
|
|
129
|
+
help="Ajuda curta, por tarefa")
|
|
48
130
|
p.add_argument("--version", action="store_true")
|
|
49
|
-
sub = p.add_subparsers(dest="command")
|
|
50
|
-
|
|
51
|
-
|
|
131
|
+
sub = p.add_subparsers(dest="command", title="comandos", metavar="<comando>")
|
|
132
|
+
child = command_parser(sub, "setup", [common], aliases=("init",))
|
|
133
|
+
child.add_argument("--skills", help="Só estas skills (separadas por vírgula); padrão: todo o catálogo")
|
|
134
|
+
child.add_argument("--group", help="Só estes grupos (separados por vírgula; veja crow-skills groups); padrão: todas")
|
|
135
|
+
child.add_argument("--no-autoupdate", action="store_true", help="Não ligar o autoupdate")
|
|
136
|
+
child.add_argument("--replace", action="store_true", help="Autorizar backup e substituição de pacote/guia não gerenciado")
|
|
137
|
+
child.add_argument("--overwrite-modified", action="store_true", help="Autorizar backup e substituição de skills/guias editados")
|
|
138
|
+
child.add_argument("--no-trust", action="store_true", help=TRUST_HELP)
|
|
139
|
+
child.add_argument("--no-probe", action="store_true", help=argparse.SUPPRESS)
|
|
140
|
+
child = command_parser(sub, "upgrade", [common])
|
|
141
|
+
child.add_argument("--skills-only", action="store_true", help="Só skills/guias/hooks, sem atualizar o crow-skills")
|
|
142
|
+
child.add_argument("--no-self", action="store_true", help="Igual a --skills-only")
|
|
143
|
+
child.add_argument("--git-pull", action="store_true", help="Checkout git: git pull --ff-only se estiver limpo em main/master")
|
|
144
|
+
child.add_argument("--no-trust", action="store_true", help=TRUST_HELP)
|
|
145
|
+
child = command_parser(sub, "help", [common])
|
|
146
|
+
child.add_argument("topic", nargs="?", help="Comando, ou flags")
|
|
147
|
+
for name in ("list", "groups", "agents", "status", "doctor"):
|
|
148
|
+
command_parser(sub, name, [common])
|
|
52
149
|
for name in ("info", "related"):
|
|
53
|
-
child = sub
|
|
150
|
+
child = command_parser(sub, name, [common])
|
|
54
151
|
child.add_argument("name")
|
|
55
152
|
for name in ("install", "update", "uninstall"):
|
|
56
|
-
child = sub
|
|
153
|
+
child = command_parser(sub, name, [common])
|
|
57
154
|
child.add_argument("skills", nargs="*")
|
|
58
155
|
child.add_argument("--all", action="store_true", help="Todos do catálogo (install) ou gerenciados (update/uninstall)")
|
|
156
|
+
if name == "install":
|
|
157
|
+
child.add_argument("--group", help="Grupos pré-definidos, separados por vírgula (crow-skills groups); "
|
|
158
|
+
"todas = catálogo inteiro; crow-behaviour sempre entra")
|
|
59
159
|
if name != "uninstall":
|
|
60
160
|
child.add_argument("--replace", action="store_true", help="Autorizar substituição com backup de pacote não gerenciado")
|
|
61
161
|
child.add_argument("--with-handoffs", action="store_true", help="Incluir apenas handoffs diretos opcionais do catálogo")
|
|
@@ -63,24 +163,26 @@ def parser():
|
|
|
63
163
|
child.add_argument("--no-guide", action="store_true", help="Não aplicar/atualizar/remover o guia do agente (--global)")
|
|
64
164
|
child.add_argument("--no-integrations", action="store_true",
|
|
65
165
|
help="Não aplicar/remover as integrações de interface (status line, tmux) em --global")
|
|
66
|
-
|
|
166
|
+
if name != "uninstall":
|
|
167
|
+
child.add_argument("--no-trust", action="store_true", help=TRUST_HELP)
|
|
168
|
+
child = command_parser(sub, "guide", [common])
|
|
67
169
|
child.add_argument("action", choices=("install", "status", "uninstall"))
|
|
68
170
|
child.add_argument("--replace", action="store_true", help="Autorizar backup e substituição de conteúdo não gerenciado no caminho do guia")
|
|
69
171
|
child.add_argument("--overwrite-modified", action="store_true", help="Autorizar backup e substituição/remoção de guia editado")
|
|
70
|
-
child = sub
|
|
172
|
+
child = command_parser(sub, "integrations", [common])
|
|
71
173
|
child.add_argument("action", choices=("install", "status", "uninstall"))
|
|
72
|
-
child
|
|
174
|
+
child.add_argument("--no-trust", action="store_true", help=TRUST_HELP)
|
|
175
|
+
child = command_parser(sub, "progress", [common])
|
|
73
176
|
child.add_argument("--watch", action="store_true", help="Redesenhar até a execução terminar ou Ctrl-C")
|
|
74
177
|
child.add_argument("--run", help="ID da execução; padrão: a ativa mais recente do diretório")
|
|
75
178
|
child.add_argument("--cwd", help="Diretório da execução; padrão: o atual")
|
|
76
|
-
child = sub
|
|
179
|
+
child = command_parser(sub, "mode", [common])
|
|
77
180
|
child.add_argument("action", nargs="?", default="status", choices=("on", "off", "status", "toggle"))
|
|
78
|
-
child = sub
|
|
181
|
+
child = command_parser(sub, "events", [common])
|
|
79
182
|
child.add_argument("action", nargs="?", default="snapshot", choices=("snapshot", "tail"))
|
|
80
183
|
child.add_argument("--limit", type=int, default=50, help="tail: quantos eventos (padrão 50; 0 = todos os retidos)")
|
|
81
184
|
child.add_argument("--follow", action="store_true", help="tail: transmitir eventos novos em JSONL até Ctrl-C")
|
|
82
|
-
child = sub
|
|
83
|
-
help="crow-broadcast: sessões vivas dos CLIs, arquivos em edição, conflitos e reservas")
|
|
185
|
+
child = command_parser(sub, "broadcast", [common])
|
|
84
186
|
child.add_argument("action", nargs="?", default="status", choices=("status", "list", "claim", "release", "watch"))
|
|
85
187
|
child.add_argument("targets", nargs="*", help="claim: caminhos, globs ou área; release: ids das reservas")
|
|
86
188
|
child.add_argument("--ttl", default="30m", help="claim: validade (ex.: 30m, 2h; máximo 24h)")
|
|
@@ -93,19 +195,21 @@ def parser():
|
|
|
93
195
|
child.add_argument("--all", action="store_true", help="release: todas as reservas desta sessão")
|
|
94
196
|
child.add_argument("--interval", type=float, default=2.0, help=argparse.SUPPRESS)
|
|
95
197
|
child.add_argument("--max-frames", type=int, default=None, help=argparse.SUPPRESS)
|
|
96
|
-
child = sub
|
|
97
|
-
help="Memória, pressão, agentes em execução e paralelismo recomendado (somente leitura)")
|
|
198
|
+
child = command_parser(sub, "resources", [common])
|
|
98
199
|
child.add_argument("--no-processes", action="store_true", help="Não varrer os processos dos CLIs de agente (mais rápido)")
|
|
99
200
|
child.add_argument("--exec-prefix", action="store_true",
|
|
100
201
|
help="Só imprimir o prefixo que roda um job pesado em prioridade baixa neste sistema (taskpolicy/nice/ionice/start /low)")
|
|
101
|
-
child = sub
|
|
202
|
+
child = command_parser(sub, "autoupdate", [common])
|
|
102
203
|
child.add_argument("action", choices=("on", "off", "status", "run"))
|
|
103
204
|
child.add_argument("--git-pull", action="store_true", help="on: também atualizar um checkout git limpo em main/master (git pull --ff-only)")
|
|
104
205
|
child.add_argument("--skills-only", action="store_true", help="run: só atualizar as skills, sem atualizar o crow-skills")
|
|
105
206
|
child.add_argument("--no-self", action="store_true", help="run: igual a --skills-only")
|
|
207
|
+
child.add_argument("--no-trust", action="store_true", help=TRUST_HELP)
|
|
106
208
|
for name in ("rollback", "recover"):
|
|
107
|
-
child = sub
|
|
209
|
+
child = command_parser(sub, name, [common])
|
|
108
210
|
child.add_argument("--transaction", required=name == "rollback")
|
|
211
|
+
p.common = common
|
|
212
|
+
p.commands = sub.choices
|
|
109
213
|
return p
|
|
110
214
|
|
|
111
215
|
|
|
@@ -229,6 +333,7 @@ def guide_sync(args, home, store, command, targets, plan, source):
|
|
|
229
333
|
if agent not in selected and not (record and path in touched):
|
|
230
334
|
continue
|
|
231
335
|
added, removed = touched.get(path, (set(), set()))
|
|
336
|
+
removed = removed - projection.projected(agent, home, store) # still provided by Uniflow's projection
|
|
232
337
|
after = sorted((set(guide.managed_skills(agent, home, store)) | added) - removed)
|
|
233
338
|
if mech["kind"] == "toml" and guide.tomllib is None:
|
|
234
339
|
report["skipped"].append({"agent": agent, "reason": "Python 3.11+ (tomllib) é necessário para editar config.toml; guia não alterado."})
|
|
@@ -284,6 +389,7 @@ def behaviour_agents(home, store, plan=None):
|
|
|
284
389
|
path = os.path.abspath(destinations(agent, home)[0]["path"])
|
|
285
390
|
added, removed = touched.get(path, (set(), set()))
|
|
286
391
|
try:
|
|
392
|
+
removed = removed - projection.projected(agent, home, store)
|
|
287
393
|
managed = set(guide.managed_skills(agent, home, store))
|
|
288
394
|
except CrowError:
|
|
289
395
|
# An unreadable skills root (e.g. a dotfiles symlink) holds nothing this CLI manages;
|
|
@@ -301,7 +407,12 @@ def integrations_preview(args, home, store, plan):
|
|
|
301
407
|
if getattr(args, "project", None) or getattr(args, "dest", None):
|
|
302
408
|
return {"changes": [], "skipped": [{"integration": "*", "reason": "Integrações de interface só existem no escopo do usuário (--global)."}],
|
|
303
409
|
"disabled": True}
|
|
304
|
-
return integrations.sync(store, home, integration_agents(args, home, store, plan), dry_run=True)
|
|
410
|
+
return integrations.sync(store, home, integration_agents(args, home, store, plan), dry_run=True, trust=trusting(args))
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def trusting(args):
|
|
414
|
+
"""Hooks are enabled/approved in each CLI unless --no-trust."""
|
|
415
|
+
return not getattr(args, "no_trust", False)
|
|
305
416
|
|
|
306
417
|
|
|
307
418
|
def integration_agents(args, home, store, plan=None, selected=None):
|
|
@@ -318,7 +429,7 @@ def integration_agents(args, home, store, plan=None, selected=None):
|
|
|
318
429
|
|
|
319
430
|
def integrations_command(args, home, store, interactive):
|
|
320
431
|
if args.action == "status":
|
|
321
|
-
return {"integrations": integrations.status(store, home)}
|
|
432
|
+
return {"integrations": integrations.status(store, home, probe=False)}
|
|
322
433
|
if not getattr(args, "global_scope", False):
|
|
323
434
|
raise CrowError("usage", "integrations " + args.action + " exige --global explícito (único escopo suportado).")
|
|
324
435
|
wanted = []
|
|
@@ -327,12 +438,12 @@ def integrations_command(args, home, store, interactive):
|
|
|
327
438
|
if args.action == "install" and not wanted:
|
|
328
439
|
raise CrowError("guide_requires_skill", "crow-behaviour não está instalada para nenhum agente; instale antes: "
|
|
329
440
|
"crow-skills install crow-behaviour --agents claude --global --yes")
|
|
330
|
-
preview = integrations.sync(store, home, wanted, dry_run=True)
|
|
441
|
+
preview = integrations.sync(store, home, wanted, dry_run=True, trust=trusting(args))
|
|
331
442
|
if preview["changes"]:
|
|
332
443
|
authorize(args, interactive, preview)
|
|
333
444
|
if getattr(args, "dry_run", False):
|
|
334
445
|
return {**preview, "applied": False}
|
|
335
|
-
return {**integrations.sync(store, home, wanted), "applied": True}
|
|
446
|
+
return {**integrations.sync(store, home, wanted, trust=trusting(args)), "applied": True}
|
|
336
447
|
|
|
337
448
|
|
|
338
449
|
def progress_command(args, home):
|
|
@@ -354,7 +465,7 @@ def mode_command(args, home):
|
|
|
354
465
|
wanted = args.action if args.action != "toggle" else ("off" if current["mode"] == "on" else "on")
|
|
355
466
|
current = hook.write_mode(home, wanted, "cli")
|
|
356
467
|
try:
|
|
357
|
-
installed = [r["integration"] for r in integrations.status(Store(home), home)
|
|
468
|
+
installed = [r["integration"] for r in integrations.status(Store(home), home, probe=False)
|
|
358
469
|
if r["status"] == "installed" and r["integration"].endswith(("-hooks", "-statusline", "-command", "tmux-status"))]
|
|
359
470
|
except CrowError:
|
|
360
471
|
installed = []
|
|
@@ -522,12 +633,13 @@ def autoupdate_command(args, home, store, interactive):
|
|
|
522
633
|
if args.action == "status":
|
|
523
634
|
return autoupdate.status(store, home)
|
|
524
635
|
if args.action == "run":
|
|
525
|
-
|
|
636
|
+
self_step = not (args.skills_only or args.no_self)
|
|
637
|
+
authorize(args, interactive, {"autoupdate": "run", "self_upgrade": self_step})
|
|
526
638
|
if getattr(args, "dry_run", False):
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
return
|
|
639
|
+
preview = autoupdate.preview(store, home, self_step=self_step, trust=trusting(args))
|
|
640
|
+
return dict(preview, summary=machine.upgrade_summary(preview.get("skills", []), True))
|
|
641
|
+
done = autoupdate.run(store, home, self_step=self_step, trust=trusting(args))
|
|
642
|
+
return dict(done, summary=machine.upgrade_summary(done["lastRun"].get("skills", []), False))
|
|
531
643
|
if args.action == "on":
|
|
532
644
|
preview = autoupdate.turn_on(store, home, dry_run=True, git_pull=args.git_pull)
|
|
533
645
|
if any(c["action"] != "unchanged" for c in preview["changes"]):
|
|
@@ -589,26 +701,159 @@ def uniflow_notice(home, store, targets, plan):
|
|
|
589
701
|
native[row["target"]]["skills"].append({"name": row["name"], "status": row["status"]})
|
|
590
702
|
if not native:
|
|
591
703
|
return {"native_duplicates": [], "uninspected": uninspected}
|
|
592
|
-
|
|
593
|
-
|
|
704
|
+
# One command per destination with only the names physically managed there: crossing names and agents
|
|
705
|
+
# would reach a Uniflow link (or an absent name) in another CLI and abort the uninstall.
|
|
706
|
+
# Destinations with the same names share one command (the usual case keeps its single command).
|
|
707
|
+
groups = {}
|
|
708
|
+
for item in native.values():
|
|
709
|
+
managed = tuple(sorted({s["name"] for s in item["skills"] if s["status"] != "unmanaged"}))
|
|
710
|
+
if managed:
|
|
711
|
+
groups.setdefault(managed, []).extend(a for a in item["agents"] if a not in groups.get(managed, []))
|
|
712
|
+
commands = ["crow-skills uninstall " + " ".join(names_) + " --agents " + ",".join(sorted(agents_)) + " --global"
|
|
713
|
+
for names_, agents_ in groups.items()]
|
|
594
714
|
return {"native_duplicates": list(native.values()), "uninspected": uninspected,
|
|
595
715
|
"note": "effect=skipped: o Uniflow não cria o link de um nome que o agente já tem nativo, e essa cópia vale no lugar do "
|
|
596
716
|
"store. effect=both: o Uniflow liga o store em ~/.codex/skills e o Codex também lê ~/.agents/skills, então vê as "
|
|
597
717
|
"duas cópias. Nada foi removido. Remover a cópia nativa de crow-behaviour remove também o guia daquele agente.",
|
|
598
|
-
"
|
|
599
|
-
|
|
718
|
+
"suggested_commands": commands, "suggested_command": " && ".join(commands) if commands else None}
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def pick(source):
|
|
722
|
+
"""Terminal picker without dependencies: a group number or name, todas, or skill names. Default: essencial."""
|
|
723
|
+
available = groups_mod.load(source)
|
|
724
|
+
default = next((g["name"] for g in available if g["name"] == "essencial"), groups_mod.ALL)
|
|
725
|
+
print("Grupos de skills (a crow-behaviour entra com qualquer grupo):", file=sys.stderr)
|
|
726
|
+
for n, group in enumerate(available, 1):
|
|
727
|
+
print(terminal(" " + str(n).rjust(2) + ". " + group["name"].ljust(11) + " " + str(len(group["skills"])).rjust(2) +
|
|
728
|
+
" skills " + group["description"]), file=sys.stderr)
|
|
729
|
+
print(" " + str(len(available) + 1).rjust(2) + ". escolher skills individualmente", file=sys.stderr)
|
|
730
|
+
answer = prompt("Número(s) ou nome(s) separados por vírgula [" + default + "]:").strip()
|
|
731
|
+
tokens = [t.strip() for t in answer.split(",") if t.strip()] or [default]
|
|
732
|
+
if tokens == [str(len(available) + 1)]:
|
|
733
|
+
for name, item in source.catalog.items():
|
|
734
|
+
print(terminal(name + " — " + item.get("title", name)), file=sys.stderr)
|
|
735
|
+
tokens = [t.strip() for t in prompt("Skills separadas por vírgula:").split(",") if t.strip()]
|
|
736
|
+
if not tokens:
|
|
737
|
+
raise CrowError("usage", "Nenhuma skill selecionada.")
|
|
738
|
+
by_number = {str(n): g["name"] for n, g in enumerate(available, 1)}
|
|
739
|
+
chosen_groups = [by_number.get(t, t) for t in tokens if t in by_number or t in {g["name"] for g in available}]
|
|
740
|
+
skills = [t for t in tokens if t not in by_number and t not in {g["name"] for g in available}]
|
|
741
|
+
for name in skills:
|
|
742
|
+
source.require(name)
|
|
743
|
+
names = groups_mod.resolve(source, ",".join(chosen_groups)) if chosen_groups else []
|
|
744
|
+
names = list(dict.fromkeys(names + skills))
|
|
745
|
+
if not names:
|
|
746
|
+
raise CrowError("usage", "Nenhuma skill selecionada.")
|
|
747
|
+
return names, ",".join(chosen_groups) or None
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def codex_projection_split(home, store, targets, names):
|
|
751
|
+
"""The user-scope codex target and which of the names Codex already sees via Uniflow (install skips them)."""
|
|
752
|
+
target = next((t for t in targets if projection.native_target("codex", t, home)), None)
|
|
753
|
+
if target is None or set(target["agents"]) - {"codex"}:
|
|
754
|
+
return None # --agents shared: other hosts read that dir without Uniflow's codex projection
|
|
755
|
+
projected = projection.projected("codex", home, store)
|
|
756
|
+
if not projected:
|
|
757
|
+
return None
|
|
758
|
+
dupes = projection.duplicates(home, store)
|
|
759
|
+
return {"target": target, "skip": set(names) & projected,
|
|
760
|
+
"duplicates": sorted(set(dupes["remove"]) | set(dupes["modified"]))}
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def merge_plans(plans):
|
|
764
|
+
merged = {"before": {}, "after": {}, "items": [], "packages": {}, "changes": []}
|
|
765
|
+
for plan in plans:
|
|
766
|
+
merged["before"].update(plan["before"])
|
|
767
|
+
merged["after"].update(plan["after"])
|
|
768
|
+
merged["items"] += plan["items"]
|
|
769
|
+
merged["packages"].update(plan["packages"])
|
|
770
|
+
merged["changes"] += plan["changes"]
|
|
771
|
+
return merged
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def unmanaged_projections(store, home, rows):
|
|
775
|
+
"""A Uniflow link to a store entry crow-skills does not manage is not an install (same rule as setup)."""
|
|
776
|
+
if not any(r["status"] == "uniflow_link" for r in rows):
|
|
777
|
+
return rows
|
|
778
|
+
managed = guide.store_managed(home, store)
|
|
779
|
+
disabled = machine.store_disabled(home, store)
|
|
780
|
+
broken = guide.store_broken(home, store)
|
|
781
|
+
for row in rows:
|
|
782
|
+
if row["status"] == "uniflow_link" and row["name"] in broken:
|
|
783
|
+
# The store entry this link resolves to was edited or lost files: not a working install.
|
|
784
|
+
row.update(status="modified", projection="uniflow_link_modified",
|
|
785
|
+
note=guide.BROKEN_REASON[0].upper() + guide.BROKEN_REASON[1:] + ". Para corrigir: " + guide.broken_fix(row["name"]))
|
|
786
|
+
elif row["status"] == "uniflow_link" and row["name"] in disabled:
|
|
787
|
+
# Managed by crow-skills but disabled by Uniflow: reported as such, never as unmanaged (no --replace).
|
|
788
|
+
row.update(status="disabled", projection="uniflow_link_disabled",
|
|
789
|
+
note="Desabilitada no Uniflow (SKILL.md.disabled no store); reabilite no Uniflow para usar.")
|
|
790
|
+
elif row["status"] == "uniflow_link" and row["name"] not in managed:
|
|
791
|
+
row.update(status="unmanaged", projection="uniflow_link_unmanaged",
|
|
792
|
+
note="Link do Uniflow para um pacote do store que o crow-skills não gerencia; não conta como instalada. "
|
|
793
|
+
"Revise o store e, para gerenciá-lo com backup: crow-skills setup --agents uniflow --replace --yes")
|
|
794
|
+
return rows
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
def group_coverage(rows):
|
|
798
|
+
"""Per destination, which catalog groups are fully or partially installed (best effort)."""
|
|
799
|
+
try:
|
|
800
|
+
available = [g for g in groups_mod.load(Source(DEFAULT_SOURCE)) if g["name"] != groups_mod.ALL]
|
|
801
|
+
except (CrowError, OSError):
|
|
802
|
+
return []
|
|
803
|
+
by_target = {}
|
|
804
|
+
for row in rows:
|
|
805
|
+
item = by_target.setdefault(row["target"], {"target": row["target"], "agents": row["agents"], "names": set()})
|
|
806
|
+
if row["name"] and row["status"] in ("installed", "modified", "disabled", "uniflow_link"):
|
|
807
|
+
item["names"].add(row["name"])
|
|
808
|
+
return [{"target": v["target"], "agents": v["agents"],
|
|
809
|
+
"groups": [c for c in groups_mod.coverage(available, v["names"]) if c["state"] != "absent"]}
|
|
810
|
+
for v in by_target.values() if v["names"]]
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def groups_command(args):
|
|
814
|
+
source = Source(getattr(args, "source", DEFAULT_SOURCE), getattr(args, "ref", "HEAD"), getattr(args, "fetch", False))
|
|
815
|
+
available = groups_mod.load(source)
|
|
816
|
+
return {"revision": source.revision, "groups": available, "always": groups_mod.BEHAVIOUR,
|
|
817
|
+
"note": "crow-behaviour entra com qualquer grupo; handoffs de outros grupos são sugeridos, não instalados "
|
|
818
|
+
"(use --with-handoffs)."}
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def help_command(args, home, topic=None):
|
|
822
|
+
"""Short, task-oriented help; help <command> for one command; help flags for the global flags."""
|
|
823
|
+
p = parser()
|
|
824
|
+
if topic in (None, "", "help") and getattr(args, "command", None) in (None, "help"):
|
|
825
|
+
line, status = machine.status_line(home)
|
|
826
|
+
return {"topic": None, "sections": [{"title": t, "commands": [{"name": n, "summary": d, "example": e} for n, d, e in items]}
|
|
827
|
+
for t, items in ui.SECTIONS],
|
|
828
|
+
"status": status, "_status_line": line, "text": None}
|
|
829
|
+
if topic == "flags":
|
|
830
|
+
return {"topic": "flags", "text": ui.flags_help(p.common._actions)}
|
|
831
|
+
name = "setup" if topic == "init" else topic
|
|
832
|
+
if name not in p.commands:
|
|
833
|
+
raise CrowError("usage", "Comando desconhecido: " + str(topic) + ".")
|
|
834
|
+
return {"topic": name, "text": p.commands[name].format_help(), "examples": COMMANDS.get(name, ("", []))[1]}
|
|
600
835
|
|
|
601
836
|
|
|
602
837
|
def run(args):
|
|
838
|
+
if getattr(args, "command", None) == "init":
|
|
839
|
+
args.command = "setup"
|
|
840
|
+
if getattr(args, "show_help", False):
|
|
841
|
+
return help_command(args, checked(getattr(args, "home", Path.home())), args.command)
|
|
603
842
|
if args.version:
|
|
604
843
|
return {"version": __version__}
|
|
605
|
-
if not args.command:
|
|
606
|
-
raise CrowError("usage", "Escolha um comando; use crow-skills --help.")
|
|
607
844
|
home = checked(getattr(args, "home", Path.home()))
|
|
845
|
+
if not args.command or args.command == "help":
|
|
846
|
+
return help_command(args, home, getattr(args, "topic", None))
|
|
608
847
|
store = Store(home)
|
|
609
848
|
interactive = sys.stdin.isatty() and not getattr(args, "non_interactive", False) and not getattr(args, "json", False)
|
|
610
|
-
if
|
|
849
|
+
if args.command == "setup":
|
|
850
|
+
return machine.setup(args, home, store, interactive)
|
|
851
|
+
if args.command == "upgrade":
|
|
852
|
+
return machine.upgrade(args, home, store, interactive)
|
|
853
|
+
if getattr(args, "fetch", False) and (getattr(args, "dry_run", False) or args.command not in ("install", "update", "list", "info", "related", "guide", "groups")):
|
|
611
854
|
raise CrowError("usage", "--fetch requer um comando com fonte e não pode ser combinado com --dry-run.")
|
|
855
|
+
if args.command == "groups":
|
|
856
|
+
return groups_command(args)
|
|
612
857
|
if args.command == "agents":
|
|
613
858
|
return {"agents": inventory(home), "note": "Detecção por PATH/diretórios não comprova carregamento da skill."}
|
|
614
859
|
if args.command == "guide":
|
|
@@ -633,25 +878,42 @@ def run(args):
|
|
|
633
878
|
return autoupdate_command(args, home, store, interactive)
|
|
634
879
|
if args.command in ("status", "doctor"):
|
|
635
880
|
targets = scope(args, home, read=True)
|
|
636
|
-
rows = store.status(targets)
|
|
881
|
+
rows = unmanaged_projections(store, home, store.status(targets))
|
|
637
882
|
pending = [t["id"] for t in store.pending()]
|
|
638
883
|
global_view = not (getattr(args, "project", None) or getattr(args, "dest", None))
|
|
639
884
|
names = [n.strip() for n in getattr(args, "agents", "").split(",")] if getattr(args, "agents", None) else list(guide.MECHANISMS)
|
|
640
885
|
guides = guide.status(store, home, names) if global_view else []
|
|
641
886
|
try:
|
|
642
|
-
|
|
887
|
+
# Only doctor asks the CLIs (codex app-server writes under ~/.codex); status stays read-only.
|
|
888
|
+
ui = integrations.status(store, home, probe=args.command == "doctor") if global_view else []
|
|
643
889
|
except CrowError as exc:
|
|
644
890
|
ui = [{"integration": "*", "status": "unsafe", "note": str(exc)}]
|
|
645
891
|
result = {"installations": rows, "guides": guides, "integrations": ui, "pending_transactions": pending,
|
|
646
892
|
"mode": hook.read_mode(home), "activation_verified": False,
|
|
647
893
|
"reload_hint": "Peça ao host para recarregar/listar skills; reinicie a sessão se necessário."}
|
|
894
|
+
if any(projection.native_target("codex", t, home) for t in targets):
|
|
895
|
+
rows += projection.status_rows(home, store, rows)
|
|
896
|
+
dupes = projection.duplicates(home, store)
|
|
897
|
+
names_ = dupes["remove"] + dupes["modified"] + dupes["shared"]
|
|
898
|
+
if names_:
|
|
899
|
+
# A warning, not unhealthy: both copies are intact and work; Codex just lists them twice.
|
|
900
|
+
result["warnings"] = [{"code": "codex_duplicates", "skills": names_,
|
|
901
|
+
"message": "O Codex vê " + str(len(names_)) + " skill(s) duas vezes (cópia em ~/.agents/skills "
|
|
902
|
+
"e link do Uniflow em " + str(projection.codex_skills_dir(home)) + ").",
|
|
903
|
+
"fix": "crow-skills setup --agents codex --yes"
|
|
904
|
+
+ (" --overwrite-modified" if dupes["modified"] else "")}]
|
|
905
|
+
result["groups"] = group_coverage(rows)
|
|
648
906
|
try:
|
|
649
907
|
result["autoupdate"] = autoupdate.status(store, home) if global_view else None
|
|
650
908
|
except CrowError as exc:
|
|
651
909
|
result["autoupdate"] = {"enabled": None, "healthy": False, "error": exc.code}
|
|
910
|
+
hooks = [r for r in ui_rows(ui) if r.get("status") == "installed" and isinstance(r.get("enabled"), dict)]
|
|
911
|
+
result["hooks"] = [{"integration": r["integration"], "agents": r.get("agents"), "state": r["enabled"].get("state"),
|
|
912
|
+
"fix": r["enabled"].get("fix")} for r in hooks]
|
|
652
913
|
if args.command == "doctor":
|
|
653
914
|
result.update(healthy=not pending and all(r["status"] not in ("modified", "missing", "unsafe", "external_link") for r in rows + guides)
|
|
654
|
-
and (result["autoupdate"] or {}).get("healthy", True) is not False
|
|
915
|
+
and (result["autoupdate"] or {}).get("healthy", True) is not False
|
|
916
|
+
and all(h["state"] not in machine.BAD_HOOKS for h in result["hooks"]),
|
|
655
917
|
agents=inventory(home))
|
|
656
918
|
return result
|
|
657
919
|
if args.command in ("rollback", "recover"):
|
|
@@ -698,18 +960,20 @@ def run(args):
|
|
|
698
960
|
return {"revision": source.revision, "skill": source.catalog[args.name],
|
|
699
961
|
"relationships": relationship_view(source, args.name, store, targets)}
|
|
700
962
|
targets = scope(args, home, interactive)
|
|
701
|
-
names = args.skills
|
|
702
|
-
|
|
703
|
-
|
|
963
|
+
names = list(args.skills)
|
|
964
|
+
group = getattr(args, "group", None)
|
|
965
|
+
if (names or group) and args.all:
|
|
966
|
+
raise CrowError("usage", "Use nomes/--group ou --all, não ambos.")
|
|
967
|
+
selection = None
|
|
968
|
+
if group is not None:
|
|
969
|
+
selection = groups_mod.parse(group)
|
|
970
|
+
names = list(dict.fromkeys(names + groups_mod.resolve(source, group)))
|
|
704
971
|
if args.command == "install" and not names and not args.all:
|
|
705
972
|
if not interactive:
|
|
706
|
-
raise CrowError("usage", "Escolha nomes
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
names = [n.strip() for n in names if n.strip()]
|
|
711
|
-
if not names:
|
|
712
|
-
raise CrowError("usage", "Nenhuma skill selecionada.")
|
|
973
|
+
raise CrowError("usage", "Escolha as skills: nomes, --group ou --all (ex.: crow-skills install --group essencial "
|
|
974
|
+
"--agents claude --global --yes; grupos: crow-skills groups).")
|
|
975
|
+
names, selection = pick(source)
|
|
976
|
+
selection = groups_mod.parse(selection) if selection else None
|
|
713
977
|
if args.command == "uninstall" and not names and not args.all:
|
|
714
978
|
raise CrowError("usage", "Uninstall exige nomes explícitos ou --all.")
|
|
715
979
|
if args.command == "install" and args.all:
|
|
@@ -721,15 +985,35 @@ def run(args):
|
|
|
721
985
|
for name in list(names):
|
|
722
986
|
source.require(name)
|
|
723
987
|
names.extend(n for n in source.catalog[name]["next"] if n not in names)
|
|
724
|
-
|
|
988
|
+
codex_view = None
|
|
989
|
+
if args.command == "install" and not (getattr(args, "project", None) or getattr(args, "dest", None)):
|
|
990
|
+
codex_view = codex_projection_split(home, store, targets, names)
|
|
991
|
+
if codex_view and codex_view["skip"]:
|
|
992
|
+
# Codex already sees these through Uniflow's links in ~/.codex/skills: no native copy for codex.
|
|
993
|
+
plans = [store.plan(args.command, [n for n in names if n not in codex_view["skip"]] if t is codex_view["target"] else names,
|
|
994
|
+
[t], source, getattr(args, "replace", False), args.overwrite_modified)
|
|
995
|
+
for t in targets if t is not codex_view["target"] or set(names) - codex_view["skip"]]
|
|
996
|
+
plan = merge_plans(plans)
|
|
997
|
+
else:
|
|
998
|
+
plan = store.plan(args.command, names, targets, source, getattr(args, "replace", False), args.overwrite_modified)
|
|
725
999
|
guides, gplan = guide_sync(args, home, store, args.command, targets, plan, source)
|
|
726
1000
|
ui = integrations_preview(args, home, store, plan)
|
|
727
1001
|
summary = {"changes": plan["changes"], "revision": source.revision if source else None,
|
|
728
1002
|
"relationships": {n: source.related(n) for n in names} if source else {},
|
|
1003
|
+
**({"groups": selection, "suggested_handoffs": groups_mod.suggested_handoffs(source, names)}
|
|
1004
|
+
if selection and not getattr(args, "with_handoffs", False) else {}),
|
|
729
1005
|
"guides": guides, "integrations": ui, "handoffs_are_optional": True, "activation_verified": False}
|
|
730
1006
|
notice = uniflow_notice(home, store, targets, plan) if args.command != "uninstall" else None
|
|
731
1007
|
if notice is not None:
|
|
732
1008
|
summary["uniflow"] = notice
|
|
1009
|
+
if codex_view and (codex_view["skip"] or codex_view["duplicates"]):
|
|
1010
|
+
summary["codex_projection"] = {
|
|
1011
|
+
"via_uniflow": sorted(codex_view["skip"]), "duplicates": codex_view["duplicates"],
|
|
1012
|
+
"note": "O Codex já vê estas skills pelo link do Uniflow em " + str(projection.codex_skills_dir(home)) +
|
|
1013
|
+
"; nenhuma cópia nativa é criada para o codex. Cópias nativas que duplicam a projeção não são removidas "
|
|
1014
|
+
"por install; remova-as com o comando sugerido ou rode crow-skills setup --yes.",
|
|
1015
|
+
"suggested_command": ("crow-skills uninstall " + " ".join(codex_view["duplicates"]) + " --agents codex --global")
|
|
1016
|
+
if codex_view["duplicates"] else None}
|
|
733
1017
|
if plan["items"] or (gplan and gplan["items"]) or ui.get("changes"):
|
|
734
1018
|
authorize(args, interactive, summary)
|
|
735
1019
|
txid = None
|
|
@@ -738,7 +1022,7 @@ def run(args):
|
|
|
738
1022
|
if not ui.get("disabled"):
|
|
739
1023
|
# Best effort after the skills/guide transactions; a refusal is reported, never undoes them.
|
|
740
1024
|
try:
|
|
741
|
-
summary["integrations"] = integrations.sync(store, home, integration_agents(args, home, store))
|
|
1025
|
+
summary["integrations"] = integrations.sync(store, home, integration_agents(args, home, store), trust=trusting(args))
|
|
742
1026
|
except (CrowError, OSError) as exc:
|
|
743
1027
|
summary["integrations"] = {"changes": [], "skipped": [{"integration": "*", "reason": "Integrações não aplicadas (" +
|
|
744
1028
|
(str(exc) or "falha de gravação") + "); skills e guia mantidos."}]}
|
|
@@ -748,10 +1032,86 @@ def run(args):
|
|
|
748
1032
|
"Operação de arquivos concluída; carregamento/ativação devem ser conferidos no host.")}
|
|
749
1033
|
|
|
750
1034
|
|
|
751
|
-
def
|
|
752
|
-
|
|
753
|
-
|
|
1035
|
+
def ui_rows(rows):
|
|
1036
|
+
return [r for r in rows if isinstance(r, dict)]
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
def public_data(data):
|
|
1040
|
+
return {k: v for k, v in data.items() if not k.startswith("_")} if isinstance(data, dict) else data
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def render_status(data, doctor=False, stream=None):
|
|
1044
|
+
stream = stream or sys.stdout
|
|
1045
|
+
mode = (data.get("mode") or {}).get("mode", "?")
|
|
1046
|
+
auto = data.get("autoupdate") or {}
|
|
1047
|
+
lines = [ui.paint(hook.indicator(mode, ui.unicode_on(stream)), "bold", stream) + " · autoupdate " +
|
|
1048
|
+
("ligado" if auto.get("enabled") else "desligado") + " · crow-skills " + __version__, ""]
|
|
1049
|
+
by_target = {}
|
|
1050
|
+
for row in data["installations"]:
|
|
1051
|
+
item = by_target.setdefault(row["target"], {"agents": row["agents"], "ok": 0, "via": 0, "bad": [], "kept": []})
|
|
1052
|
+
if row.get("projection") == "uniflow_link_unmanaged":
|
|
1053
|
+
item["kept"].append(row["name"] + " link do Uniflow não gerenciado (crow-skills setup --agents uniflow --replace --yes)")
|
|
1054
|
+
if row["status"] == "uniflow_link":
|
|
1055
|
+
item["ok"] += 1
|
|
1056
|
+
item["via"] += 1 # projected by Uniflow from its store: installed for this CLI
|
|
1057
|
+
elif row["status"] in ("installed", "disabled"):
|
|
1058
|
+
item["ok"] += 1
|
|
1059
|
+
elif row["status"] in ("modified", "missing", "unsafe", "external_link"):
|
|
1060
|
+
item["bad"].append((row["name"] or "raiz") + " " + row["status"])
|
|
1061
|
+
rows = [[ui.mark("fail" if v["bad"] else ("warn" if v["kept"] else "ok"), stream), ",".join(v["agents"]),
|
|
1062
|
+
str(v["ok"]) + " skills" + (" (" + str(v["via"]) + " via uniflow)" if v["via"] else ""),
|
|
1063
|
+
"; ".join(v["bad"] + v["kept"])] for v in by_target.values() if v["ok"] or v["bad"] or v["kept"]]
|
|
1064
|
+
if rows:
|
|
1065
|
+
lines += ui.table(rows, ["", "agente", "instaladas", "problemas"], stream)
|
|
1066
|
+
cover = [[",".join(c["agents"]), ", ".join(g["group"] + (" ✓" if g["state"] == "complete" and ui.unicode_on(stream) else
|
|
1067
|
+
" completo" if g["state"] == "complete" else
|
|
1068
|
+
" " + str(g["installed"]) + "/" + str(g["total"]))
|
|
1069
|
+
for g in c["groups"])] for c in data.get("groups") or [] if c["groups"]]
|
|
1070
|
+
if cover:
|
|
1071
|
+
lines += ["", " Grupos (completos ✓ ou parciais n/total):" if ui.unicode_on(stream) else " Grupos:"]
|
|
1072
|
+
lines += ui.table(cover, stream=stream, indent=" ")
|
|
1073
|
+
else:
|
|
1074
|
+
lines.append(" Nenhuma skill instalada; comece com: crow-skills setup --yes")
|
|
1075
|
+
guides = [g for g in data.get("guides", []) if g.get("status") != "absent"]
|
|
1076
|
+
if guides:
|
|
1077
|
+
lines.append("")
|
|
1078
|
+
lines += ui.table([[ui.mark("ok" if g["status"] == "installed" else ("warn" if g["status"] == "outdated" else "fail"), stream),
|
|
1079
|
+
"guia " + g["agent"], ui.word(g["status"]), ui.clean(g.get("note") or "")] for g in guides], stream=stream)
|
|
1080
|
+
hooks = data.get("hooks") or []
|
|
1081
|
+
if hooks:
|
|
1082
|
+
lines.append("")
|
|
1083
|
+
lines += ui.table([[ui.mark("ok" if h["state"] in ("trusted", "not_required") else
|
|
1084
|
+
("fail" if h["state"] in machine.BAD_HOOKS else "warn"), stream),
|
|
1085
|
+
h["integration"], ui.word(h["state"]),
|
|
1086
|
+
ui.clean(h.get("fix") or "")] for h in hooks], stream=stream)
|
|
1087
|
+
for warning in data.get("warnings") or []:
|
|
1088
|
+
lines += ["", ui.mark("warn", stream) + " " + ui.clean(warning["message"]) + "\n Para corrigir: " + warning["fix"]]
|
|
1089
|
+
if data.get("pending_transactions"):
|
|
1090
|
+
lines += ["", ui.mark("fail", stream) + " Transação pendente: crow-skills recover --yes"]
|
|
1091
|
+
if doctor:
|
|
1092
|
+
lines += ["", (ui.mark("ok", stream) + " healthy") if data.get("healthy") else
|
|
1093
|
+
(ui.mark("fail", stream) + " não saudável; detalhes: crow-skills doctor --json")]
|
|
1094
|
+
return "\n".join(lines)
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def render_help(data, stream=None):
|
|
1098
|
+
if data.get("topic") is None:
|
|
1099
|
+
return ui.top_help(__version__, stream, data.get("_status_line"))
|
|
1100
|
+
return data["text"].rstrip("\n")
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
def emit(command, data, as_json):
|
|
1104
|
+
envelope = {"schema_version": 1, "ok": True, "command": command, "data": public_data(data)}
|
|
1105
|
+
if as_json:
|
|
754
1106
|
print(json.dumps(envelope, ensure_ascii=False, separators=(",", ":")))
|
|
1107
|
+
elif command == "help":
|
|
1108
|
+
print(render_help(data))
|
|
1109
|
+
elif command == "setup":
|
|
1110
|
+
print(machine.render_setup(data))
|
|
1111
|
+
elif command == "upgrade" or (command == "autoupdate" and isinstance(data, dict) and "summary" in data):
|
|
1112
|
+
print(machine.render_upgrade(data))
|
|
1113
|
+
elif command in ("status", "doctor"):
|
|
1114
|
+
print(render_status(data, doctor=command == "doctor"))
|
|
755
1115
|
elif command == "progress":
|
|
756
1116
|
if data is not None:
|
|
757
1117
|
print(data["text"] or "crow: nenhuma execução registrada neste diretório.")
|
|
@@ -771,6 +1131,13 @@ def emit(command, data, machine):
|
|
|
771
1131
|
elif command == "events":
|
|
772
1132
|
if data is not None:
|
|
773
1133
|
print(data["text"] if "text" in data else "\n".join(json.dumps(e, ensure_ascii=False) for e in data["events"]))
|
|
1134
|
+
elif command == "groups":
|
|
1135
|
+
lines = []
|
|
1136
|
+
for g in data["groups"]:
|
|
1137
|
+
lines.append(ui.paint(g["name"], "cyan") + " (" + str(len(g["skills"])) + ") — " + terminal(g["description"]))
|
|
1138
|
+
lines.append(" " + ", ".join(g["skills"]))
|
|
1139
|
+
lines += ["", "crow-behaviour entra com qualquer grupo. Ex.: crow-skills install --group essencial --agents claude --global --yes"]
|
|
1140
|
+
print("\n".join(lines))
|
|
774
1141
|
elif command == "list":
|
|
775
1142
|
print("Fonte: " + data["revision"])
|
|
776
1143
|
for item in data["skills"]:
|
|
@@ -781,31 +1148,41 @@ def emit(command, data, machine):
|
|
|
781
1148
|
|
|
782
1149
|
def main(argv=None):
|
|
783
1150
|
argv = list(sys.argv[1:] if argv is None else argv)
|
|
784
|
-
|
|
1151
|
+
as_json = "--json" in argv
|
|
785
1152
|
command = None
|
|
786
1153
|
try:
|
|
787
1154
|
args = parser().parse_args(argv)
|
|
788
1155
|
command = args.command or ("version" if args.version else None)
|
|
1156
|
+
if command == "init":
|
|
1157
|
+
command = "setup"
|
|
1158
|
+
if command is None or getattr(args, "show_help", False):
|
|
1159
|
+
command = "help"
|
|
789
1160
|
result = run(args)
|
|
790
|
-
emit(command, result,
|
|
1161
|
+
emit(command, result, as_json)
|
|
1162
|
+
if command in ("setup", "upgrade") and isinstance(result, dict) and result.get("healthy") is False:
|
|
1163
|
+
return 1
|
|
791
1164
|
return 0
|
|
1165
|
+
except SystemExit as exc: # <command> --help printed by argparse
|
|
1166
|
+
return exc.code if isinstance(exc.code, int) else 0
|
|
792
1167
|
except CrowError as exc:
|
|
793
|
-
if
|
|
1168
|
+
if as_json:
|
|
794
1169
|
print(json.dumps({"schema_version": 1, "ok": False, "command": command,
|
|
795
1170
|
"error": {"code": exc.code, "message": str(exc)}}, ensure_ascii=False))
|
|
796
1171
|
else:
|
|
797
|
-
print(
|
|
1172
|
+
print(ui.error_text(exc.code, str(exc), command, sys.stderr), file=sys.stderr)
|
|
798
1173
|
return 2 if exc.code == "usage" else 1
|
|
799
1174
|
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
800
1175
|
# No traceback or subprocess stderr in machine output; credentials stay external.
|
|
801
|
-
if
|
|
1176
|
+
if as_json:
|
|
802
1177
|
print(json.dumps({"schema_version": 1, "ok": False, "command": command,
|
|
803
1178
|
"error": {"code": "io_error", "message": "Falha de leitura/gravação ou estado inválido; nenhuma conclusão de sucesso."}}))
|
|
804
1179
|
else:
|
|
805
|
-
print("Falha de leitura/gravação ou estado inválido.
|
|
1180
|
+
print(ui.error_text("io_error", "Falha de leitura/gravação ou estado inválido.", command, sys.stderr) +
|
|
1181
|
+
"\n Para corrigir: confira permissões e transações pendentes (crow-skills doctor; crow-skills recover --yes)",
|
|
1182
|
+
file=sys.stderr)
|
|
806
1183
|
return 1
|
|
807
1184
|
except KeyboardInterrupt:
|
|
808
|
-
if
|
|
1185
|
+
if as_json:
|
|
809
1186
|
print(json.dumps({"schema_version": 1, "ok": False, "command": command,
|
|
810
1187
|
"error": {"code": "interrupted", "message": "Operação interrompida; confira status/recover."}}))
|
|
811
1188
|
return 130
|