@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.
@@ -100,11 +100,14 @@ def resources_field(home):
100
100
  """crow-resources/1 subset for terminals: memory, pressure and the recommendation.
101
101
 
102
102
  Added in 0.9.0 without changing crow-snapshot/1: consumers that do not know the
103
- field ignore it; the field carries its own schema for future changes.
103
+ field ignore it; the field carries its own schema for future changes. 0.10.1 adds
104
+ pressure.swap and cpu (additive).
104
105
  """
105
106
  data = resources.probe(home, processes=False, use_cache=True)
106
107
  return {"schema": data["schema"], "generatedAt": data["generatedAt"], "cached": data["cached"],
107
- "memory": data["memory"], "pressure": {"level": data["pressure"]["level"], "reasons": data["pressure"]["reasons"]},
108
+ "memory": data["memory"], "pressure": {"level": data["pressure"]["level"], "reasons": data["pressure"]["reasons"],
109
+ "swap": data["pressure"].get("swap")},
110
+ "cpu": {k: data["cpu"].get(k) for k in ("count", "load1", "load5", "load15", "loadPerCpu1", "loadPerCpu5", "level", "reasons")},
108
111
  "recommendation": data["recommendation"], "alert": resources.alert(data), "segment": resources.segment(data)}
109
112
 
110
113
 
@@ -0,0 +1,76 @@
1
+ """Install groups: named sets of skills declared in catalog.json ("groups"), the single source of truth.
2
+
3
+ ``todas`` is implicit (every skill of the catalog). Any group also brings crow-behaviour, the coordinator.
4
+ Handoffs of the selected skills that stay outside the selection are only suggested (``--with-handoffs``
5
+ installs them). A catalog without "groups" (older snapshots) only offers ``todas``.
6
+ """
7
+ import json
8
+ import re
9
+
10
+ from .source import CrowError
11
+
12
+ ALL = "todas"
13
+ BEHAVIOUR = "crow-behaviour"
14
+ NAME = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*\Z")
15
+
16
+
17
+ def raw_catalog(source):
18
+ raw = source.bundle_file("catalog.json") if getattr(source, "bundle", None) else source.git("show", source.revision + ":catalog.json")
19
+ return json.loads(raw)
20
+
21
+
22
+ def load(source):
23
+ """[{name, title, description, skills}] in catalog order, plus the implicit "todas" at the end."""
24
+ try:
25
+ data = raw_catalog(source).get("groups") or []
26
+ except (CrowError, OSError, ValueError, AttributeError):
27
+ data = []
28
+ groups = []
29
+ try:
30
+ for item in data:
31
+ name = item["name"]
32
+ skills = [s for s in item["skills"] if s in source.catalog]
33
+ if not isinstance(name, str) or not NAME.match(name) or name == ALL or name in source.catalog or not skills:
34
+ raise ValueError("invalid group")
35
+ groups.append({"name": name, "title": str(item.get("title") or name), "description": str(item.get("description") or ""),
36
+ "skills": list(dict.fromkeys(skills))})
37
+ except (KeyError, TypeError, ValueError) as exc:
38
+ raise CrowError("invalid_catalog", "Grupos inválidos no catálogo selecionado.") from exc
39
+ groups.append({"name": ALL, "title": "Todas", "description": "Todas as skills do catálogo", "skills": list(source.catalog)})
40
+ return groups
41
+
42
+
43
+ def parse(selection):
44
+ """Group names from --group: trimmed, without blanks or repeats."""
45
+ return list(dict.fromkeys(n.strip() for n in str(selection or "").split(",") if n.strip()))
46
+
47
+
48
+ def resolve(source, selection):
49
+ """Skills for --group a,b: union in catalog order, crow-behaviour always included."""
50
+ groups = {g["name"]: g for g in load(source)}
51
+ chosen = parse(selection)
52
+ if not chosen:
53
+ raise CrowError("usage", "Informe ao menos um grupo em --group (veja crow-skills groups).")
54
+ unknown = [n for n in chosen if n not in groups]
55
+ if unknown:
56
+ raise CrowError("unknown_group", "Grupo desconhecido: " + ", ".join(unknown) + ". Grupos: " + ", ".join(groups) + ".")
57
+ wanted = {BEHAVIOUR} if BEHAVIOUR in source.catalog else set()
58
+ for name in chosen:
59
+ wanted.update(groups[name]["skills"])
60
+ return [n for n in source.catalog if n in wanted]
61
+
62
+
63
+ def suggested_handoffs(source, names):
64
+ """Handoffs of the selection that stay outside it: listed, never installed implicitly."""
65
+ chosen = set(names)
66
+ return sorted({n for name in names for n in source.catalog[name]["next"] if n not in chosen})
67
+
68
+
69
+ def coverage(groups, installed):
70
+ """{group: "completo"|"parcial"|"ausente", ...} for a set of installed names."""
71
+ result = []
72
+ for group in groups:
73
+ have = [s for s in group["skills"] if s in installed]
74
+ result.append({"group": group["name"], "installed": len(have), "total": len(group["skills"]),
75
+ "state": "complete" if len(have) == len(group["skills"]) else ("partial" if have else "absent")})
76
+ return result
@@ -182,9 +182,22 @@ def clean(text):
182
182
 
