@giamme/forge 0.20.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +7 -0
  3. package/VERSION +1 -1
  4. package/docs/README.md +1 -0
  5. package/docs/development.md +1 -1
  6. package/package.json +1 -1
  7. package/scripts/forge-config.py +10 -9
  8. package/scripts/forge-control.py +51 -35
  9. package/scripts/forge-group.py +2 -1
  10. package/scripts/forge-guard.py +71 -33
  11. package/scripts/forge-handoff.py +14 -17
  12. package/scripts/forge-issues.py +5 -2
  13. package/scripts/forge-parallel.sh +18 -10
  14. package/scripts/forge-planner.py +28 -2
  15. package/scripts/forge-pre-review.py +11 -4
  16. package/scripts/forge-ripwire.py +68 -22
  17. package/scripts/forge-route.py +10 -3
  18. package/scripts/forge-runs-compact.py +3 -2
  19. package/scripts/forge-runs-rm.py +14 -14
  20. package/scripts/forge-runtime.py +36 -19
  21. package/scripts/forge-schedule.py +72 -55
  22. package/scripts/forge-shadow.py +16 -9
  23. package/scripts/forge-summarize.py +7 -3
  24. package/scripts/forge-sweep.py +7 -2
  25. package/scripts/forge-ui.py +8 -13
  26. package/scripts/forge-verify.py +29 -23
  27. package/scripts/forge_brief/__init__.py +1 -1
  28. package/scripts/forge_brief/proposals.py +7 -2
  29. package/scripts/forge_decide/budget.py +6 -1
  30. package/scripts/forge_decide/replay.py +6 -1
  31. package/scripts/forge_findings/apply.py +2 -1
  32. package/scripts/forge_findings/store.py +16 -4
  33. package/scripts/forge_findings/triage.py +6 -15
  34. package/scripts/forge_flock.py +87 -0
  35. package/scripts/forge_fractal/__init__.py +7 -3
  36. package/scripts/forge_fractal/cli.py +7 -2
  37. package/scripts/forge_fractal/execution.py +14 -14
  38. package/scripts/forge_fractal/invocation.py +3 -2
  39. package/scripts/forge_fractal/pipeline.py +2 -1
  40. package/scripts/forge_fractal/selection.py +2 -1
  41. package/scripts/forge_identity.py +2 -1
  42. package/scripts/forge_locations.py +14 -4
  43. package/scripts/forge_posix.py +108 -0
  44. package/scripts/forge_proc.py +399 -0
  45. package/scripts/forge_registry.py +15 -6
  46. package/scripts/forge_retro/__init__.py +8 -2
  47. package/scripts/forge_retro/issues.py +2 -1
  48. package/scripts/forge_side/__init__.py +19 -10
  49. package/scripts/forge_storage.py +11 -1
  50. package/ui/forge_ui/control.py +35 -12
  51. package/ui/forge_ui/reader.py +18 -17
  52. package/ui/forge_ui/server.py +10 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,22 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and versions follow the format `{major}.{minor}[.{patch}]` ([...] parts appear only when non-zero).
7
7
 
8
+ ## [0.21] - 2026-11-19
9
+
10
+ Groundwork for native Windows support, plus fixes for macOS with Python 3.9 and for parallel tasks that start at the same moment.
11
+
12
+ ### Highlights
13
+
14
+ - First step toward native Windows support: file locking, safe file opening and process handling now go through one cross-platform layer that also works on Windows. Nothing changes on macOS or Linux, and Windows isn't usable yet: the Windows launcher, installer and docs come in the next part. Thanks to Kratoswer-byte for the port.
15
+
16
+ ### Fixed
17
+
18
+ - On macOS with Python 3.9, such as the system `python3`, every phase of a run was recorded as taking about 0 seconds, so `report` and forge-ui showed wrong phase times. Phases are now timed on a clock that all of forge's processes share.
19
+ - In brief mode, a task that waits for the brief writer could start right away on macOS with Python 3.9, as if the writer had already finished. The scheduler now always checks the writer the first time.
20
+ - forge-ui no longer looks up the machine's full host name before it starts listening, which could delay its startup by several seconds on macOS.
21
+ - The planner refuses a reply nested more than 64 levels deep or holding a number over 4,300 digits the same way on every Python version, and forge-ui refuses a profile nested that deep. Before, Python 3.12 and later accepted the deep profile, and older Python 3.9 builds spent a long time parsing the huge number.
22
+ - In a parallel run, a task that started at the same moment as others could end ERROR with "could not create worktree — fatal: could not open '.git/worktrees/<id>/gitdir'". Tasks no longer clean up stale worktree registrations while another task is creating its worktree.
23
+
8
24
  ## [0.20] - 2026-11-17
