Repository navigation
Expand file tree
/
Copy pathdelegate_coding_cli.py
More file actions
executable file
·2712 lines (2441 loc) · 105 KB
/
Copy pathdelegate_coding_cli.py
File metadata and controls
executable file
·2712 lines (2441 loc) · 105 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
"""Delegate repository-local coding work to Codex CLI or Gemini CLI safely."""
from __future__ import annotations
import argparse
import dataclasses
import datetime as dt
import fcntl
import json
import os
import re
import signal
import shlex
import shutil
import subprocess
import sys
import time
import threading
from pathlib import Path
from typing import Any, Iterable
INSTALL_COMMANDS = {
"codex": "npm i -g @openai/codex",
"gemini": "npm install -g @google/gemini-cli",
"git": "install git with your OS package manager or Xcode Command Line Tools on macOS",
"python3": "install Python 3 from https://www.python.org/ or your OS package manager",
}
SENSITIVE_NAMES = {
".env",
".env.local",
".env.production",
".npmrc",
".pypirc",
".netrc",
".ssh",
".config",
".gnupg",
"id_rsa",
"id_dsa",
"id_ecdsa",
"id_ed25519",
}
SENSITIVE_SUFFIXES = {
".pem",
".key",
".p12",
".pfx",
}
LOG_EXCLUDE_PATHSPEC = ":(exclude).hermes/delegate-runs/**"
LOCK_EXCLUDE_PATHSPEC = ":!*.lock"
GENERATED_STATUS_PREFIXES = (
"__pycache__/",
".pytest_cache/",
"node_modules/",
".mypy_cache/",
".ruff_cache/",
)
CACHE_DIR_NAMES = {
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
}
DEFAULT_CODEX_MODEL = "gpt-5.4-mini"
DEFAULT_CODEX_REASONING_EFFORT = "medium"
DEFAULT_GEMINI_MODEL = "gemini-3-flash-preview"
DEFAULT_GEMINI_REVIEW_MODEL = "gemini-3.1-flash-lite-preview"
DEFAULT_GEMINI_FINAL_REVIEW_MODEL = "gemini-3.1-pro-preview"
DEFAULT_WORKSPACE_MODE = "direct"
DEFAULT_QUALITY_MODE = "auto"
DEFAULT_STDOUT_MODE = "brief"
HANDOFF_SECTIONS = ("brief", "findings", "tests", "changed_files", "attempts", "logs", "full")
ESCALATION_RECOMMENDATION = (
"Task exceeded max fixup attempts with current executor. Recommend escalating to a stronger model "
"(e.g., gemini-3.1-pro-preview) and resubmitting the task."
)
ACTIVE_PROCESSES: dict[int, subprocess.Popen[Any]] = {}
ACTIVE_PROCESSES_LOCK = threading.RLock()
CLEANUP_EVENTS: list[dict[str, Any]] = []
@dataclasses.dataclass
class DelegateRequest:
repo: str
task: str
executor: str = "auto"
mode: str = "implement"
timeout: int = 1800
codex_model: str = DEFAULT_CODEX_MODEL
codex_reasoning_effort: str = DEFAULT_CODEX_REASONING_EFFORT
gemini_model: str = DEFAULT_GEMINI_MODEL
review_model: str = DEFAULT_GEMINI_REVIEW_MODEL
final_review_model: str = DEFAULT_GEMINI_FINAL_REVIEW_MODEL
quality_mode: str = DEFAULT_QUALITY_MODE
review: str = "always"
max_fixup_rounds: int = 2
check_health: bool = False
stdout_mode: str = DEFAULT_STDOUT_MODE
workspace: str | None = None
workspace_mode: str = DEFAULT_WORKSPACE_MODE
@dataclasses.dataclass
class CommandResult:
cmd: list[str]
cwd: str
returncode: int | None
stdout: str
stderr: str
duration_sec: float
timed_out: bool = False
@property
def ok(self) -> bool:
return self.returncode == 0 and not self.timed_out
def to_json(self) -> dict:
return {
"cmd": self.cmd,
"cwd": self.cwd,
"returncode": self.returncode,
"duration_sec": round(self.duration_sec, 2),
"timed_out": self.timed_out,
"stdout_tail": tail(self.stdout),
"stderr_tail": tail(self.stderr),
}
def tail(text: str, limit: int = 4000) -> str:
if len(text) <= limit:
return text
return text[-limit:]
def emit_heartbeat(step_name: str, message: str) -> None:
print(f"[Heartbeat] {step_name}: {message}", file=sys.stderr, flush=True)
def _decode_stream(value: str | bytes | None) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
return value.decode(errors="replace")
def _register_active_process(process: subprocess.Popen[Any]) -> None:
with ACTIVE_PROCESSES_LOCK:
ACTIVE_PROCESSES[process.pid] = process
def _unregister_active_process(pid: int) -> None:
with ACTIVE_PROCESSES_LOCK:
ACTIVE_PROCESSES.pop(pid, None)
def _record_cleanup_event(event: dict[str, Any]) -> None:
with ACTIVE_PROCESSES_LOCK:
CLEANUP_EVENTS.append(event)
def terminate_process_group(process: subprocess.Popen[Any], reason: str, grace_seconds: float = 5.0) -> dict[str, Any]:
event: dict[str, Any] = {
"pid": process.pid,
"reason": reason,
"signals": [],
}
if process.poll() is not None:
event["already_exited"] = True
event["returncode"] = process.returncode
return event
for signame, sig in (("SIGTERM", signal.SIGTERM),):
try:
os.killpg(process.pid, sig)
event["signals"].append(signame)
except ProcessLookupError:
event["group_missing"] = True
break
except PermissionError as exc:
event["signal_error"] = str(exc)
try:
process.wait(timeout=grace_seconds)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
event["signals"].append("SIGKILL")
except ProcessLookupError:
event["group_missing"] = True
except PermissionError as exc:
event["signal_error"] = str(exc)
try:
process.wait(timeout=grace_seconds)
except subprocess.TimeoutExpired:
event["wait_error"] = "process did not exit after SIGKILL"
event["returncode"] = process.returncode
return event
def cleanup_active_processes(reason: str) -> list[dict[str, Any]]:
cleaned: list[dict[str, Any]] = []
with ACTIVE_PROCESSES_LOCK:
processes = list(ACTIVE_PROCESSES.values())
for process in processes:
try:
event = terminate_process_group(process, reason)
try:
process.communicate()
except Exception as drain_exc:
event["drain_error"] = str(drain_exc)
except Exception as exc:
event = {"pid": process.pid, "reason": reason, "signals": [], "error": str(exc)}
cleaned.append(event)
_record_cleanup_event(event)
_unregister_active_process(process.pid)
return cleaned
def reset_runtime_state() -> None:
with ACTIVE_PROCESSES_LOCK:
ACTIVE_PROCESSES.clear()
CLEANUP_EVENTS.clear()
def acquire_workspace_lock(workspace: Path, timestamp: str) -> tuple[Any, dict[str, Any]]:
lock_path = workspace / ".hermes" / "delegate.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
handle = lock_path.open("a+", encoding="utf-8")
try:
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
handle.close()
raise RuntimeError(f"Workspace is already locked: {lock_path}") from exc
lock_info = {
"lock_path": str(lock_path),
"pid": os.getpid(),
"timestamp": timestamp,
}
handle.seek(0)
handle.truncate()
handle.write(json.dumps(lock_info, indent=2, ensure_ascii=False))
handle.flush()
os.fsync(handle.fileno())
return handle, lock_info
def release_workspace_lock(handle: Any | None) -> None:
if handle is None:
return
try:
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
finally:
handle.close()
def inspect_lockfile(lock_path: Path) -> dict[str, Any] | None:
if not lock_path.exists():
return None
handle = lock_path.open("a+", encoding="utf-8")
locked = False
try:
try:
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
locked = True
handle.seek(0)
raw = handle.read().strip()
try:
payload = json.loads(raw) if raw else None
except json.JSONDecodeError:
payload = raw or None
if not locked:
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
return {
"lock_path": str(lock_path),
"locked": locked,
"content": payload,
}
finally:
handle.close()
def collect_runtime_health(repo: Path) -> dict[str, Any]:
ps_result: CommandResult | None = None
ps_error: str | None = None
snapshot: dict[str, Any] = {
"available": False,
"total_processes": None,
"codex_like_processes": None,
"gemini_like_processes": None,
"antigravity_like_processes": None,
"node_like_processes": None,
"zombie_processes": None,
"healthy": None,
}
try:
ps_result = run_command(["ps", "-axo", "pid,ppid,stat,command"], repo, 20)
lines = [line.strip() for line in ps_result.stdout.splitlines() if line.strip()]
process_rows = lines[1:] if lines and lines[0].lower().startswith("pid") else lines
snapshot = {
"available": True,
"total_processes": len(process_rows),
"codex_like_processes": 0,
"gemini_like_processes": 0,
"antigravity_like_processes": 0,
"node_like_processes": 0,
"zombie_processes": 0,
}
for row in process_rows:
parts = row.split(None, 3)
if len(parts) < 4:
continue
stat = parts[2]
command = parts[3].lower()
if "codex" in command:
snapshot["codex_like_processes"] += 1
if "gemini" in command:
snapshot["gemini_like_processes"] += 1
if "antigravity" in command:
snapshot["antigravity_like_processes"] += 1
if "node" in command:
snapshot["node_like_processes"] += 1
if stat.startswith("Z"):
snapshot["zombie_processes"] += 1
snapshot["healthy"] = snapshot["total_processes"] < 2000 and snapshot["zombie_processes"] < 10
except Exception as exc:
ps_error = str(exc)
return {
"timestamp": now_timestamp(),
"repo": str(repo),
"process_snapshot": snapshot,
"active_helper_processes": len(ACTIVE_PROCESSES),
"cleanup_events_seen": len(CLEANUP_EVENTS),
"workspace_lock": inspect_lockfile(repo / ".hermes" / "delegate.lock"),
"ps_command": ps_result.to_json() if ps_result else None,
"ps_error": ps_error,
}
def now_timestamp() -> str:
return dt.datetime.now().strftime("%Y%m%d-%H%M%S")
def path_is_relative_to(path: Path, base: Path) -> bool:
try:
path.relative_to(base)
return True
except ValueError:
return False
def is_sensitive_name(path: Path) -> bool:
parts = set(path.parts)
if parts.intersection(SENSITIVE_NAMES):
return True
name = path.name.lower()
if name in SENSITIVE_NAMES:
return True
if any(name.endswith(suffix) for suffix in SENSITIVE_SUFFIXES):
return True
if "token" in name and not name.endswith(".md"):
return True
if "secret" in name and not name.endswith(".md"):
return True
return False
def is_generated_path(path: Path) -> bool:
parts = set(path.parts)
if parts.intersection(CACHE_DIR_NAMES):
return True
text = str(path)
return text.startswith(GENERATED_STATUS_PREFIXES)
QUALITY_RISK_WORDS = (
"security",
"auth",
"payment",
"migration",
"database",
"permission",
"crypto",
"concurrency",
"race",
"idempot",
"transaction",
"rollback",
"cache",
"state",
"session",
"token",
"oauth",
"jwt",
"acl",
"rbac",
"filesystem",
"storage",
"destructive",
"breaking",
"refactor",
"rewrite",
"replace",
"optimi",
"data loss",
"安全",
"权限",
"支付",
"迁移",
"并发",
"幂等",
"事务",
"回滚",
"缓存",
"状态",
"会话",
"令牌",
)
LOW_SIGNAL_RISK_WORDS = (
"cache",
"state",
"refactor",
"rewrite",
"replace",
"optimi",
"缓存",
"状态",
)
QUALITY_CRITICAL_RISK_WORDS = (
"security",
"auth",
"payment",
"migration",
"database",
"permission",
"crypto",
"concurrency",
"race",
"idempot",
"transaction",
"rollback",
"crash",
"deadlock",
"memory leak",
"overflow",
"fork",
"zombie",
"data loss",
"安全",
"权限",
"支付",
"迁移",
"并发",
"幂等",
"事务",
"回滚",
)
PRO_ESCALATION_WORDS = (
"security",
"auth",
"payment",
"migration",
"database",
"permission",
"crypto",
"concurrency",
"race",
"idempot",
"transaction",
"rollback",
"cache",
"state",
"session",
"token",
"oauth",
"jwt",
"acl",
"rbac",
"filesystem",
"storage",
"data loss",
"regression",
"architecture",
"breaking",
"high risk",
"critical",
"refactor",
"rewrite",
"replace",
"optimi",
"安全",
"权限",
"支付",
"迁移",
"并发",
"幂等",
"事务",
"回滚",
"缓存",
"状态",
"会话",
"令牌",
)
def task_has_risk_words(task: str) -> bool:
lowered = task.lower()
critical_hits = sum(1 for word in QUALITY_CRITICAL_RISK_WORDS if word in lowered)
if critical_hits >= 1:
return True
high_signal_words = tuple(word for word in QUALITY_RISK_WORDS if word not in LOW_SIGNAL_RISK_WORDS)
high_signal_matches = sum(1 for word in high_signal_words if word in lowered)
if high_signal_matches >= 2:
return True
low_signal_matches = sum(1 for word in LOW_SIGNAL_RISK_WORDS if word in lowered)
if low_signal_matches >= 3 and high_signal_matches >= 1:
return True
if any(word in lowered for word in ("critical", "major", "high risk", "breaking change", "regression")) and (
high_signal_matches >= 1 or low_signal_matches >= 2
):
return True
return False
def resolve_quality_mode(requested_mode: str, task: str) -> str:
if requested_mode == "auto":
return "safe" if task_has_risk_words(task) else "fast"
if requested_mode not in {"fast", "safe"}:
raise ValueError("quality_mode must be one of: auto, fast, safe")
return requested_mode
def default_review_policy_for_quality_mode(quality_mode: str) -> str:
return "always" if quality_mode == "safe" else "auto"
def default_fixup_rounds_for_quality_mode(quality_mode: str) -> int:
return 2 if quality_mode == "safe" else 0
def validate_repo_path(repo_arg: str) -> Path:
raw = Path(repo_arg).expanduser()
if not raw.exists():
raise ValueError(f"Repo path does not exist: {raw}")
if not raw.is_dir():
raise ValueError(f"Repo path is not a directory: {raw}")
resolved = raw.resolve()
home = Path.home().resolve()
forbidden_roots = [
Path("/").resolve(),
home,
(home / ".ssh").resolve(),
(home / ".config").resolve(),
Path("/etc").resolve(),
Path("/usr").resolve(),
Path("/var").resolve(),
Path("/private").resolve(),
]
if resolved == Path("/").resolve() or resolved == home:
raise ValueError(f"Refusing broad unsafe path: {resolved}")
for root in forbidden_roots[2:]:
if resolved == root:
raise ValueError(f"Refusing unsafe path: {resolved}")
if root != Path("/private").resolve() and path_is_relative_to(resolved, root):
raise ValueError(f"Refusing path inside unsafe root {root}: {resolved}")
private = Path("/private").resolve()
private_tmp = Path("/private/tmp").resolve()
if path_is_relative_to(resolved, private) and not path_is_relative_to(resolved, private_tmp):
raise ValueError(f"Refusing path inside unsafe root {private}: {resolved}")
if is_sensitive_name(resolved):
raise ValueError(f"Refusing sensitive path: {resolved}")
return resolved
def validate_workspace_path(workspace_arg: str) -> Path:
raw = Path(workspace_arg).expanduser()
resolved = raw.resolve(strict=False)
tmp_roots = {Path("/tmp").resolve(), Path("/private/tmp").resolve()}
if not any(path_is_relative_to(resolved, root) and resolved != root for root in tmp_roots):
raise ValueError(f"Workspace must be an isolated path under /tmp: {resolved}")
if is_sensitive_name(resolved):
raise ValueError(f"Refusing sensitive workspace path: {resolved}")
if resolved.exists():
raise ValueError(f"Workspace path already exists; provide a new isolated path: {resolved}")
return resolved
def run_command(
cmd: list[str],
cwd: Path,
timeout: int,
input_text: str | None = None,
env: dict[str, str] | None = None,
) -> CommandResult:
started = time.time()
process = subprocess.Popen(
cmd,
cwd=str(cwd),
stdin=subprocess.PIPE if input_text is not None else None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
shell=False,
env=env,
start_new_session=True,
)
_register_active_process(process)
stdout = ""
stderr = ""
returncode: int | None = None
timed_out = False
try:
stdout, stderr = process.communicate(input=input_text, timeout=timeout)
returncode = process.returncode
except subprocess.TimeoutExpired as exc:
timed_out = True
stdout = _decode_stream(exc.stdout)
stderr = _decode_stream(exc.stderr)
cleanup_event: dict[str, Any]
try:
cleanup_event = terminate_process_group(process, "timeout")
except Exception as cleanup_exc:
cleanup_event = {"pid": process.pid, "reason": "timeout", "signals": [], "error": str(cleanup_exc)}
_record_cleanup_event(cleanup_event)
try:
drained_stdout, drained_stderr = process.communicate()
except Exception as drain_exc:
drained_stdout, drained_stderr = "", ""
cleanup_event["drain_error"] = str(drain_exc)
stdout += drained_stdout
stderr += drained_stderr
returncode = process.returncode
except BaseException as exc:
if process.poll() is None:
cleanup_event = {"pid": process.pid, "reason": type(exc).__name__, "signals": []}
try:
cleanup_event = terminate_process_group(process, type(exc).__name__)
except Exception as cleanup_exc:
cleanup_event["error"] = str(cleanup_exc)
_record_cleanup_event(cleanup_event)
try:
process.communicate()
except Exception:
pass
raise
finally:
_unregister_active_process(process.pid)
return CommandResult(
cmd=cmd,
cwd=str(cwd),
returncode=returncode,
stdout=stdout,
stderr=stderr,
duration_sec=time.time() - started,
timed_out=timed_out,
)
def require_tools() -> list[dict]:
needed = ["git", "python3"]
missing = []
for tool in dict.fromkeys(needed):
if shutil.which(tool) is None:
missing.append({"tool": tool, "install": INSTALL_COMMANDS.get(tool, "")})
if shutil.which("codex") is None and shutil.which("gemini") is None:
missing.extend(
[
{"tool": "codex", "install": INSTALL_COMMANDS["codex"]},
{"tool": "gemini", "install": INSTALL_COMMANDS["gemini"]},
]
)
return missing
def git_toplevel(path: Path) -> Path | None:
result = run_command(["git", "-C", str(path), "rev-parse", "--show-toplevel"], path, 20)
if result.ok and result.stdout.strip():
return Path(result.stdout.strip()).resolve()
return None
def git_has_head(repo: Path) -> bool:
result = run_command(["git", "-C", str(repo), "rev-parse", "--verify", "HEAD"], repo, 20)
return result.ok
def git_status_short(repo: Path) -> str:
result = run_command(["git", "-C", str(repo), "status", "--short"], repo, 20)
return result.stdout
def git_current_branch(repo: Path) -> str | None:
result = run_command(["git", "-C", str(repo), "rev-parse", "--abbrev-ref", "HEAD"], repo, 20)
branch = result.stdout.strip()
if result.ok and branch and branch != "HEAD":
return branch
return None
def ensure_no_tracked_sensitive_files(repo: Path) -> list[str]:
result = run_command(["git", "-C", str(repo), "ls-files", "-z"], repo, 30)
if not result.ok:
return []
paths = [Path(part) for part in result.stdout.split("\0") if part]
return [str(path) for path in paths if is_sensitive_name(path)]
def copy_ignore(_dir: str, names: list[str]) -> set[str]:
ignored = set()
for name in names:
path = Path(name)
if name in {".git", ".hermes"} or is_sensitive_name(path):
ignored.add(name)
return ignored
def init_baseline_git(workspace: Path, timeout: int) -> list[CommandResult]:
commands = [
["git", "init"],
["git", "add", "."],
["git", "-c", "user.name=Hermes Delegate", "-c", "user.email=hermes@example.invalid", "commit", "-m", "baseline"],
]
return [run_command(cmd, workspace, timeout) for cmd in commands]
def capture_git_state(workspace: Path, log_dir: Path, prefix: str, include_stat: bool) -> dict:
status = run_git_capture(
["git", "-C", str(workspace), "status", "--short", "--", ".", LOG_EXCLUDE_PATHSPEC],
workspace,
30,
log_dir / f"{prefix}_git_status_short.txt",
)
diff = run_git_capture(
["git", "-C", str(workspace), "diff", "--", ".", LOCK_EXCLUDE_PATHSPEC, LOG_EXCLUDE_PATHSPEC],
workspace,
30,
log_dir / f"{prefix}_git_diff.patch",
)
result = {
"status": status.to_json(),
"diff": diff.to_json(),
}
if include_stat:
stat = run_git_capture(
["git", "-C", str(workspace), "diff", "--stat", "--", ".", LOCK_EXCLUDE_PATHSPEC, LOG_EXCLUDE_PATHSPEC],
workspace,
30,
log_dir / f"{prefix}_git_diff_stat.txt",
)
result["diff_stat"] = stat.to_json()
return result
def create_workspace(
repo: Path,
timestamp: str,
timeout: int,
workspace_mode: str,
requested_workspace: Path | None = None,
) -> tuple[Path, str | None, str, list[str], list[CommandResult]]:
warnings: list[str] = []
setup_results: list[CommandResult] = []
toplevel = git_toplevel(repo)
repo_name = repo.name or "workspace"
if workspace_mode == "direct":
if not toplevel or not git_has_head(toplevel):
raise ValueError("direct workspace mode requires a git repository with HEAD; use copy mode for non-git projects.")
if requested_workspace is not None:
warnings.append("workspace was provided but ignored in direct mode.")
return repo.resolve(), git_current_branch(toplevel), "direct", warnings, setup_results
if workspace_mode == "worktree":
if not toplevel or not git_has_head(toplevel):
raise ValueError("worktree mode requires a git repository with HEAD.")
sensitive = ensure_no_tracked_sensitive_files(toplevel)
if sensitive:
joined = ", ".join(sensitive[:20])
raise ValueError(f"Refusing to delegate because tracked sensitive-looking files exist: {joined}")
branch = f"hermes/delegate-{timestamp}"
workspace = requested_workspace or Path("/tmp/hermes-coding-worktrees") / f"{toplevel.name}-{timestamp}"
workspace.parent.mkdir(parents=True, exist_ok=True)
result = run_command(
["git", "-C", str(toplevel), "worktree", "add", "-b", branch, str(workspace), "HEAD"],
toplevel,
timeout,
)
setup_results.append(result)
if not result.ok:
raise RuntimeError(f"Failed to create git worktree: {tail(result.stderr or result.stdout, 1000)}")
if git_status_short(toplevel).strip():
warnings.append("Source repository has uncommitted changes that are not included in the new worktree.")
return workspace.resolve(), branch, "git-worktree", warnings, setup_results
if workspace_mode != "copy":
raise ValueError(f"Unsupported workspace mode: {workspace_mode}")
workspace = requested_workspace or Path("/tmp/hermes-coding-workspaces") / f"{repo_name}-{timestamp}"
workspace.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(repo, workspace, ignore=copy_ignore)
setup_results.extend(init_baseline_git(workspace, timeout))
if toplevel:
warnings.append("Git repository has no commits; used a temporary copy with a baseline commit instead of a worktree.")
else:
warnings.append("Path is not a git repository; used a temporary copy with a baseline commit.")
return workspace.resolve(), None, "temporary-copy", warnings, setup_results
def sanitize_env() -> dict[str, str]:
env = os.environ.copy()
sensitive_markers = ("TOKEN", "SECRET", "PASSWORD", "API_KEY", "PRIVATE_KEY", "CREDENTIAL")
for key in list(env.keys()):
upper = key.upper()
if any(marker in upper for marker in sensitive_markers):
env.pop(key, None)
return env
def build_delegate_prompt(
task: str,
workspace: Path,
executor: str,
mode: str,
quality_mode: str,
codex_model: str,
gemini_model: str,
review_model: str,
final_review_model: str,
codex_reasoning_effort: str,
workspace_mode: str,
) -> str:
mode_instruction = {
"plan": "Plan only. Do not edit files. Return a concise implementation plan, risks, and tests to run.",
"review": (
"Review only. Do not edit files. Identify bugs, risks, missing tests, and concrete recommendations. "
"If the review fails, output the feedback strictly in a structured format containing: 1. Target File, "
"2. Line Number, 3. Error Classification, 4. Required Fix Action. If there are no findings, output exactly PASS."
),
"implement": "Implement the requested change with minimal, focused edits. The helper may run bounded step-review fixup rounds and a final review without needing another Hermes handoff.",
}[mode]
return f"""You are a local coding CLI delegated by Hermes.
Mode: {mode}
Quality mode: {quality_mode}
Executor: {executor}
Codex model: {codex_model}
Codex reasoning effort: {codex_reasoning_effort}
Gemini primary model: {gemini_model}
Gemini step review model: {review_model}
Gemini final review model: {final_review_model}
Workspace mode: {workspace_mode}
Workspace: {workspace}
Original user task:
{task.strip()}
Hard constraints:
- Work only inside the workspace path above.
- Do not read private keys, tokens, browser profiles, password stores, ~/.ssh, ~/.config, .env files, or unrelated home directories.
- Do not push, deploy, merge, publish, delete repositories, or modify system files.
- Make minimal, focused changes.
- Run relevant tests if available.
- Do not invent destructive build steps.
- For quality mode `fast`, keep step review rare and let final review escalate automatically only when the helper sees enough risk.
- For quality mode `safe`, use flash-lite as the first-pass reviewer for step review, then finish with pro for the final review and any risky step-review escalation.
- At the end, summarize changed files and tests.
Mode-specific instruction:
{mode_instruction}
"""
def codex_supports_approval_flag() -> bool:
result = run_command(["codex", "exec", "--help"], Path.cwd(), 20)
return "--ask-for-approval" in result.stdout
def run_executor(
executor: str,
mode: str,
workspace: Path,
prompt: str,
log_dir: Path,
timeout: int,
codex_model: str,
gemini_model: str | None,
gemini_policy_paths: list[Path] | None = None,
label: str = "executor",
) -> tuple[CommandResult, Path | None, list[str]]:
env = sanitize_env()
warnings: list[str] = []
last_message_path: Path | None = None
if executor == "codex":
sandbox = "read-only" if mode in {"plan", "review"} else "workspace-write"
last_message_path = log_dir / f"{label}_codex_last_message.md"
cmd = ["codex", "exec", "--cd", str(workspace), "--sandbox", sandbox]
if codex_model:
cmd.extend(["--model", codex_model])
if codex_supports_approval_flag():
cmd.extend(["--ask-for-approval", "never"])
else:
warnings.append("Installed Codex CLI does not expose --ask-for-approval; omitted that flag.")
cmd.extend(["--ephemeral", "--output-last-message", str(last_message_path), "-"])
return run_command(cmd, workspace, timeout, input_text=prompt, env=env), last_message_path, warnings
if executor == "gemini":
if gemini_model:
cmd = ["gemini", "--skip-trust", "--model", gemini_model, "--prompt", "Follow the task from stdin.", "--output-format", "json"]
else:
cmd = ["gemini", "--skip-trust", "--prompt", "Follow the task from stdin.", "--output-format", "json"]
for policy_path in gemini_policy_paths or []:
cmd.extend(["--policy", str(policy_path)])
if mode in {"plan", "review"}:
cmd.extend(["--approval-mode", "plan"])
else:
cmd.extend(["--sandbox", "--approval-mode", "auto_edit"])
return run_command(cmd, workspace, timeout, input_text=prompt, env=env), None, warnings
raise ValueError(f"Unsupported executor: {executor}")
def normalize_optional_model(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
if not text or text.lower() == "auto":
return None
return text
def normalize_workspace_mode(value: Any) -> str:
text = str(value or DEFAULT_WORKSPACE_MODE).strip().lower()
if text not in {"direct", "worktree", "copy"}:
raise ValueError("workspace_mode must be one of: direct, worktree, copy")
return text
def choose_executor(requested: str) -> str:
codex_available = shutil.which("codex") is not None
gemini_available = shutil.which("gemini") is not None
if requested == "gemini":
if gemini_available:
return "gemini"
if codex_available:
return "codex"
raise RuntimeError("Missing executor: gemini")
if requested == "codex":
if codex_available:
return "codex"
if gemini_available:
return "gemini"
raise RuntimeError("Missing executor: codex")
if requested == "auto" and gemini_available:
return "gemini"
if codex_available:
return "codex"
if gemini_available:
return "gemini"
raise RuntimeError("Missing executor(s): codex, gemini")
def load_json_object(path_arg: str) -> dict[str, Any]:
path = Path(path_arg).expanduser().resolve()
if not path.exists() or not path.is_file():
raise ValueError(f"Request JSON does not exist or is not a file: {path}")
if is_sensitive_name(path):
raise ValueError(f"Refusing sensitive-looking request JSON path: {path}")
with path.open(encoding="utf-8") as handle:
data = json.load(handle)
if not isinstance(data, dict):
raise ValueError("Request JSON must be an object.")
return data
def normalize_request(args: argparse.Namespace) -> DelegateRequest:
data = load_json_object(args.request_json) if args.request_json else {}
def pick(name: str, default: Any = None) -> Any:
value = getattr(args, name, None)
if value is not None:
return value
return data.get(name, default)