@giamme/forge 0.19.0 → 0.21.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.
- package/CHANGELOG.md +32 -0
- package/README.md +7 -0
- package/SKILL.md +3 -0
- package/VERSION +1 -1
- package/docs/README.md +1 -0
- package/docs/commands.md +137 -5
- package/docs/development.md +1 -1
- package/docs/forge-ui.md +70 -19
- package/forge +8 -2
- package/package.json +1 -1
- package/references/decompose.md +20 -8
- package/references/memory.md +30 -5
- package/scripts/forge-config.py +10 -9
- package/scripts/forge-control.py +51 -35
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-group.py +2 -1
- package/scripts/forge-guard.py +71 -33
- package/scripts/forge-handoff.py +14 -17
- package/scripts/forge-issues.py +233 -99
- package/scripts/forge-memory.sh +471 -19
- package/scripts/forge-parallel.sh +24 -14
- package/scripts/forge-planner.py +28 -2
- package/scripts/forge-pre-review.py +11 -4
- package/scripts/forge-ripwire.py +68 -22
- package/scripts/forge-route.py +10 -3
- package/scripts/forge-runs-compact.py +3 -2
- package/scripts/forge-runs-rm.py +14 -14
- package/scripts/forge-runtime.py +36 -19
- package/scripts/forge-schedule.py +135 -62
- package/scripts/forge-shadow.py +16 -9
- package/scripts/forge-summarize.py +7 -3
- package/scripts/forge-sweep.py +206 -46
- package/scripts/forge-ui.py +8 -13
- package/scripts/forge-verify.py +29 -23
- package/scripts/forge_brief/__init__.py +1 -1
- package/scripts/forge_brief/proposals.py +7 -2
- package/scripts/forge_decide/budget.py +6 -1
- package/scripts/forge_decide/replay.py +6 -1
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +442 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +595 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +594 -0
- package/scripts/forge_flock.py +87 -0
- package/scripts/forge_fractal/__init__.py +7 -3
- package/scripts/forge_fractal/cli.py +7 -2
- package/scripts/forge_fractal/execution.py +14 -14
- package/scripts/forge_fractal/invocation.py +3 -2
- package/scripts/forge_fractal/pipeline.py +2 -1
- package/scripts/forge_fractal/selection.py +2 -1
- package/scripts/forge_identity.py +328 -0
- package/scripts/forge_locations.py +14 -4
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_posix.py +108 -0
- package/scripts/forge_proc.py +399 -0
- package/scripts/forge_registry.py +15 -6
- package/scripts/forge_retro/__init__.py +8 -2
- package/scripts/forge_retro/issues.py +2 -1
- package/scripts/forge_side/__init__.py +232 -38
- package/scripts/forge_storage.py +11 -1
- package/ui/docs/api.md +130 -12
- package/ui/forge_ui/control.py +693 -17
- package/ui/forge_ui/export.py +1 -1
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/reader.py +18 -17
- package/ui/forge_ui/server.py +10 -1
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/index.html +2 -0
- package/ui/forge_ui/static/projectsview.js +600 -45
- package/ui/forge_ui/static/style.css +59 -0
- package/ui/forge_ui/static/triageview.js +423 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Cross-platform POSIX open-flag and directory-handle helpers.
|
|
2
|
+
|
|
3
|
+
On POSIX, keeps exact kernel-enforced ``O_NOFOLLOW``, ``O_NONBLOCK``,
|
|
4
|
+
``O_CLOEXEC``, ``O_DIRECTORY``, and ``dir_fd`` semantics. On Windows, validates
|
|
5
|
+
symlinks and NTFS reparse points (junctions) via ``os.lstat`` before opening
|
|
6
|
+
(note: the lstat-then-open fallback is best-effort/TOCTOU on Windows).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import errno
|
|
11
|
+
import os
|
|
12
|
+
import stat
|
|
13
|
+
|
|
14
|
+
O_NOFOLLOW = getattr(os, 'O_NOFOLLOW', 0)
|
|
15
|
+
O_NONBLOCK = getattr(os, 'O_NONBLOCK', 0)
|
|
16
|
+
O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0)
|
|
17
|
+
O_DIRECTORY = getattr(os, 'O_DIRECTORY', 0)
|
|
18
|
+
|
|
19
|
+
_REPARSE_ATTR = getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)
|
|
20
|
+
|
|
21
|
+
SUPPORTS_DIR_FD = (
|
|
22
|
+
os.open in os.supports_dir_fd
|
|
23
|
+
and os.stat in os.supports_dir_fd
|
|
24
|
+
and os.unlink in os.supports_dir_fd
|
|
25
|
+
and os.mkdir in os.supports_dir_fd
|
|
26
|
+
and os.rename in os.supports_dir_fd
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _is_link_or_reparse(st: os.stat_result) -> bool:
|
|
31
|
+
return stat.S_ISLNK(st.st_mode) or bool(getattr(st, 'st_file_attributes', 0) & _REPARSE_ATTR)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _reject_symlink(path: os.PathLike | str) -> None:
|
|
35
|
+
"""Raise ELOOP if ``path`` is a symlink or reparse point (Windows fallback)."""
|
|
36
|
+
try:
|
|
37
|
+
st = os.lstat(path)
|
|
38
|
+
except FileNotFoundError:
|
|
39
|
+
return
|
|
40
|
+
if _is_link_or_reparse(st):
|
|
41
|
+
raise OSError(errno.ELOOP, 'Too many levels of symbolic links', os.fspath(path))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def open_nofollow(path: os.PathLike | str, flags: int, mode: int = 0o777) -> int:
|
|
45
|
+
"""Open ``path`` without following symlinks or junctions."""
|
|
46
|
+
if O_NOFOLLOW != 0:
|
|
47
|
+
flags |= O_NOFOLLOW
|
|
48
|
+
else:
|
|
49
|
+
_reject_symlink(path)
|
|
50
|
+
return os.open(path, flags, mode)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def open_dir(path: os.PathLike | str, *, nofollow: bool = True) -> int | str:
|
|
54
|
+
"""Open a real directory safely; returns an int dir_fd on POSIX or path str on Windows."""
|
|
55
|
+
flags = os.O_RDONLY | O_DIRECTORY | (O_NOFOLLOW if nofollow else 0) | O_CLOEXEC
|
|
56
|
+
if SUPPORTS_DIR_FD:
|
|
57
|
+
return os.open(path, flags)
|
|
58
|
+
st = os.lstat(path)
|
|
59
|
+
if nofollow and _is_link_or_reparse(st):
|
|
60
|
+
raise OSError(errno.ELOOP, 'Too many levels of symbolic links', os.fspath(path))
|
|
61
|
+
if not stat.S_ISDIR(st.st_mode):
|
|
62
|
+
raise OSError(errno.ENOTDIR, 'Not a directory', os.fspath(path))
|
|
63
|
+
return os.fspath(path)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def close_dir(handle: int | str) -> None:
|
|
67
|
+
if isinstance(handle, int):
|
|
68
|
+
os.close(handle)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def enter_dir(handle: int | str, part: str, *, nofollow: bool = True) -> int | str:
|
|
72
|
+
if isinstance(handle, int):
|
|
73
|
+
flags = os.O_RDONLY | O_DIRECTORY | (O_NOFOLLOW if nofollow else 0) | O_CLOEXEC
|
|
74
|
+
return os.open(part, flags, dir_fd=handle)
|
|
75
|
+
return open_dir(os.path.join(handle, part), nofollow=nofollow)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def mkdir_at(handle: int | str, part: str) -> None:
|
|
79
|
+
if isinstance(handle, int):
|
|
80
|
+
os.mkdir(part, dir_fd=handle)
|
|
81
|
+
else:
|
|
82
|
+
os.mkdir(os.path.join(handle, part))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def stat_at(handle: int | str, leaf: str, *, follow_symlinks: bool = False) -> os.stat_result:
|
|
86
|
+
if isinstance(handle, int):
|
|
87
|
+
return os.stat(leaf, dir_fd=handle, follow_symlinks=follow_symlinks)
|
|
88
|
+
return os.stat(os.path.join(handle, leaf), follow_symlinks=follow_symlinks)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def open_at(handle: int | str, leaf: str, flags: int, mode: int = 0o644) -> int:
|
|
92
|
+
if isinstance(handle, int):
|
|
93
|
+
return os.open(leaf, flags, mode, dir_fd=handle)
|
|
94
|
+
return open_nofollow(os.path.join(handle, leaf), flags, mode)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def replace_at(handle: int | str, src: str, dst: str) -> None:
|
|
98
|
+
if isinstance(handle, int):
|
|
99
|
+
os.replace(src, dst, src_dir_fd=handle, dst_dir_fd=handle)
|
|
100
|
+
else:
|
|
101
|
+
os.replace(os.path.join(handle, src), os.path.join(handle, dst))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def unlink_at(handle: int | str, leaf: str) -> None:
|
|
105
|
+
if isinstance(handle, int):
|
|
106
|
+
os.unlink(leaf, dir_fd=handle)
|
|
107
|
+
else:
|
|
108
|
+
os.unlink(os.path.join(handle, leaf))
|
|
@@ -0,0 +1,399 @@
|
|
|
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
|
+
|
|
24
|
+
_STILL_ACTIVE = 259
|
|
25
|
+
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
26
|
+
_PROCESS_TERMINATE = 0x0001
|
|
27
|
+
_TH32CS_SNAPPROCESS = 0x00000002
|
|
28
|
+
_ERROR_ACCESS_DENIED = 5
|
|
29
|
+
_CREATE_NO_WINDOW = getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_windows_bash_stub(path: str) -> bool:
|
|
33
|
+
low = path.replace('/', '\\').lower()
|
|
34
|
+
return '\\system32\\bash.exe' in low or '\\syswow64\\bash.exe' in low or '\\windowsapps\\' in low
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def bash_executable() -> str:
|
|
38
|
+
"""Path to GNU bash (/bin/bash on POSIX; Git Bash avoiding WSL stub on Windows)."""
|
|
39
|
+
if not IS_WINDOWS:
|
|
40
|
+
if os.path.exists('/bin/bash'):
|
|
41
|
+
return '/bin/bash'
|
|
42
|
+
return shutil.which('bash') or '/bin/bash'
|
|
43
|
+
|
|
44
|
+
for env_key in ('FORGE_BASH', 'BASH'):
|
|
45
|
+
cand = os.environ.get(env_key, '').strip()
|
|
46
|
+
if cand and os.path.isfile(cand) and not _is_windows_bash_stub(cand):
|
|
47
|
+
return cand
|
|
48
|
+
|
|
49
|
+
which_bash = shutil.which('bash')
|
|
50
|
+
if which_bash and not _is_windows_bash_stub(which_bash):
|
|
51
|
+
if which_bash.replace('/', '\\').lower().endswith('\\usr\\bin\\bash.exe'):
|
|
52
|
+
git_bin = Path(which_bash).resolve().parents[2] / 'bin' / 'bash.exe'
|
|
53
|
+
if git_bin.is_file():
|
|
54
|
+
return str(git_bin)
|
|
55
|
+
return which_bash
|
|
56
|
+
|
|
57
|
+
candidates: list[Path] = []
|
|
58
|
+
which_git = shutil.which('git')
|
|
59
|
+
if which_git:
|
|
60
|
+
git_path = Path(which_git).resolve()
|
|
61
|
+
for parent in git_path.parents:
|
|
62
|
+
candidates.append(parent / 'bin' / 'bash.exe')
|
|
63
|
+
candidates.append(parent / 'usr' / 'bin' / 'bash.exe')
|
|
64
|
+
for root in (os.environ.get('ProgramFiles'), os.environ.get('ProgramFiles(x86)'),
|
|
65
|
+
os.environ.get('LocalAppData')):
|
|
66
|
+
if root:
|
|
67
|
+
candidates.append(Path(root) / 'Git' / 'bin' / 'bash.exe')
|
|
68
|
+
candidates.append(Path(root) / 'Git' / 'usr' / 'bin' / 'bash.exe')
|
|
69
|
+
candidates.append(Path(root) / 'Programs' / 'Git' / 'bin' / 'bash.exe')
|
|
70
|
+
candidates.extend((
|
|
71
|
+
Path(r'C:\Program Files\Git\bin\bash.exe'),
|
|
72
|
+
Path(r'C:\Program Files\Git\usr\bin\bash.exe'),
|
|
73
|
+
Path(r'C:\Program Files (x86)\Git\bin\bash.exe'),
|
|
74
|
+
))
|
|
75
|
+
for cand in candidates:
|
|
76
|
+
if cand.is_file():
|
|
77
|
+
return str(cand)
|
|
78
|
+
return which_bash or 'bash'
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def bash_cmd(*args: str | os.PathLike[str]) -> list[str]:
|
|
82
|
+
"""Build an argv list starting with the resolved bash executable."""
|
|
83
|
+
return [bash_executable(), *(os.fspath(a) for a in args)]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def resolve_win_command(argv: list[str]) -> tuple[Path, list[str]]:
|
|
87
|
+
"""Resolve an executable path and Windows wrapper (.cmd/.bat/shebang) for CreateProcess."""
|
|
88
|
+
raw = argv[0]
|
|
89
|
+
if not IS_WINDOWS:
|
|
90
|
+
return Path(raw).resolve(), list(argv)
|
|
91
|
+
found = shutil.which(raw)
|
|
92
|
+
if found:
|
|
93
|
+
binary = Path(found).resolve()
|
|
94
|
+
if binary.suffix.lower() in ('.cmd', '.bat'):
|
|
95
|
+
return binary, ['cmd.exe', '/c', str(binary), *argv[1:]]
|
|
96
|
+
if binary.suffix.lower() in ('.exe', '.com'):
|
|
97
|
+
return binary, [str(binary), *argv[1:]]
|
|
98
|
+
else:
|
|
99
|
+
binary = Path(raw).resolve()
|
|
100
|
+
if binary.is_file():
|
|
101
|
+
if binary.suffix.lower() in ('.cmd', '.bat'):
|
|
102
|
+
return binary, ['cmd.exe', '/c', str(binary), *argv[1:]]
|
|
103
|
+
try:
|
|
104
|
+
with binary.open('rb') as handle:
|
|
105
|
+
head = handle.read(256)
|
|
106
|
+
except OSError:
|
|
107
|
+
head = b''
|
|
108
|
+
if head.startswith(b'#!'):
|
|
109
|
+
line = head.splitlines()[0][2:].decode('utf-8', 'replace').strip()
|
|
110
|
+
if 'python' in line:
|
|
111
|
+
return binary, [sys.executable, str(binary), *argv[1:]]
|
|
112
|
+
if 'sh' in line:
|
|
113
|
+
return binary, bash_cmd(str(binary), *argv[1:])
|
|
114
|
+
return binary, [str(binary), *argv[1:]] if found else list(argv)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def install_signal(sig: int | None, handler) -> None:
|
|
118
|
+
"""Install a signal handler when the signal exists on this platform."""
|
|
119
|
+
if sig is not None:
|
|
120
|
+
signal.signal(sig, handler)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@contextlib.contextmanager
|
|
124
|
+
def mask_sigterm():
|
|
125
|
+
"""Block SIGTERM around non-interruptible writes on POSIX; no-op on Windows."""
|
|
126
|
+
if hasattr(signal, 'pthread_sigmask') and hasattr(signal, 'SIG_BLOCK'):
|
|
127
|
+
signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
|
|
128
|
+
try:
|
|
129
|
+
yield
|
|
130
|
+
finally:
|
|
131
|
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGTERM})
|
|
132
|
+
else:
|
|
133
|
+
yield
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def popen_group_kwargs(*, detached: bool = False) -> dict[str, object]:
|
|
137
|
+
"""Keyword arguments placing a subprocess into its own group/session."""
|
|
138
|
+
if IS_WINDOWS:
|
|
139
|
+
flags = getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0) | _CREATE_NO_WINDOW
|
|
140
|
+
if detached:
|
|
141
|
+
flags |= getattr(subprocess, 'DETACHED_PROCESS', 0)
|
|
142
|
+
return {'creationflags': flags}
|
|
143
|
+
return {'start_new_session': True}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def exec_or_exit(argv: list[str], env: dict[str, str] | None = None, *, inherit_fds: bool = False) -> None:
|
|
147
|
+
"""Replace the current process on POSIX; on Windows run and exit so inherited locks remain held."""
|
|
148
|
+
if not IS_WINDOWS:
|
|
149
|
+
if env is not None:
|
|
150
|
+
os.execve(argv[0], argv, env)
|
|
151
|
+
else:
|
|
152
|
+
os.execvp(argv[0], argv)
|
|
153
|
+
raise AssertionError('unreachable')
|
|
154
|
+
done = subprocess.run(argv, env=env, close_fds=not inherit_fds)
|
|
155
|
+
sys.exit(done.returncode)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
if IS_WINDOWS:
|
|
159
|
+
import ctypes.wintypes as _wintypes
|
|
160
|
+
|
|
161
|
+
_kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
|
|
162
|
+
|
|
163
|
+
class _FILETIME(ctypes.Structure):
|
|
164
|
+
_fields_ = [('dwLowDateTime', _wintypes.DWORD), ('dwHighDateTime', _wintypes.DWORD)]
|
|
165
|
+
|
|
166
|
+
class _PROCESSENTRY32W(ctypes.Structure):
|
|
167
|
+
_fields_ = [
|
|
168
|
+
('dwSize', _wintypes.DWORD),
|
|
169
|
+
('cntUsage', _wintypes.DWORD),
|
|
170
|
+
('th32ProcessID', _wintypes.DWORD),
|
|
171
|
+
('th32DefaultHeapID', ctypes.c_size_t),
|
|
172
|
+
('th32ModuleID', _wintypes.DWORD),
|
|
173
|
+
('cntThreads', _wintypes.DWORD),
|
|
174
|
+
('th32ParentProcessID', _wintypes.DWORD),
|
|
175
|
+
('pcPriClassBase', _wintypes.LONG),
|
|
176
|
+
('dwFlags', _wintypes.DWORD),
|
|
177
|
+
('szExeFile', _wintypes.WCHAR * 260),
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
_kernel32.OpenProcess.argtypes = [_wintypes.DWORD, _wintypes.BOOL, _wintypes.DWORD]
|
|
181
|
+
_kernel32.OpenProcess.restype = _wintypes.HANDLE
|
|
182
|
+
_kernel32.CloseHandle.argtypes = [_wintypes.HANDLE]
|
|
183
|
+
_kernel32.CloseHandle.restype = _wintypes.BOOL
|
|
184
|
+
_kernel32.GetExitCodeProcess.argtypes = [_wintypes.HANDLE, ctypes.POINTER(_wintypes.DWORD)]
|
|
185
|
+
_kernel32.GetExitCodeProcess.restype = _wintypes.BOOL
|
|
186
|
+
_kernel32.GetProcessTimes.argtypes = [
|
|
187
|
+
_wintypes.HANDLE,
|
|
188
|
+
ctypes.POINTER(_FILETIME),
|
|
189
|
+
ctypes.POINTER(_FILETIME),
|
|
190
|
+
ctypes.POINTER(_FILETIME),
|
|
191
|
+
ctypes.POINTER(_FILETIME),
|
|
192
|
+
]
|
|
193
|
+
_kernel32.GetProcessTimes.restype = _wintypes.BOOL
|
|
194
|
+
_kernel32.TerminateProcess.argtypes = [_wintypes.HANDLE, _wintypes.UINT]
|
|
195
|
+
_kernel32.TerminateProcess.restype = _wintypes.BOOL
|
|
196
|
+
_kernel32.CreateToolhelp32Snapshot.argtypes = [_wintypes.DWORD, _wintypes.DWORD]
|
|
197
|
+
_kernel32.CreateToolhelp32Snapshot.restype = _wintypes.HANDLE
|
|
198
|
+
_kernel32.Process32FirstW.argtypes = [_wintypes.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)]
|
|
199
|
+
_kernel32.Process32FirstW.restype = _wintypes.BOOL
|
|
200
|
+
_kernel32.Process32NextW.argtypes = [_wintypes.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)]
|
|
201
|
+
_kernel32.Process32NextW.restype = _wintypes.BOOL
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def pid_alive(pid: int, *, min_pid: int = 1) -> bool:
|
|
205
|
+
"""Return True iff ``pid`` names a running OS process (with ``pid >= min_pid``)."""
|
|
206
|
+
if not isinstance(pid, int) or isinstance(pid, bool) or pid < min_pid:
|
|
207
|
+
return False
|
|
208
|
+
if not IS_WINDOWS:
|
|
209
|
+
try:
|
|
210
|
+
os.kill(pid, 0)
|
|
211
|
+
except (ProcessLookupError, OverflowError):
|
|
212
|
+
return False
|
|
213
|
+
except PermissionError:
|
|
214
|
+
return True
|
|
215
|
+
except OSError:
|
|
216
|
+
return False
|
|
217
|
+
return True
|
|
218
|
+
|
|
219
|
+
if pid > 0xFFFFFFFF:
|
|
220
|
+
return False
|
|
221
|
+
handle = _kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
|
222
|
+
if not handle:
|
|
223
|
+
return ctypes.get_last_error() == _ERROR_ACCESS_DENIED
|
|
224
|
+
try:
|
|
225
|
+
code = _wintypes.DWORD()
|
|
226
|
+
if not _kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
227
|
+
return True
|
|
228
|
+
return code.value == _STILL_ACTIVE
|
|
229
|
+
finally:
|
|
230
|
+
_kernel32.CloseHandle(handle)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def process_start_time(pid: int) -> str | None:
|
|
234
|
+
"""Stable opaque creation timestamp for an active Windows PID (None if exited/unavailable)."""
|
|
235
|
+
if not IS_WINDOWS or not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0 or pid > 0xFFFFFFFF:
|
|
236
|
+
return None
|
|
237
|
+
handle = _kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
|
238
|
+
if not handle:
|
|
239
|
+
return None
|
|
240
|
+
try:
|
|
241
|
+
code = _wintypes.DWORD()
|
|
242
|
+
if _kernel32.GetExitCodeProcess(handle, ctypes.byref(code)) and code.value != _STILL_ACTIVE:
|
|
243
|
+
return None
|
|
244
|
+
c, e, k, u = _FILETIME(), _FILETIME(), _FILETIME(), _FILETIME()
|
|
245
|
+
if not _kernel32.GetProcessTimes(handle, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u)):
|
|
246
|
+
return None
|
|
247
|
+
return str((c.dwHighDateTime << 32) | c.dwLowDateTime)
|
|
248
|
+
finally:
|
|
249
|
+
_kernel32.CloseHandle(handle)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def win_ps_table() -> dict[int, tuple[int, str, str]]:
|
|
253
|
+
"""Windows snapshot matching forge-guard.ps_table(): {pid: (ppid, start_time, exe)}."""
|
|
254
|
+
if not IS_WINDOWS:
|
|
255
|
+
return {}
|
|
256
|
+
snap = _kernel32.CreateToolhelp32Snapshot(_TH32CS_SNAPPROCESS, 0)
|
|
257
|
+
if not snap or snap == _wintypes.HANDLE(-1).value:
|
|
258
|
+
return {}
|
|
259
|
+
table: dict[int, tuple[int, str, str]] = {}
|
|
260
|
+
try:
|
|
261
|
+
entry = _PROCESSENTRY32W()
|
|
262
|
+
entry.dwSize = ctypes.sizeof(entry)
|
|
263
|
+
ok = _kernel32.Process32FirstW(snap, ctypes.byref(entry))
|
|
264
|
+
while ok:
|
|
265
|
+
pid = int(entry.th32ProcessID)
|
|
266
|
+
ppid = int(entry.th32ParentProcessID)
|
|
267
|
+
if pid > 0:
|
|
268
|
+
start = process_start_time(pid) or ''
|
|
269
|
+
table[pid] = (ppid, start, entry.szExeFile)
|
|
270
|
+
ok = _kernel32.Process32NextW(snap, ctypes.byref(entry))
|
|
271
|
+
finally:
|
|
272
|
+
_kernel32.CloseHandle(snap)
|
|
273
|
+
return table
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _started_not_before(child_start: str, parent_start: str) -> bool:
|
|
277
|
+
"""Guard against stale Windows th32ParentProcessID when a PID was reused."""
|
|
278
|
+
if not IS_WINDOWS:
|
|
279
|
+
return True
|
|
280
|
+
if child_start.isdigit() and parent_start.isdigit():
|
|
281
|
+
return int(child_start) >= int(parent_start)
|
|
282
|
+
return True
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def win_descendants(table: dict[int, tuple[int, str, str]], roots: set[int]) -> set[int]:
|
|
286
|
+
"""Return descendant PIDs in ``table`` whose creation time >= their parent's."""
|
|
287
|
+
by_parent: dict[int, list[int]] = {}
|
|
288
|
+
for pid, (ppid, _start, _exe) in table.items():
|
|
289
|
+
if pid != ppid:
|
|
290
|
+
by_parent.setdefault(ppid, []).append(pid)
|
|
291
|
+
found: set[int] = set()
|
|
292
|
+
queue = list(roots)
|
|
293
|
+
while queue:
|
|
294
|
+
parent = queue.pop(0)
|
|
295
|
+
parent_start = table[parent][1] if parent in table else ''
|
|
296
|
+
for child in by_parent.get(parent, ()):
|
|
297
|
+
if child in found or child in roots:
|
|
298
|
+
continue
|
|
299
|
+
child_start = table[child][1]
|
|
300
|
+
if not _started_not_before(child_start, parent_start):
|
|
301
|
+
continue
|
|
302
|
+
found.add(child)
|
|
303
|
+
queue.append(child)
|
|
304
|
+
return found
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _win_terminate_pid(pid: int) -> bool:
|
|
308
|
+
if pid <= 0 or pid > 0xFFFFFFFF:
|
|
309
|
+
return False
|
|
310
|
+
handle = _kernel32.OpenProcess(_PROCESS_TERMINATE, False, pid)
|
|
311
|
+
if not handle:
|
|
312
|
+
return False
|
|
313
|
+
try:
|
|
314
|
+
return bool(_kernel32.TerminateProcess(handle, 1))
|
|
315
|
+
finally:
|
|
316
|
+
_kernel32.CloseHandle(handle)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def signal_pid(pid: int, force: bool = False) -> bool:
|
|
320
|
+
"""Terminate a single process (`SIGTERM`/`SIGKILL` on POSIX; `TerminateProcess` on Windows)."""
|
|
321
|
+
if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
|
|
322
|
+
return False
|
|
323
|
+
if not IS_WINDOWS:
|
|
324
|
+
sig = SIGKILL if force else signal.SIGTERM
|
|
325
|
+
try:
|
|
326
|
+
os.kill(pid, sig)
|
|
327
|
+
return True
|
|
328
|
+
except PermissionError:
|
|
329
|
+
return True
|
|
330
|
+
except OSError:
|
|
331
|
+
return False
|
|
332
|
+
|
|
333
|
+
if not force:
|
|
334
|
+
try:
|
|
335
|
+
os.kill(pid, signal.SIGTERM)
|
|
336
|
+
return True
|
|
337
|
+
except OSError:
|
|
338
|
+
return False
|
|
339
|
+
if _win_terminate_pid(pid):
|
|
340
|
+
return True
|
|
341
|
+
try:
|
|
342
|
+
os.kill(pid, signal.SIGTERM)
|
|
343
|
+
return True
|
|
344
|
+
except OSError:
|
|
345
|
+
return False
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def kill_tree(pid: int, force: bool = False) -> None:
|
|
349
|
+
"""Signal/terminate a process and its descendant tree (start-time guarded on Windows)."""
|
|
350
|
+
if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
|
|
351
|
+
return
|
|
352
|
+
if not IS_WINDOWS:
|
|
353
|
+
sig = SIGKILL if force else signal.SIGTERM
|
|
354
|
+
try:
|
|
355
|
+
os.killpg(pid, sig)
|
|
356
|
+
except (ProcessLookupError, PermissionError):
|
|
357
|
+
pass
|
|
358
|
+
except OSError:
|
|
359
|
+
try:
|
|
360
|
+
os.kill(pid, sig)
|
|
361
|
+
except OSError:
|
|
362
|
+
pass
|
|
363
|
+
return
|
|
364
|
+
|
|
365
|
+
table = win_ps_table()
|
|
366
|
+
targets = ({pid} if pid in table else set()) | win_descendants(table, {pid})
|
|
367
|
+
self_pid = os.getpid()
|
|
368
|
+
# Signal descendants before root, validating start times against snapshot before terminating.
|
|
369
|
+
for target in sorted(targets - {pid}, reverse=True):
|
|
370
|
+
if target == self_pid:
|
|
371
|
+
continue
|
|
372
|
+
expected_start = table.get(target, (0, '', ''))[1]
|
|
373
|
+
current_start = process_start_time(target)
|
|
374
|
+
if expected_start and current_start and current_start != expected_start:
|
|
375
|
+
continue
|
|
376
|
+
_win_terminate_pid(target)
|
|
377
|
+
if pid != self_pid:
|
|
378
|
+
expected_start = table.get(pid, (0, '', ''))[1]
|
|
379
|
+
current_start = process_start_time(pid)
|
|
380
|
+
if not (expected_start and current_start and current_start != expected_start):
|
|
381
|
+
if force or pid_alive(pid):
|
|
382
|
+
_win_terminate_pid(pid)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def group_alive(pgid: int) -> bool:
|
|
386
|
+
"""Return True if process group (POSIX) or root PID (Windows) has live processes."""
|
|
387
|
+
if not isinstance(pgid, int) or isinstance(pgid, bool) or pgid <= 0:
|
|
388
|
+
return False
|
|
389
|
+
if not IS_WINDOWS:
|
|
390
|
+
try:
|
|
391
|
+
os.killpg(pgid, 0)
|
|
392
|
+
except ProcessLookupError:
|
|
393
|
+
return False
|
|
394
|
+
except PermissionError:
|
|
395
|
+
return True
|
|
396
|
+
except OSError:
|
|
397
|
+
return False
|
|
398
|
+
return True
|
|
399
|
+
return pid_alive(pgid)
|
|
@@ -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.
|
|
@@ -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 =
|
|
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 |
|
|
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 =
|
|
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 =
|
|
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,7 +282,7 @@ 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 |
|
|
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
|
|
@@ -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':
|
|
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(
|
|
753
|
+
systems.append(platform.system())
|
|
753
754
|
return ', '.join(versions), ', '.join(systems)
|
|
754
755
|
|
|
755
756
|
|