183
183
 
184
184
  def managed_skills(agent, home, store):
185
- """crow-* packages this CLI manages for the agent (edited copies still count)."""
185
+ """crow-* packages available to the agent: the ones this CLI manages there (edited copies still count) and
186
+ the ones Uniflow projects into its skills dir from the store (managed with --agents uniflow)."""
186
187
  target = destinations(agent, home)[0]
187
- return sorted(r["name"] for r in store.status([target], ()) if r["status"] in ("installed", "modified"))
188
+ rows = store.status([target], ())
189
+ store_ok = store_managed(home, store) if any(r["status"] == "uniflow_link" for r in rows) else set()
190
+ return sorted(r["name"] for r in rows if r["status"] in ("installed", "modified")
191
+ or (r["status"] == "uniflow_link" and r["name"] in store_ok))
192
+
193
+
194
+ def store_managed(home, store):
195
+ """Names whose Uniflow store copy is a crow-skills install (a record, files installed or edited).
196
+ A link to a store entry the user wrote by hand is not a crow-skills install for the CLI."""
197
+ try:
198
+ return {r["name"] for r in store.status(destinations("uniflow", home), ()) if r["status"] in ("installed", "modified")}
199
+ except (CrowError, OSError):
200
+ return set()
188
201
 
189
202
 
190
203
  def present_skills(agent, home, store, catalog):
@@ -44,14 +44,15 @@ import shlex
44
44
  import shutil
45
45
  import sys
46
46
 
47
+ from . import trust as hooktrust
47
48
  from .guide import protect, read_regular, sha, tomllib, write_atomic
48
49
  from .source import CrowError
49
50
  from .storage import atomic_json, checked, private_dir, read_json
50
51
 
51
- NAMES = ("claude-statusline", "claude-hooks", "claude-command", "codex-statusline", "codex-hooks",
52
+ NAMES = ("claude-statusline", "claude-hooks", "claude-command", "codex-statusline", "codex-hooks", "codex-hooks-trust",
52
53
  "gemini-hooks", "gemini-command", "agy-hooks", "agy-statusline", "devin-hooks", "tmux-status")
53
54
  OWNERS = {"claude-statusline": ("claude",), "claude-hooks": ("claude",), "claude-command": ("claude",),
54
- "codex-statusline": ("codex",), "codex-hooks": ("codex",),
55
+ "codex-statusline": ("codex",), "codex-hooks": ("codex",), "codex-hooks-trust": ("codex",),
55
56
  "gemini-hooks": ("gemini",), "gemini-command": ("gemini",), "agy-hooks": ("gemini",), "agy-statusline": ("gemini",),
56
57
  "devin-hooks": ("devin",), "tmux-status": ("claude", "codex", "gemini", "devin")}
57
58
  HOOK_SCRIPT = "crow_hook.py"
@@ -60,6 +61,9 @@ BROADCAST_SCRIPT = "crow_broadcast.py"
60
61
  COMMAND_HEADER = "Gerenciado por crow-skills (comando /crow). Não edite; use crow-skills integrations."
61
62
  BEGIN = "# >>> crow-skills integrations (gerenciado; use crow-skills integrations uninstall) >>>"
62
63
  END = "# <<< crow-skills integrations <<<"
64
+ # codex-hooks inside ~/.codex/config.toml, used when ~/.codex/hooks.json is a symlink (a dotfiles repo) or unsafe.
65
+ HOOKS_BEGIN = "# >>> crow-skills codex-hooks (gerenciado; use crow-skills integrations uninstall) >>>"
66
+ HOOKS_END = "# <<< crow-skills codex-hooks <<<"
63
67
  CODEX_ITEMS = ["model-with-reasoning", "context-remaining", "current-dir", "task-progress", "used-tokens"]
64
68
  SNIPPET_HEADER = "# Gerenciado por crow-skills (integração tmux). Não edite; use crow-skills integrations."
65
69
  UNSUPPORTED = {
@@ -364,14 +368,16 @@ HOOKS = {
364
368
 
365
369
 
366
370
  def codex_hooks_feature(home):
367
- """Codex runs hooks only with [features] hooks = true; report it, never edit it here."""
371
+ """Codex runs hooks unless [features] hooks = false (the default is on since 0.1xx, "stable").
372
+ An explicit false is the user's choice: reported, never edited."""
368
373
  try:
369
374
  data = tomllib.loads((home / ".codex" / "config.toml").read_text(encoding="utf-8")) if tomllib else {}
370
375
  except (OSError, ValueError):
371
376
  data = {}
372
- if (data.get("features") or {}).get("hooks") is True:
373
- return ""
374
- return " Habilite também [features] hooks = true em ~/.codex/config.toml (não alterado pelo crow-skills)."
377
+ if hooktrust.feature_off(data):
378
+ return (" [features] hooks = false em ~/.codex/config.toml desliga todos os hooks do Codex; mantido como você definiu "
379
+ "(troque para true para os hooks do crow-skills rodarem).")
380
+ return ""
375
381
 
376
382
 
377
383
  def hook_command(store, home, python, host, event, check=False):
@@ -494,6 +500,24 @@ def add_hooks(data, entries, layout):
494
500
 
495
501
 
496
502
  def hooks_sync(name, store, home, record, desired, python, dry):
503
+ if name == "codex-hooks":
504
+ unsafe = codex_hooks_json_unsafe(home)
505
+ if record and record.get("mode") != "toml" and unsafe:
506
+ # Installed into a regular hooks.json that has since become a symlink (moved into dotfiles):
507
+ # our entries live in the target now. Keep the record (and the script they call) until the
508
+ # user removes them; then the hooks move to config.toml on the next install.
509
+ left = codex_json_duplicates(home)
510
+ if left:
511
+ return record, "skip", ("~/.codex/hooks.json virou symlink (ou ficou inseguro) depois que o crow-skills gravou nele: "
512
+ + str(left) + " entrada(s) do crow-skills com crow_hook.py continuam no arquivo de destino, "
513
+ "que o crow-skills não edita. Remova-as de lá" + (" e rode crow-skills integrations install de novo: os hooks "
514
+ "passam para ~/.codex/config.toml." if desired else "; o registro e o script que elas chamam ficam "
515
+ "até isso, para o Codex não chamar um script apagado."))
516
+ record = None
517
+ if not desired:
518
+ return None, "skip", "Entradas do crow-skills já ausentes de ~/.codex/hooks.json; controle encerrado."
519
+ if (record or {}).get("mode") == "toml" or (unsafe and (desired or not record)):
520
+ return codex_hooks_toml_sync(store, home, record, desired, python, dry, unsafe)
497
521
  spec = HOOKS[name]
498
522
  target = spec["file"](home)
499
523
  if desired and not record and spec["requires"] is not None and not os.path.exists(spec["requires"](home)):
@@ -527,14 +551,320 @@ def hooks_sync(name, store, home, record, desired, python, dry):
527
551
  "created_file": record.get("created_file", False) if record else old is None}
528
552
  note = None
529
553
  if spec["host"] == "codex":
530
- note = ("Codex só executa hook novo ou alterado depois de aprovado: abra o Codex, rode /hooks e aprove as entradas "
531
- "do crow-skills (o hook do usuário já aprovado continua no mesmo índice).") + codex_hooks_feature(home)
554
+ note = (codex_approval_note() + codex_hooks_feature(home)).strip() or None
532
555
  if dry:
533
556
  return new_record, action, note
534
557
  tracked_write(store, path, dump(wanted), old, spec["backup"])
535
558
  return new_record, action, note
536
559
 
537
560
 
561
+ # --- codex-hooks in config.toml ------------------------------------------------------------------
562
+ # Codex 0.165 reads hooks from hooks.json and from config.toml (HooksToml: one array of matcher
563
+ # groups per event, each {matcher?, hooks: [{type = "command", command, timeout, async, ...}]};
564
+ # the same schema as hooks.json, read from the binary). When ~/.codex/hooks.json is a symlink
565
+ # (typically into a dotfiles repository) crow-skills never writes through it: the entries go to a
566
+ # marked block at the end of config.toml, verified by parsing and restored byte for byte.
567
+
568
+ def codex_hooks_json_unsafe(home):
569
+ """Why ~/.codex/hooks.json cannot be edited safely ("symlink" or a reason), or None."""
570
+ path = home / ".codex" / "hooks.json"
571
+ if os.path.islink(path):
572
+ return "symlink"
573
+ try:
574
+ read_regular(protect(path, home))
575
+ except CrowError as exc:
576
+ return str(exc)
577
+ return None
578
+
579
+
580
+ def codex_json_duplicates(home):
581
+ """crow_hook.py entries in ~/.codex/hooks.json when crow-skills does not manage that file
582
+ (read only, through the symlink): with the config.toml block they would run twice."""
583
+ path = home / ".codex" / "hooks.json"
584
+ try:
585
+ if not os.path.exists(path) or os.path.getsize(path) > 1024 * 1024:
586
+ return 0
587
+ with open(path, "r", encoding="utf-8") as handle:
588
+ data = json.load(handle)
589
+ except (OSError, ValueError):
590
+ return 0
591
+ count = 0
592
+ hooks = data.get("hooks") if isinstance(data, dict) else None
593
+ for groups in (hooks.values() if isinstance(hooks, dict) else ()):
594
+ for group in groups if isinstance(groups, list) else []:
595
+ items = group.get("hooks") if isinstance(group, dict) else None
596
+ for item in items if isinstance(items, list) else []:
597
+ if isinstance(item, dict) and HOOK_SCRIPT in str(item.get("command", "")):
598
+ count += 1
599
+ return count
600
+
601
+
602
+ def toml_string(value):
603
+ return json.dumps(value, ensure_ascii=False) # a JSON string is a valid TOML basic string
604
+
605
+
606
+ def codex_hooks_block(entries):
607
+ lines = [HOOKS_BEGIN]
608
+ for event, groups in entries.items():
609
+ for group in groups:
610
+ lines.append("[[hooks." + event + "]]")
611
+ if "matcher" in group:
612
+ lines.append("matcher = " + toml_string(group["matcher"]))
613
+ for item in group["hooks"]:
614
+ lines.append("[[hooks." + event + ".hooks]]")
615
+ for key, value in item.items():
616
+ lines.append(key + " = " + (("true" if value else "false") if isinstance(value, bool) else
617
+ str(value) if isinstance(value, int) else toml_string(value)))
618
+ return "\n".join(lines + [HOOKS_END]) + "\n"
619
+
620
+
621
+ def without_groups(parsed, groups):
622
+ """parsed minus each of groups ({event: [group]}), each removed once by equality; None when
623
+ one of them is not there unchanged (edited, or keys appended to it)."""
624
+ result = deepcopy(parsed)
625
+ hooks = result.get("hooks")
626
+ for event, wanted in groups.items():
627
+ current = hooks.get(event) if isinstance(hooks, dict) else None
628
+ if not isinstance(current, list):
629
+ return None
630
+ for group in wanted:
631
+ if group not in current:
632
+ return None
633
+ del current[len(current) - 1 - current[::-1].index(group)] # the last equal one: ours come after the user's
634
+ if not current:
635
+ del hooks[event]
636
+ return result
637
+
638
+
639
+ def codex_hooks_toml_sync(store, home, record, desired, python, dry, unsafe):
640
+ label = "~/.codex/config.toml"
641
+ if tomllib is None:
642
+ return record, "skip", "Python 3.11+ (tomllib) é necessário para gravar os hooks do Codex em config.toml com verificação."
643
+ directory = home / ".codex"
644
+ if desired and not record and not directory.is_dir():
645
+ return None, "skip", "~/.codex/hooks.json: CLI não configurado neste perfil; nada alterado."
646
+ path = protect(directory / "config.toml", home)
647
+ old = read_regular(path)
648
+ try:
649
+ text = old.decode("utf-8") if old is not None else ""
650
+ except UnicodeDecodeError:
651
+ return record, "skip", "config.toml não é UTF-8; hooks do Codex não configurados."
652
+ span = marked(text, HOOKS_BEGIN, HOOKS_END)
653
+ stripped = text[:span[0]] + text[span[1]:] if span else text
654
+ try:
655
+ current = tomllib.loads(text)
656
+ base = tomllib.loads(stripped)
657
+ except tomllib.TOMLDecodeError:
658
+ return record, "skip", "config.toml não é TOML válido; hooks do Codex não configurados."
659
+ old_block = text[span[0]:span[1]] if span else None
660
+ if span and (not record or record.get("block_sha") != sha(old_block.encode("utf-8"))):
661
+ return (record if desired else None), "skip", ("Bloco codex-hooks do crow-skills em config.toml foi editado ou não tem registro; "
662
+ "nada alterado. Remova o bloco manualmente e rode crow-skills integrations install.")
663
+ if span:
664
+ old_groups = tomllib.loads(old_block).get("hooks", {})
665
+ expected_base = without_groups(current, old_groups)
666
+ if expected_base is not None and "hooks" in expected_base and not expected_base["hooks"] and "hooks" not in base:
667
+ expected_base.pop("hooks")
668
+ if expected_base != base:
669
+ return (record if desired else None), "skip", ("Chaves acrescentadas logo depois do bloco codex-hooks em config.toml mudariam de "
670
+ "tabela; nada alterado. Revise o arquivo manualmente.")
671
+ added_newline = (record or {}).get("added_newline", False)
672
+ if not desired:
673
+ if not record:
674
+ return None, "unchanged", None
675
+ if not span:
676
+ return None, "skip", "Bloco codex-hooks ausente de config.toml; controle encerrado."
677
+ result = stripped
678
+ if added_newline and span[1] == len(text) and result.endswith("\n"):
679
+ result = result[:-1]
680
+ if dry:
681
+ return None, "remove", None
682
+ backup(store, "codex-config", old)
683
+ if record.get("created_file") and not result.strip():
684
+ path.unlink()
685
+ else:
686
+ write(path, result.encode("utf-8"), old)
687
+ return None, "remove", None
688
+ if not quoted_ok(python, hook_script_path(store), home):
689
+ return record, "skip", "Caminho do Python, do estado ou do home contém aspas/variáveis; hooks não configurados."
690
+ entries = hook_entries(store, home, python, "codex")
691
+ block = codex_hooks_block(entries)
692
+ if span:
693
+ if old_block == block:
694
+ report_duplicates(home)
695
+ return record, "unchanged", None
696
+ result = text[:span[0]] + block + text[span[1]:]
697
+ else:
698
+ added_newline = bool(stripped) and not stripped.endswith("\n")
699
+ result = stripped + ("\n" if added_newline else "") + block
700
+ expected = deepcopy(base)
701
+ hooks = expected.setdefault("hooks", {})
702
+ try:
703
+ for event, groups in entries.items():
704
+ if not isinstance(hooks.setdefault(event, []), list):
705
+ raise ValueError(event)
706
+ hooks[event].extend(deepcopy(groups))
707
+ if tomllib.loads(result) != expected:
708
+ raise ValueError("diff")
709
+ except (tomllib.TOMLDecodeError, ValueError, AttributeError):
710
+ return record, "skip", ("A tabela [hooks] de config.toml tem um formato que o bloco do crow-skills não preservaria "
711
+ "(por exemplo, hooks definidos inline); nada alterado.")
712
+ action = "update" if record else "install"
713
+ new_record = {"path": str(path), "mode": "toml", "added_newline": added_newline, "installed_at": now(),
714
+ "block_sha": sha(block.encode("utf-8")),
715
+ "created_file": record.get("created_file", False) if record and record.get("mode") == "toml" else old is None}
716
+ note = ("~/.codex/hooks.json " + ("é symlink" if unsafe == "symlink" else "não pode ser editado com segurança") +
717
+ "; os hooks do crow-skills foram gravados em ~/.codex/config.toml (bloco marcado) e o hooks.json não foi tocado. " +
718
+ codex_approval_note()) + codex_hooks_feature(home)
719
+ report_duplicates(home)
720
+ if dry:
721
+ return new_record, action, note.strip()
722
+ new_record["backup"] = backup(store, "codex-config", old)
723
+ write(path, result.encode("utf-8"), old)
724
+ return new_record, action, note.strip()
725
+
726
+
727
+ def codex_approval_note():
728
+ if _TRUST[0]:
729
+ return "" # codex-hooks-trust approves them right after, through Codex's own hooks/list
730
+ return ("--no-trust: o Codex só executa hook novo ou alterado depois de aprovado; abra o Codex, rode /hooks e aprove as "
731
+ "entradas do crow-skills (o hook do usuário já aprovado continua no mesmo índice).")
732
+
733
+
734
+ # --- codex-hooks-trust ---------------------------------------------------------------------------
735
+ # Codex 0.165 runs a user hook only when [hooks.state."<key>"] trusted_hash equals its current hash.
736
+ # Key and hash come from Codex itself (codex app-server, hooks/list); see crow_skills/trust.py.
737
+
738
+ _TRUST = [True]
739
+ _CHANGED = set()
740
+ _CHECKS = []
741
+
742
+
743
+ def codex_trust_sync(store, home, record, desired, python, dry):
744
+ if tomllib is None:
745
+ return record, "skip", "Python 3.11+ (tomllib) é necessário para aprovar os hooks do Codex com verificação."
746
+ directory = home / ".codex"
747
+ if not desired:
748
+ if not record:
749
+ return None, "unchanged", None
750
+ path = protect(directory / "config.toml", home)
751
+ old, text = hooktrust.read_config(path)
752
+ if not hooktrust.marked_span(text) and not record.get("keys"):
753
+ return None, "skip", "Bloco codex-hooks-trust ausente de config.toml; controle encerrado."
754
+ try:
755
+ result = hooktrust.plan(text, [], record)[0]
756
+ except (ValueError, tomllib.TOMLDecodeError):
757
+ return None, "skip", "Remover o bloco codex-hooks-trust mudaria outras chaves de config.toml; nada alterado, revise o arquivo."
758
+ if dry:
759
+ return None, "remove", None
760
+ backup(store, "codex-config", old)
761
+ if record.get("created_file") and not result.strip():
762
+ path.unlink()
763
+ else:
764
+ write(path, result.encode("utf-8"), old)
765
+ return None, "remove", None
766
+ hooks_record = _LIVE.get("codex-hooks")
767
+ if not _TRUST[0] or not isinstance(hooks_record, dict) or not hooks_record.get("path"):
768
+ return record, "unchanged", None # --no-trust, or no crow hooks in Codex to approve
769
+ if not quoted_ok(python, hook_script_path(store), home):
770
+ return record, "skip", "Caminho do Python, do estado ou do home contém aspas/variáveis; hooks não aprovados."
771
+ binary = hooktrust.codex_binary()
772
+ if not binary:
773
+ return record, "skip", ("codex não encontrado no PATH: os hooks do crow-skills " + ("seriam gravados" if dry else "foram gravados") +
774
+ ", mas não aprovados. " + hooktrust.MANUAL)
775
+ if dry:
776
+ # A preview never starts Codex (its app server writes state files in ~/.codex): the hashes are
777
+ # read from hooks/list when the change is applied.
778
+ if record and "codex-hooks" not in _CHANGED:
779
+ # Unchanged hooks keep their hash unless Codex itself changed how it hashes (an upgrade);
780
+ # that is re-checked on apply and reported then, without asking for a confirmation now.
781
+ _CHECKS.append({"integration": "codex-hooks-trust",
782
+ "reason": "Aprovação no Codex reconferida com o codex app-server ao aplicar (a prévia não o inicia)."})
783
+ return record, "unchanged", None
784
+ return (record or {"path": str(directory / "config.toml")}), ("update" if record else "install"), (
785
+ "Os hashes vêm do Codex (codex app-server, hooks/list) quando a mudança for aplicada.")
786
+ entries = hook_entries(store, home, python, "codex")
787
+ try:
788
+ listed = hooktrust.hooks_list(directory, home, binary)
789
+ except hooktrust.ProbeError as exc:
790
+ return record, "skip", "Não foi possível consultar o Codex (" + str(exc) + "); hooks não aprovados. " + hooktrust.MANUAL
791
+ ours, foreign, missing = hooktrust.classify(listed, entries, hooks_record["path"], hook_script_path(store))
792
+ notes = []
793
+ if foreign:
794
+ notes.append(str(len(foreign)) + " hook(s) com crow_hook.py não batem com o que o crow-skills gravou (editados ou de outro "
795
+ "arquivo) e não foram aprovados.")
796
+ if missing:
797
+ notes.append(str(len(missing)) + " hook(s) do crow-skills não aparecem no Codex (hooks/list); confira crow-skills doctor.")
798
+ pairs = sorted((h["key"], h["currentHash"]) for h, _ in ours)
799
+ path = protect(directory / "config.toml", home)
800
+ old, text = hooktrust.read_config(path)
801
+ span = hooktrust.marked_span(text)
802
+ if span and not record:
803
+ return None, "skip", ("Bloco codex-hooks-trust em config.toml sem registro no estado do crow-skills; nada alterado. "
804
+ "Remova o bloco manualmente e rode crow-skills integrations install.")
805
+ if not pairs and not span:
806
+ return record, "skip", " ".join(notes) or "Codex não lista hooks do crow-skills para aprovar."
807
+ try:
808
+ result, adopted, kept, added_newline, block = hooktrust.plan(text, pairs, record)
809
+ except (ValueError, tomllib.TOMLDecodeError, AttributeError):
810
+ return record, "skip", ("A tabela [hooks.state] de config.toml tem um formato que o bloco do crow-skills não preservaria "
811
+ "(por exemplo, definida inline); hooks não aprovados. " + hooktrust.MANUAL)
812
+ if kept:
813
+ notes.append(str(len(kept)) + " hook(s) do crow-skills têm estado definido por você em [hooks.state] (por exemplo, "
814
+ "enabled = false); mantido, não aprovado pelo crow-skills.")
815
+ if adopted:
816
+ notes.append(str(len(adopted)) + " aprovação(ões) já existente(s) para hooks do crow-skills passaram para o bloco gerenciado.")
817
+ off = hooktrust.feature_off(tomllib.loads(text))
818
+ if off:
819
+ notes.append(codex_hooks_feature(home).strip())
820
+ trusted = dict(p for p in pairs if p[0] not in kept)
821
+ new_record = {"path": str(path), "keys": trusted, "added_newline": added_newline,
822
+ "installed_at": (record or {}).get("installed_at") or now(),
823
+ "created_file": record.get("created_file", False) if record else old is None}
824
+ note = " ".join(notes) or None
825
+ if result == text:
826
+ if note:
827
+ _WARNINGS.append({"integration": "codex-hooks-trust", "reason": note})
828
+ return (record if record and record.get("keys") == trusted else new_record), "unchanged", None
829
+ if not block:
830
+ new_record = None
831
+ action = "update" if record else ("adopt" if adopted and not [k for k in trusted if k not in adopted] else "install")
832
+ if dry:
833
+ return new_record, action, note
834
+ new_record_backup = backup(store, "codex-config", old)
835
+ write(path, result.encode("utf-8"), old)
836
+ if new_record is not None:
837
+ new_record["backup"] = new_record_backup
838
+ try: # confirm with Codex itself that the hooks now report "trusted"
839
+ after = hooktrust.classify(hooktrust.hooks_list(directory, home, binary), entries, hooks_record["path"],
840
+ hook_script_path(store))[0]
841
+ pending = [h["key"] for h, _ in after if h["key"] in trusted and h.get("trustStatus") != "trusted"]
842
+ if pending:
843
+ note = ((note + " ") if note else "") + str(len(pending)) + " hook(s) ainda não aparecem como aprovados no Codex."
844
+ except hooktrust.ProbeError:
845
+ pass
846
+ return new_record, action, note
847
+
848
+
849
+ # Findings that do not stop an integration but need the user (reported in "skipped").
850
+ _WARNINGS = []
851
+
852
+
853
+ def report_duplicates(home):
854
+ note = codex_duplicates_note(home)
855
+ if note:
856
+ _WARNINGS.append({"integration": "codex-hooks", "reason": note})
857
+
858
+
859
+ def codex_duplicates_note(home):
860
+ count = codex_json_duplicates(home)
861
+ if not count:
862
+ return None
863
+ return ("~/.codex/hooks.json (não gerenciado pelo crow-skills) já tem " + str(count) +
864
+ " entrada(s) com crow_hook.py, provavelmente adicionadas à mão; com o bloco em config.toml elas rodariam em dobro. "
865
+ "Remova-as do hooks.json (ou do arquivo para onde o symlink aponta); o crow-skills não edita esse arquivo.")
866
+
867
+
538
868
  # --- /crow slash commands ------------------------------------------------------------------------
539
869
 
540
870
  COMMANDS = {
@@ -612,9 +942,9 @@ def command_sync(name, store, home, record, desired, python, dry):
612
942
 
613
943
  # --- codex ---------------------------------------------------------------------------------
614
944
 
615
- def marked(text):
616
- begins = [m.start() for m in re.finditer(r"(?m)^" + re.escape(BEGIN) + r"\n", text)]
617
- ends = [m.end() for m in re.finditer(r"(?m)^" + re.escape(END) + r"\n", text)]
945
+ def marked(text, begin=BEGIN, end=END):
946
+ begins = [m.start() for m in re.finditer(r"(?m)^" + re.escape(begin) + r"\n", text)]
947
+ ends = [m.end() for m in re.finditer(r"(?m)^" + re.escape(end) + r"\n", text)]
618
948
  if not begins and not ends:
619
949
  return None
620
950
  if len(begins) != 1 or len(ends) != 1 or ends[0] <= begins[0]:
@@ -858,6 +1188,7 @@ def tmux_sync(store, home, record, desired, python, dry):
858
1188
 
859
1189
 
860
1190
  SYNC = {"claude-statusline": claude_sync, "codex-statusline": codex_sync, "tmux-status": tmux_sync,
1191
+ "codex-hooks-trust": codex_trust_sync,
861
1192
  "agy-statusline": agy_statusline_sync,
862
1193
  **{name: (lambda n: lambda *a: hooks_sync(n, *a))(name) for name in HOOKS},
863
1194
  **{name: (lambda n: lambda *a: command_sync(n, *a))(name) for name in COMMANDS}}
@@ -865,7 +1196,7 @@ SYNC = {"claude-statusline": claude_sync, "codex-statusline": codex_sync, "tmux-
865
1196
 
866
1197
  # --- orchestration -------------------------------------------------------------------------
867
1198
 
868
- def sync(store, home, wanted, dry_run=False, python=None):
1199
+ def sync(store, home, wanted, dry_run=False, python=None, trust=True):
869
1200
  """Bring every integration in line with the agents that have crow-behaviour.
870
1201
 
871
1202
  wanted: agents that will have crow-behaviour managed after the command.
@@ -886,6 +1217,10 @@ def sync(store, home, wanted, dry_run=False, python=None):
886
1217
  after["files"][record["path"]] = {"backup": record.get("backup"), "created_file": record.get("created_file", False),
887
1218
  "written_sha": record["written_sha"]}
888
1219
  global _FILES, _LIVE
1220
+ del _WARNINGS[:]
1221
+ _TRUST[0] = trust
1222
+ _CHANGED.clear()
1223
+ del _CHECKS[:]
889
1224
  _FILES = {k: dict(v) for k, v in after["files"].items()}
890
1225
  _LIVE = after["integrations"]
891
1226
  with (nullcontext() if dry_run else store.lock()):
@@ -906,6 +1241,8 @@ def sync(store, home, wanted, dry_run=False, python=None):
906
1241
  except (CrowError, OSError, ValueError) as exc:
907
1242
  report["skipped"].append({"integration": name, "reason": str(exc) or "falha de leitura/gravação"})
908
1243
  continue
1244
+ if action not in ("skip", "unchanged"):
1245
+ _CHANGED.add(name)
909
1246
  if action == "skip":
910
1247
  report["skipped"].append({"integration": name, "reason": note})
911
1248
  elif action != "unchanged" or note:
@@ -930,13 +1267,59 @@ def sync(store, home, wanted, dry_run=False, python=None):
930
1267
  if script.exists():
931
1268
  script.unlink()
932
1269
  remove_bytecode(store)
1270
+ report["skipped"].extend(_WARNINGS)
1271
+ del _WARNINGS[:]
933
1272
  for key in ("changes", "skipped"):
934
1273
  report[key].sort(key=lambda c: NAMES.index(c["integration"]) if c["integration"] in NAMES else 99)
1274
+ if _CHECKS:
1275
+ report["checks"] = list(_CHECKS) # verified on apply; informative, never a change to confirm
1276
+ del _CHECKS[:]
935
1277
  report["dry_run"] = dry_run
936
1278
  return report
937
1279
 
938
1280
 
939
- def status(store, home):
1281
+ def hooks_enabled(name, store, home, record, probe=True):
1282
+ """Whether the CLI will actually run the crow hooks: {state, fix?} (see trust.py)."""
1283
+ host = HOOKS[name]["host"]
1284
+ if host != "codex":
1285
+ return hooktrust.non_codex_state(host, home)
1286
+ base = {}
1287
+ try:
1288
+ parsed = tomllib.loads((home / ".codex" / "config.toml").read_text(encoding="utf-8")) if tomllib else {}
1289
+ except (OSError, ValueError):
1290
+ parsed = {}
1291
+ if hooktrust.feature_off(parsed):
1292
+ return {"state": "feature_off", "fix": codex_hooks_feature(home).strip()}
1293
+ if not probe:
1294
+ return {"state": "unknown", "fix": "Aprovação no Codex não consultada aqui; rode crow-skills doctor para conferir."}
1295
+ binary = hooktrust.codex_binary()
1296
+ if not binary:
1297
+ return {"state": "unknown", "fix": "codex não encontrado no PATH; não dá para conferir a aprovação dos hooks. " + hooktrust.MANUAL}
1298
+ try:
1299
+ listed = hooktrust.hooks_list(home / ".codex", home, binary)
1300
+ except hooktrust.ProbeError as exc:
1301
+ return {"state": "unknown", "fix": "Não foi possível consultar o Codex (" + str(exc) + "). " + hooktrust.MANUAL}
1302
+ python = python_from(record, store, home) or python_binary()
1303
+ base.update(hooktrust.report(listed, hook_entries(store, home, python, "codex"), record["path"], hook_script_path(store), parsed))
1304
+ return base
1305
+
1306
+
1307
+ def python_from(record, store, home):
1308
+ """The Python the installed hooks call (the first token of a written command), or None."""
1309
+ del record
1310
+ script = str(hook_script_path(store))
1311
+ for path in (home / ".codex" / "hooks.json", home / ".codex" / "config.toml"):
1312
+ try:
1313
+ text = (read_regular(path) or b"").decode("utf-8", "replace")
1314
+ except (CrowError, OSError):
1315
+ continue
1316
+ found = re.search(r"([^\s\"'=]+) -I -S " + re.escape(script), text)
1317
+ if found:
1318
+ return found.group(1)
1319
+ return None
1320
+
1321
+
1322
+ def status(store, home, probe=True):
940
1323
  state = load_state(store)
941
1324
  rows = []
942
1325
  for name in NAMES:
@@ -946,6 +1329,14 @@ def status(store, home):
946
1329
  row["path"] = record.get("path") or record.get("conf")
947
1330
  if name == "tmux-status" and not record.get("block"):
948
1331
  row["note"] = "tmux.conf é symlink; linha source-file adicionada manualmente pelo usuário."
1332
+ if name == "codex-hooks" and record.get("mode") == "toml":
1333
+ row["note"] = "Gravado em ~/.codex/config.toml (bloco marcado): ~/.codex/hooks.json é symlink ou inseguro e não é editado."
1334
+ duplicates = codex_duplicates_note(home)
1335
+ if duplicates:
1336
+ row["note"] += " " + duplicates
1337
+ row["duplicates"] = codex_json_duplicates(home)
1338
+ if name in HOOKS:
1339
+ row["enabled"] = hooks_enabled(name, store, home, record, probe)
949
1340
  rows.append(row)
950
1341
  for agent, reason in UNSUPPORTED.items():
951
1342
  rows.append({"integration": UNSUPPORTED_ROW[agent], "agents": [agent], "status": "unsupported", "note": reason})