9
25
 
10
26
  Review findings you can trust and manage: one record per repository with issue states from GitHub, forge findings and forge-ui actions, an optional triage agent, and a sweep per finding.
package/README.md CHANGED
@@ -188,6 +188,13 @@ python3 ui/tools/demo_runs.py /tmp/forge-demo
188
188
  | [Ripwire and Jev](docs/add-ons.md) | optional repository context and advisory judgments |
189
189
  | [Troubleshooting](docs/troubleshooting.md) | symptoms, causes and fixes |
190
190
  | [Development](docs/development.md) | repository layout, offline checks, runtime measurement |
191
+ | [Contributing](CONTRIBUTING.md) | setting up, running the tests, the rules reviewers check, pull requests |
192
+
193
+ ## Contributing
194
+
195
+ Issues and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers setting up,
196
+ running the tests and what reviewers look for. Please report security issues privately, as
197
+ [SECURITY.md](SECURITY.md) describes.
191
198
 
192
199
  ## License
193
200
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.20
1
+ 0.21
package/docs/README.md CHANGED
@@ -20,6 +20,7 @@ The README is the short overview. These pages hold the rest, one topic each.
20
20
  | [Ripwire and Jev](add-ons.md) | optional repository context and advisory judgments |
21
21
  | [Troubleshooting](troubleshooting.md) | symptoms, causes and fixes |
22
22
  | [Development](development.md) | repository layout, offline checks, runtime measurement |
23
+ | [Contributing](../CONTRIBUTING.md) | setting up, running the tests, the rules reviewers check, pull requests |
23
24
 
24
25
  Deeper material that the skill itself reads lives in [`references/`](../references/): the
25
26
  per-harness details, the decomposition and Fractal contracts, memory internals, Jev and the
@@ -57,7 +57,7 @@ forge/
57
57
  ## Offline checks
58
58
 
59
59
  Run `bash tests/check.sh` for offline regression checks. See [tests](../tests/README.md) for skill
60
- invocation scenarios and verification limits. Two CI workflows, neither of which runs the tests: one builds and publishes the website ([site/README.md](../site/README.md)), and `.github/workflows/npm-publish.yml` publishes the package to npm when a GitHub Release is published (npm trusted publishing, no token).
60
+ invocation scenarios and verification limits. Three CI workflows: `.github/workflows/test.yml` runs `tests/check.sh` on every pull request (Ubuntu, Python 3.9; documentation-only changes skip it) and on every push to `dev` (also the latest 3.x, and macOS with the system Bash 3.2), `.github/workflows/pages.yml` builds and publishes the website ([site/README.md](../site/README.md)), and `.github/workflows/npm-publish.yml` publishes the package to npm when a GitHub Release is published (npm trusted publishing, no token).
61
61
 
62
62
  ## Runtime efficiency and measurement
63
63
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giamme/forge",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Multi-model coding with a reviewer that reads the code: plan, build in parallel worktrees, review every real diff, merge only what passes.",
5
5
  "keywords": ["claude-code", "codex", "opencode", "agent-skill", "code-review", "multi-model"],
6
6
  "license": "MIT",
@@ -64,6 +64,7 @@ import sys
64
64
  SKILL = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
65
65
  sys.path.insert(0, os.path.join(SKILL, 'scripts'))
66
66
 
67
+ import forge_posix # noqa: E402
67
68
  from forge_decide import GATES, MODES, load_repo, load_user, save_repo, save_user, user_path
68
69
  from forge_decide import profiles
69
70
  from forge_decide.migrate import run as migrate_run
@@ -153,8 +154,8 @@ def read_small(path):
153
154
  if st.st_size >= CONTENT_MAX:
154
155
  return None, 'larger than 64 KiB'
