-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhydra.py
More file actions
2657 lines (2251 loc) · 93.5 KB
/
hydra.py
File metadata and controls
2657 lines (2251 loc) · 93.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import fnmatch
import glob as globlib
import json
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
from pathlib import PurePosixPath
class HydraError(RuntimeError):
pass
MctlError = HydraError
HYDRA_DIRNAME = ".hydra"
AGENTS_DIRNAME = ".agents"
TASKS_DIRNAME = "tasks"
LOCKS_DB_NAME = "locks.db"
CONFIG_NAME = "config.json"
DEFAULT_SHARED_DEPS = ["node_modules", "venv", ".venv", "target"]
ZELLIJ_LAYOUT_NAME = "layout.kdl"
# Default Zellij layout (KDL). This is a per-project file created under `.hydra/`.
ZELLIJ_LAYOUT_TEMPLATE = """// CodeHydra default Zellij layout
//
// Usage:
// zellij --session <project> --layout .hydra/layout.kdl
//
// Notes:
// - Starts with a single `main` tab (for the Claude Lead).
// - Create agent tabs dynamically (eg. `zellij action new-tab -n codex-1`).
layout {
default_tab_template {
// Standard Zellij UI (tab bar + status bar)
pane size=1 borderless=true {
plugin location="zellij:tab-bar"
}
children
pane size=2 borderless=true {
plugin location="zellij:status-bar"
}
}
tab name="main" focus=true {
pane
}
}
"""
# Guide file templates
CLAUDE_MD_TEMPLATE = """# Claude Lead 工作指南
## 角色定位
你是 **Claude Lead**:项目经理,负责理解需求、拆解任务、调度子 AI(Codex/Gemini),对最终交付负责。
## 工作环境
- **当前位置**:main 终端(项目根目录)
- **Tmux Session**:项目名称
- **子 AI 位置**:同一 session 的不同 window
## 核心职责
1. 需求理解:与用户沟通,明确目标和验收标准
2. 任务拆解:将复杂任务分解为可执行的子任务
3. Agent 调度:派遣 Codex(执行)和 Gemini(顾问)
4. 进度跟踪:监控子 AI 进度,及时调整计划
5. 质量把控:验证交付物,确保符合要求
## 完整操作手册
详细操作说明请参考:`CLAUDE_GUIDE.md`
"""
AGENT_MD_TEMPLATE = """# Codex Agent 工作指南
## 角色定位
你是 **Codex**:代码执行者,负责实现具体功能、修复 Bug、编写测试。
## 工作环境
- **当前位置**:Agent 工作区(`.agents/<agent-name>/<task-id>/`)
- **Git 分支**:`agent/<agent-name>/<task-id>`
- **文件权限**:只能修改任务 allow 列表中的文件
## 核心职责
1. 代码实现:根据需求编写高质量代码
2. Bug 修复:定位并修复问题
3. 测试编写:确保代码可测试
4. 文档更新:必要时更新相关文档
## 提交修改
**重要**:任务完成后,必须先提交所有修改,然后再通知 Claude Lead。
```bash
# 1. 查看修改状态
git status
# 2. 添加所有修改(包括代码和文档)
git add <修改的文件>
# 3. 提交修改
git commit -m "任务描述
详细说明修改内容
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"
```
**提交内容应包括**:
- 所有代码修改
- 测试文件
- 文档(如实现说明、设计文档等)
- 配置文件修改
**为什么要提交**:
- 确保修改可以被 merge 到主分支
- 保留完整的修改历史
- 避免 Claude Lead 无法合并你的工作
## 完成通知
任务完成后通知 Claude Lead:
**方式1(推荐)**:直接使用 hydra.py(已通过软链接在当前目录)
```bash
python hydra.py agent notify "任务完成:<简要说明>"
```
**方式2(备用)**:使用环境变量
```bash
python $HYDRA_PROJECT_ROOT/hydra.py agent notify "任务完成:<简要说明>"
```
**何时通知**:
- 任务完成时
- 遇到阻塞问题需要帮助时
- 发现需求不明确需要澄清时
"""
GEMINI_MD_TEMPLATE = """# Gemini Agent 工作指南
## 角色定位
你是 **Gemini**:技术顾问,负责提供第二观点、长文总结、架构建议。
## 工作环境
- **当前位置**:Agent 工作区(`.agents/<agent-name>/<task-id>/`)
- **Git 分支**:`agent/<agent-name>/<task-id>`
- **工作模式**:研究、分析、建议
## 核心职责
1. 技术调研:研究技术方案,提供多个选项
2. 架构建议:评估架构设计,指出潜在问题
3. 长文总结:总结复杂文档,提取关键信息
4. 第二观点:对 Codex 的方案提供补充意见
## 提交修改
**重要**:研究完成后,必须先提交所有修改,然后再通知 Claude Lead。
```bash
# 1. 查看修改状态
git status
# 2. 添加所有修改(包括研究文档、分析报告等)
git add <修改的文件>
# 3. 提交修改
git commit -m "研究任务描述
详细说明研究内容和结论
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"
```
**提交内容应包括**:
- 研究报告和分析文档
- 技术方案对比文档
- 架构设计建议
- 总结文档
**为什么要提交**:
- 确保研究成果可以被 merge 到主分支
- 保留完整的研究历史
- 避免 Claude Lead 无法合并你的工作
## 完成通知
研究完成后通知 Claude Lead:
**方式1(推荐)**:直接使用 hydra.py(已通过软链接在当前目录)
```bash
python hydra.py agent notify "研究完成:<简要结论>"
```
**方式2(备用)**:使用环境变量
```bash
python $HYDRA_PROJECT_ROOT/hydra.py agent notify "研究完成:<简要结论>"
```
**何时通知**:
- 研究完成时
- 发现关键问题需要立即讨论时
- 需要 Claude Lead 做决策时
"""
def _now_ts() -> int:
return int(time.time())
def _run(
argv: Sequence[str],
*,
cwd: Optional[Path] = None,
check: bool = True,
capture: bool = True,
env: Optional[Dict[str, str]] = None,
) -> subprocess.CompletedProcess:
kwargs = {
"cwd": str(cwd) if cwd else None,
"check": False,
"text": True,
"env": env,
}
if capture:
kwargs["stdout"] = subprocess.PIPE
kwargs["stderr"] = subprocess.PIPE
proc = subprocess.run(list(argv), **kwargs) # nosec - CLI tool by design
if check and proc.returncode != 0:
stderr = (proc.stderr or "").strip()
stdout = (proc.stdout or "").strip()
msg = f"Command failed ({proc.returncode}): {' '.join(argv)}"
if stdout:
msg += f"\nSTDOUT:\n{stdout}"
if stderr:
msg += f"\nSTDERR:\n{stderr}"
raise HydraError(msg)
return proc
def _git(root: Path, args: Sequence[str], *, capture: bool = True) -> subprocess.CompletedProcess:
return _run(["git", *args], cwd=root, capture=capture)
def _tmux(args: Sequence[str], *, capture: bool = True) -> subprocess.CompletedProcess:
return _run(["tmux", *args], capture=capture)
def _tmux_available() -> bool:
return shutil.which("tmux") is not None
def _zellij_available() -> bool:
# Temporarily disabled - prefer tmux for stability
return False
# return shutil.which("zellij") is not None
def _find_project_root(start: Optional[Path] = None) -> Path:
cur = (start or Path.cwd()).resolve()
# Prefer the common git dir so this works inside linked worktrees.
try:
out = _run(["git", "rev-parse", "--git-common-dir"], cwd=cur, capture=True).stdout.strip()
if out:
common_dir = Path(out)
if not common_dir.is_absolute():
common_dir = (cur / common_dir).resolve()
if common_dir.is_dir():
root = common_dir.parent
if (root / ".git").exists():
return root
except HydraError:
pass
for candidate in (cur, *cur.parents):
if (candidate / ".git").is_dir():
return candidate
raise HydraError("Not inside a git repository (could not find a .git directory).")
def _find_hydra_root_for_hooks() -> Path:
explicit = os.environ.get("HYDRA_PROJECT_ROOT", "").strip()
if explicit:
p = Path(explicit).expanduser()
if p.exists():
return p.resolve()
return _find_project_root()
def _ensure_dirs(root: Path) -> Tuple[Path, Path, Path]:
hydra_dir = root / HYDRA_DIRNAME
agents_dir = root / AGENTS_DIRNAME
tasks_dir = root / TASKS_DIRNAME
hydra_dir.mkdir(parents=True, exist_ok=True)
agents_dir.mkdir(parents=True, exist_ok=True)
tasks_dir.mkdir(parents=True, exist_ok=True)
return hydra_dir, agents_dir, tasks_dir
def _ensure_config(hydra_dir: Path) -> Path:
cfg = hydra_dir / CONFIG_NAME
if not cfg.exists():
cfg.write_text(json.dumps({"created": _now_ts(), "version": "0.1.0"}, indent=2) + "\n", encoding="utf-8")
return cfg
def _ensure_zellij_layout(hydra_dir: Path, *, quiet: bool = True) -> Path:
layout_path = hydra_dir / ZELLIJ_LAYOUT_NAME
if not layout_path.exists():
layout_path.write_text(ZELLIJ_LAYOUT_TEMPLATE, encoding="utf-8")
if not quiet:
print(f"Created {layout_path}")
return layout_path
def _ensure_tmux_session(root: Path, hydra_dir: Path, explicit_session: Optional[str] = None) -> None:
"""Ensure tmux session exists for the project."""
if not _tmux_available():
print("hydra warning: tmux not found; skipping tmux session creation", file=sys.stderr)
_save_session_name(hydra_dir, explicit_session or root.name)
return
# If explicit session name provided, use it directly
if explicit_session:
result = subprocess.run(
["tmux", "has-session", "-t", explicit_session],
capture_output=True,
text=True
)
if result.returncode == 0:
print(f"Tmux session '{explicit_session}' already exists")
_save_session_name(hydra_dir, explicit_session)
return
# Create the session with explicit name
try:
subprocess.run(
["tmux", "new-session", "-d", "-s", explicit_session, "-c", str(root)],
check=True,
capture_output=True,
text=True
)
print(f"Created tmux session '{explicit_session}'")
_save_session_name(hydra_dir, explicit_session)
except subprocess.CalledProcessError as e:
print(f"Warning: Failed to create tmux session: {e.stderr}")
return
base_name = root.name
session_name = base_name
suffix = 0
while True:
# Check if session exists
result = subprocess.run(
["tmux", "has-session", "-t", session_name],
capture_output=True,
text=True
)
if result.returncode != 0:
# Session doesn't exist, create it
break
# Session exists, check if it's for this project
cwd_result = subprocess.run(
["tmux", "display-message", "-t", f"{session_name}:0", "-p", "#{pane_current_path}"],
capture_output=True,
text=True
)
if cwd_result.returncode == 0:
session_cwd = Path(cwd_result.stdout.strip())
if session_cwd == root:
print(f"Tmux session '{session_name}' already exists for this project")
_save_session_name(hydra_dir, session_name)
return
# Different project, try next suffix
suffix += 1
session_name = f"{base_name}-{suffix}"
# Create new session
try:
subprocess.run(
["tmux", "new-session", "-d", "-s", session_name, "-c", str(root)],
check=True,
capture_output=True,
text=True
)
print(f"Created tmux session '{session_name}'")
_save_session_name(hydra_dir, session_name)
except subprocess.CalledProcessError as e:
print(f"Warning: Failed to create tmux session: {e.stderr}")
def _ensure_zellij_session(root: Path, hydra_dir: Path) -> None:
"""Ensure Zellij session exists for the project."""
if not _zellij_available():
print("hydra warning: zellij not found; skipping zellij session creation", file=sys.stderr)
_save_session_name(hydra_dir, root.name)
return
layout_path = hydra_dir / ZELLIJ_LAYOUT_NAME
if not layout_path.exists():
print(f"hydra warning: layout file {layout_path} not found", file=sys.stderr)
_save_session_name(hydra_dir, root.name)
return
session_name = root.name
# Check if session exists by listing sessions
try:
result = subprocess.run(
["zellij", "list-sessions"],
capture_output=True,
text=True,
check=False
)
# Parse session list to check if our session exists
if result.returncode == 0:
for line in result.stdout.splitlines():
# Session line format: "session-name [Created ...] (current/EXITED)"
if line.strip().startswith(session_name + " "):
print(f"Zellij session '{session_name}' already exists for this project")
_save_session_name(hydra_dir, session_name)
return
except subprocess.CalledProcessError:
pass
# Session doesn't exist, create it in detached mode
# Note: Zellij doesn't have a direct "detached" mode like tmux
# We create the session but it will need to be attached manually
print(f"Zellij session '{session_name}' needs to be created manually.")
print(f"Run: zellij --new-session-with-layout {layout_path} -s {session_name}")
_save_session_name(hydra_dir, session_name)
def _save_session_name(hydra_dir: Path, session_name: str) -> None:
"""Save tmux session name to config file."""
cfg_path = hydra_dir / CONFIG_NAME
if cfg_path.exists():
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
else:
cfg = {}
cfg["tmux_session"] = session_name
cfg_path.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
def _spawn_agent_zellij(session_name: str, tab_name: str, worktree: Path, cmd: List[str]) -> None:
"""Spawn an agent in a new Zellij tab."""
# Create new tab
subprocess.run(
["zellij", "action", "new-tab", "-n", tab_name],
check=True,
capture_output=True,
text=True
)
# Switch to the new tab
subprocess.run(
["zellij", "action", "go-to-tab-name", tab_name],
check=True,
capture_output=True,
text=True
)
# Change to worktree directory
cd_cmd = f"cd {worktree}"
subprocess.run(
["zellij", "action", "write-chars", cd_cmd],
check=True,
capture_output=True,
text=True
)
subprocess.run(
["zellij", "action", "write", "10"], # Send Enter (ASCII 10)
check=True,
capture_output=True,
text=True
)
# Send agent command
agent_cmd = " ".join(cmd)
subprocess.run(
["zellij", "action", "write-chars", agent_cmd],
check=True,
capture_output=True,
text=True
)
subprocess.run(
["zellij", "action", "write", "10"], # Send Enter
check=True,
capture_output=True,
text=True
)
# Wait 0.5 second before switching back
time.sleep(0.5)
# Switch back to main tab
subprocess.run(
["zellij", "action", "go-to-tab-name", "main"],
check=True,
capture_output=True,
text=True
)
def _connect_db(hydra_dir: Path) -> sqlite3.Connection:
db_path = hydra_dir / LOCKS_DB_NAME
conn = sqlite3.connect(str(db_path))
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA foreign_keys=ON;")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS locks (
file TEXT PRIMARY KEY,
agent TEXT NOT NULL,
task TEXT NOT NULL,
locked_at INTEGER NOT NULL,
tmux_session TEXT
);
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS locks_agent_task_idx ON locks(agent, task);")
conn.commit()
return conn
def _write_executable(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
mode = path.stat().st_mode
path.chmod(mode | 0o111)
def _install_git_hooks(root: Path) -> None:
hooks_dir = root / ".git" / "hooks"
hooks_dir.mkdir(parents=True, exist_ok=True)
hook_header = "# Installed by CodeHydra (hydra.py)\n"
# Record the actual path to hydra.py at install time
hydra_py_path = Path(__file__).resolve()
def hook_script(hook_name: str, args: str) -> str:
return (
"#!/usr/bin/env bash\n"
"set -euo pipefail\n"
f"{hook_header}"
"\n"
'PY="python3"\n'
'command -v "$PY" >/dev/null 2>&1 || PY="python"\n'
"\n"
f'HYDRA_PY="{hydra_py_path}"\n'
"\n"
f'exec "$PY" "$HYDRA_PY" hook {hook_name} {args}\n'
)
scripts: Dict[str, str] = {
"commit-msg": hook_script("commit-msg", '"$1"'),
"pre-commit": hook_script("pre-commit", ""),
"post-commit": hook_script("post-commit", ""),
}
ts = _now_ts()
for name, content in scripts.items():
path = hooks_dir / name
if path.exists():
try:
existing = path.read_text(encoding="utf-8", errors="replace")
except Exception:
existing = ""
if "Installed by CodeHydra" not in existing:
backup = hooks_dir / f"{name}.bak.{ts}"
path.rename(backup)
_write_executable(path, content)
_git(root, ["config", "core.hooksPath", str(hooks_dir.resolve())], capture=True)
def _sanitize_ref_component(value: str, *, label: str) -> str:
if not value:
raise MctlError(f"{label} must be non-empty.")
if "/" in value or value.startswith(".") or value.endswith("."):
raise MctlError(f"Invalid {label}: {value!r}")
safe = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-")
if not safe:
raise MctlError(f"Invalid {label}: {value!r}")
return safe
def _sanitize_task_id(task_id: str) -> str:
# 支持两种格式:t1737123456(时间戳)或 t3005(短编号)
if not re.fullmatch(r"t[0-9]+", task_id):
raise MctlError(f"Invalid task id: {task_id!r} (expected like t1737123456 or t3005)")
return task_id
def _is_glob_pattern(pattern: str) -> bool:
if "**" in pattern:
return True
return any(ch in pattern for ch in "*?[]")
def _validate_allow_pattern(pattern: str) -> str:
if not pattern:
raise MctlError("Empty allow pattern is not allowed.")
if os.path.isabs(pattern):
raise MctlError(f"Allow pattern must be relative: {pattern!r}")
norm = pattern.replace("\\", "/")
if norm.startswith("../") or "/../" in norm or norm == "..":
raise MctlError(f"Allow pattern must not escape repo root: {pattern!r}")
return norm.lstrip("./")
def _expand_allow(root: Path, allow: Sequence[str]) -> List[str]:
locked: set[str] = set()
for raw in allow:
pattern = _validate_allow_pattern(raw)
if not _is_glob_pattern(pattern):
# Lock explicit file paths even if they don't exist yet.
locked.add(Path(pattern).as_posix())
continue
matches = globlib.glob(str(root / pattern), recursive=True)
for m in matches:
p = Path(m)
try:
rp = p.resolve()
except FileNotFoundError:
continue
if not rp.is_file():
continue
try:
rel = rp.relative_to(root)
except ValueError:
continue
locked.add(rel.as_posix())
return sorted(locked)
def _path_is_allowed(path: str, allow_patterns: Sequence[str]) -> bool:
normalized_path = path.replace("\\", "/")
for raw in allow_patterns:
pattern = _validate_allow_pattern(raw)
if fnmatch.fnmatch(normalized_path, pattern):
return True
return False
def _git_status_porcelain(worktree: Path) -> List[Tuple[str, str]]:
out = _run(["git", "status", "--porcelain"], cwd=worktree, capture=True).stdout
rows: List[Tuple[str, str]] = []
for line in (out or "").splitlines():
if not line:
continue
status = line[:2]
rest = line[3:] if len(line) > 3 else ""
if " -> " in rest:
rest = rest.split(" -> ", 1)[1]
rows.append((status, rest.strip()))
return rows
def _wait_for_worktree_quiet(
worktree: Path, *, debounce_seconds: float, max_wait_seconds: float, poll_seconds: float = 0.5
) -> None:
if debounce_seconds <= 0:
return
start = time.time()
while True:
rows = _git_status_porcelain(worktree)
if not rows:
return
latest_mtime = 0.0
for _status, rel in rows:
if not rel:
continue
p = (worktree / rel).resolve()
try:
st = p.stat()
except FileNotFoundError:
continue
if not p.is_file():
continue
latest_mtime = max(latest_mtime, st.st_mtime)
quiet_for = time.time() - latest_mtime if latest_mtime else debounce_seconds
if quiet_for >= debounce_seconds:
return
if (time.time() - start) >= max_wait_seconds:
raise HydraError(
f"Timed out waiting for files to stop changing (debounce={debounce_seconds}s, max_wait={max_wait_seconds}s)."
)
time.sleep(min(poll_seconds, max(0.05, debounce_seconds - quiet_for)))
def _git_staged_paths() -> List[str]:
out = _run(["git", "diff", "--cached", "--name-only", "--diff-filter=ACMRD"], capture=True).stdout
return [line.strip() for line in (out or "").splitlines() if line.strip()]
def _hook_commit_msg(args: argparse.Namespace) -> int:
msg_path = Path(args.msg_file)
agent = os.environ.get("AGENT_ID", "").strip()
task = os.environ.get("TASK_ID", "").strip()
if not agent or not task:
return 0
try:
text = msg_path.read_text(encoding="utf-8", errors="replace")
except FileNotFoundError:
return 0
if re.search(r"(?mi)^Agent:\\s*\\S+", text) and re.search(r"(?mi)^Task:\\s*\\S+", text):
return 0
out = text
if out and not out.endswith("\n"):
out += "\n"
if out and not out.endswith("\n\n"):
out += "\n"
out += f"Agent: {agent}\nTask: {task}\n"
msg_path.write_text(out, encoding="utf-8")
return 0
def _hook_pre_commit(_args: argparse.Namespace) -> int:
# Skip if explicitly requested (e.g., during merge)
if os.environ.get("HYDRA_SKIP_HOOKS", "").strip():
return 0
agent = os.environ.get("AGENT_ID", "").strip()
task_id = os.environ.get("TASK_ID", "").strip()
if not agent or not task_id:
return 0
root = _find_hydra_root_for_hooks()
hydra_dir, _agents_dir, tasks_dir = _ensure_dirs(root)
task_file = os.environ.get("HYDRA_TASK_FILE", "").strip()
if task_file:
task_path = Path(task_file)
if not task_path.is_absolute():
task_path = (root / task_path).resolve()
if not task_path.exists():
raise HydraError(f"Task file not found: {task_path}")
data = json.loads(task_path.read_text(encoding="utf-8"))
allow = data.get("allow")
if not isinstance(allow, list) or not all(isinstance(x, str) for x in allow):
raise HydraError(f"Invalid task allow list in {task_path}")
allow_patterns = [_validate_allow_pattern(x) for x in allow]
else:
task = _load_task(tasks_dir, task_id)
allow_patterns = task.allow
staged = _git_staged_paths()
if not staged:
return 0
not_allowed = [p for p in staged if not _path_is_allowed(p, allow_patterns)]
if not_allowed:
pretty = "\n".join([f"- {p}" for p in not_allowed[:50]])
more = "" if len(not_allowed) <= 50 else f"\n... and {len(not_allowed) - 50} more"
raise HydraError(f"Pre-commit blocked: staged files outside task allow list:\n{pretty}{more}")
db_path = hydra_dir / LOCKS_DB_NAME
if not db_path.exists():
raise HydraError(f"Locks DB not found: {db_path}. Did you run `hydra init`?")
now = _now_ts()
with sqlite3.connect(str(db_path)) as conn:
conn.execute("PRAGMA foreign_keys=ON;")
conn.execute("BEGIN IMMEDIATE;")
try:
conflicts: List[Tuple[str, str, str]] = []
for rel in staged:
row = conn.execute("SELECT agent, task FROM locks WHERE file=?", (rel,)).fetchone()
if row is None:
conn.execute(
"INSERT INTO locks(file, agent, task, locked_at, tmux_session) VALUES(?,?,?,?,?)",
(rel, agent, task_id, now, ""),
)
continue
locked_agent, locked_task = str(row[0]), str(row[1])
if locked_agent != agent or locked_task != task_id:
conflicts.append((rel, locked_agent, locked_task))
if conflicts:
pretty = "\n".join([f"- {f} (held by {a}/{t})" for (f, a, t) in conflicts[:50]])
more = "" if len(conflicts) <= 50 else f"\n... and {len(conflicts) - 50} more"
raise HydraError(f"Pre-commit blocked: lock conflict(s):\n{pretty}{more}")
conn.commit()
except Exception:
conn.rollback()
raise
return 0
def _append_journal_jsonl(path: Path, obj: Dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(obj, ensure_ascii=False) + "\n"
with path.open("a", encoding="utf-8") as f:
try:
import fcntl # type: ignore
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
except Exception:
pass
f.write(line)
f.flush()
try:
os.fsync(f.fileno())
except Exception:
pass
try:
import fcntl # type: ignore
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
except Exception:
pass
@dataclass(frozen=True)
class JournalEntry:
ts: int
sha: str
agent: str
task: str
files: str
index: int
def _format_ts_local(ts: int) -> str:
try:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(ts)))
except Exception:
return str(ts)
def _parse_duration_seconds(text: str) -> Optional[int]:
s = text.strip().lower()
if not s:
return None
if s.endswith("ago"):
s = s[: -len("ago")].strip()
units = {
"s": 1,
"sec": 1,
"secs": 1,
"second": 1,
"seconds": 1,
"m": 60,
"min": 60,
"mins": 60,
"minute": 60,
"minutes": 60,
"h": 3600,
"hr": 3600,
"hrs": 3600,
"hour": 3600,
"hours": 3600,
"d": 86400,
"day": 86400,
"days": 86400,
"w": 604800,
"week": 604800,
"weeks": 604800,
}
total = 0.0
pattern = re.compile(r"(\d+(?:\.\d+)?)\s*([a-z]+)")
pos = 0
for m in pattern.finditer(s):
if s[pos : m.start()].strip():
return None
pos = m.end()
num = float(m.group(1))
unit = m.group(2)
mult = units.get(unit)
if mult is None:
return None
total += num * mult
if s[pos:].strip():
return None
return int(total)
def _parse_datetime_local_ts(text: str) -> Optional[int]:
s = text.strip()
if not s:
return None
s = s.replace("T", " ")
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
st = time.strptime(s, fmt)
except ValueError:
continue
try:
return int(time.mktime(st))
except Exception:
return None
return None
def _parse_since_to_ts(value: str, *, now_ts: Optional[int] = None) -> int:
s = (value or "").strip()
if not s:
raise HydraError("Empty --since value.")
if re.fullmatch(r"\d+", s):
return int(s)
now = _now_ts() if now_ts is None else int(now_ts)
delta = _parse_duration_seconds(s)
if delta is not None:
return now - delta
dt = _parse_datetime_local_ts(s)
if dt is not None:
return dt
raise HydraError(
f"Unable to parse --since: {value!r}. Expected unix seconds, 'YYYY-MM-DD[ HH:MM[:SS]]', or duration like '10 minutes'."
)
def _read_journal_entries(path: Path) -> Tuple[List[JournalEntry], int]:
if not path.exists():
return [], 0
entries: List[JournalEntry] = []
invalid = 0
with path.open("r", encoding="utf-8", errors="replace") as f:
for idx, raw in enumerate(f):
line = raw.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
invalid += 1
continue
if not isinstance(obj, dict):
invalid += 1
continue
try:
ts = int(obj.get("ts") or 0)
sha = str(obj.get("sha") or "")
agent = str(obj.get("agent") or "")
task = str(obj.get("task") or "")
files = str(obj.get("files") or "")
except Exception:
invalid += 1
continue
entries.append(JournalEntry(ts=ts, sha=sha, agent=agent, task=task, files=files, index=idx))
return entries, invalid
def _format_journal_files(files: str) -> str:
parts: List[str] = []
for raw in (files or "").split(";"):
raw = raw.strip()
if not raw:
continue
cols = [c for c in raw.split("\t") if c != ""]
status = cols[0].strip() if cols else ""
paths = [c.strip() for c in cols[1:] if c.strip()]
if not status:
continue
if status.startswith(("R", "C")) and len(paths) >= 2:
parts.append(f"{status} {paths[0]} -> {paths[1]}")
elif paths:
if len(paths) == 1:
parts.append(f"{status} {paths[0]}")
else:
parts.append(f"{status} {' '.join(paths)}")
else:
parts.append(status)
return "; ".join(parts)
def _hook_post_commit(_args: argparse.Namespace) -> int:
root = _find_hydra_root_for_hooks()
hydra_dir, _agents_dir, _tasks_dir = _ensure_dirs(root)
sha = _run(["git", "rev-parse", "HEAD"], capture=True).stdout.strip()
files_out = _run(["git", "diff-tree", "--no-commit-id", "--name-status", "-r", "HEAD"], capture=True).stdout
files = ";".join([line.strip() for line in (files_out or "").splitlines() if line.strip()])
agent = os.environ.get("AGENT_ID", "").strip()
task = os.environ.get("TASK_ID", "").strip()
entry = {"ts": _now_ts(), "sha": sha, "agent": agent, "task": task, "files": files}
_append_journal_jsonl(hydra_dir / "journal.jsonl", entry)
return 0