@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
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env bash
2
+ # forge-win.sh — sourced first by forge's entry scripts. Does nothing except on Windows in
3
+ # MSYS2 mode.
4
+ #
5
+ # On Windows forge runs natively by default: Git Bash with Windows' own Python. MSYS2 mode is
6
+ # the alternative for POSIX behaviour as on Linux: forge runs inside MSYS2, whose bash, git,
7
+ # python3 and ps agree on process ids, process groups, signals, flock and symlinks. It is opt-in:
8
+ #
9
+ # FORGE_WIN_MODE=msys2 an entry script started from Git Bash re-runs itself inside MSYS2
10
+ # an MSYS2 shell forge started there runs there, whatever FORGE_WIN_MODE says
11
+ #
12
+ # Inside MSYS2 this file exports FORGE_WIN_MODE=msys2, so helpers that adapt forge to native
13
+ # Windows can tell they are not in native mode.
14
+ #
15
+ # pacman -S python git procps-ng diffutils in the MSYS2 at FORGE_MSYS2_ROOT (default C:/msys64)
16
+ #
17
+ # Symlinks are made as real Windows symlinks (Developer Mode must be on). A link to a target
18
+ # that does not exist yet falls back to an MSYS-only link, which native programs see as a file.
19
+ #
20
+ # FORGE_WIN_AGENT_PATH is the PATH forge started with, in Git Bash or an MSYS2 shell, before
21
+ # /usr/bin goes first. forge-dispatch.sh gives it back to the agent CLIs, so they see what they
22
+ # would outside forge rather than MSYS2's tools first.
23
+ #
24
+ # This file is sourced on macOS too, so it keeps to Bash 3.2: no mapfile, no ${var,,}.
25
+ if [ "${BASH_SOURCE[0]}" = "$0" ]; then
26
+ # Run, not sourced: the landing side of the hop below. The original command line arrives in
27
+ # FORGE_WIN_ARGV, NUL-separated and base64-encoded, because a Windows command line cannot
28
+ # carry every argument unchanged (a double quote inside one is lost).
29
+ [ -n "${FORGE_WIN_ARGV:-}" ] || { echo "forge-win.sh is sourced by forge's entry scripts; it is not a command" >&2; exit 2; }
30
+ _forge_argv=()
31
+ while IFS= read -r -d '' _forge_arg; do _forge_argv+=("$_forge_arg"); done \
32
+ < <(printf '%s' "$FORGE_WIN_ARGV" | /usr/bin/base64 -d)
33
+ unset FORGE_WIN_ARGV _forge_arg
34
+ exec /usr/bin/bash "${_forge_argv[@]}"
35
+ fi
36
+ case "${OSTYPE:-}" in msys*|cygwin*) ;; *) return 0 ;; esac
37
+ case "${FORGE_WIN_MODE:-native}" in
38
+ native|msys2) ;;
39
+ *) echo "forge: FORGE_WIN_MODE is '$FORGE_WIN_MODE'; use native (the default) or msys2" >&2; exit 2 ;;
40
+ esac
41
+
42
+ # MSYS2 has pacman; Git for Windows has git-bash.exe at its root (its SDK, which has both, is
43
+ # Git Bash too). Only file tests here: native mode must not pay for a single extra process.
44
+ if [ ! -x /usr/bin/pacman ] || [ -e /git-bash.exe ]; then
45
+ [ "${FORGE_WIN_MODE:-native}" = msys2 ] || return 0 # native mode: Git Bash runs forge itself
46
+ _forge_msys="${FORGE_MSYS2_ROOT:-C:/msys64}"
47
+ _forge_msys="${_forge_msys%/}"
48
+ if [ ! -x "$_forge_msys/usr/bin/bash.exe" ]; then
49
+ echo "forge: FORGE_WIN_MODE=msys2, but MSYS2 was not found at $_forge_msys (set FORGE_MSYS2_ROOT)" >&2
50
+ exit 127
51
+ fi
52
+ # One hop only: landing anywhere but an MSYS2 would otherwise re-run the script for ever.
53
+ if [ -n "${FORGE_WIN_REEXEC:-}" ]; then
54
+ echo "forge: re-ran inside $_forge_msys, which does not look like MSYS2 (no /usr/bin/pacman)" >&2
55
+ exit 127
56
+ fi
57
+ # The hop goes through a native program. Started directly, MSYS2's bash would get almost none of
58
+ # this environment: two copies of the MSYS runtime cannot hand it to each other.
59
+ _forge_native=""
60
+ for _forge_tool in python3 python py; do
61
+ if "$_forge_tool" -c 'import sys; sys.exit(sys.platform != "win32")' 2>/dev/null; then _forge_native="$_forge_tool"; break; fi
62
+ done
63
+ if [ -z "$_forge_native" ]; then
64
+ echo "forge: MSYS2 mode needs a native Windows Python on the Git Bash PATH to hand over to MSYS2; or start forge from an MSYS2 shell" >&2
65
+ exit 127
66
+ fi
67
+ FORGE_WIN_ARGV="$(printf '%s\0' "$(/usr/bin/cygpath -m "$0")" "$@" | /usr/bin/base64 -w0)"
68
+ export FORGE_WIN_ARGV FORGE_WIN_REEXEC=1 FORGE_WIN_MSYSTEM="${MSYSTEM-}"
69
+ # Ctrl-C reaches MSYS2's bash as well, and forge's own handlers clean up (worktrees, agents).
70
+ # The hand-over only waits for it: subprocess.call would kill it on KeyboardInterrupt.
71
+ MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' exec "$_forge_native" -c '
72
+ import subprocess, sys
73
+ child = subprocess.Popen(sys.argv[1:])
74
+ while True:
75
+ try:
76
+ sys.exit(child.wait())
77
+ except KeyboardInterrupt:
78
+ pass
79
+ ' "$_forge_msys/usr/bin/bash.exe" "$(/usr/bin/cygpath -m "${BASH_SOURCE[0]}")"
80
+ fi
81
+
82
+ # Inside MSYS2: started from an MSYS2 shell, or just arrived from Git Bash.
83
+ _forge_msys="$(/usr/bin/cygpath -m /)"
84
+ _forge_msys="${_forge_msys%/}"
85
+ for _forge_tool in python3 git procps cmp diff; do
86
+ if [ ! -x "/usr/bin/$_forge_tool" ]; then
87
+ echo "forge: the MSYS2 at $_forge_msys has no $_forge_tool; run there: pacman -S python git procps-ng diffutils" >&2
88
+ exit 127
89
+ fi
90
+ done
91
+ [ -z "${FORGE_WIN_REEXEC:-}" ] || unset FORGE_WIN_REEXEC MSYS_NO_PATHCONV MSYS2_ARG_CONV_EXCL
92
+ # The PATH and MSYSTEM forge started with (Git Bash's, or the MSYS2 shell's) are what an agent
93
+ # CLI should see. forge itself needs MSYS2's python3 and git ahead of everything: a UCRT64 or
94
+ # MINGW64 shell puts /ucrt64/bin or /mingw64/bin first, where a MinGW Python is a native Windows
95
+ # Python. Child scripts inherit both, so this runs once.
96
+ if [ -z "${FORGE_WIN_AGENT_PATH:-}" ]; then
97
+ export FORGE_WIN_AGENT_PATH="$PATH"
98
+ [ -n "${FORGE_WIN_MSYSTEM+set}" ] || export FORGE_WIN_MSYSTEM="${MSYSTEM-}"
99
+ fi
100
+ case "$PATH" in /usr/bin:*) ;; *) export PATH="/usr/bin:$PATH" ;; esac
101
+ # Real Windows symlinks, unless the user already chose how MSYS2 makes them.
102
+ case " ${MSYS-} " in *" winsymlinks"*) ;; *) MSYS="${MSYS:+$MSYS }winsymlinks:native" ;; esac
103
+ # FORGE_WIN_MODE says which mode runs, to every child script and helper, also when forge was
104
+ # started from an MSYS2 shell without it: native-port helpers must treat MSYS2 mode as POSIX.
105
+ export MSYSTEM=MSYS MSYS FORGE_WIN_MODE=msys2
106
+ # Worktree links must be relative: Git for Windows, which the native agent CLIs use, cannot follow
107
+ # the /c/... paths MSYS2's git writes. The setting travels in the environment, but the first
108
+ # worktree made with it adds extensions.relativeWorktrees to the repository's config, and from
109
+ # then on Git older than 2.48 (and libgit2- or JGit-based tools) refuses to open the repository.
110
+ # So both gits must be 2.48 or newer; children of this script inherit the result.
111
+ if [ -z "${FORGE_WIN_GIT_CHECKED:-}" ]; then
112
+ _forge_git_too_old() { # _forge_git_too_old <git> <how to update>: says why and succeeds when < 2.48
113
+ local version major minor
114
+ version="$("$1" --version 2>/dev/null)"
115
+ version="${version#git version }"
116
+ major="${version%%.*}"
117
+ minor="${version#*.}"
118
+ minor="${minor%%.*}"
119
+ case "$major.$minor" in
120
+ [0-9]*.[0-9]*) ;;
121
+ *) echo "forge: cannot read the version of $1 ('$version'); MSYS2 mode needs Git 2.48 or newer" >&2; return 0 ;;
122
+ esac
123
+ if [ "$major" -gt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -ge 48 ]; }; then return 1; fi
124
+ echo "forge: MSYS2 mode needs Git 2.48 or newer for relative worktree links; $1 is $version: $2" >&2
125
+ return 0
126
+ }
127
+ if _forge_git_too_old /usr/bin/git 'update MSYS2 with pacman -Syu'; then exit 127; fi
128
+ _forge_agent_git="$(PATH="${FORGE_WIN_AGENT_PATH:-$PATH}" command -v git)"
129
+ if [ -n "$_forge_agent_git" ] && [ "$_forge_agent_git" != /usr/bin/git ] \
130
+ && _forge_git_too_old "$_forge_agent_git" 'update Git for Windows'; then exit 127; fi
131
+ unset -f _forge_git_too_old
132
+ export FORGE_WIN_GIT_CHECKED=1
133
+ fi
134
+ case " ${GIT_CONFIG_KEY_0-} ${GIT_CONFIG_KEY_1-} ${GIT_CONFIG_KEY_2-} ${GIT_CONFIG_KEY_3-} " in
135
+ *" worktree.useRelativePaths "*) ;;
136
+ *) _forge_n="${GIT_CONFIG_COUNT:-0}"
137
+ export "GIT_CONFIG_KEY_$_forge_n=worktree.useRelativePaths" "GIT_CONFIG_VALUE_$_forge_n=true"
138
+ export GIT_CONFIG_COUNT="$((_forge_n + 1))" ;;
139
+ esac
140
+ # procps' pkill reads every /proc/<pid>/stat, which Cygwin fills by asking Windows: about half a
141
+ # second per process. forge only runs `pkill [-SIGNAL] -P <parent>`, which /proc/<pid>/ppid answers
142
+ # at once. Anything else goes to the real pkill. Scripts sourced after this file (forge-metrics.sh)
143
+ # get the function too.
144
+ pkill() {
145
+ local sig=TERM parent="" arg dir ppid found=1
146
+ for arg in "$@"; do
147
+ case "$arg" in -P) ;; -[A-Z]*|-[0-9]*) sig="${arg#-}" ;; [0-9]*) parent="$arg" ;; *) command pkill "$@"; return ;; esac
148
+ done
149
+ [ -n "$parent" ] || { command pkill "$@"; return; }
150
+ for dir in /proc/[0-9]*; do
151
+ read -r ppid < "$dir/ppid" 2>/dev/null || continue
152
+ [ "$ppid" = "$parent" ] && kill -s "$sig" "${dir#/proc/}" 2>/dev/null && found=0
153
+ done
154
+ return "$found"
155
+ }
156
+ unset _forge_msys _forge_tool _forge_n _forge_native _forge_agent_git
@@ -392,7 +392,12 @@ def _task_lock(plan: Path, task: str):
392
392
  fcntl.flock(fd, fcntl.LOCK_EX)
393
393
  yield
394
394
  finally:
395
- os.close(fd)
395
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases can leave
396
+ # another thread of this process waiting on it for ever.
397
+ try:
398
+ fcntl.flock(fd, fcntl.LOCK_UN)
399
+ finally:
400
+ os.close(fd)
396
401
 
397
402
 
398
403
  def _record(plan: Path, task: str, model: str, level: str, questions, error) -> dict:
@@ -506,7 +506,12 @@ def _proposals_lock(plan):
506
506
  fcntl.flock(fd, fcntl.LOCK_EX)
507
507
  yield
508
508
  finally:
509
- os.close(fd)
509
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases can leave
510
+ # another thread of this process waiting on it for ever.
511
+ try:
512
+ fcntl.flock(fd, fcntl.LOCK_UN)
513
+ finally:
514
+ os.close(fd)
510
515
 
511
516
 
512
517
  @contextlib.contextmanager
@@ -119,15 +119,20 @@ def _add(path: Path, tokens: int, usd: float) -> None:
119
119
  path.parent.mkdir(parents=True, exist_ok=True)
120
120
  with open(f'{path}.lock', 'a') as lock:
121
121
  fcntl.flock(lock, fcntl.LOCK_EX)
122
- total = _read(path)
123
- total['tokens'] += tokens
124
- total['usd'] = _sum_usd(total['usd'], usd)
125
- tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
126
122
  try:
127
- tmp.write_text(json.dumps(total))
128
- os.replace(tmp, path)
123
+ total = _read(path)
124
+ total['tokens'] += tokens
125
+ total['usd'] = _sum_usd(total['usd'], usd)
126
+ tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
127
+ try:
128
+ tmp.write_text(json.dumps(total))
129
+ os.replace(tmp, path)
130
+ finally:
131
+ tmp.unlink(missing_ok=True)
129
132
  finally:
130
- tmp.unlink(missing_ok=True)
133
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases
134
+ # can leave another thread of this process waiting on it for ever.
135
+ fcntl.flock(lock, fcntl.LOCK_UN)
131
136
  except Exception: # fail-open: a charge that cannot be recorded is dropped
132
137
  pass
133
138
 
@@ -297,10 +297,15 @@ def record(gate: str, result: dict) -> Path:
297
297
  _private_dir(path.parent)
298
298
  with open(f'{path}.lock', 'a') as lock:
299
299
  fcntl.flock(lock, fcntl.LOCK_EX)
300
- data = _load(path)
301
- results = data.get('results') if isinstance(data.get('results'), dict) else {}
302
- results['%s/%s' % (result['provider'], result['model'])] = {k: result[k] for k in _RECORDED if k in result}
303
- _save(path, dict(data, version=VERSION, results=results), 0o600)
300
+ try:
301
+ data = _load(path)
302
+ results = data.get('results') if isinstance(data.get('results'), dict) else {}
303
+ results['%s/%s' % (result['provider'], result['model'])] = {k: result[k] for k in _RECORDED if k in result}
304
+ _save(path, dict(data, version=VERSION, results=results), 0o600)
305
+ finally:
306
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases
307
+ # can leave another thread of this process waiting on it for ever.
308
+ fcntl.flock(lock, fcntl.LOCK_UN)
304
309
  return path
305
310
 
306
311
 
@@ -11,6 +11,7 @@ from __future__ import annotations
11
11
 
12
12
  import errno
13
13
  import os
14
+ import sys
14
15
  import time
15
16
 
16
17
  try:
@@ -33,6 +34,11 @@ else:
33
34
 
34
35
  _LOCK_OFFSET = 0x40000000 # 1 GiB sentinel byte; msvcrt does not extend file size
35
36
 
37
+ # Cygwin (Windows MSYS2 mode): flock sometimes fails with EFAULT when threads of one process lock
38
+ # the same file at the same moment, and the same call succeeds when repeated.
39
+ _CYGWIN = sys.platform == 'cygwin'
40
+ _CYGWIN_EFAULT_TRIES = 100 # 10 ms apart: about a second
41
+
36
42
  _BUSY_ERRNOS = frozenset(
37
43
  getattr(errno, name)
38
44
  for name in ('EACCES', 'EAGAIN', 'EWOULDBLOCK', 'EDEADLK')
@@ -57,8 +63,17 @@ def _msvcrt_lock_sentinel(fd: int, mode: int) -> None:
57
63
  def flock(fd_or_file, operation: int) -> None:
58
64
  """Acquire or release an advisory lock matching ``fcntl.flock`` semantics."""
59
65
  if _fcntl is not None:
60
- _fcntl.flock(fd_or_file, operation)
61
- return
66
+ if not _CYGWIN:
67
+ _fcntl.flock(fd_or_file, operation)
68
+ return
69
+ for attempt in range(_CYGWIN_EFAULT_TRIES):
70
+ try:
71
+ _fcntl.flock(fd_or_file, operation)
72
+ return
73
+ except OSError as exc:
74
+ if exc.errno != errno.EFAULT or attempt == _CYGWIN_EFAULT_TRIES - 1:
75
+ raise
76
+ time.sleep(0.01)
62
77
 
63
78
  fd = _fileno(fd_or_file)
64
79
  nonblocking = bool(operation & LOCK_NB)
@@ -9,8 +9,12 @@ from __future__ import annotations
9
9
 
10
10
  import errno
11
11
  import os
12
+ import re
12
13
  import stat
13
14
 
15
+ IS_WINDOWS = os.name == 'nt'
16
+ _MSYS_PATH_RE = re.compile(r'^/([a-zA-Z])(?:/(.*))?$')
17
+
14
18
  O_NOFOLLOW = getattr(os, 'O_NOFOLLOW', 0)
15
19
  O_NONBLOCK = getattr(os, 'O_NONBLOCK', 0)
16
20
  O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0)
@@ -106,3 +110,16 @@ def unlink_at(handle: int | str, leaf: str) -> None:
106
110
  os.unlink(leaf, dir_fd=handle)
107
111
  else:
108
112
  os.unlink(os.path.join(handle, leaf))
113
+
114
+
115
+ def host_path(path: os.PathLike | str) -> str:
116
+ """Convert an MSYS/Git-Bash `/c/...` path to `C:/...` on native Windows."""
117
+ text = os.fspath(path)
118
+ if IS_WINDOWS and text:
119
+ if text.startswith('\\\\?\\') and len(text) >= 6 and text[5] == ':':
120
+ text = text[4:]
121
+ m = _MSYS_PATH_RE.fullmatch(text)
122
+ if m:
123
+ rest = m.group(2) or ''
124
+ return f'{m.group(1).upper()}:/{rest}'
125
+ return text
@@ -20,12 +20,16 @@ IS_WINDOWS = os.name == 'nt'
20
20
  SIGKILL = getattr(signal, 'SIGKILL', signal.SIGTERM)
21
21
  SIGUSR1 = getattr(signal, 'SIGUSR1', None)
22
22
  SIGQUIT = getattr(signal, 'SIGQUIT', None)
23
+ SIGBREAK = getattr(signal, 'SIGBREAK', None)
23
24
 
24
25
  _STILL_ACTIVE = 259
25
26
  _PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
27
+ _PROCESS_SET_QUOTA = 0x0100
26
28
  _PROCESS_TERMINATE = 0x0001
27
29
  _TH32CS_SNAPPROCESS = 0x00000002
28
30
  _ERROR_ACCESS_DENIED = 5
31
+ _JOB_OBJECT_EXTENDED_LIMIT_INFO = 9
32
+ _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
29
33
  _CREATE_NO_WINDOW = getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
30
34
 
31
35
 
@@ -88,6 +92,11 @@ def resolve_win_command(argv: list[str]) -> tuple[Path, list[str]]:
88
92
  raw = argv[0]
89
93
  if not IS_WINDOWS:
90
94
  return Path(raw).resolve(), list(argv)
95
+ if raw in ('/bin/bash', '/bin/sh'):
96
+ exe = bash_executable()
97
+ return Path(exe), [exe, *argv[1:]]
98
+ if len(raw) >= 2 and raw[0] == '/' and raw[1].isalpha() and (len(raw) == 2 or raw[2] == '/'):
99
+ raw = f'{raw[1].upper()}:/{raw[3:]}'
91
100
  found = shutil.which(raw)
92
101
  if found:
93
102
  binary = Path(found).resolve()
@@ -177,6 +186,47 @@ if IS_WINDOWS:
177
186
  ('szExeFile', _wintypes.WCHAR * 260),
178
187
  ]
179
188
 
189
+ class _IO_COUNTERS(ctypes.Structure):
190
+ _fields_ = [
191
+ ('ReadOperationCount', ctypes.c_uint64),
192
+ ('WriteOperationCount', ctypes.c_uint64),
193
+ ('OtherOperationCount', ctypes.c_uint64),
194
+ ('ReadTransferCount', ctypes.c_uint64),
195
+ ('WriteTransferCount', ctypes.c_uint64),
196
+ ('OtherTransferCount', ctypes.c_uint64),
197
+ ]
198
+
199
+ class _JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
200
+ _fields_ = [
201
+ ('PerProcessUserTimeLimit', ctypes.c_int64),
202
+ ('PerJobUserTimeLimit', ctypes.c_int64),
203
+ ('LimitFlags', _wintypes.DWORD),
204
+ ('MinimumWorkingSetSize', ctypes.c_size_t),
205
+ ('MaximumWorkingSetSize', ctypes.c_size_t),
206
+ ('ActiveProcessLimit', _wintypes.DWORD),
207
+ ('Affinity', ctypes.c_size_t),
208
+ ('PriorityClass', _wintypes.DWORD),
209
+ ('SchedulingClass', _wintypes.DWORD),
210
+ ]
211
+
212
+ class _JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
213
+ _fields_ = [
214
+ ('BasicLimitInformation', _JOBOBJECT_BASIC_LIMIT_INFORMATION),
215
+ ('IoInfo', _IO_COUNTERS),
216
+ ('ProcessMemoryLimit', ctypes.c_size_t),
217
+ ('JobMemoryLimit', ctypes.c_size_t),
218
+ ('PeakProcessMemoryUsed', ctypes.c_size_t),
219
+ ('PeakJobMemoryUsed', ctypes.c_size_t),
220
+ ]
221
+
222
+ _kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, _wintypes.LPCWSTR]
223
+ _kernel32.CreateJobObjectW.restype = _wintypes.HANDLE
224
+ _kernel32.SetInformationJobObject.argtypes = [_wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, _wintypes.DWORD]
225
+ _kernel32.SetInformationJobObject.restype = _wintypes.BOOL
226
+ _kernel32.AssignProcessToJobObject.argtypes = [_wintypes.HANDLE, _wintypes.HANDLE]
227
+ _kernel32.AssignProcessToJobObject.restype = _wintypes.BOOL
228
+ _kernel32.TerminateJobObject.argtypes = [_wintypes.HANDLE, _wintypes.UINT]
229
+ _kernel32.TerminateJobObject.restype = _wintypes.BOOL
180
230
  _kernel32.OpenProcess.argtypes = [_wintypes.DWORD, _wintypes.BOOL, _wintypes.DWORD]
181
231
  _kernel32.OpenProcess.restype = _wintypes.HANDLE
182
232
  _kernel32.CloseHandle.argtypes = [_wintypes.HANDLE]
@@ -397,3 +447,61 @@ def group_alive(pgid: int) -> bool:
397
447
  return False
398
448
  return True
399
449
  return pid_alive(pgid)
450
+
451
+
452
+ class ProcessJob:
453
+ """Win32 Job Object binding child/grandchild processes to this guardian handle.
454
+
455
+ Configures ``JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`` so an abrupt kill of the
456
+ guardian cleans up the entire descendant tree atomically; ``disarm()`` clears
457
+ the flag after a clean wait so intentional orphan reaping runs as designed.
458
+ """
459
+
460
+ def __init__(self) -> None:
461
+ self._handle: int | None = None
462
+
463
+ def attach(self, pid: int, *, kill_on_close: bool = True) -> bool:
464
+ if not IS_WINDOWS or not isinstance(pid, int) or pid <= 0 or pid > 0xFFFFFFFF:
465
+ return False
466
+ job = _kernel32.CreateJobObjectW(None, None)
467
+ if not job:
468
+ return False
469
+ if kill_on_close and not self._set_limit_flags(job, _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE):
470
+ _kernel32.CloseHandle(job)
471
+ return False
472
+ proc = _kernel32.OpenProcess(_PROCESS_SET_QUOTA | _PROCESS_TERMINATE, False, pid)
473
+ if not proc:
474
+ _kernel32.CloseHandle(job)
475
+ return False
476
+ try:
477
+ if not _kernel32.AssignProcessToJobObject(job, proc):
478
+ _kernel32.CloseHandle(job)
479
+ return False
480
+ finally:
481
+ _kernel32.CloseHandle(proc)
482
+ self._handle = job
483
+ return True
484
+
485
+ def _set_limit_flags(self, handle: int, flags: int) -> bool:
486
+ info = _JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
487
+ info.BasicLimitInformation.LimitFlags = flags
488
+ return bool(_kernel32.SetInformationJobObject(
489
+ handle,
490
+ _JOB_OBJECT_EXTENDED_LIMIT_INFO,
491
+ ctypes.byref(info),
492
+ ctypes.sizeof(info),
493
+ ))
494
+
495
+ def disarm(self) -> None:
496
+ if self._handle:
497
+ self._set_limit_flags(self._handle, 0)
498
+
499
+ def terminate(self, exit_code: int = 1) -> bool:
500
+ if self._handle:
501
+ return bool(_kernel32.TerminateJobObject(self._handle, exit_code))
502
+ return False
503
+
504
+ def close(self) -> None:
505
+ if self._handle:
506
+ _kernel32.CloseHandle(self._handle)
507
+ self._handle = None
@@ -62,7 +62,7 @@ def registry_dir() -> Path:
62
62
  user's repo. ``config_path()`` is ``<that>/forge/jev.json``; the registry is the
63
63
  sibling ``runs`` directory.
64
64
  """
65
- value = os.environ.get('XDG_CONFIG_HOME') or ''
65
+ value = forge_posix.host_path(os.environ.get('XDG_CONFIG_HOME') or '')
66
66
  base = Path(value).expanduser() if value else None
67
67
  if base is None or not base.is_absolute():
68
68
  base = Path.home() / '.config'
@@ -286,7 +286,7 @@ def _repo_of(run_dir: Path) -> Path | None:
286
286
  with os.fdopen(fd, 'rb') as handle:
287
287
  if not stat.S_ISREG(os.fstat(fd).st_mode):
288
288
  return None
289
- line = handle.readline(_REPO_LINE_MAX).decode(errors='replace').strip()
289
+ line = forge_posix.host_path(handle.readline(_REPO_LINE_MAX).decode(errors='replace').strip())
290
290
  # Empty, or text no path can hold, or relative: a relative repo would be resolved
291
291
  # against whatever directory the runner happened to start in, and keyed to the wrong repo.
292
292
  if not line or '\x00' in line or not os.path.isabs(line):
@@ -253,6 +253,13 @@ def _count(kind_dir: Path) -> int:
253
253
  return total
254
254
 
255
255
 
256
+ def _slot_number(name: str) -> int | None:
257
+ """Parse an ASCII base-10 slot directory name, ignoring Unicode digits like `²`."""
258
+ if not (name.isascii() and name.isdigit()):
259
+ return None
260
+ return int(name)
261
+
262
+
256
263
  def _next_n(kind_dir: Path, task: str) -> int:
257
264
  """1 + the highest numeric `<n>` already under this task. Other tasks have their own count."""
258
265
  highest = 0
@@ -263,8 +270,9 @@ def _next_n(kind_dir: Path, task: str) -> int:
263
270
  except OSError:
264
271
  children = []
265
272
  for child in children:
266
- if child.is_dir() and child.name.isdigit():
267
- highest = max(highest, int(child.name))
273
+ number = _slot_number(child.name)
274
+ if number is not None and child.is_dir():
275
+ highest = max(highest, number)
268
276
  return highest + 1
269
277
 
270
278
 
@@ -357,7 +365,8 @@ def _triage_slots(home: Path) -> tuple[int, int]:
357
365
  except OSError:
358
366
  return 0, 0
359
367
  for child in children:
360
- if not child.name.isdigit():
368
+ number = _slot_number(child.name)
369
+ if number is None:
361
370
  continue
362
371
  try:
363
372
  info = child.lstat()
@@ -367,7 +376,7 @@ def _triage_slots(home: Path) -> tuple[int, int]:
367
376
  raise ValueError('triage dispatch dir must be a real directory, not a symlink')
368
377
  if not stat.S_ISDIR(info.st_mode):
369
378
  continue
370
- highest = max(highest, int(child.name))
379
+ highest = max(highest, number)
371
380
  count += 1
372
381
  return highest, count
373
382
 
@@ -349,7 +349,9 @@ class Context:
349
349
  `limit` is the route's timeout; a timeout given to `dispatch` (a test's) replaces it.
350
350
  `stdin` is bytes for a call that uses `--file -`, or None. `json_stdout` is false when a
351
351
  successful CLI prints text (a brief answer, including a late-answer notice)."""
352
- result = run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin)
352
+ raw = [str(self.cli), *args]
353
+ argv = forge_proc.resolve_win_command(raw)[1] if forge_proc.IS_WINDOWS else raw
354
+ result = run_cli(argv, self.timeout or limit or TIMEOUT_S, stdin=stdin)
353
355
  return map_exit(result) if json_stdout else _text_exit(result)
354
356
 
355
357
  def locked(self, work):
@@ -1943,7 +1945,10 @@ def _specs_check(ctx):
1943
1945
  spec = _triage_spec(params['spec'])
1944
1946
  except BadBody as exc:
1945
1947
  return _invalid(str(exc))
1946
- result = run_cli(['bash', _DISPATCH, 'doctor', '--spec', spec, '--role', 'side'], ctx.timeout or TIMEOUT_S)
1948
+ argv = forge_proc.bash_cmd(_DISPATCH, 'doctor', '--spec', spec, '--role', 'side') if forge_proc.IS_WINDOWS else [
1949
+ 'bash', _DISPATCH, 'doctor', '--spec', spec, '--role', 'side',
1950
+ ]
1951
+ result = run_cli(argv, ctx.timeout or TIMEOUT_S)
1947
1952
  if result.timed_out:
1948
1953
  return 504, {'error': 'timeout', 'detail': TIMEOUT_DETAIL}
1949
1954
  if result.error:
@@ -368,7 +368,12 @@ def _created(path, names):
368
368
  info = os.stat(path / name)
369
369
  except (OSError, ValueError):
370
370
  continue
371
- value = getattr(info, 'st_birthtime', None) or info.st_mtime
371
+ birth = getattr(info, 'st_birthtime', None)
372
+ if birth and sys.platform in ('win32', 'cygwin'):
373
+ # Windows keeps a file's creation time when its mtime is set earlier, where macOS moves
374
+ # the birth time back with it: the earlier of the two is the start there too.
375
+ birth = min(birth, info.st_mtime)
376
+ value = birth or info.st_mtime
372
377
  if math.isfinite(value):
373
378
  times.append(float(value))
374
379
  return min(times) if times else None
@@ -19,6 +19,16 @@ const clamp = v => Math.max(0, Math.min(1, v));
19
19
  const segT = (v, a, b) => clamp((v - a) / (b - a));
20
20
  const ez = t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
21
21
  const back = t => t <= 0 ? 0 : t >= 1 ? 1 : 1 + 2.2 * Math.pow(t - 1, 3) + 1.2 * Math.pow(t - 1, 2);
22
+ // Opening stagger window on the parent task's progress p (0..1): keeps step 0.05 through
23
+ // 8 slots (maxIdx <= 7) and scales down above that so the last part's window still ends at 1.
24
+ export function partWindow(idx, maxIdx) {
25
+ const step = maxIdx > 7 ? .36 / maxIdx : .05;
26
+ return [.34 + idx * step, .64 + idx * step];
27
+ }
28
+ export function partRise(p, idx, maxIdx) {
29
+ const [a, b] = partWindow(idx, maxIdx);
30
+ return back(segT(p, a, b));
31
+ }
22
32
  const MODEL_PALETTE = ['#4e9af1', '#f08c3a', '#6cc070', '#c46fd8', '#e0c341', '#4fc2c0', '#e06a8c', '#9a8cff', '#a3b84a', '#d98f6b'];
23
33
  const KIND_H = { dwarf: 24, qa: 13, shadow: 12 };
24
34
 
@@ -351,6 +361,8 @@ export async function createStage(host, cb = {}) {
351
361
  const padX = 10, padT = 22, padB = 10, gx = 8, gy = 7;
352
362
  const cw = (w - 2 * padX - (C - 1) * gx) / C, ch = Math.min(46, (d - padT - padB - (R - 1) * gy) / R);
353
363
  el.zoneEls = [];
364
+ const partEls = [];
365
+ let maxIdx = 0;
354
366
  tp.zones.forEach((z, ci) => {
355
367
  const zx = x + padX + ci * (cw + gx), zy = y + padT;
356
368
  const zm = E.lmat({ dashed: true, dashSize: 4 * TS, gapSize: 3 * TS });
@@ -365,7 +377,9 @@ export async function createStage(host, cb = {}) {
365
377
  const part = tp.parts.find(p => p.id === pid);
366
378
  const ph = KIND_H[part.kind] || 14;
367
379
  const n = { x: zx, y: zy + ri * (ch + gy), w: cw, d: ch, h: ph };
368
- const k = newEl('p:' + task.id + ':' + part.id, 'part', G, n, { part, task: task.id, parent: el.id, idx: ri + ci * R });
380
+ const idx = ri + ci * R;
381
+ maxIdx = Math.max(maxIdx, idx);
382
+ const k = newEl('p:' + task.id + ':' + part.id, 'part', G, n, { part, task: task.id, parent: el.id, idx, maxIdx: 0 });
369
383
  el.root.remove(k.root); G.add(k.root);
370
384
  setStatus(k, part.planned ? 'PENDING' : part.status);
371
385
  const r = part.kind === 'qa' ? Math.min(cw, ch) * .3 : Math.min(4, Math.min(cw, ch) * .07);
@@ -380,9 +394,11 @@ export async function createStage(host, cb = {}) {
380
394
  const fs = pt.exec && pt.exec.findings || pt.shadow && pt.shadow.findings;
381
395
  if (fs && fs.worst) chip(cx, s, Cc, pad, ch - pad - 6 * 1.6, `${fs.worst}×${fs[fs.worst]}`, E.sevHex(fs.worst), { f: Math.min(5, ch * .14) });
382
396
  }, 'cover', { x: zx, y: n.y, z: ph });
397
+ partEls.push(k);
383
398
  el.kids.push(k);
384
399
  });
385
400
  });
401
+ for (const k of partEls) k.data.maxIdx = maxIdx;
386
402
  el.innerFlows = [];
387
403
  for (const l of tp.links) {
388
404
  const a = EL.get('p:' + task.id + ':' + l.from), b = EL.get('p:' + task.id + ':' + l.to); if (!a || !b) continue;
@@ -952,7 +968,7 @@ export async function createStage(host, cb = {}) {
952
968
  let lift = 0, ob = 1, ol = 1;
953
969
  const pr = PROG.get(el.id);
954
970
  if (pr) { const p = pr.p; lift = ez(segT(p, .04, .46)); ob = 1 - segT(p, .06, .3); ol = 1 - segT(p, .14, .46); }
955
- if (el.kind === 'part') { const par = EL.get(el.data.parent), pp = par && PROG.get(par.id); const p = pp ? pp.p : 0; const [a, b] = [.34 + el.data.idx * .05, .64 + el.data.idx * .05]; const q = back(segT(p, a, b)); el.q = q; el.root.visible = q > .001; el.cover.scale.y = Math.max(.001, q); }
971
+ if (el.kind === 'part') { const par = EL.get(el.data.parent), pp = par && PROG.get(par.id); const p = pp ? pp.p : 0; const q = partRise(p, el.data.idx, el.data.maxIdx); el.q = q; el.root.visible = q > .001; el.cover.scale.y = Math.max(.001, q); }
956
972
  el.cover.visible = ol > .003;
957
973
  el.cover.position.y = (el.kind === 'task' ? 120 : 0) * lift * TS;
958
974
  if (el.kind === 'task' || el.kind === 'finish') el.cover.scale.y = Math.max(.05, c.hk);
@@ -1440,6 +1456,11 @@ export async function createStage(host, cb = {}) {
1440
1456
  return {
1441
1457
  view: st.view, mode: st.mode, rebuilds: st.rebuilds, sel: st.sel, prog: [...PROG].map(([id, p]) => [id, p.p, p.t]), fade: !!st.fade,
1442
1458
  nodes: [...EL.values()].map(el => ({ id: el.id, kind: el.kind, status: el.status, sel: el.tgt.sel, vis: el.tgt.vis })),
1459
+ parts(taskId) {
1460
+ const prefix = 'p:' + taskId + ':';
1461
+ return [...EL.values()].filter(el => el.kind === 'part' && el.id.startsWith(prefix))
1462
+ .map(el => ({ id: el.id, idx: el.data.idx, maxIdx: el.data.maxIdx, q: el.q, visible: el.root.visible, scaleY: el.cover.scale.y }));
1463
+ },
1443
1464
  screenPos(id) { const el = EL.get(id); if (!el) return null; const r = E.canvas.getBoundingClientRect(); const p = E.project(el.n.x + el.n.w / 2, el.n.y + el.n.d / 2, el.n.h); return { x: r.left + p.x, y: r.top + p.y, on: p.on }; },
1444
1465
  settle() { for (const el of EL.values()) Object.assign(el.cur, el.tgt); for (const pr of PROG.values()) pr.p = pr.t; E.invalidate(); },
1445
1466
  beaconScale: () => ({ unit: BEACONS.unit, ppu: E.pxPerUnit() }),