155
156
  try:
156
- flags = os.O_RDONLY | os.O_NOFOLLOW | getattr(os, 'O_NONBLOCK', 0)
157
- with os.fdopen(os.open(path, flags), 'rb') as handle:
157
+ flags = os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK
158
+ with os.fdopen(forge_posix.open_nofollow(path, flags), 'rb') as handle:
158
159
  data = handle.read(CONTENT_MAX + 1)
159
160
  except OSError as err:
160
161
  return None, 'unreadable: %s' % err.strerror
@@ -170,7 +171,7 @@ def open_forge_dir(d):
170
171
  except FileExistsError:
171
172
  pass
172
173
  try:
173
- return os.open(d, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
174
+ return forge_posix.open_dir(d, nofollow=True)
174
175
  except OSError as err:
175
176
  raise Invalid('%s must be a real directory, not a symlink or file (%s)' % (d, err.strerror))
176
177
 
@@ -180,21 +181,21 @@ def atomic_write(d, target, text):
180
181
  name = os.path.basename(target)
181
182
  tmp = '.%s.%d.tmp' % (name, os.getpid())
182
183
  try:
183
- fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644, dir_fd=dfd)
184
+ fd = forge_posix.open_at(dfd, tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | forge_posix.O_NOFOLLOW, 0o644)
184
185
  try:
185
186
  with os.fdopen(fd, 'w') as handle:
186
187
  handle.write(text)
187
188
  handle.flush()
188
189
  os.fsync(handle.fileno())
189
- os.replace(tmp, name, src_dir_fd=dfd, dst_dir_fd=dfd)
190
+ forge_posix.replace_at(dfd, tmp, name)
190
191
  except BaseException:
191
192
  try:
192
- os.unlink(tmp, dir_fd=dfd)
193
+ forge_posix.unlink_at(dfd, tmp)
193
194
  except OSError:
194
195
  pass
195
196
  raise
196
197
  finally:
197
- os.close(dfd)
198
+ forge_posix.close_dir(dfd)
198
199
 
199
200
 
200
201
  # ------------------------------------------------------------------------------------------ show
@@ -533,9 +534,9 @@ def cmd_unset(args):
533
534
  if d and os.path.lexists(target):
534
535
  dfd = open_forge_dir(d)
535
536
  try:
536
- os.unlink(os.path.basename(target), dir_fd=dfd)
537
+ forge_posix.unlink_at(dfd, os.path.basename(target))
537
538
  finally:
538
- os.close(dfd)
539
+ forge_posix.close_dir(dfd)
539
540
  emit(args, args.key, previous, None)
540
541
  return 0
541
542
 
@@ -65,7 +65,6 @@ from __future__ import annotations
65
65
  import argparse
66
66
  import contextlib
67
67
  import errno
68
- import fcntl
69
68
  import json
70
69
  import os
71
70
  import re
@@ -82,7 +81,10 @@ from pathlib import Path
82
81
  SCRIPTS = os.path.dirname(os.path.realpath(__file__))
83
82
  if SCRIPTS not in sys.path:
84
83
  sys.path.insert(0, SCRIPTS)
84
+ import forge_flock as fcntl # noqa: E402
85
85
  import forge_infra # noqa: E402
86
+ import forge_posix # noqa: E402
87
+ import forge_proc # noqa: E402
86
88
 
87
89
  SKILL = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
88
90
  LOCK_WAIT = 5.0
@@ -94,7 +96,6 @@ DEFAULT_VERIFY_RETRIES = 1 # forge-parallel.sh
94
96
  DEFAULT_PRE_REVIEW_PARALLEL = 2 # forge-artifact.sh forge_pre_review
95
97
  LEVELS = ('P0', 'P1', 'P2', 'P3')
96
98
  STOP_MARKERS = ('escalation.stop', 'split.suggested', 'escalation.next')
97
- DIR_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
98
99
 
99
100
  NEXT_ATTEMPT = "at the task's next attempt"
100
101
  NEXT_DECISION = 'at the next retry decision'
@@ -126,7 +127,7 @@ def valid_task_id(name):
126
127
 
127
128
  def _enter(fd, part, create, rel):
128
129
  try:
