@giamme/forge 0.21.0 → 0.22.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +6 -3
  3. package/VERSION +1 -1
  4. package/bin/forge.js +104 -0
  5. package/docs/development.md +1 -1
  6. package/docs/install.md +91 -2
  7. package/docs/reviews.md +6 -4
  8. package/docs/troubleshooting.md +1 -1
  9. package/forge +4 -0
  10. package/forge.cmd +56 -0
  11. package/package.json +5 -3
  12. package/scripts/forge-artifact.sh +5 -1
  13. package/scripts/forge-control.py +10 -3
  14. package/scripts/forge-dispatch.sh +108 -31
  15. package/scripts/forge-guard.py +137 -6
  16. package/scripts/forge-install.sh +82 -9
  17. package/scripts/forge-lib-env.sh +158 -0
  18. package/scripts/forge-lib-group.sh +5 -5
  19. package/scripts/forge-lib-plans.sh +8 -3
  20. package/scripts/forge-lib-task.sh +40 -15
  21. package/scripts/forge-memory.sh +2 -0
  22. package/scripts/forge-metrics.sh +6 -1
  23. package/scripts/forge-parallel.sh +156 -43
  24. package/scripts/forge-runtime.py +2 -2
  25. package/scripts/forge-schedule.py +18 -1
  26. package/scripts/forge-solo.sh +6 -2
  27. package/scripts/forge-sweep.py +1 -1
  28. package/scripts/forge-update.sh +6 -1
  29. package/scripts/forge-verify.py +1 -0
  30. package/scripts/forge-win.sh +156 -0
  31. package/scripts/forge_brief/__init__.py +6 -1
  32. package/scripts/forge_brief/proposals.py +6 -1
  33. package/scripts/forge_decide/budget.py +12 -7
  34. package/scripts/forge_decide/replay.py +9 -4
  35. package/scripts/forge_flock.py +17 -2
  36. package/scripts/forge_posix.py +17 -0
  37. package/scripts/forge_proc.py +108 -0
  38. package/scripts/forge_registry.py +2 -2
  39. package/scripts/forge_side/__init__.py +13 -4
  40. package/ui/forge_ui/control.py +7 -2
  41. package/ui/forge_ui/reader.py +6 -1
  42. package/ui/forge_ui/static/scene3d.js +23 -2
@@ -65,6 +65,10 @@
65
65
  set -uo pipefail
66
66
 
67
67
  SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
68
+ # Windows: re-run inside MSYS2 when started from Git Bash (no-op elsewhere).
69
+ . "$SKILL_DIR/scripts/forge-win.sh"
70
+ source "$SKILL_DIR/scripts/forge-lib-env.sh"
71
+ forge_ensure_python3
68
72
  REGISTRY="${FORGE_REGISTRY:-$SKILL_DIR/registry.tsv}"
69
73
  RUNTIME="$SKILL_DIR/scripts/forge-runtime.py"
70
74
  GUARD="$SKILL_DIR/scripts/forge-guard.py"
@@ -94,6 +98,51 @@ binary_for() {
94
98
  case "$1" in antigravity) echo agy ;; *) echo "$1" ;; esac
95
99
  }
96
100
 
101
+ # Resolve a harness CLI: first PATH, then well-known per-user Windows install paths.
102
+ resolve_binary() { # resolve_binary <harness> -> path on stdout, exit 1 if missing
103
+ local name bin cand localappdata appdata userprofile
104
+ name="$(binary_for "$1")"
105
+ if bin="$(command -v "$name" 2>/dev/null)" && [ -n "$bin" ]; then
106
+ printf '%s\n' "$bin"; return 0
107
+ fi
108
+ forge_is_windows || return 1
109
+ if bin="$(command -v "$name.cmd" 2>/dev/null)" && [ -n "$bin" ]; then
110
+ printf '%s\n' "$bin"; return 0
111
+ fi
112
+ localappdata="$(forge_posix_path "${LOCALAPPDATA:-}")"
113
+ appdata="$(forge_posix_path "${APPDATA:-}")"
114
+ userprofile="$(forge_posix_path "${USERPROFILE:-}")"
115
+ case "$1" in
116
+ antigravity)
117
+ for cand in ${localappdata:+"$localappdata/agy/bin/agy.exe"}; do
118
+ [ -f "$cand" ] && { printf '%s\n' "$cand"; return 0; }
119
+ done ;;
120
+ opencode)
121
+ if bin="$(command -v opencode-cli 2>/dev/null)" && [ -n "$bin" ]; then
122
+ printf '%s\n' "$bin"; return 0
123
+ fi
124
+ for cand in \
125
+ ${localappdata:+"$localappdata/Programs/@opencode-aidesktop/resources/opencode-cli.exe"} \
126
+ ${appdata:+"$appdata/npm/opencode.cmd"} \
127
+ ${appdata:+"$appdata/npm/opencode"}; do
128
+ [ -f "$cand" ] && { printf '%s\n' "$cand"; return 0; }
129
+ done ;;
130
+ claude)
131
+ for cand in \
132
+ ${userprofile:+"$userprofile/.local/bin/claude.exe"} \
133
+ ${HOME:+"$HOME/.local/bin/claude.exe"}; do
134
+ [ -f "$cand" ] && { printf '%s\n' "$cand"; return 0; }
135
+ done ;;
136
+ openclaude|codex)
137
+ for cand in \
138
+ ${appdata:+"$appdata/npm/$name.cmd"} \
139
+ ${appdata:+"$appdata/npm/$name"}; do
140
+ [ -f "$cand" ] && { printf '%s\n' "$cand"; return 0; }
141
+ done ;;
142
+ esac
143
+ return 1
144
+ }
145
+
97
146
  # Every effort word forge recognizes, weakest first. Used only to tell "you asked
98
147
  # for more thinking than this pairing offers" (clamp, keep going) apart from "that
99
148
  # is not an effort level" (stop). ultra and ultracode are each their harness's top
@@ -190,7 +239,7 @@ doctor() {
190
239
  local rc=0 h bin
191
240
  printf '%-12s %-10s %s\n' HARNESS STATUS DETAIL
192
241
  for h in codex claude openclaude opencode antigravity grok; do
193
- bin="$(command -v "$(binary_for "$h")" 2>/dev/null)"
242
+ bin="$(resolve_binary "$h" 2>/dev/null)"
194
243
  if [ -z "$bin" ]; then
195
244
  printf '%-12s %-10s %s\n' "$h" MISSING "$(binary_for "$h") not on PATH"; rc=1; continue
196
245
  fi
@@ -432,19 +481,20 @@ if [ "$PREFLIGHT" != 1 ] && [ "$DRY" != 1 ]; then
432
481
  # dispatch and must not be the thing that hangs it.
433
482
  exit_cleanup() {
434
483
  [ -z "${tpid:-}" ] || kill -TERM "$tpid" 2>/dev/null
484
+ local _hw="${hwinpid:-${hpid:-}}"
435
485
  if [ -n "${hpid:-}" ] && kill -0 "$hpid" 2>/dev/null; then
436
- [ "${GUARD_ON:-0}" != 1 ] || kill -s TERM -- "-$hpid" 2>/dev/null
437
- pkill -TERM -P "$hpid" 2>/dev/null; kill -TERM "$hpid" 2>/dev/null
486
+ [ "${GUARD_ON:-0}" != 1 ] || forge_kill_group "$hpid" TERM
487
+ forge_kill_children "$hpid" TERM; kill -TERM "$hpid" 2>/dev/null
438
488
  if [ "${GUARD_ON:-0}" = 1 ]; then
439
- sleep 1; kill -s KILL -- "-$hpid" 2>/dev/null
489
+ sleep 1; forge_kill_group "$hpid" KILL
440
490
  # what it started in sessions of their own (#129)
441
- python3 "$GUARD" reap "$hpid" "$RUN_DIR/$ROLE.orphans" --tracked "$RUN_DIR/$ROLE.tracked" >/dev/null 2>&1
491
+ python3 "$GUARD" reap "$_hw" "$RUN_DIR/$ROLE.orphans" --tracked "$RUN_DIR/$ROLE.tracked" >/dev/null 2>&1
442
492
  fi
443
- elif [ "${GUARD_ON:-0}" = 1 ] && [ "${reaped:-0}" != 1 ] && [ -n "${hpid:-}" ]; then
493
+ elif [ "${GUARD_ON:-0}" = 1 ] && [ "${reaped:-0}" != 1 ] && [ -n "${_hw:-}" ]; then
444
494
  # Interrupted after the harness exited but before the normal reap.
445
- python3 "$GUARD" reap "$hpid" "$RUN_DIR/$ROLE.orphans" --tracked "$RUN_DIR/$ROLE.tracked" >/dev/null 2>&1
495
+ python3 "$GUARD" reap "$_hw" "$RUN_DIR/$ROLE.orphans" --tracked "$RUN_DIR/$ROLE.tracked" >/dev/null 2>&1
446
496
  fi
447
- for watcher in ${wpid:-} ${spid:-}; do pkill -P "$watcher" 2>/dev/null; kill "$watcher" 2>/dev/null; done
497
+ for watcher in ${wpid:-} ${spid:-}; do forge_kill_children "$watcher" TERM; kill "$watcher" 2>/dev/null; done
448
498
  [ -z "${cpid:-}" ] || kill "$cpid" 2>/dev/null
449
499
  rm -f "$RUN_DIR/$ROLE.harness" "$RUN_DIR/$ROLE.tracked"
450
500
  case "${ROLE_TMP:-}" in "$RUN_DIR"/.*-tmp.*) [ ! -d "$ROLE_TMP" ] || rm -rf -- "$ROLE_TMP" ;; esac
@@ -547,6 +597,15 @@ codex_read_only() {
547
597
  }
548
598
 
549
599
  # Sets CMD (and PROMPT_VIA_STDIN) for the dispatch, or for the fresh one when CONTINUE_ID is empty.
600
+ D_REPO="$REPO"; D_RUN_DIR="$RUN_DIR"; D_LAST="$LAST"; D_PROMPT_FILE="$PROMPT_FILE"; D_GUARD="$GUARD"
601
+ if forge_is_windows; then
602
+ D_REPO="$(forge_host_path "$REPO")"
603
+ D_RUN_DIR="$(forge_host_path "$RUN_DIR")"
604
+ D_LAST="$(forge_host_path "$LAST")"
605
+ D_PROMPT_FILE="$(forge_host_path "$PROMPT_FILE")"
606
+ D_GUARD="$(forge_host_path "$GUARD")"
607
+ fi
608
+
550
609
  build_cmd() {
551
610
  CMD=()
552
611
  case "$HARNESS" in
@@ -557,7 +616,7 @@ build_cmd() {
557
616
  # whether the diff is correct, but not whether it is the change that was
558
617
  # actually asked for. `codex exec review` also has no --cd, hence the
559
618
  # subshell cd below.
560
- CMD=(codex exec review --json -m "$MODEL" --skip-git-repo-check -o "$LAST")
619
+ CMD=(codex exec review --json -m "$MODEL" --skip-git-repo-check -o "$D_LAST")
561
620
  [ -n "$EFFORT" ] && CMD+=(-c "model_reasoning_effort=$EFFORT")
562
621
  [ "$SERVICE_TIER" = fast ] && CMD+=(-c "service_tier=fast")
563
622
  if [ -n "$REVIEW_BASE" ]; then CMD+=(--base "$REVIEW_BASE"); else CMD+=(--uncommitted); fi
@@ -569,7 +628,7 @@ build_cmd() {
569
628
  # An id that starts with '-' would be read as a flag, so it goes after a `--`.
570
629
  CMD=(codex exec resume)
571
630
  case "$CONTINUE_ID" in -*) ;; *) CMD+=("$CONTINUE_ID") ;; esac
572
- CMD+=(--json -m "$MODEL" --skip-git-repo-check -o "$LAST")
631
+ CMD+=(--json -m "$MODEL" --skip-git-repo-check -o "$D_LAST")
573
632
  [ -n "$EFFORT" ] && CMD+=(-c "model_reasoning_effort=$EFFORT")
574
633
  [ "$SERVICE_TIER" = fast ] && CMD+=(-c "service_tier=fast")
575
634
  if [ "$YOLO" = 1 ]; then CMD+=(--dangerously-bypass-approvals-and-sandbox)
@@ -578,7 +637,7 @@ build_cmd() {
578
637
  CMD+=(-)
579
638
  PROMPT_VIA_STDIN=1
580
639
  else
581
- CMD=(codex exec --json -m "$MODEL" -C "$REPO" --skip-git-repo-check -o "$LAST")
640
+ CMD=(codex exec --json -m "$MODEL" -C "$D_REPO" --skip-git-repo-check -o "$D_LAST")
582
641
  [ -n "$EFFORT" ] && CMD+=(-c "model_reasoning_effort=$EFFORT")
583
642
  [ "$SERVICE_TIER" = fast ] && CMD+=(-c "service_tier=fast")
584
643
  # --approve-for-me and --dangerously-bypass-... are mutually exclusive.
@@ -593,7 +652,7 @@ build_cmd() {
593
652
  # The run dir sits outside the repo (so it stays out of the diff), which also
594
653
  # puts it outside the harness's default reach — without this the agent
595
654
  # refuses to open the very artifacts forge just wrote for it.
596
- CMD=("$HARNESS" -p --model "$MODEL" --add-dir "$RUN_DIR")
655
+ CMD=("$HARNESS" -p --model "$MODEL" --add-dir "$D_RUN_DIR")
597
656
  # One JSON message per line: what the agent said and every tool call, so the run keeps
598
657
  # its conversation (forge-ui reads it), ending in the `result` line forge-runtime.py
599
658
  # takes the final message and the tokens from. stream-json needs --verbose with -p.
@@ -639,7 +698,7 @@ build_cmd() {
639
698
  PROMPT_VIA_STDIN=1
640
699
  ;;
641
700
  opencode)
642
- CMD=(opencode run -m "$MODEL" --dir "$REPO")
701
+ CMD=(opencode run -m "$MODEL" --dir "$D_REPO")
643
702
  [ -n "$EFFORT" ] && CMD+=(--variant "$EFFORT")
644
703
  # opencode run exposes no sandbox tier — without --auto it blocks on a
645
704
  # permission prompt that nothing can answer headlessly, so it is always set.
@@ -660,7 +719,7 @@ build_cmd() {
660
719
  # --add-dir on the repo is not optional. Antigravity is workspace-scoped
661
720
  # rather than cwd-scoped, so without it the agent searches the wrong tree and
662
721
  # the run dies on "Find command timed out: context deadline exceeded".
663
- CMD+=(--add-dir "$REPO" --add-dir "$RUN_DIR")
722
+ CMD+=(--add-dir "$D_REPO" --add-dir "$D_RUN_DIR")
664
723
  if [ "$YOLO" = 1 ]; then CMD+=(--dangerously-skip-permissions)
665
724
  elif read_only_role; then CMD+=(--mode plan)
666
725
  else CMD+=(--mode accept-edits); fi
@@ -672,7 +731,7 @@ build_cmd() {
672
731
  # claude gives without acceptEdits, so the dwarf gets edits and the whole shell.
673
732
  # The Messages-format stream ends in a claude-shaped `result` line, which
674
733
  # forge-runtime.py reads for the final message and the tokens.
675
- CMD=(grok --model "$MODEL" --prompt-file "$PROMPT_FILE" --output-format streaming-messages-json)
734
+ CMD=(grok --model "$MODEL" --prompt-file "$D_PROMPT_FILE" --output-format streaming-messages-json)
676
735
  [ -n "$EFFORT" ] && CMD+=(--reasoning-effort "$EFFORT")
677
736
  # After its last turn a headless run waits for the background work it started (a test
678
737
  # suite, say) and wakes the model with each result, but by default for only 600 s: then
@@ -693,6 +752,9 @@ build_cmd() {
693
752
  ;;
694
753
  *) die "no dispatch recipe for harness '$HARNESS'" ;;
695
754
  esac
755
+ if [ -n "${RESOLVED_BIN:-}" ] && ! command -v "$(binary_for "$HARNESS")" >/dev/null 2>&1; then
756
+ CMD[0]="$RESOLVED_BIN"
757
+ fi
696
758
  }
697
759
  # A read-only role's own writable temp dir (#148). Test runners need one (Vitest's EPERM in a
698
760
  # read-only sandbox), and the role gets none otherwise. It sits in the run dir, outside the
@@ -700,12 +762,15 @@ build_cmd() {
700
762
  # point at it, and the dispatch removes it when it ends. A dry run or a preflight only shows
701
763
  # its shape.
702
764
  ROLE_TMP=""
765
+ D_ROLE_TMP=""
703
766
  if read_only_role; then
704
767
  if [ -n "$ATTEMPT" ]; then
705
768
  ROLE_TMP="$(mktemp -d "$RUN_DIR/.$ROLE-tmp.XXXXXX")" || ROLE_TMP=""
706
769
  else
707
770
  ROLE_TMP="$RUN_DIR/.$ROLE-tmp.XXXXXX"
708
771
  fi
772
+ D_ROLE_TMP="$ROLE_TMP"
773
+ [ -z "$ROLE_TMP" ] || ! forge_is_windows || D_ROLE_TMP="$(forge_host_path "$ROLE_TMP")"
709
774
  fi
710
775
  build_cmd
711
776
 
@@ -735,7 +800,12 @@ unadvertised_flag() { # unadvertised_flag <help text>
735
800
  preflight_command() {
736
801
  local bin help flag request="$CONTINUE_ID"
737
802
  local help_args=(--help) continue_args=(--help)
738
- bin="$(command -v "$(binary_for "$HARNESS")")" || die "harness '$HARNESS' is not installed" 3
803
+ bin="$(resolve_binary "$HARNESS")" || die "harness '$HARNESS' is not installed" 3
804
+ ! forge_is_windows || bin="$(forge_host_path "$bin")"
805
+ RESOLVED_BIN="$bin"
806
+ if ! command -v "$(binary_for "$HARNESS")" >/dev/null 2>&1; then
807
+ CMD[0]="$RESOLVED_BIN"
808
+ fi
739
809
  case "$HARNESS" in
740
810
  codex) help_args=(exec --help); continue_args=(exec resume --help); [ "$NATIVE_REVIEW" = 1 ] && help_args=(exec review --help) ;;
741
811
  opencode) help_args=(run --help) ;;
@@ -829,7 +899,11 @@ fi
829
899
  if [ "$YOLO" = 1 ]; then
830
900
  note "YOLO: $HARNESS runs with sandbox and approvals disabled in $REPO"
831
901
  fi
832
- [ -n "$(command -v "$(binary_for "$HARNESS")")" ] || die "harness '$HARNESS' is not installed ($(binary_for "$HARNESS") not on PATH)" 3
902
+ RESOLVED_BIN="$(resolve_binary "$HARNESS")" || die "harness '$HARNESS' is not installed ($(binary_for "$HARNESS") not on PATH)" 3
903
+ ! forge_is_windows || RESOLVED_BIN="$(forge_host_path "$RESOLVED_BIN")"
904
+ if ! command -v "$(binary_for "$HARNESS")" >/dev/null 2>&1; then
905
+ CMD[0]="$RESOLVED_BIN"
906
+ fi
833
907
 
834
908
  # Harnesses that take the prompt on argv get stdin redirected from /dev/null:
835
909
  # codex exec otherwise blocks waiting to append piped input to the prompt, which
@@ -861,14 +935,17 @@ case "${FORGE_ORPHAN_GUARD:-on}" in off|OFF|Off|0|no|false) ;; *)
861
935
  if [ -z "${FORGE_FRACTAL_RUN:-}" ] && [ -r "$GUARD" ] && [ "$(python3 "$GUARD" ping 2>/dev/null)" = ok ]; then GUARD_ON=1; fi ;;
862
936
  esac
863
937
  RUNCMD=("${CMD[@]}")
864
- [ "$GUARD_ON" != 1 ] || RUNCMD=(python3 "$GUARD" session -- "${CMD[@]}")
865
- role_env() { [ -z "$ROLE_TMP" ] || export TMPDIR="$ROLE_TMP" TMP="$ROLE_TMP" TEMP="$ROLE_TMP"; }
938
+ # Windows MSYS2 mode (forge-win.sh): the harness gets the PATH it had in Git Bash, not MSYS2's.
939
+ [ -z "${FORGE_WIN_AGENT_PATH:-}" ] || RUNCMD=(env -u MSYS -u FORGE_WIN_AGENT_PATH "PATH=$FORGE_WIN_AGENT_PATH" "MSYSTEM=${FORGE_WIN_MSYSTEM-}" "${CMD[@]}")
940
+ [ "$GUARD_ON" != 1 ] || RUNCMD=(python3 "$D_GUARD" session -- "${RUNCMD[@]}")
941
+ role_env() { [ -z "$D_ROLE_TMP" ] || export TMPDIR="$D_ROLE_TMP" TMP="$D_ROLE_TMP" TEMP="$D_ROLE_TMP"; }
866
942
  if [ "$PROMPT_VIA_STDIN" = 1 ]; then
867
- ( cd "$REPO" && role_env && exec "${RUNCMD[@]}" < "$PROMPT_FILE" ) > "$LOG" 2>&1 &
943
+ ( cd "$REPO" && role_env && { ! forge_is_windows || export MSYS_NO_PATHCONV=1; } && exec "${RUNCMD[@]}" < "$PROMPT_FILE" ) > "$LOG" 2>&1 &
868
944
  else
869
- ( cd "$REPO" && role_env && exec "${RUNCMD[@]}" </dev/null ) > "$LOG" 2>&1 &
945
+ ( cd "$REPO" && role_env && { ! forge_is_windows || export MSYS_NO_PATHCONV=1; } && exec "${RUNCMD[@]}" </dev/null ) > "$LOG" 2>&1 &
870
946
  fi
871
947
  hpid=$!
948
+ hwinpid="$(forge_winpid "$hpid")"
872
949
  # Log clock: when the log grew, so forge-ui can time the commands of a harness whose events
873
950
  # carry no time (codex, grok). Advisory and off with FORGE_LOG_CLOCK=off; it ends on its own
874
951
  # if this dispatch dies first.
@@ -881,9 +958,9 @@ esac
881
958
  # (forge-guard.py stop) in case this dispatch dies before the trap finishes. The start time
882
959
  # tells the pid apart from a later reuse, and survives the exec chain $! still goes through.
883
960
  if [ "$GUARD_ON" = 1 ]; then
884
- hident="$(python3 "$GUARD" identity "$hpid" 2>/dev/null)" || hident=""
961
+ hident="$(python3 "$GUARD" identity "$hwinpid" 2>/dev/null)" || hident=""
885
962
  if [ -n "$hident" ]; then
886
- printf '%s\t%s\n' "$hpid" "$hident" > "$RUN_DIR/.$ROLE.harness.tmp" \
963
+ printf '%s\t%s\n' "$hwinpid" "$hident" > "$RUN_DIR/.$ROLE.harness.tmp" \
887
964
  && mv -f "$RUN_DIR/.$ROLE.harness.tmp" "$RUN_DIR/$ROLE.harness"
888
965
  fi
889
966
  fi
@@ -892,19 +969,19 @@ fi
892
969
  # it as a descendant, so the reap finds it by pid and start time. Advisory, like the guard.
893
970
  tpid=""
894
971
  if [ "$GUARD_ON" = 1 ]; then
895
- python3 "$GUARD" track "$hpid" "$RUN_DIR/$ROLE.tracked" </dev/null >/dev/null 2>&1 & tpid=$!
972
+ python3 "$GUARD" track "$hwinpid" "$RUN_DIR/$ROLE.tracked" </dev/null >/dev/null 2>&1 & tpid=$!
896
973
  fi
897
974
 
898
975
  # Ends the harness: the whole process group first when the harness has its own (GUARD_ON),
899
976
  # then children, then the process itself, then SIGKILL for a CLI that traps TERM and takes
900
977
  # its time. Without the guard there is no group to signal as a unit.
901
978
  stop_harness() {
902
- [ "$GUARD_ON" != 1 ] || kill -s TERM -- "-$hpid" 2>/dev/null
903
- pkill -TERM -P "$hpid" 2>/dev/null
979
+ [ "$GUARD_ON" != 1 ] || forge_kill_group "$hpid" TERM
980
+ forge_kill_children "$hpid" TERM
904
981
  kill -TERM "$hpid" 2>/dev/null
905
982
  sleep 5
906
- [ "$GUARD_ON" != 1 ] || kill -s KILL -- "-$hpid" 2>/dev/null
907
- pkill -KILL -P "$hpid" 2>/dev/null
983
+ [ "$GUARD_ON" != 1 ] || forge_kill_group "$hpid" KILL
984
+ forge_kill_children "$hpid" KILL
908
985
  kill -KILL "$hpid" 2>/dev/null
909
986
  }
910
987
 
@@ -929,7 +1006,7 @@ spid=""
929
1006
  case "$HARNESS" in claude|openclaude)
930
1007
  if [ "$RESULT_GRACE" != 0 ]; then
931
1008
  (
932
- python3 "$RUNTIME" settle "$LOG" "$RESULT_GRACE" "$hpid" </dev/null || exit 0
1009
+ python3 "$RUNTIME" settle "$LOG" "$RESULT_GRACE" "$hwinpid" </dev/null || exit 0
933
1010
  kill -0 "$hpid" 2>/dev/null || exit 0
934
1011
  : > "$RUN_DIR/$ROLE.settled"
935
1012
  stop_harness
@@ -950,7 +1027,7 @@ fi
950
1027
  for watcher in $wpid $spid; do
951
1028
  # The watchdog is asleep in a child of its own, and so is the grace watcher; kill that
952
1029
  # too or it outlives the run as an orphan holding the timer.
953
- pkill -P "$watcher" 2>/dev/null
1030
+ forge_kill_children "$watcher" TERM
954
1031
  kill "$watcher" 2>/dev/null
955
1032
  wait "$watcher" 2>/dev/null
956
1033
  done
@@ -961,7 +1038,7 @@ done
961
1038
  # changes nothing about the exit code.
962
1039
  if [ -n "$tpid" ]; then kill -TERM "$tpid" 2>/dev/null; wait "$tpid" 2>/dev/null; tpid=""; fi
963
1040
  if [ "$GUARD_ON" = 1 ]; then
964
- orphans_found="$(python3 "$GUARD" reap "$hpid" "$RUN_DIR/$ROLE.orphans" --tracked "$RUN_DIR/$ROLE.tracked" 2>/dev/null)"
1041
+ orphans_found="$(python3 "$GUARD" reap "$hwinpid" "$RUN_DIR/$ROLE.orphans" --tracked "$RUN_DIR/$ROLE.tracked" 2>/dev/null)"
965
1042
  case "$orphans_found" in ''|*[!0-9]*|0) ;; *) note "$HARNESS left $orphans_found process(es) running after it exited; killed — see $RUN_DIR/$ROLE.orphans" ;; esac
966
1043
  fi
967
1044
  reaped=1
@@ -55,6 +55,7 @@
55
55
  """
56
56
  from __future__ import annotations
57
57
 
58
+ import datetime
58
59
  import os
59
60
  import re
60
61
  import signal
@@ -76,6 +77,7 @@ KILL_WAIT_S = 1.0
76
77
  # --- session ------------------------------------------------------------------
77
78
  def _win_session(argv: list[str]) -> int:
78
79
  _, exec_argv = forge_proc.resolve_win_command(argv)
80
+ job = forge_proc.ProcessJob()
79
81
  try:
80
82
  proc = subprocess.Popen(exec_argv)
81
83
  except FileNotFoundError:
@@ -84,7 +86,16 @@ def _win_session(argv: list[str]) -> int:
84
86
  except OSError as error:
85
87
  print('forge-guard: cannot execute %s: %s' % (argv[0], error), file=sys.stderr)
86
88
  return 126
87
- return proc.wait()
89
+ job.attach(proc.pid)
90
+ try:
91
+ rc = proc.wait()
92
+ # Keep KILL_ON_JOB_CLOSE armed while the child runs so an abrupt guardian
93
+ # termination cleans up descendants atomically; disarm on normal return so
94
+ # `reap` can still observe and record intentional orphans.
95
+ job.disarm()
96
+ return rc
97
+ finally:
98
+ job.close()
88
99
 
89
100
 
90
101
  def session(argv: list[str]) -> int:
@@ -285,9 +296,15 @@ def read_tracked(path):
285
296
  return found
286
297
 
287
298
 
299
+ def _same_start(recorded, current) -> bool:
300
+ """Whether two start times (identity, ps_table) name the same process start. Plain equality;
301
+ the Cygwin block below replaces it, since there a start older than a day is known to the day."""
302
+ return recorded == current
303
+
304
+
288
305
  def _mine(table, known):
289
306
  """The recorded processes still alive with their recorded start time (not a reused pid)."""
290
- return {pid for pid, start in known.items() if pid in table and table[pid][1] == start}
307
+ return {pid for pid, start in known.items() if pid in table and _same_start(start, table[pid][1])}
291
308
 
292
309
 
293
310
  def track(root: int, path: str, interval: float = TRACK_INTERVAL_S) -> int:
@@ -393,13 +410,24 @@ def stop_tree(root: int, wait: float) -> int:
393
410
  while left and time.monotonic() < deadline:
394
411
  time.sleep(0.2)
395
412
  now = ps_table() or {}
396
- left = {pid for pid in left if pid in now and now[pid][1] == starts[pid]}
413
+ left = {pid for pid in left if pid in now and _same_start(starts[pid], now[pid][1])}
397
414
  for pid in left:
398
415
  forge_proc.signal_pid(pid, force=True)
399
416
  print(len(targets))
400
417
  return 0
401
418
 
402
419
 
420
+ def kill_children(parent_pid: int, force: bool = False) -> int:
421
+ """Terminate descendants of `parent_pid` (used on platforms lacking `pkill -P`)."""
422
+ table = ps_table()
423
+ if table is None or parent_pid <= 1:
424
+ return 0
425
+ targets = descendants(table, {parent_pid}) - _never(table)
426
+ for pid in sorted(targets, reverse=True):
427
+ forge_proc.signal_pid(pid, force=force)
428
+ return 0
429
+
430
+
403
431
  def reap(pgid: int, orphans_file: str, tracked: str | None = None) -> int:
404
432
  count = _reap_group(pgid, orphans_file)
405
433
  extra = _reap_tracked(tracked, pgid) if tracked else []
@@ -430,6 +458,8 @@ def _ps_field(pid: int, field: str) -> str | None:
430
458
  def identity(pid: int) -> str | None:
431
459
  if forge_proc.IS_WINDOWS:
432
460
  return forge_proc.process_start_time(pid)
461
+ # On Cygwin (Windows MSYS2 mode) this is Cygwin ps's STIME made absolute (see the Cygwin
462
+ # block below). After 24 hours it is known only to the day: compare it with _same_start.
433
463
  return _ps_field(pid, 'lstart')
434
464
 
435
465
 
@@ -514,7 +544,8 @@ def stop(record: str) -> int:
514
544
  if pid > 1:
515
545
  if _pid_alive(pid):
516
546
  # A mismatch, or no way to tell, means the pid now belongs to someone else.
517
- if recorded and identity(pid) == recorded:
547
+ current = identity(pid)
548
+ if recorded and current is not None and _same_start(recorded, current):
518
549
  count = _stop_live(pid)
519
550
  else:
520
551
  count = _reap_group(pid, None)
@@ -602,12 +633,106 @@ def promises(path: str, tail_bytes: int = 3000) -> int:
602
633
  return 0
603
634
 
604
635
 
636
+ # --- Windows (MSYS2/Cygwin) -----------------------------------------------------
637
+ # procps builds each row from /proc/<pid>/stat, which Cygwin fills by asking Windows: about half
638
+ # a second per process, so one listing takes 15-20 s and outlives every timeout above, leaving
639
+ # the guards blind. Its start time is also the Windows process's, which changes when a Cygwin
640
+ # process execs a native program (a harness), so an identity recorded before the exec never
641
+ # matched again. Cygwin's own ps reads the same process table in milliseconds, keeps the start
642
+ # time across exec and hides zombies. Its STIME has one-second resolution and gives the time of
643
+ # day for the first 24 hours, then only the date: _cygwin_start makes either absolute, and
644
+ # _cygwin_same_start lets a start known to the day match one known to the second, so `stop`
645
+ # still recognises a harness after a day (to the day: a pid reused on that same day would pass).
646
+ _CYGWIN_MONTHS = {name: number for number, name in enumerate(
647
+ ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), 1)}
648
+
649
+
650
+ def _cygwin_start(stime: str, now: float | None = None) -> str:
651
+ """Cygwin ps's STIME as an absolute local start: 'YYYY-MM-DD HH:MM:SS' while ps gives the time
652
+ of day (the last 24 hours), 'YYYY-MM-DD' once it gives only the date ('Nov 19'). Text in
653
+ neither form comes back unchanged."""
654
+ today = time.localtime(time.time() if now is None else now)
655
+ parts = stime.split()
656
+ if len(parts) == 1 and re.fullmatch(r'\d\d:\d\d:\d\d', parts[0]):
657
+ day = datetime.date(today.tm_year, today.tm_mon, today.tm_mday)
658
+ if parts[0] > time.strftime('%H:%M:%S', today): # later than now: it was yesterday
659
+ day -= datetime.timedelta(days=1) # by the date: a day is not always 86400 s
660
+ return '%s %s' % (day.isoformat(), parts[0])
661
+ if len(parts) == 2 and parts[0] in _CYGWIN_MONTHS and parts[1].isdigit():
662
+ month, mday = _CYGWIN_MONTHS[parts[0]], int(parts[1])
663
+ year = today.tm_year - ((month, mday) > (today.tm_mon, today.tm_mday))
664
+ return '%04d-%02d-%02d' % (year, month, mday)
665
+ return stime
666
+
667
+
668
+ def _cygwin_same_start(recorded: str, current: str) -> bool:
669
+ """Whether two _cygwin_start values name the same start: equal, or one known only to the day
670
+ and the other on that day."""
671
+ if recorded == current:
672
+ return True
673
+ shorter, longer = sorted((recorded, current), key=len)
674
+ return len(shorter) == 10 and longer.startswith(shorter + ' ')
675
+
676
+
677
+ if sys.platform == 'cygwin':
678
+ CYGWIN_PS = '/usr/bin/ps'
679
+ _CYGWIN_ROW = re.compile(r'^\s*[A-Z]?\s*(\d+)\s+(\d+)\s+(\d+)\s+\d+\s+\S+\s+\d+\s+'
680
+ r'(\d\d:\d\d:\d\d|[A-Z][a-z]{2}\s+\d+)\s+(.*)$')
681
+ _same_start = _cygwin_same_start
682
+
683
+ def _cygwin_rows(pid: int | None = None):
684
+ """{pid: (ppid, pgid, start, executable)} of live processes, or None when ps cannot run.
685
+ LC_ALL=C keeps STIME's month names in English for _cygwin_start."""
686
+ try:
687
+ out = subprocess.run([CYGWIN_PS, '-l'] + (['-p', str(pid)] if pid else ['-a']),
688
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=30,
689
+ env=dict(os.environ, LC_ALL='C')).stdout.decode(errors='replace')
690
+ except (OSError, subprocess.SubprocessError):
691
+ return None
692
+ rows = {}
693
+ for line in out.splitlines()[1:]:
694
+ match = _CYGWIN_ROW.match(line)
695
+ if match:
696
+ rows[int(match[1])] = (int(match[2]), int(match[3]), _cygwin_start(match[4]), match[5].strip())
697
+ return rows
698
+
699
+ def _command(pid: int, fallback: str) -> str:
700
+ """The full command line where Cygwin can read it cheaply; the executable otherwise."""
701
+ try:
702
+ with open('/proc/%d/cmdline' % pid, 'rb') as handle:
703
+ return handle.read().replace(b'\0', b' ').decode(errors='replace').strip() or fallback
704
+ except OSError:
705
+ return fallback
706
+
707
+ def list_group(pgid: int):
708
+ rows = _cygwin_rows()
709
+ if rows is None:
710
+ return None
711
+ me = os.getpid()
712
+ return [(pid, _command(pid, exe)) for pid, (_ppid, group, _start, exe) in sorted(rows.items())
713
+ if group == pgid and pid != me]
714
+
715
+ def ps_table():
716
+ rows = _cygwin_rows()
717
+ if rows is None:
718
+ return None
719
+ return {pid: (ppid, start, exe) for pid, (ppid, _group, start, exe) in rows.items()}
720
+
721
+ def _ps_field(pid: int, field: str) -> str | None:
722
+ if pid <= 0:
723
+ return None
724
+ row = (_cygwin_rows(pid) or {}).get(pid)
725
+ if row is None:
726
+ return None
727
+ return {'stat': 'S', 'lstart': row[2], 'ppid': str(row[0]), 'pgid': str(row[1])}.get(field)
728
+
729
+
605
730
  # --- cli ----------------------------------------------------------------------
606
731
  def main(argv: list[str]) -> int:
607
732
  if not argv:
608
733
  print('usage: forge-guard.py ping | session -- CMD... | reap <pgid> <orphans-file> [--tracked FILE] | '
609
- 'track <pid> <file> [--interval S] | stop-tree <pid> [--wait S] | identity <pid> | '
610
- 'stop <record-file> | '
734
+ 'track <pid> <file> [--interval S] | stop-tree <pid> [--wait S] | kill-children <pid> [TERM|KILL] | '
735
+ 'identity <pid> | stop <record-file> | '
611
736
  'promises <file> [--tail-bytes N]', file=sys.stderr)
612
737
  return 2
613
738
  command, rest = argv[0], argv[1:]
@@ -639,6 +764,12 @@ def main(argv: list[str]) -> int:
639
764
  print('usage: forge-guard.py stop-tree <pid> [--wait S]', file=sys.stderr)
640
765
  return 2
641
766
  return stop_tree(int(rest[0]), max(0.0, wait))
767
+ if command == 'kill-children':
768
+ if len(rest) not in (1, 2):
769
+ print('usage: forge-guard.py kill-children <pid> [TERM|KILL]', file=sys.stderr)
770
+ return 2
771
+ force = len(rest) == 2 and rest[1].upper() == 'KILL'
772
+ return kill_children(int(rest[0]), force=force)
642
773
  if command == 'track':
643
774
  interval = TRACK_INTERVAL_S
644
775
  if '--interval' in rest: