@giamme/forge 0.20.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 (71) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +13 -3
  3. package/VERSION +1 -1
  4. package/bin/forge.js +104 -0
  5. package/docs/README.md +1 -0
  6. package/docs/development.md +1 -1
  7. package/docs/install.md +91 -2
  8. package/docs/reviews.md +6 -4
  9. package/docs/troubleshooting.md +1 -1
  10. package/forge +4 -0
  11. package/forge.cmd +56 -0
  12. package/package.json +5 -3
  13. package/scripts/forge-artifact.sh +5 -1
  14. package/scripts/forge-config.py +10 -9
  15. package/scripts/forge-control.py +61 -38
  16. package/scripts/forge-dispatch.sh +108 -31
  17. package/scripts/forge-group.py +2 -1
  18. package/scripts/forge-guard.py +207 -38
  19. package/scripts/forge-handoff.py +14 -17
  20. package/scripts/forge-install.sh +82 -9
  21. package/scripts/forge-issues.py +5 -2
  22. package/scripts/forge-lib-env.sh +158 -0
  23. package/scripts/forge-lib-group.sh +5 -5
  24. package/scripts/forge-lib-plans.sh +8 -3
  25. package/scripts/forge-lib-task.sh +40 -15
  26. package/scripts/forge-memory.sh +2 -0
  27. package/scripts/forge-metrics.sh +6 -1
  28. package/scripts/forge-parallel.sh +174 -53
  29. package/scripts/forge-planner.py +28 -2
  30. package/scripts/forge-pre-review.py +11 -4
  31. package/scripts/forge-ripwire.py +68 -22
  32. package/scripts/forge-route.py +10 -3
  33. package/scripts/forge-runs-compact.py +3 -2
  34. package/scripts/forge-runs-rm.py +14 -14
  35. package/scripts/forge-runtime.py +38 -21
  36. package/scripts/forge-schedule.py +90 -56
  37. package/scripts/forge-shadow.py +16 -9
  38. package/scripts/forge-solo.sh +6 -2
  39. package/scripts/forge-summarize.py +7 -3
  40. package/scripts/forge-sweep.py +8 -3
  41. package/scripts/forge-ui.py +8 -13
  42. package/scripts/forge-update.sh +6 -1
  43. package/scripts/forge-verify.py +30 -23
  44. package/scripts/forge-win.sh +156 -0
  45. package/scripts/forge_brief/__init__.py +7 -2
  46. package/scripts/forge_brief/proposals.py +13 -3
  47. package/scripts/forge_decide/budget.py +18 -8
  48. package/scripts/forge_decide/replay.py +15 -5
  49. package/scripts/forge_findings/apply.py +2 -1
  50. package/scripts/forge_findings/store.py +16 -4
  51. package/scripts/forge_findings/triage.py +6 -15
  52. package/scripts/forge_flock.py +102 -0
  53. package/scripts/forge_fractal/__init__.py +7 -3
  54. package/scripts/forge_fractal/cli.py +7 -2
  55. package/scripts/forge_fractal/execution.py +14 -14
  56. package/scripts/forge_fractal/invocation.py +3 -2
  57. package/scripts/forge_fractal/pipeline.py +2 -1
  58. package/scripts/forge_fractal/selection.py +2 -1
  59. package/scripts/forge_identity.py +2 -1
  60. package/scripts/forge_locations.py +14 -4
  61. package/scripts/forge_posix.py +125 -0
  62. package/scripts/forge_proc.py +507 -0
  63. package/scripts/forge_registry.py +17 -8
  64. package/scripts/forge_retro/__init__.py +8 -2
  65. package/scripts/forge_retro/issues.py +2 -1
  66. package/scripts/forge_side/__init__.py +32 -14
  67. package/scripts/forge_storage.py +11 -1
  68. package/ui/forge_ui/control.py +42 -14
  69. package/ui/forge_ui/reader.py +24 -18
  70. package/ui/forge_ui/server.py +10 -1
  71. package/ui/forge_ui/static/scene3d.js +23 -2
@@ -0,0 +1,507 @@
1
+ """Cross-platform process, signal, and bash resolution adapters for forge.
2
+
3
+ Keeps POSIX semantics (process groups, signals, /bin/bash, exec) unchanged on
4
+ macOS/Linux while providing pure-stdlib Windows equivalents using Win32 kernel32
5
+ APIs via ctypes.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import ctypes
11
+ import os
12
+ from pathlib import Path
13
+ import shutil
14
+ import signal
15
+ import subprocess
16
+ import sys
17
+
18
+ IS_WINDOWS = os.name == 'nt'
19
+
20
+ SIGKILL = getattr(signal, 'SIGKILL', signal.SIGTERM)
21
+ SIGUSR1 = getattr(signal, 'SIGUSR1', None)
22
+ SIGQUIT = getattr(signal, 'SIGQUIT', None)
23
+ SIGBREAK = getattr(signal, 'SIGBREAK', None)
24
+
25
+ _STILL_ACTIVE = 259
26
+ _PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
27
+ _PROCESS_SET_QUOTA = 0x0100
28
+ _PROCESS_TERMINATE = 0x0001
29
+ _TH32CS_SNAPPROCESS = 0x00000002
30
+ _ERROR_ACCESS_DENIED = 5
31
+ _JOB_OBJECT_EXTENDED_LIMIT_INFO = 9
32
+ _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
33
+ _CREATE_NO_WINDOW = getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
34
+
35
+
36
+ def _is_windows_bash_stub(path: str) -> bool:
37
+ low = path.replace('/', '\\').lower()
38
+ return '\\system32\\bash.exe' in low or '\\syswow64\\bash.exe' in low or '\\windowsapps\\' in low
39
+
40
+
41
+ def bash_executable() -> str:
42
+ """Path to GNU bash (/bin/bash on POSIX; Git Bash avoiding WSL stub on Windows)."""
43
+ if not IS_WINDOWS:
44
+ if os.path.exists('/bin/bash'):
45
+ return '/bin/bash'
46
+ return shutil.which('bash') or '/bin/bash'
47
+
48
+ for env_key in ('FORGE_BASH', 'BASH'):
49
+ cand = os.environ.get(env_key, '').strip()
50
+ if cand and os.path.isfile(cand) and not _is_windows_bash_stub(cand):
51
+ return cand
52
+
53
+ which_bash = shutil.which('bash')
54
+ if which_bash and not _is_windows_bash_stub(which_bash):
55
+ if which_bash.replace('/', '\\').lower().endswith('\\usr\\bin\\bash.exe'):
56
+ git_bin = Path(which_bash).resolve().parents[2] / 'bin' / 'bash.exe'
57
+ if git_bin.is_file():
58
+ return str(git_bin)
59
+ return which_bash
60
+
61
+ candidates: list[Path] = []
62
+ which_git = shutil.which('git')
63
+ if which_git:
64
+ git_path = Path(which_git).resolve()
65
+ for parent in git_path.parents:
66
+ candidates.append(parent / 'bin' / 'bash.exe')
67
+ candidates.append(parent / 'usr' / 'bin' / 'bash.exe')
68
+ for root in (os.environ.get('ProgramFiles'), os.environ.get('ProgramFiles(x86)'),
69
+ os.environ.get('LocalAppData')):
70
+ if root:
71
+ candidates.append(Path(root) / 'Git' / 'bin' / 'bash.exe')
72
+ candidates.append(Path(root) / 'Git' / 'usr' / 'bin' / 'bash.exe')
73
+ candidates.append(Path(root) / 'Programs' / 'Git' / 'bin' / 'bash.exe')
74
+ candidates.extend((
75
+ Path(r'C:\Program Files\Git\bin\bash.exe'),
76
+ Path(r'C:\Program Files\Git\usr\bin\bash.exe'),
77
+ Path(r'C:\Program Files (x86)\Git\bin\bash.exe'),
78
+ ))
79
+ for cand in candidates:
80
+ if cand.is_file():
81
+ return str(cand)
82
+ return which_bash or 'bash'
83
+
84
+
85
+ def bash_cmd(*args: str | os.PathLike[str]) -> list[str]:
86
+ """Build an argv list starting with the resolved bash executable."""
87
+ return [bash_executable(), *(os.fspath(a) for a in args)]
88
+
89
+
90
+ def resolve_win_command(argv: list[str]) -> tuple[Path, list[str]]:
91
+ """Resolve an executable path and Windows wrapper (.cmd/.bat/shebang) for CreateProcess."""
92
+ raw = argv[0]
93
+ if not IS_WINDOWS:
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:]}'
100
+ found = shutil.which(raw)
101
+ if found:
102
+ binary = Path(found).resolve()
103
+ if binary.suffix.lower() in ('.cmd', '.bat'):
104
+ return binary, ['cmd.exe', '/c', str(binary), *argv[1:]]
105
+ if binary.suffix.lower() in ('.exe', '.com'):
106
+ return binary, [str(binary), *argv[1:]]
107
+ else:
108
+ binary = Path(raw).resolve()
109
+ if binary.is_file():
110
+ if binary.suffix.lower() in ('.cmd', '.bat'):
111
+ return binary, ['cmd.exe', '/c', str(binary), *argv[1:]]
112
+ try:
113
+ with binary.open('rb') as handle:
114
+ head = handle.read(256)
115
+ except OSError:
116
+ head = b''
117
+ if head.startswith(b'#!'):
118
+ line = head.splitlines()[0][2:].decode('utf-8', 'replace').strip()
119
+ if 'python' in line:
120
+ return binary, [sys.executable, str(binary), *argv[1:]]
121
+ if 'sh' in line:
122
+ return binary, bash_cmd(str(binary), *argv[1:])
123
+ return binary, [str(binary), *argv[1:]] if found else list(argv)
124
+
125
+
126
+ def install_signal(sig: int | None, handler) -> None:
127
+ """Install a signal handler when the signal exists on this platform."""
128
+ if sig is not None:
129
+ signal.signal(sig, handler)
130
+
131
+
132
+ @contextlib.contextmanager
133
+ def mask_sigterm():
134
+ """Block SIGTERM around non-interruptible writes on POSIX; no-op on Windows."""
135
+ if hasattr(signal, 'pthread_sigmask') and hasattr(signal, 'SIG_BLOCK'):
136
+ signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
137
+ try:
138
+ yield
139
+ finally:
140
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGTERM})
141
+ else:
142
+ yield
143
+
144
+
145
+ def popen_group_kwargs(*, detached: bool = False) -> dict[str, object]:
146
+ """Keyword arguments placing a subprocess into its own group/session."""
147
+ if IS_WINDOWS:
148
+ flags = getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0) | _CREATE_NO_WINDOW
149
+ if detached:
150
+ flags |= getattr(subprocess, 'DETACHED_PROCESS', 0)
151
+ return {'creationflags': flags}
152
+ return {'start_new_session': True}
153
+
154
+
155
+ def exec_or_exit(argv: list[str], env: dict[str, str] | None = None, *, inherit_fds: bool = False) -> None:
156
+ """Replace the current process on POSIX; on Windows run and exit so inherited locks remain held."""
157
+ if not IS_WINDOWS:
158
+ if env is not None:
159
+ os.execve(argv[0], argv, env)
160
+ else:
161
+ os.execvp(argv[0], argv)
162
+ raise AssertionError('unreachable')
163
+ done = subprocess.run(argv, env=env, close_fds=not inherit_fds)
164
+ sys.exit(done.returncode)
165
+
166
+
167
+ if IS_WINDOWS:
168
+ import ctypes.wintypes as _wintypes
169
+
170
+ _kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
171
+
172
+ class _FILETIME(ctypes.Structure):
173
+ _fields_ = [('dwLowDateTime', _wintypes.DWORD), ('dwHighDateTime', _wintypes.DWORD)]
174
+
175
+ class _PROCESSENTRY32W(ctypes.Structure):
176
+ _fields_ = [
177
+ ('dwSize', _wintypes.DWORD),
178
+ ('cntUsage', _wintypes.DWORD),
179
+ ('th32ProcessID', _wintypes.DWORD),
180
+ ('th32DefaultHeapID', ctypes.c_size_t),
181
+ ('th32ModuleID', _wintypes.DWORD),
182
+ ('cntThreads', _wintypes.DWORD),
183
+ ('th32ParentProcessID', _wintypes.DWORD),
184
+ ('pcPriClassBase', _wintypes.LONG),
185
+ ('dwFlags', _wintypes.DWORD),
186
+ ('szExeFile', _wintypes.WCHAR * 260),
187
+ ]
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
230
+ _kernel32.OpenProcess.argtypes = [_wintypes.DWORD, _wintypes.BOOL, _wintypes.DWORD]
231
+ _kernel32.OpenProcess.restype = _wintypes.HANDLE
232
+ _kernel32.CloseHandle.argtypes = [_wintypes.HANDLE]
233
+ _kernel32.CloseHandle.restype = _wintypes.BOOL
234
+ _kernel32.GetExitCodeProcess.argtypes = [_wintypes.HANDLE, ctypes.POINTER(_wintypes.DWORD)]
235
+ _kernel32.GetExitCodeProcess.restype = _wintypes.BOOL
236
+ _kernel32.GetProcessTimes.argtypes = [
237
+ _wintypes.HANDLE,
238
+ ctypes.POINTER(_FILETIME),
239
+ ctypes.POINTER(_FILETIME),
240
+ ctypes.POINTER(_FILETIME),
241
+ ctypes.POINTER(_FILETIME),
242
+ ]
243
+ _kernel32.GetProcessTimes.restype = _wintypes.BOOL
244
+ _kernel32.TerminateProcess.argtypes = [_wintypes.HANDLE, _wintypes.UINT]
245
+ _kernel32.TerminateProcess.restype = _wintypes.BOOL
246
+ _kernel32.CreateToolhelp32Snapshot.argtypes = [_wintypes.DWORD, _wintypes.DWORD]
247
+ _kernel32.CreateToolhelp32Snapshot.restype = _wintypes.HANDLE
248
+ _kernel32.Process32FirstW.argtypes = [_wintypes.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)]
249
+ _kernel32.Process32FirstW.restype = _wintypes.BOOL
250
+ _kernel32.Process32NextW.argtypes = [_wintypes.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)]
251
+ _kernel32.Process32NextW.restype = _wintypes.BOOL
252
+
253
+
254
+ def pid_alive(pid: int, *, min_pid: int = 1) -> bool:
255
+ """Return True iff ``pid`` names a running OS process (with ``pid >= min_pid``)."""
256
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid < min_pid:
257
+ return False
258
+ if not IS_WINDOWS:
259
+ try:
260
+ os.kill(pid, 0)
261
+ except (ProcessLookupError, OverflowError):
262
+ return False
263
+ except PermissionError:
264
+ return True
265
+ except OSError:
266
+ return False
267
+ return True
268
+
269
+ if pid > 0xFFFFFFFF:
270
+ return False
271
+ handle = _kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
272
+ if not handle:
273
+ return ctypes.get_last_error() == _ERROR_ACCESS_DENIED
274
+ try:
275
+ code = _wintypes.DWORD()
276
+ if not _kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
277
+ return True
278
+ return code.value == _STILL_ACTIVE
279
+ finally:
280
+ _kernel32.CloseHandle(handle)
281
+
282
+
283
+ def process_start_time(pid: int) -> str | None:
284
+ """Stable opaque creation timestamp for an active Windows PID (None if exited/unavailable)."""
285
+ if not IS_WINDOWS or not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0 or pid > 0xFFFFFFFF:
286
+ return None
287
+ handle = _kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
288
+ if not handle:
289
+ return None
290
+ try:
291
+ code = _wintypes.DWORD()
292
+ if _kernel32.GetExitCodeProcess(handle, ctypes.byref(code)) and code.value != _STILL_ACTIVE:
293
+ return None
294
+ c, e, k, u = _FILETIME(), _FILETIME(), _FILETIME(), _FILETIME()
295
+ if not _kernel32.GetProcessTimes(handle, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u)):
296
+ return None
297
+ return str((c.dwHighDateTime << 32) | c.dwLowDateTime)
298
+ finally:
299
+ _kernel32.CloseHandle(handle)
300
+
301
+
302
+ def win_ps_table() -> dict[int, tuple[int, str, str]]:
303
+ """Windows snapshot matching forge-guard.ps_table(): {pid: (ppid, start_time, exe)}."""
304
+ if not IS_WINDOWS:
305
+ return {}
306
+ snap = _kernel32.CreateToolhelp32Snapshot(_TH32CS_SNAPPROCESS, 0)
307
+ if not snap or snap == _wintypes.HANDLE(-1).value:
308
+ return {}
309
+ table: dict[int, tuple[int, str, str]] = {}
310
+ try:
311
+ entry = _PROCESSENTRY32W()
312
+ entry.dwSize = ctypes.sizeof(entry)
313
+ ok = _kernel32.Process32FirstW(snap, ctypes.byref(entry))
314
+ while ok:
315
+ pid = int(entry.th32ProcessID)
316
+ ppid = int(entry.th32ParentProcessID)
317
+ if pid > 0:
318
+ start = process_start_time(pid) or ''
319
+ table[pid] = (ppid, start, entry.szExeFile)
320
+ ok = _kernel32.Process32NextW(snap, ctypes.byref(entry))
321
+ finally:
322
+ _kernel32.CloseHandle(snap)
323
+ return table
324
+
325
+
326
+ def _started_not_before(child_start: str, parent_start: str) -> bool:
327
+ """Guard against stale Windows th32ParentProcessID when a PID was reused."""
328
+ if not IS_WINDOWS:
329
+ return True
330
+ if child_start.isdigit() and parent_start.isdigit():
331
+ return int(child_start) >= int(parent_start)
332
+ return True
333
+
334
+
335
+ def win_descendants(table: dict[int, tuple[int, str, str]], roots: set[int]) -> set[int]:
336
+ """Return descendant PIDs in ``table`` whose creation time >= their parent's."""
337
+ by_parent: dict[int, list[int]] = {}
338
+ for pid, (ppid, _start, _exe) in table.items():
339
+ if pid != ppid:
340
+ by_parent.setdefault(ppid, []).append(pid)
341
+ found: set[int] = set()
342
+ queue = list(roots)
343
+ while queue:
344
+ parent = queue.pop(0)
345
+ parent_start = table[parent][1] if parent in table else ''
346
+ for child in by_parent.get(parent, ()):
347
+ if child in found or child in roots:
348
+ continue
349
+ child_start = table[child][1]
350
+ if not _started_not_before(child_start, parent_start):
351
+ continue
352
+ found.add(child)
353
+ queue.append(child)
354
+ return found
355
+
356
+
357
+ def _win_terminate_pid(pid: int) -> bool:
358
+ if pid <= 0 or pid > 0xFFFFFFFF:
359
+ return False
360
+ handle = _kernel32.OpenProcess(_PROCESS_TERMINATE, False, pid)
361
+ if not handle:
362
+ return False
363
+ try:
364
+ return bool(_kernel32.TerminateProcess(handle, 1))
365
+ finally:
366
+ _kernel32.CloseHandle(handle)
367
+
368
+
369
+ def signal_pid(pid: int, force: bool = False) -> bool:
370
+ """Terminate a single process (`SIGTERM`/`SIGKILL` on POSIX; `TerminateProcess` on Windows)."""
371
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
372
+ return False
373
+ if not IS_WINDOWS:
374
+ sig = SIGKILL if force else signal.SIGTERM
375
+ try:
376
+ os.kill(pid, sig)
377
+ return True
378
+ except PermissionError:
379
+ return True
380
+ except OSError:
381
+ return False
382
+
383
+ if not force:
384
+ try:
385
+ os.kill(pid, signal.SIGTERM)
386
+ return True
387
+ except OSError:
388
+ return False
389
+ if _win_terminate_pid(pid):
390
+ return True
391
+ try:
392
+ os.kill(pid, signal.SIGTERM)
393
+ return True
394
+ except OSError:
395
+ return False
396
+
397
+
398
+ def kill_tree(pid: int, force: bool = False) -> None:
399
+ """Signal/terminate a process and its descendant tree (start-time guarded on Windows)."""
400
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
401
+ return
402
+ if not IS_WINDOWS:
403
+ sig = SIGKILL if force else signal.SIGTERM
404
+ try:
405
+ os.killpg(pid, sig)
406
+ except (ProcessLookupError, PermissionError):
407
+ pass
408
+ except OSError:
409
+ try:
410
+ os.kill(pid, sig)
411
+ except OSError:
412
+ pass
413
+ return
414
+
415
+ table = win_ps_table()
416
+ targets = ({pid} if pid in table else set()) | win_descendants(table, {pid})
417
+ self_pid = os.getpid()
418
+ # Signal descendants before root, validating start times against snapshot before terminating.
419
+ for target in sorted(targets - {pid}, reverse=True):
420
+ if target == self_pid:
421
+ continue
422
+ expected_start = table.get(target, (0, '', ''))[1]
423
+ current_start = process_start_time(target)
424
+ if expected_start and current_start and current_start != expected_start:
425
+ continue
426
+ _win_terminate_pid(target)
427
+ if pid != self_pid:
428
+ expected_start = table.get(pid, (0, '', ''))[1]
429
+ current_start = process_start_time(pid)
430
+ if not (expected_start and current_start and current_start != expected_start):
431
+ if force or pid_alive(pid):
432
+ _win_terminate_pid(pid)
433
+
434
+
435
+ def group_alive(pgid: int) -> bool:
436
+ """Return True if process group (POSIX) or root PID (Windows) has live processes."""
437
+ if not isinstance(pgid, int) or isinstance(pgid, bool) or pgid <= 0:
438
+ return False
439
+ if not IS_WINDOWS:
440
+ try:
441
+ os.killpg(pgid, 0)
442
+ except ProcessLookupError:
443
+ return False
444
+ except PermissionError:
445
+ return True
446
+ except OSError:
447
+ return False
448
+ return True
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
@@ -25,7 +25,6 @@ from __future__ import annotations
25
25
 
26
26
  import contextlib
27
27
  import errno
28
- import fcntl
29
28
  import hashlib
30
29
  import os
31
30
  import stat
@@ -34,6 +33,12 @@ import tempfile
34
33
  import time
35
34
  from pathlib import Path
36
35
 
36
+ _SCRIPTS = str(Path(__file__).resolve().parent)
37
+ if _SCRIPTS not in sys.path:
38
+ sys.path.insert(0, _SCRIPTS)
39
+ import forge_flock as fcntl # noqa: E402
40
+ import forge_posix # noqa: E402
41
+
37
42
  # register_run_dir runs before forge ui open's own timeouts: it waits this long for the lock,
38
43
  # then appends without it. unregister_run_dir is only ever called by `forge runs rm`, which
39
44
  # can afford to wait for a busy lock, but not for ever.
@@ -57,7 +62,7 @@ def registry_dir() -> Path:
57
62
  user's repo. ``config_path()`` is ``<that>/forge/jev.json``; the registry is the
58
63
  sibling ``runs`` directory.
59
64
  """
60
- value = os.environ.get('XDG_CONFIG_HOME') or ''
65
+ value = forge_posix.host_path(os.environ.get('XDG_CONFIG_HOME') or '')
61
66
  base = Path(value).expanduser() if value else None
62
67
  if base is None or not base.is_absolute():
63
68
  base = Path.home() / '.config'
@@ -92,7 +97,11 @@ def _registry_lock(wait_s: float):
92
97
  A filesystem that cannot flock at all (ENOLCK, EOPNOTSUPP) gets no locking, as it
93
98
  would anywhere else in forge, rather than a registry nobody can change.
94
99
  """
95
- fd = os.open(registry_dir() / LOCK_NAME, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
100
+ fd = forge_posix.open_nofollow(
101
+ registry_dir() / LOCK_NAME,
102
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
103
+ 0o600,
104
+ )
96
105
  try:
97
106
  if not stat.S_ISREG(os.fstat(fd).st_mode):
98
107
  raise OSError(errno.EINVAL, 'the registry lock is not a regular file', LOCK_NAME)
@@ -159,7 +168,7 @@ def register_run_dir(repo: Path, run_dir: Path) -> None:
159
168
  header = [] if existing else ['# forge run dirs for ' + str(Path(repo).resolve())]
160
169
  # O_NONBLOCK: a FIFO with no reader fails at once (ENXIO) instead of blocking the
161
170
  # open, and anything that is not a regular file is left alone.
162
- fd = os.open(registry, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NONBLOCK, 0o644)
171
+ fd = os.open(registry, os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NONBLOCK, 0o644)
163
172
  with os.fdopen(fd, 'a') as handle:
164
173
  written = os.fstat(fd)
165
174
  if not stat.S_ISREG(written.st_mode):
@@ -190,7 +199,7 @@ def _rewrite_without(path: Path, wanted: set) -> bool:
190
199
  replace, and whatever it gained since the read is appended to the new one.
191
200
  """
192
201
  try:
193
- fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
202
+ fd = forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NONBLOCK | forge_posix.O_NOFOLLOW)
194
203
  except OSError as error:
195
204
  if error.errno in (errno.ENOENT, errno.ELOOP):
196
205
  return False
@@ -229,7 +238,7 @@ def _rewrite_without(path: Path, wanted: set) -> bool:
229
238
  if extra:
230
239
  if content and not content.endswith(b'\n'):
231
240
  extra.insert(0, b'\n')
232
- out = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW | os.O_NONBLOCK)
241
+ out = forge_posix.open_nofollow(path, os.O_WRONLY | os.O_APPEND | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK)
233
242
  with os.fdopen(out, 'ab') as handle:
234
243
  handle.write(b''.join(extra))
235
244
  return True
@@ -273,11 +282,11 @@ def _repo_of(run_dir: Path) -> Path | None:
273
282
  hold the open, and nothing but a regular file is read (a FIFO, a device or a directory
274
283
  named ``repo`` is ignored).
275
284
  """
276
- fd = os.open(run_dir / 'repo', os.O_RDONLY | os.O_NONBLOCK)
285
+ fd = os.open(run_dir / 'repo', os.O_RDONLY | forge_posix.O_NONBLOCK)
277
286
  with os.fdopen(fd, 'rb') as handle:
278
287
  if not stat.S_ISREG(os.fstat(fd).st_mode):
279
288
  return None
280
- 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())
281
290
  # Empty, or text no path can hold, or relative: a relative repo would be resolved
282
291
  # against whatever directory the runner happened to start in, and keyed to the wrong repo.
283
292
  if not line or '\x00' in line or not os.path.isabs(line):
@@ -11,13 +11,19 @@ from `note`, is always `claimed`.
11
11
  """
12
12
  from __future__ import annotations
13
13
 
14
- import fcntl
15
14
  import json
16
15
  import os
17
16
  from pathlib import Path
17
+ import platform
18
+ import sys
18
19
  import tempfile
19
20
  import time
20
21
 
22
+ _SCRIPTS = str(Path(__file__).resolve().parents[1])
23
+ if _SCRIPTS not in sys.path:
24
+ sys.path.insert(0, _SCRIPTS)
25
+ import forge_flock as fcntl # noqa: E402
26
+
21
27
  SKILL = Path(__file__).resolve().parents[2]
22
28
  TYPES = ('environment', 'sandbox', 'tooling', 'prompt', 'forge-bug', 'other')
23
29
  FIXABLE = ('user', 'forge', 'unsure')
@@ -225,7 +231,7 @@ def _context(plan: Path, role: str, resolved: dict, task, attempt) -> dict:
225
231
  'attempt': _attempt(attempt),
226
232
  'run_id': _first_line(plan / 'run_id'),
227
233
  'version': _first_line(SKILL / 'VERSION'),
228
- 'os': os.uname().sysname,
234
+ 'os': platform.system(),
229
235
  't': int(time.time()),
230
236
  }
231
237
 
@@ -16,6 +16,7 @@ import importlib.util
16
16
  import json
17
17
  import os
18
18
  from pathlib import Path
19
+ import platform
19
20
  import re
20
21
  import sys
21
22
  import tempfile
@@ -749,7 +750,7 @@ def _version_os(notes: list) -> tuple:
749
750
  if not versions:
750
751
  versions.append(_read(SKILL / 'VERSION').strip() or 'unknown')
751
752
  if not systems:
752
- systems.append(os.uname().sysname)
753
+ systems.append(platform.system())
753
754
  return ', '.join(versions), ', '.join(systems)
754
755
 
755
756