129
- return os.open(part, DIR_FLAGS, dir_fd=fd)
130
+ return forge_posix.enter_dir(fd, part, nofollow=True)
130
131
  except FileNotFoundError:
131
132
  if not create:
132
133
  return None
@@ -135,11 +136,11 @@ def _enter(fd, part, create, rel):
135
136
  raise Invalid(f'{rel}: {part} is not a real directory')
136
137
  raise
137
138
  try:
138
- os.mkdir(part, dir_fd=fd)
139
+ forge_posix.mkdir_at(fd, part)
139
140
  except FileExistsError:
140
141
  pass
141
142
  try:
142
- return os.open(part, DIR_FLAGS, dir_fd=fd)
143
+ return forge_posix.enter_dir(fd, part, nofollow=True)
143
144
  except OSError as error:
144
145
  if error.errno in (errno.ELOOP, errno.ENOTDIR):
145
146
  raise Invalid(f'{rel}: {part} is not a real directory')
@@ -149,25 +150,25 @@ def _enter(fd, part, create, rel):
149
150
  def _open_parent(plan, rel, create=False):
150
151
  """(fd of rel's parent dir, leaf name); (None, leaf) when a parent does not exist and create is off."""
151
152
  *dirs, leaf = rel.split('/')
152
- fd = os.open(plan, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
153
+ fd = forge_posix.open_dir(plan, nofollow=False)
153
154
  try:
154
155
  for part in dirs:
155
156
  nxt = _enter(fd, part, create, rel)
156
- os.close(fd)
157
+ forge_posix.close_dir(fd)
157
158
  fd = nxt
158
159
  if fd is None:
159
160
  return None, leaf
160
161
  return fd, leaf
161
162
  except BaseException:
162
163
  if fd is not None:
163
- os.close(fd)
164
+ forge_posix.close_dir(fd)
164
165
  raise
165
166
 
166
167
 
167
168
  def _regular(fd, leaf, rel):
168
169
  """The lstat of an existing regular file, None when absent; anything else is unsafe."""
169
170
  try:
170
- st = os.stat(leaf, dir_fd=fd, follow_symlinks=False)
171
+ st = forge_posix.stat_at(fd, leaf, follow_symlinks=False)
171
172
  except FileNotFoundError:
172
173
  return None
173
174
  if not stat.S_ISREG(st.st_mode):
@@ -183,7 +184,7 @@ def probe(plan, rel):
183
184
  try:
184
185
  return _regular(fd, leaf, rel) is not None
185
186
  finally:
186
- os.close(fd)
187
+ forge_posix.close_dir(fd)
187
188
 
188
189
 
189
190
  def _read(plan, rel, tail):
@@ -192,7 +193,11 @@ def _read(plan, rel, tail):
192
193
  return None
193
194
  try:
194
195
  try:
195
- rfd = os.open(leaf, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=fd)
196
+ rfd = forge_posix.open_at(
197
+ fd,
198
+ leaf,
199
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK | forge_posix.O_CLOEXEC,
200
+ )
196
201
  except FileNotFoundError:
197
202
  return None
198
203
  except OSError as error:
@@ -210,7 +215,7 @@ def _read(plan, rel, tail):
210
215
  finally:
211
216
  os.close(rfd)
212
217
  finally:
213
- os.close(fd)
218
+ forge_posix.close_dir(fd)
214
219
  if cut:
215
220
  data = data.partition(b'\n')[2] # the first line is cut in half
216
221
  return data.decode('utf-8', 'replace')
@@ -243,18 +248,23 @@ def write_atomic(plan, rel, text):
243
248
  tmp = f'.{leaf}.{os.getpid()}.{time.time_ns()}.tmp'
244
249
  try:
245
250
  _regular(fd, leaf, rel)
246
- tfd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644, dir_fd=fd)
251
+ tfd = forge_posix.open_at(
252
+ fd,
253
+ tmp,
254
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | forge_posix.O_NOFOLLOW | forge_posix.O_CLOEXEC,
255
+ 0o644,
256
+ )
247
257
  try:
248
258
  os.write(tfd, text.encode('utf-8'))
249
259
  finally:
250
260
  os.close(tfd)
251
- os.replace(tmp, leaf, src_dir_fd=fd, dst_dir_fd=fd)
261
+ forge_posix.replace_at(fd, tmp, leaf)
252
262
  except BaseException:
253
263
  with contextlib.suppress(OSError):
254
- os.unlink(tmp, dir_fd=fd)
264
+ forge_posix.unlink_at(fd, tmp)
255
265
  raise
256
266
  finally:
257
- os.close(fd)
267
+ forge_posix.close_dir(fd)
258
268
 
259
269
 
260
270
  def remove_safe(plan, rel):
@@ -265,12 +275,12 @@ def remove_safe(plan, rel):
265
275
  try:
266
276
  if _regular(fd, leaf, rel) is None:
267
277
  return False
268
- os.unlink(leaf, dir_fd=fd)
278
+ forge_posix.unlink_at(fd, leaf)
269
279
  return True
270
280
  except FileNotFoundError:
271
281
  return False
272
282
  finally:
273
- os.close(fd)
283
+ forge_posix.close_dir(fd)
274
284
 
275
285
 
276
286
  def append_line(plan, rel, line):
@@ -281,7 +291,12 @@ def append_line(plan, rel, line):
281
291
  raise Invalid(f'{rel}: a parent directory is missing')
282
292
  try:
283
293
  _regular(fd, leaf, rel)
284
- afd = os.open(leaf, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644, dir_fd=fd)
294
+ afd = forge_posix.open_at(
295
+ fd,
296
+ leaf,
297
+ os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_CLOEXEC,
298
+ 0o644,
299
+ )
285
300
  try:
286
301
  if not stat.S_ISREG(os.fstat(afd).st_mode):
287
302
  raise Invalid(f'{rel} is not a regular file')
@@ -289,7 +304,7 @@ def append_line(plan, rel, line):
289
304
  finally:
290
305
  os.close(afd)
291
306
  finally:
292
- os.close(fd)
307
+ forge_posix.close_dir(fd)
293
308
 
294
309
 
295
310
  @contextlib.contextmanager
@@ -299,13 +314,18 @@ def control_lock(plan):
299
314
  try:
300
315
  _regular(fd, leaf, 'control.lock') # a FIFO would block the open
301
316
  try:
302
- lock = os.open(leaf, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644, dir_fd=fd)
317
+ lock = forge_posix.open_at(
318
+ fd,
319
+ leaf,
320
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_CLOEXEC,
321
+ 0o644,
322
+ )
303
323
  except OSError as error:
304
324
  if error.errno == errno.ELOOP:
305
325
  raise Invalid('control.lock is not a regular file')
306
326
  raise
307
327
  finally:
308
- os.close(fd)
328
+ forge_posix.close_dir(fd)
309
329
  try:
310
330
  deadline = time.monotonic() + LOCK_WAIT
311
331
  while True:
@@ -351,17 +371,7 @@ def is_live(plan):
351
371
  pid = json.loads(read_file(plan, 'scheduler.live') or '')['pid']
352
372
  except (ValueError, KeyError, TypeError):
353
373
  return False
354
- if type(pid) is not int or pid <= 0:
355
- return False
356
- try:
357
- os.kill(pid, 0)
358
- except ProcessLookupError:
359
- return False
360
- except PermissionError:
361
- return True
362
- except (OSError, OverflowError):
363
- return False
364
- return True
374
+ return forge_proc.pid_alive(pid)
365
375
 
366
376
 
367
377
  def is_fractal(plan):
@@ -709,7 +719,8 @@ def start_summaries(plan, task):
709
719
  command += ['--task', task]
710
720
  try:
711
721
  with open(os.path.join(plan, 'summaries.out'), 'ab') as out:
712
- subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out, start_new_session=True)
722
+ subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
723
+ **forge_proc.popen_group_kwargs(detached=True))
713
724
  except OSError:
714
725
  pass
715
726
 
@@ -717,7 +728,12 @@ def start_summaries(plan, task):
717
728
  def doctor(spec, role='dwarf'):
718
729
  """Offline capability check of a spec: Refused when it fails, no quota spent."""
719
730
  override = os.environ.get('FORGE_CONTROL_DOCTOR')
720
- base = shlex.split(override) if override else ['bash', os.path.join(SKILL, 'scripts', 'forge-dispatch.sh'), 'doctor']
731
+ if override:
732
+ base = shlex.split(override)
733
+ elif forge_proc.IS_WINDOWS:
734
+ base = forge_proc.bash_cmd(os.path.join(SKILL, 'scripts', 'forge-dispatch.sh'), 'doctor')
735
+ else:
736
+ base = ['bash', os.path.join(SKILL, 'scripts', 'forge-dispatch.sh'), 'doctor']
721
737
  try:
722
738
  done = subprocess.run(base + ['--spec', spec, '--role', role], capture_output=True, text=True,
723
739
  stdin=subprocess.DEVNULL, timeout=60)
@@ -42,6 +42,7 @@ from pathlib import Path
42
42
 
43
43
  sys.path.insert(0, str(Path(__file__).resolve().parent))
44
44
  import forge_groups # noqa: E402
45
+ import forge_proc # noqa: E402
45
46
 
46
47
  SCRIPTS = Path(__file__).resolve().parent
47
48
  PARALLEL = SCRIPTS / 'forge-parallel.sh'
@@ -346,7 +347,7 @@ def rearm(plan: str, gid: str, seen: str, reason: str) -> None:
346
347
  def run_settle(plan: str, gid: str, tasks: list) -> int:
347
348
  """_group_settle --tasks. Outside the control lock: post_attempt takes that same lock
348
349
  when the retry policy writes a marker, and holding it here would time that write out."""
349
- command = ['/bin/bash', str(PARALLEL), '_group_settle', plan, gid, '--tasks', ','.join(tasks)]
350
+ command = forge_proc.bash_cmd(PARALLEL, '_group_settle', plan, gid, '--tasks', ','.join(tasks))
350
351
  try:
351
352
  result = subprocess.run(command, capture_output=True, text=True, timeout=120)
352
353
  except OSError as error:
@@ -62,16 +62,37 @@ import subprocess
62
62
  import sys
63
63
  import time
64
64
 
65
+ _SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
66
+ if _SCRIPTS_DIR not in sys.path:
67
+ sys.path.insert(0, _SCRIPTS_DIR)
68
+
69
+ import forge_proc # noqa: E402
70
+
65
71
  PS_CANDIDATES = ('/bin/ps', '/usr/bin/ps')
66
72
  TERM_WAIT_S = 2.0
67
73
  KILL_WAIT_S = 1.0
68
74
 
69
75
 
70
76
  # --- session ------------------------------------------------------------------
77
+ def _win_session(argv: list[str]) -> int:
78
+ _, exec_argv = forge_proc.resolve_win_command(argv)
79
+ try:
80
+ proc = subprocess.Popen(exec_argv)
81
+ except FileNotFoundError:
82
+ print('forge-guard: cannot execute %s: not found' % argv[0], file=sys.stderr)
83
+ return 127
84
+ except OSError as error:
85
+ print('forge-guard: cannot execute %s: %s' % (argv[0], error), file=sys.stderr)
86
+ return 126
87
+ return proc.wait()
88
+
89
+
71
90
  def session(argv: list[str]) -> int:
72
91
  if not argv:
73
92
  print('forge-guard: session needs a command', file=sys.stderr)
74
93
  return 2
94
+ if forge_proc.IS_WINDOWS:
95
+ return _win_session(argv)
75
96
  try:
76
97
  os.setsid()
77
98
  except OSError:
@@ -91,15 +112,7 @@ def session(argv: list[str]) -> int:
91
112
 
92
113
  # --- reap ---------------------------------------------------------------------
93
114
  def group_exists(pgid: int) -> bool:
94
- try:
95
- os.killpg(pgid, 0)
96
- except ProcessLookupError:
97
- return False
98
- except PermissionError:
99
- return True
100
- except OSError:
101
- return False
102
- return True
115
+ return forge_proc.group_alive(pgid)
103
116
 
104
117
 
105
118
  def list_group(pgid: int):
@@ -107,6 +120,12 @@ def list_group(pgid: int):
107
120
 
108
121
  Zombies are skipped: they are already dead and only wait for their parent.
109
122
  """
123
+ if forge_proc.IS_WINDOWS:
124
+ table = ps_table()
125
+ if table is None:
126
+ return None
127
+ pids = ({pgid} if pgid in table else set()) | descendants(table, {pgid})
128
+ return [(pid, table[pid][2]) for pid in sorted(pids) if pid != os.getpid()]
110
129
  for ps in PS_CANDIDATES:
111
130
  if not os.access(ps, os.X_OK):
112
131
  continue
@@ -148,6 +167,8 @@ def wait_gone(pgid: int, seconds: float) -> bool:
148
167
 
149
168
  def _forbidden() -> set:
150
169
  # Never signal ourselves, the process that called us, or init.
170
+ if forge_proc.IS_WINDOWS:
171
+ return {0, 1, os.getpid(), os.getppid()}
151
172
  forbidden = {0, 1, os.getpgrp()}
152
173
  try:
153
174
  forbidden.add(os.getpgid(os.getppid()))
@@ -160,7 +181,7 @@ def _reap_group(pgid: int, orphans_file: str | None) -> int:
160
181
  """TERM, then KILL, whatever is alive in the group; how many were found."""
161
182
  if pgid in _forbidden() or pgid < 0:
162
183
  return 0
163
- if not group_exists(pgid):
184
+ if not group_exists(pgid) and not (forge_proc.IS_WINDOWS and list_group(pgid)):
164
185
  return 0
165
186
  members = list_group(pgid)
166
187
  if members is not None and not members:
@@ -174,7 +195,16 @@ def _reap_group(pgid: int, orphans_file: str | None) -> int:
174
195
  handle.write('%s\t%s\n' % (pid or '?', ' '.join(command.split()) or '?'))
175
196
  except OSError:
176
197
  pass
177
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
198
+ if forge_proc.IS_WINDOWS:
199
+ for force, wait in ((False, TERM_WAIT_S), (True, KILL_WAIT_S)):
200
+ forge_proc.kill_tree(pgid, force=force)
201
+ for pid, _cmd in found:
202
+ if pid and pid not in _forbidden():
203
+ forge_proc.signal_pid(pid, force=force)
204
+ if wait_gone(pgid, wait):
205
+ break
206
+ return len(found)
207
+ for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (forge_proc.SIGKILL, KILL_WAIT_S)):
178
208
  try:
179
209
  os.killpg(pgid, sig)
180
210
  except OSError:
@@ -191,6 +221,8 @@ TRACK_INTERVAL_S = 2.0
191
221
  def ps_table():
192
222
  """{pid: (ppid, start time, command)} of every live process but zombies, or None when ps is
193
223
  unavailable. The start time is `identity`'s, whitespace-normalised the same way."""
224
+ if forge_proc.IS_WINDOWS:
225
+ return forge_proc.win_ps_table()
194
226
  for ps in PS_CANDIDATES:
195
227
  if not os.access(ps, os.X_OK):
196
228
  continue
@@ -218,6 +250,8 @@ def ps_table():
218
250
 
219
251
  def descendants(table, roots):
220
252
  """Every live descendant of `roots` in a ps_table, the roots excluded."""
253
+ if forge_proc.IS_WINDOWS:
254
+ return forge_proc.win_descendants(table, {r for r in roots if r > 1})
221
255
  children = {}
222
256
  for pid, (ppid, _start, _command) in table.items():
223
257
  children.setdefault(ppid, []).append(pid)
@@ -301,7 +335,7 @@ def _reap_tracked(path: str, skip_group: int | None) -> list:
301
335
  if not known:
302
336
  return []
303
337
  found = {}
304
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
338
+ for force, wait in ((False, TERM_WAIT_S), (True, KILL_WAIT_S)):
305
339
  table = ps_table()
306
340
  if table is None:
307
341
  break
@@ -309,16 +343,13 @@ def _reap_tracked(path: str, skip_group: int | None) -> list:
309
343
  targets = _mine(table, known)
310
344
  targets |= descendants(table, targets)
311
345
  targets -= never
312
- if skip_group is not None:
346
+ if skip_group is not None and not forge_proc.IS_WINDOWS:
313
347
  targets = {pid for pid in targets if _pgid(pid) != skip_group}
314
348
  if not targets:
315
349
  break
316
350
  for pid in targets:
317
351
  found.setdefault(pid, table[pid][2])
318
- try:
319
- os.kill(pid, sig)
320
- except OSError:
321
- pass
352
+ forge_proc.signal_pid(pid, force=force)
322
353
  deadline = time.monotonic() + wait
323
354
  while time.monotonic() < deadline:
324
355
  table = ps_table() or {}
@@ -329,6 +360,8 @@ def _reap_tracked(path: str, skip_group: int | None) -> list:
329
360
 
330
361
 
331
362
  def _pgid(pid: int):
363
+ if not hasattr(os, 'getpgid'):
364
+ return None
332
365
  try:
333
366
  return os.getpgid(pid)
334
367
  except OSError:
@@ -354,10 +387,7 @@ def stop_tree(root: int, wait: float) -> int:
354
387
  targets = (({root} if root in table else set()) | descendants(table, {root})) - _never(table)
355
388
  starts = {pid: table[pid][1] for pid in targets}
356
389
  for pid in targets:
357
- try:
358
- os.kill(pid, signal.SIGTERM)
359
- except OSError:
360
- pass
390
+ forge_proc.signal_pid(pid, force=False)
361
391
  deadline = time.monotonic() + wait
362
392
  left = set(targets)
363
393
  while left and time.monotonic() < deadline:
@@ -365,10 +395,7 @@ def stop_tree(root: int, wait: float) -> int:
365
395
  now = ps_table() or {}
366
396
  left = {pid for pid in left if pid in now and now[pid][1] == starts[pid]}
367
397
  for pid in left:
368
- try:
369
- os.kill(pid, signal.SIGKILL)
370
- except OSError:
371
- pass
398
+ forge_proc.signal_pid(pid, force=True)
372
399
  print(len(targets))
373
400
  return 0
374
401
 
@@ -401,18 +428,16 @@ def _ps_field(pid: int, field: str) -> str | None:
401
428
 
402
429
 
403
430
  def identity(pid: int) -> str | None:
431
+ if forge_proc.IS_WINDOWS:
432
+ return forge_proc.process_start_time(pid)
404
433
  return _ps_field(pid, 'lstart')
405
434
 
406
435
 
407
436
  def _pid_alive(pid: int) -> bool:
408
- try:
409
- os.kill(pid, 0)
410
- except ProcessLookupError:
437
+ if not forge_proc.pid_alive(pid):
411
438
  return False
412
- except PermissionError:
439
+ if forge_proc.IS_WINDOWS:
413
440
  return True
414
- except OSError:
415
- return False
416
441
  # A zombie still answers kill(0) until its parent waits for it.
417
442
  return not (_ps_field(pid, 'stat') or 'Z').startswith('Z')
418
443
 
@@ -427,6 +452,19 @@ def _wait_pid_gone(pid: int, seconds: float) -> bool:
427
452
 
428
453
 
429
454
  def _stop_live(pid: int) -> int:
455
+ if forge_proc.IS_WINDOWS:
456
+ if pid in _forbidden():
457
+ return 0
458
+ members = list_group(pid)
459
+ count = len(members) if members else 1
460
+ for force, wait in ((False, TERM_WAIT_S), (True, KILL_WAIT_S)):
461
+ forge_proc.kill_tree(pid, force=force)
462
+ for mpid, _cmd in (members or []):
463
+ if mpid and mpid not in _forbidden():
464
+ forge_proc.signal_pid(mpid, force=force)
465
+ if wait_gone(pid, wait):
466
+ break
467
+ return count
430
468
  try:
431
469
  leader = os.getpgid(pid) == pid
432
470
  except OSError:
@@ -436,7 +474,7 @@ def _stop_live(pid: int) -> int:
436
474
  return 0
437
475
  members = list_group(pid)
438
476
  count = len(members) if members else 1
439
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
477
+ for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (forge_proc.SIGKILL, KILL_WAIT_S)):
440
478
  try:
441
479
  os.killpg(pid, sig)
442
480
  except OSError:
@@ -445,7 +483,7 @@ def _stop_live(pid: int) -> int:
445
483
  break
446
484
  return count
447
485
  # Recorded before setsid: the pid is still in its dispatcher's group, so only it is ours.
448
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
486
+ for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (forge_proc.SIGKILL, KILL_WAIT_S)):
449
487
  try:
450
488
  os.kill(pid, sig)
451
489
  except OSError: