@hivey/cli 0.9.47 → 0.9.50

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.
@@ -5,23 +5,58 @@ Creates <root>/<agent>/ (and <root>/<agent>/.claude/skills/) and writes
5
5
  <root>/<agent>/.claude/settings.json with:
6
6
  - permissions.additionalDirectories: the swarm root (and --vault, if given), so the agent
7
7
  can read and write the whole swarm folder;
8
- - env.AGENTS_TTS = "0": workers stay silent; only the master speaks its summaries.
8
+ - env.AGENTS_TTS = "0": workers stay silent; only the master speaks its summaries;
9
+ - hooks.Stop: the swarm done gate (swarm_gate.py, Claude Code only): an agent that tries
10
+ to stop while it still owns an in-progress task is reminded once to submit it, mark it
11
+ blocked, or say why it stays open. --no-gate leaves it out.
9
12
  Existing settings are kept and merged. The coordinator writes the agent's CLAUDE.md; skills
10
13
  are installed separately, as `hivey skills guide` says.
11
14
 
12
15
  --worktree REPO gives a coding agent its own git worktree of REPO at <root>/<agent>/repo on
13
16
  branch swarm/<agent>, so parallel builders never overwrite each other. REPO needs at least one
14
- commit. The integrator (the critic or a dedicated agent) merges the branches.
17
+ commit. The integrator (the critic or a dedicated agent) merges the branches. Gitignored files
18
+ the worktree needs (`.env`, local config) are copied in when REPO has a `.worktreeinclude`
19
+ (gitignore syntax, the same file Claude Code's own worktrees read).
15
20
 
16
- Usage: setup_agent.py <swarm_root> <agent> [--vault PATH] [--worktree REPO]
21
+ Usage: setup_agent.py <swarm_root> <agent> [--vault PATH] [--worktree REPO] [--no-gate]
17
22
  """
18
23
  import argparse
19
24
  import json
20
25
  import re
26
+ import shutil
21
27
  import subprocess
22
28
  from pathlib import Path
23
29
 
24
30
  NAME_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$") # hivey agent-name rule
31
+ GATE = Path(__file__).absolute().parent / "swarm_gate.py" # keep the installed path
32
+
33
+
34
+ def copy_included(repo, worktree):
35
+ """Copy REPO's untracked files that match its .worktreeinclude into the new worktree."""
36
+ include = repo / ".worktreeinclude"
37
+ if not include.is_file():
38
+ return []
39
+ r = subprocess.run(["git", "-C", str(repo), "ls-files", "--others", "--ignored",
40
+ f"--exclude-from={include}"], capture_output=True, text=True)
41
+ copied = []
42
+ for rel in r.stdout.splitlines():
43
+ src, dst = repo / rel, worktree / rel
44
+ if not src.is_file() or dst.exists():
45
+ continue
46
+ dst.parent.mkdir(parents=True, exist_ok=True)
47
+ shutil.copy2(src, dst)
48
+ copied.append(rel)
49
+ return copied
50
+
51
+
52
+ def add_gate(settings):
53
+ """Register the swarm done gate as a Stop hook (idempotent). True when added."""
54
+ cmd = f"python3 {GATE}"
55
+ entries = settings.setdefault("hooks", {}).setdefault("Stop", [])
56
+ if any(h.get("command") == cmd for m in entries for h in m.get("hooks", [])):
57
+ return False
58
+ entries.append({"hooks": [{"type": "command", "command": cmd, "timeout": 30}]})
59
+ return True
25
60
 
26
61
 
27
62
  def add_worktree(repo, worktree, agent):
@@ -42,6 +77,8 @@ def main():
42
77
  p.add_argument("agent", help="agent key, e.g. builder (matches [a-z][a-z0-9_-]{0,31})")
43
78
  p.add_argument("--vault", help="the swarm's wiki, if it lives outside the root; the agent gets access")
44
79
  p.add_argument("--worktree", metavar="REPO", help="git repo to give this agent its own worktree of")
80
+ p.add_argument("--no-gate", action="store_true",
81
+ help="don't register the done gate (the Stop hook that reminds about open tasks)")
45
82
  args = p.parse_args()
46
83
 
47
84
  if not NAME_RE.match(args.agent):
@@ -51,10 +88,12 @@ def main():
51
88
  agent_dir = root / args.agent
52
89
  (agent_dir / ".claude" / "skills").mkdir(parents=True, exist_ok=True)
53
90
 
54
- worktree = None
91
+ worktree, copied = None, []
55
92
  if args.worktree:
56
93
  worktree = agent_dir / "repo"
57
- add_worktree(Path(args.worktree).expanduser().resolve(), worktree, args.agent)
94
+ repo = Path(args.worktree).expanduser().resolve()
95
+ add_worktree(repo, worktree, args.agent)
96
+ copied = copy_included(repo, worktree)
58
97
 
59
98
  settings_path = agent_dir / ".claude" / "settings.json"
60
99
  try:
@@ -66,10 +105,12 @@ def main():
66
105
  if str(d) not in dirs:
67
106
  dirs.append(str(d))
68
107
  settings.setdefault("env", {})["AGENTS_TTS"] = "0" # workers stay silent; only the master speaks
108
+ gate = False if args.no_gate else add_gate(settings)
69
109
  settings_path.write_text(json.dumps(settings, indent=2) + "\n")
70
110
 
71
111
  print(json.dumps({"agent": args.agent, "dir": str(agent_dir), "settings": str(settings_path),
72
- "worktree": str(worktree) if worktree else None}, indent=2))
112
+ "worktree": str(worktree) if worktree else None, "copied": copied,
113
+ "gate_added": gate}, indent=2))
73
114
 
74
115
 
75
116
  if __name__ == "__main__":
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env python3
2
+ """Stop-hook "done gate" for a hivey swarm agent (Claude Code), from hivey-swarm-creator.
3
+
4
+ Registered in the agent's own .claude/settings.json by setup_agent.py. When the agent tries
5
+ to finish a turn while it still owns an `in-progress` task on the swarm's board
6
+ (<root>/.swarm/tasks.json), the stop is blocked once with a reminder: submit the task for
7
+ review, mark it blocked with a note, or say in one line why it stays open (waiting for a reply
8
+ or for background work). One reminder per task per in-progress episode, so it can never loop,
9
+ and nothing happens when the agent owns no open task. Standard library only; any problem just
10
+ lets the agent stop.
11
+
12
+ Usage: registered as `python3 swarm_gate.py` (reads the Stop hook's JSON on stdin).
13
+ """
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ HERE = Path(__file__).absolute().parent
21
+ TASKS = HERE / "swarm_tasks.py"
22
+
23
+
24
+ def find_agent(start):
25
+ """(swarm root, agent key): the folder holding .swarm/ and the first folder below it."""
26
+ p = Path(start).resolve()
27
+ for d in [p, *p.parents]:
28
+ if (d / ".swarm").is_dir():
29
+ if d == p:
30
+ return None
31
+ return d, p.relative_to(d).parts[0]
32
+ return None
33
+
34
+
35
+ def log_event(root, actor, **fields):
36
+ rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "type": "gate", "actor": actor, **fields}
37
+ try:
38
+ with open(root / ".swarm" / "events.jsonl", "a") as f:
39
+ f.write(json.dumps(rec) + "\n")
40
+ except OSError:
41
+ pass
42
+
43
+
44
+ def main():
45
+ try:
46
+ event = json.load(sys.stdin)
47
+ except ValueError:
48
+ event = {}
49
+ found = find_agent(event.get("cwd") or os.environ.get("CLAUDE_PROJECT_DIR") or ".")
50
+ if not found:
51
+ return
52
+ root, agent = found
53
+ try:
54
+ tasks = json.loads((root / ".swarm" / "tasks.json").read_text()).get("tasks", [])
55
+ except (OSError, ValueError):
56
+ return
57
+ open_ids = sorted(t["id"] for t in tasks
58
+ if t.get("owner") == agent and t.get("status") == "in-progress")
59
+
60
+ state_path = root / ".swarm" / "gate" / f"{agent}.json"
61
+ try:
62
+ reminded = set(json.loads(state_path.read_text()).get("reminded", []))
63
+ except (OSError, ValueError):
64
+ reminded = set()
65
+ # A task that left in-progress starts a new episode next time.
66
+ reminded &= set(open_ids)
67
+ fresh = [tid for tid in open_ids if tid not in reminded]
68
+ if fresh:
69
+ reminded |= set(fresh)
70
+ try:
71
+ state_path.parent.mkdir(parents=True, exist_ok=True)
72
+ state_path.write_text(json.dumps({"reminded": sorted(reminded)}) + "\n")
73
+ except OSError:
74
+ return
75
+ if not fresh:
76
+ return
77
+
78
+ ids = ", ".join(fresh)
79
+ first = fresh[0]
80
+ log_event(root, agent, tasks=fresh)
81
+ print(json.dumps({
82
+ "decision": "block",
83
+ "reason": (
84
+ f"Swarm done gate: you still own {ids} (in-progress) on the board. Before you stop:\n"
85
+ f"- finished: `python3 {TASKS} submit {first} --as {agent} --artifact <path>` "
86
+ "(add --repo/--range for code), so the fresh critics review it;\n"
87
+ f"- stuck or waiting on someone: `python3 {TASKS} set {first} blocked --as {agent} "
88
+ "--note '<why>'` and tell your master;\n"
89
+ "- only pausing (waiting for a reply or background work): say so in one line and stop.\n"
90
+ "This reminder comes once per task."
91
+ ),
92
+ }))
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()