@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
@@ -55,6 +55,7 @@
55
55
  """
56
56
  from __future__ import annotations
57
57
 
58
+ import datetime
58
59
  import os
59
60
  import re
60
61
  import signal
@@ -62,16 +63,47 @@ import subprocess
62
63
  import sys
63
64
  import time
64
65
 
66
+ _SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
67
+ if _SCRIPTS_DIR not in sys.path:
68
+ sys.path.insert(0, _SCRIPTS_DIR)
69
+
70
+ import forge_proc # noqa: E402
71
+
65
72
  PS_CANDIDATES = ('/bin/ps', '/usr/bin/ps')
66
73
  TERM_WAIT_S = 2.0
67
74
  KILL_WAIT_S = 1.0
68
75
 
69
76
 
70
77
  # --- session ------------------------------------------------------------------
78
+ def _win_session(argv: list[str]) -> int:
79
+ _, exec_argv = forge_proc.resolve_win_command(argv)
80
+ job = forge_proc.ProcessJob()
81
+ try:
82
+ proc = subprocess.Popen(exec_argv)
83
+ except FileNotFoundError:
84
+ print('forge-guard: cannot execute %s: not found' % argv[0], file=sys.stderr)
85
+ return 127
86
+ except OSError as error:
87
+ print('forge-guard: cannot execute %s: %s' % (argv[0], error), file=sys.stderr)
88
+ return 126
89
+ job.attach(proc.pid)
90
+ try:
91
+ rc = proc.wait()
92
+ # Keep KILL_ON_JOB_CLOSE armed while the child runs so an abrupt guardian
93
+ # termination cleans up descendants atomically; disarm on normal return so
94
+ # `reap` can still observe and record intentional orphans.
95
+ job.disarm()
96
+ return rc
97
+ finally:
98
+ job.close()
99
+
100
+
71
101
  def session(argv: list[str]) -> int:
72
102
  if not argv:
73
103
  print('forge-guard: session needs a command', file=sys.stderr)
74
104
  return 2
105
+ if forge_proc.IS_WINDOWS:
106
+ return _win_session(argv)
75
107
  try:
76
108
  os.setsid()
77
109
  except OSError:
@@ -91,15 +123,7 @@ def session(argv: list[str]) -> int:
91
123
 
92
124
  # --- reap ---------------------------------------------------------------------
93
125
  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
126
+ return forge_proc.group_alive(pgid)
103
127
 
104
128
 
105
129
  def list_group(pgid: int):
@@ -107,6 +131,12 @@ def list_group(pgid: int):
107
131
 
108
132
  Zombies are skipped: they are already dead and only wait for their parent.
109
133
  """
134
+ if forge_proc.IS_WINDOWS:
135
+ table = ps_table()
136
+ if table is None:
137
+ return None
138
+ pids = ({pgid} if pgid in table else set()) | descendants(table, {pgid})
139
+ return [(pid, table[pid][2]) for pid in sorted(pids) if pid != os.getpid()]
110
140
  for ps in PS_CANDIDATES:
111
141
  if not os.access(ps, os.X_OK):
112
142
  continue
@@ -148,6 +178,8 @@ def wait_gone(pgid: int, seconds: float) -> bool:
148
178
 
149
179
  def _forbidden() -> set:
150
180
  # Never signal ourselves, the process that called us, or init.
181
+ if forge_proc.IS_WINDOWS:
182
+ return {0, 1, os.getpid(), os.getppid()}
151
183
  forbidden = {0, 1, os.getpgrp()}
152
184
  try:
153
185
  forbidden.add(os.getpgid(os.getppid()))
@@ -160,7 +192,7 @@ def _reap_group(pgid: int, orphans_file: str | None) -> int:
160
192
  """TERM, then KILL, whatever is alive in the group; how many were found."""
161
193
  if pgid in _forbidden() or pgid < 0:
162
194
  return 0
163
- if not group_exists(pgid):
195
+ if not group_exists(pgid) and not (forge_proc.IS_WINDOWS and list_group(pgid)):
164
196
  return 0
165
197
  members = list_group(pgid)
166
198
  if members is not None and not members:
@@ -174,7 +206,16 @@ def _reap_group(pgid: int, orphans_file: str | None) -> int:
174
206
  handle.write('%s\t%s\n' % (pid or '?', ' '.join(command.split()) or '?'))
175
207
  except OSError:
176
208
  pass
177
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
209
+ if forge_proc.IS_WINDOWS:
210
+ for force, wait in ((False, TERM_WAIT_S), (True, KILL_WAIT_S)):
211
+ forge_proc.kill_tree(pgid, force=force)
212
+ for pid, _cmd in found:
213
+ if pid and pid not in _forbidden():
214
+ forge_proc.signal_pid(pid, force=force)
215
+ if wait_gone(pgid, wait):
216
+ break
217
+ return len(found)
218
+ for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (forge_proc.SIGKILL, KILL_WAIT_S)):
178
219
  try:
179
220
  os.killpg(pgid, sig)
180
221
  except OSError:
@@ -191,6 +232,8 @@ TRACK_INTERVAL_S = 2.0
191
232
  def ps_table():
192
233
  """{pid: (ppid, start time, command)} of every live process but zombies, or None when ps is
193
234
  unavailable. The start time is `identity`'s, whitespace-normalised the same way."""
235
+ if forge_proc.IS_WINDOWS:
236
+ return forge_proc.win_ps_table()
194
237
  for ps in PS_CANDIDATES:
195
238
  if not os.access(ps, os.X_OK):
196
239
  continue
@@ -218,6 +261,8 @@ def ps_table():
218
261
 
219
262
  def descendants(table, roots):
220
263
  """Every live descendant of `roots` in a ps_table, the roots excluded."""
264
+ if forge_proc.IS_WINDOWS:
265
+ return forge_proc.win_descendants(table, {r for r in roots if r > 1})
221
266
  children = {}
222
267
  for pid, (ppid, _start, _command) in table.items():
223
268
  children.setdefault(ppid, []).append(pid)
@@ -251,9 +296,15 @@ def read_tracked(path):
251
296
  return found
252
297
 
253
298
 
299
+ def _same_start(recorded, current) -> bool:
300
+ """Whether two start times (identity, ps_table) name the same process start. Plain equality;
301
+ the Cygwin block below replaces it, since there a start older than a day is known to the day."""
302
+ return recorded == current
303
+
304
+
254
305
  def _mine(table, known):
255
306
  """The recorded processes still alive with their recorded start time (not a reused pid)."""
256
- return {pid for pid, start in known.items() if pid in table and table[pid][1] == start}
307
+ return {pid for pid, start in known.items() if pid in table and _same_start(start, table[pid][1])}
257
308
 
258
309
 
259
310
  def track(root: int, path: str, interval: float = TRACK_INTERVAL_S) -> int:
@@ -301,7 +352,7 @@ def _reap_tracked(path: str, skip_group: int | None) -> list:
301
352
  if not known:
302
353
  return []
303
354
  found = {}
304
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
355
+ for force, wait in ((False, TERM_WAIT_S), (True, KILL_WAIT_S)):
305
356
  table = ps_table()
306
357
  if table is None:
307
358
  break
@@ -309,16 +360,13 @@ def _reap_tracked(path: str, skip_group: int | None) -> list:
309
360
  targets = _mine(table, known)
310
361
  targets |= descendants(table, targets)
311
362
  targets -= never
312
- if skip_group is not None:
363
+ if skip_group is not None and not forge_proc.IS_WINDOWS:
313
364
  targets = {pid for pid in targets if _pgid(pid) != skip_group}
314
365
  if not targets:
315
366
  break
316
367
  for pid in targets:
317
368
  found.setdefault(pid, table[pid][2])
318
- try:
319
- os.kill(pid, sig)
320
- except OSError:
321
- pass
369
+ forge_proc.signal_pid(pid, force=force)
322
370
  deadline = time.monotonic() + wait
323
371
  while time.monotonic() < deadline:
324
372
  table = ps_table() or {}
@@ -329,6 +377,8 @@ def _reap_tracked(path: str, skip_group: int | None) -> list:
329
377
 
330
378
 
331
379
  def _pgid(pid: int):
380
+ if not hasattr(os, 'getpgid'):
381
+ return None
332
382
  try:
333
383
  return os.getpgid(pid)
334
384
  except OSError:
@@ -354,25 +404,30 @@ def stop_tree(root: int, wait: float) -> int:
354
404
  targets = (({root} if root in table else set()) | descendants(table, {root})) - _never(table)
355
405
  starts = {pid: table[pid][1] for pid in targets}
356
406
  for pid in targets:
357
- try:
358
- os.kill(pid, signal.SIGTERM)
359
- except OSError:
360
- pass
407
+ forge_proc.signal_pid(pid, force=False)
361
408
  deadline = time.monotonic() + wait
362
409
  left = set(targets)
363
410
  while left and time.monotonic() < deadline:
364
411
  time.sleep(0.2)
365
412
  now = ps_table() or {}
366
- left = {pid for pid in left if pid in now and now[pid][1] == starts[pid]}
413
+ left = {pid for pid in left if pid in now and _same_start(starts[pid], now[pid][1])}
367
414
  for pid in left:
368
- try:
369
- os.kill(pid, signal.SIGKILL)
370
- except OSError:
371
- pass
415
+ forge_proc.signal_pid(pid, force=True)
372
416
  print(len(targets))
373
417
  return 0
374
418
 
375
419
 
420
+ def kill_children(parent_pid: int, force: bool = False) -> int:
421
+ """Terminate descendants of `parent_pid` (used on platforms lacking `pkill -P`)."""
422
+ table = ps_table()
423
+ if table is None or parent_pid <= 1:
424
+ return 0
425
+ targets = descendants(table, {parent_pid}) - _never(table)
426
+ for pid in sorted(targets, reverse=True):
427
+ forge_proc.signal_pid(pid, force=force)
428
+ return 0
429
+
430
+
376
431
  def reap(pgid: int, orphans_file: str, tracked: str | None = None) -> int:
377
432
  count = _reap_group(pgid, orphans_file)
378
433
  extra = _reap_tracked(tracked, pgid) if tracked else []
@@ -401,18 +456,18 @@ def _ps_field(pid: int, field: str) -> str | None:
401
456
 
402
457
 
403
458
  def identity(pid: int) -> str | None:
459
+ if forge_proc.IS_WINDOWS:
460
+ return forge_proc.process_start_time(pid)
461
+ # On Cygwin (Windows MSYS2 mode) this is Cygwin ps's STIME made absolute (see the Cygwin
462
+ # block below). After 24 hours it is known only to the day: compare it with _same_start.
404
463
  return _ps_field(pid, 'lstart')
405
464
 
406
465
 
407
466
  def _pid_alive(pid: int) -> bool:
408
- try:
409
- os.kill(pid, 0)
410
- except ProcessLookupError:
467
+ if not forge_proc.pid_alive(pid):
411
468
  return False
412
- except PermissionError:
469
+ if forge_proc.IS_WINDOWS:
413
470
  return True
414
- except OSError:
415
- return False
416
471
  # A zombie still answers kill(0) until its parent waits for it.
417
472
  return not (_ps_field(pid, 'stat') or 'Z').startswith('Z')
418
473
 
@@ -427,6 +482,19 @@ def _wait_pid_gone(pid: int, seconds: float) -> bool:
427
482
 
428
483
 
429
484
  def _stop_live(pid: int) -> int:
485
+ if forge_proc.IS_WINDOWS:
486
+ if pid in _forbidden():
487
+ return 0
488
+ members = list_group(pid)
489
+ count = len(members) if members else 1
490
+ for force, wait in ((False, TERM_WAIT_S), (True, KILL_WAIT_S)):
491
+ forge_proc.kill_tree(pid, force=force)
492
+ for mpid, _cmd in (members or []):
493
+ if mpid and mpid not in _forbidden():
494
+ forge_proc.signal_pid(mpid, force=force)
495
+ if wait_gone(pid, wait):
496
+ break
497
+ return count
430
498
  try:
431
499
  leader = os.getpgid(pid) == pid
432
500
  except OSError:
@@ -436,7 +504,7 @@ def _stop_live(pid: int) -> int:
436
504
  return 0
437
505
  members = list_group(pid)
438
506
  count = len(members) if members else 1
439
- for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (signal.SIGKILL, KILL_WAIT_S)):
507
+ for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (forge_proc.SIGKILL, KILL_WAIT_S)):
440
508
  try:
441
509
  os.killpg(pid, sig)
442
510
  except OSError:
@@ -445,7 +513,7 @@ def _stop_live(pid: int) -> int:
445
513
  break
446
514
  return count
447
515
  # 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)):
516
+ for sig, wait in ((signal.SIGTERM, TERM_WAIT_S), (forge_proc.SIGKILL, KILL_WAIT_S)):
449
517
  try:
450
518
  os.kill(pid, sig)
451
519
  except OSError:
@@ -476,7 +544,8 @@ def stop(record: str) -> int:
476
544
  if pid > 1:
477
545
  if _pid_alive(pid):
478
546
  # A mismatch, or no way to tell, means the pid now belongs to someone else.
479
- if recorded and identity(pid) == recorded:
547
+ current = identity(pid)
548
+ if recorded and current is not None and _same_start(recorded, current):
480
549
  count = _stop_live(pid)
481
550
  else:
482
551
  count = _reap_group(pid, None)
@@ -564,12 +633,106 @@ def promises(path: str, tail_bytes: int = 3000) -> int:
564
633
  return 0
565
634
 
566
635
 
636
+ # --- Windows (MSYS2/Cygwin) -----------------------------------------------------
637
+ # procps builds each row from /proc/<pid>/stat, which Cygwin fills by asking Windows: about half
638
+ # a second per process, so one listing takes 15-20 s and outlives every timeout above, leaving
639
+ # the guards blind. Its start time is also the Windows process's, which changes when a Cygwin
640
+ # process execs a native program (a harness), so an identity recorded before the exec never
641
+ # matched again. Cygwin's own ps reads the same process table in milliseconds, keeps the start
642
+ # time across exec and hides zombies. Its STIME has one-second resolution and gives the time of
643
+ # day for the first 24 hours, then only the date: _cygwin_start makes either absolute, and
644
+ # _cygwin_same_start lets a start known to the day match one known to the second, so `stop`
645
+ # still recognises a harness after a day (to the day: a pid reused on that same day would pass).
646
+ _CYGWIN_MONTHS = {name: number for number, name in enumerate(
647
+ ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), 1)}
648
+
649
+
650
+ def _cygwin_start(stime: str, now: float | None = None) -> str:
651
+ """Cygwin ps's STIME as an absolute local start: 'YYYY-MM-DD HH:MM:SS' while ps gives the time
652
+ of day (the last 24 hours), 'YYYY-MM-DD' once it gives only the date ('Nov 19'). Text in
653
+ neither form comes back unchanged."""
654
+ today = time.localtime(time.time() if now is None else now)
655
+ parts = stime.split()
656
+ if len(parts) == 1 and re.fullmatch(r'\d\d:\d\d:\d\d', parts[0]):
657
+ day = datetime.date(today.tm_year, today.tm_mon, today.tm_mday)
658
+ if parts[0] > time.strftime('%H:%M:%S', today): # later than now: it was yesterday
659
+ day -= datetime.timedelta(days=1) # by the date: a day is not always 86400 s
660
+ return '%s %s' % (day.isoformat(), parts[0])
661
+ if len(parts) == 2 and parts[0] in _CYGWIN_MONTHS and parts[1].isdigit():
662
+ month, mday = _CYGWIN_MONTHS[parts[0]], int(parts[1])
663
+ year = today.tm_year - ((month, mday) > (today.tm_mon, today.tm_mday))
664
+ return '%04d-%02d-%02d' % (year, month, mday)
665
+ return stime
666
+
667
+
668
+ def _cygwin_same_start(recorded: str, current: str) -> bool:
669
+ """Whether two _cygwin_start values name the same start: equal, or one known only to the day
670
+ and the other on that day."""
671
+ if recorded == current:
672
+ return True
673
+ shorter, longer = sorted((recorded, current), key=len)
674
+ return len(shorter) == 10 and longer.startswith(shorter + ' ')
675
+
676
+
677
+ if sys.platform == 'cygwin':
678
+ CYGWIN_PS = '/usr/bin/ps'
679
+ _CYGWIN_ROW = re.compile(r'^\s*[A-Z]?\s*(\d+)\s+(\d+)\s+(\d+)\s+\d+\s+\S+\s+\d+\s+'
680
+ r'(\d\d:\d\d:\d\d|[A-Z][a-z]{2}\s+\d+)\s+(.*)$')
681
+ _same_start = _cygwin_same_start
682
+
683
+ def _cygwin_rows(pid: int | None = None):
684
+ """{pid: (ppid, pgid, start, executable)} of live processes, or None when ps cannot run.
685
+ LC_ALL=C keeps STIME's month names in English for _cygwin_start."""
686
+ try:
687
+ out = subprocess.run([CYGWIN_PS, '-l'] + (['-p', str(pid)] if pid else ['-a']),
688
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=30,
689
+ env=dict(os.environ, LC_ALL='C')).stdout.decode(errors='replace')
690
+ except (OSError, subprocess.SubprocessError):
691
+ return None
692
+ rows = {}
693
+ for line in out.splitlines()[1:]:
694
+ match = _CYGWIN_ROW.match(line)
695
+ if match:
696
+ rows[int(match[1])] = (int(match[2]), int(match[3]), _cygwin_start(match[4]), match[5].strip())
697
+ return rows
698
+
699
+ def _command(pid: int, fallback: str) -> str:
700
+ """The full command line where Cygwin can read it cheaply; the executable otherwise."""
701
+ try:
702
+ with open('/proc/%d/cmdline' % pid, 'rb') as handle:
703
+ return handle.read().replace(b'\0', b' ').decode(errors='replace').strip() or fallback
704
+ except OSError:
705
+ return fallback
706
+
707
+ def list_group(pgid: int):
708
+ rows = _cygwin_rows()
709
+ if rows is None:
710
+ return None
711
+ me = os.getpid()
712
+ return [(pid, _command(pid, exe)) for pid, (_ppid, group, _start, exe) in sorted(rows.items())
713
+ if group == pgid and pid != me]
714
+
715
+ def ps_table():
716
+ rows = _cygwin_rows()
717
+ if rows is None:
718
+ return None
719
+ return {pid: (ppid, start, exe) for pid, (ppid, _group, start, exe) in rows.items()}
720
+
721
+ def _ps_field(pid: int, field: str) -> str | None:
722
+ if pid <= 0:
723
+ return None
724
+ row = (_cygwin_rows(pid) or {}).get(pid)
725
+ if row is None:
726
+ return None
727
+ return {'stat': 'S', 'lstart': row[2], 'ppid': str(row[0]), 'pgid': str(row[1])}.get(field)
728
+
729
+
567
730
  # --- cli ----------------------------------------------------------------------
568
731
  def main(argv: list[str]) -> int:
569
732
  if not argv:
570
733
  print('usage: forge-guard.py ping | session -- CMD... | reap <pgid> <orphans-file> [--tracked FILE] | '
571
- 'track <pid> <file> [--interval S] | stop-tree <pid> [--wait S] | identity <pid> | '
572
- 'stop <record-file> | '
734
+ 'track <pid> <file> [--interval S] | stop-tree <pid> [--wait S] | kill-children <pid> [TERM|KILL] | '
735
+ 'identity <pid> | stop <record-file> | '
573
736
  'promises <file> [--tail-bytes N]', file=sys.stderr)
574
737
  return 2
575
738
  command, rest = argv[0], argv[1:]
@@ -601,6 +764,12 @@ def main(argv: list[str]) -> int:
601
764
  print('usage: forge-guard.py stop-tree <pid> [--wait S]', file=sys.stderr)
602
765
  return 2
603
766
  return stop_tree(int(rest[0]), max(0.0, wait))
767
+ if command == 'kill-children':
768
+ if len(rest) not in (1, 2):
769
+ print('usage: forge-guard.py kill-children <pid> [TERM|KILL]', file=sys.stderr)
770
+ return 2
771
+ force = len(rest) == 2 and rest[1].upper() == 'KILL'
772
+ return kill_children(int(rest[0]), force=force)
604
773
  if command == 'track':
605
774
  interval = TRACK_INTERVAL_S
606
775
  if '--interval' in rest:
@@ -53,9 +53,15 @@ import shutil
53
53
  import stat
54
54
  import subprocess
55
55
  import sys
56
+ from pathlib import Path
57
+
58
+ _SCRIPTS = str(Path(__file__).resolve().parent)
59
+ if _SCRIPTS not in sys.path:
60
+ sys.path.insert(0, _SCRIPTS)
61
+ import forge_posix # noqa: E402
62
+ import forge_proc # noqa: E402
56
63
  import tempfile
57
64
  import time
58
- from pathlib import Path
59
65
 
60
66
  SCRIPTS = Path(__file__).resolve().parent
61
67
  sys.path.insert(0, str(SCRIPTS))
@@ -134,7 +140,7 @@ class Plan:
134
140
  """The text of a regular file under the run dir, or None (missing: silent; anything else warns)."""
135
141
  try:
136
142
  # O_NONBLOCK: a FIFO with no writer would block an open; it is not a regular file anyway.
137
- fd = os.open(self.path / rel, os.O_RDONLY | os.O_NONBLOCK)
143
+ fd = os.open(self.path / rel, os.O_RDONLY | forge_posix.O_NONBLOCK)
138
144
  except FileNotFoundError:
139
145
  return None
140
146
  except (OSError, ValueError) as error:
@@ -240,17 +246,7 @@ def flags_section(plan):
240
246
 
241
247
 
242
248
  def pid_alive(pid):
243
- if type(pid) is not int or pid <= 0:
244
- return False
245
- try:
246
- os.kill(pid, 0)
247
- except ProcessLookupError:
248
- return False
249
- except PermissionError:
250
- return True
251
- except (OSError, OverflowError):
252
- return False
253
- return True
249
+ return forge_proc.pid_alive(pid)
254
250
 
255
251
 
256
252
  def scheduler_section(plan):
@@ -790,7 +786,7 @@ def run_command(plan, flags):
790
786
  value = flags.get(key)
791
787
  return value if type(value) is int and value >= least else None
792
788
 
793
- command = ['/bin/bash', parallel_script(), 'run', str(plan)]
789
+ command = forge_proc.bash_cmd(parallel_script(), 'run', str(plan))
794
790
  for key, option, least in (('retry_failed', '--retry-failed', 0), ('infra_retries', '--infra-retries', 0)):
795
791
  if whole(key, least) is not None:
796
792
  command += [option, str(flags[key])]
@@ -977,7 +973,7 @@ def recover_task(ctrl, plan, wt_root, run_id, task, warn):
977
973
 
978
974
  def prepare_task(plan, task):
979
975
  """forge-parallel.sh retry PLAN TASK --no-dispatch. {task, ok, message}."""
980
- command = ['/bin/bash', parallel_script(), 'retry', str(plan), task, '--no-dispatch']
976
+ command = forge_proc.bash_cmd(parallel_script(), 'retry', str(plan), task, '--no-dispatch')
981
977
  try:
982
978
  result = subprocess.run(command, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=600)
983
979
  except (OSError, subprocess.SubprocessError) as error:
@@ -992,8 +988,9 @@ def start_run(plan, command):
992
988
  log, done = os.path.join(plan, f'resume-{stamp}.log'), os.path.join(plan, f'resume-{stamp}.done')
993
989
  wrapper = '"${@:2}"; rc=$?; printf "%s\\n" "$rc" > "$1.tmp" && mv -f "$1.tmp" "$1"; exit "$rc"'
994
990
  with open(log, 'ab') as out:
995
- process = subprocess.Popen(['/bin/bash', '-c', wrapper, 'forge-resume', done, *command], stdin=subprocess.DEVNULL,
996
- stdout=out, stderr=subprocess.STDOUT, start_new_session=True, cwd=plan)
991
+ process = subprocess.Popen(forge_proc.bash_cmd('-c', wrapper, 'forge-resume', done, *command),
992
+ stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
993
+ cwd=plan, **forge_proc.popen_group_kwargs(detached=True))
997
994
  return {'pid': process.pid, 'log': log, 'done': done}
998
995
 
999
996
 
@@ -13,7 +13,9 @@
13
13
  # forge-install.sh [--dry-run]
14
14
  set -uo pipefail
15
15
 
16
- SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
16
+ SKILL_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
17
+ source "$SKILL_DIR/scripts/forge-lib-env.sh"
18
+ forge_ensure_python3
17
19
  RESULT=0
18
20
  DRY=0
19
21
  # `forge install --help` must never install; nor may a mistyped --dry-run.
@@ -28,16 +30,33 @@ say() { printf '%s\n' "$*"; }
28
30
  do_() { if [ "$DRY" = 1 ]; then say " would: $*"; else "$@"; fi; }
29
31
 
30
32
  link_dir() { # link_dir <target-parent> <label>
31
- local parent="$1" label="$2" dest="$1/forge"
33
+ local parent="$1" label="$2" dest="$1/forge" target=""
32
34
  if [ ! -d "$parent" ]; then say "$label: skipped ($parent does not exist)"; return; fi
33
35
  if [ "$dest" = "$SKILL_DIR" ]; then say "$label: is the source directory"; return; fi
34
- if [ -L "$dest" ] && [ "$(readlink "$dest")" = "$SKILL_DIR" ]; then
35
- say "$label: already linked"; return
36
+ if [ -L "$dest" ]; then
37
+ # Canonicalize physically so /tmp mounts, 8.3 short names, and relative symlinks match SKILL_DIR.
38
+ target="$(cd -P -- "$dest" 2>/dev/null && pwd -P || true)"
39
+ if [ -n "$target" ] && [ "$target" = "$SKILL_DIR" ]; then
40
+ say "$label: already linked"; return
41
+ fi
36
42
  fi
37
43
  if [ -e "$dest" ] && [ ! -L "$dest" ]; then
38
44
  # Never clobber a real directory the user may have edited in place.
39
45
  say "$label: SKIPPED — $dest exists and is not a symlink; move it aside first"; return 1
40
46
  fi
47
+ if forge_is_windows; then
48
+ if [ "$DRY" = 1 ]; then
49
+ say " would: mklink /J $(forge_win_path "$dest") $(forge_win_path "$SKILL_DIR")"
50
+ say "$label: linked -> $dest"
51
+ return 0
52
+ fi
53
+ if forge_link_dir "$SKILL_DIR" "$dest"; then
54
+ say "$label: linked (junction) -> $dest"
55
+ else
56
+ cp -R "$SKILL_DIR" "$dest" && say "$label: copied -> $dest (re-run forge install after editing)"
57
+ fi
58
+ return $?
59
+ fi
41
60
  do_ ln -sfn "$SKILL_DIR" "$dest" && say "$label: linked -> $dest"
42
61
  }
43
62
 
@@ -51,6 +70,35 @@ report_opencode() {
51
70
  say "opencode : auto-detected from ~/.claude/skills (no install needed)"
52
71
  }
53
72
 
73
+ copy_skill_dir() { # copy_skill_dir <target-parent> <label> — real directory copy for scanners that ignore junctions
74
+ local parent="$1" label="$2" dest="$1/forge" item stage
75
+ if [ ! -d "$parent" ]; then say "$label: skipped ($parent does not exist)"; return; fi
76
+ if [ "$dest" = "$SKILL_DIR" ]; then say "$label: is the source directory"; return; fi
77
+ if [ "$DRY" = 1 ]; then
78
+ say " would: copy skill files to $dest"
79
+ say "$label: copied -> $dest (re-run forge install after editing)"
80
+ return 0
81
+ fi
82
+ if [ -L "$dest" ]; then
83
+ rmdir "$dest" 2>/dev/null || rm -f "$dest" 2>/dev/null || rm -rf "$dest"
84
+ elif [ -e "$dest" ] && [ ! -f "$dest/.forge-installed" ]; then
85
+ say "$label: SKIPPED — $dest exists and is not managed by forge; move it aside first"; return 1
86
+ fi
87
+ stage="$dest.tmp.$$"
88
+ rm -rf "$stage"
89
+ mkdir -p "$stage" || return 1
90
+ for item in SKILL.md VERSION LICENSE package.json forge forge.cmd bin scripts references ui; do
91
+ if [ -e "$SKILL_DIR/$item" ]; then
92
+ cp -R "$SKILL_DIR/$item" "$stage/$item" || { rm -rf "$stage"; return 1; }
93
+ fi
94
+ done
95
+ find "$stage" -type d -name '__pycache__' -exec rm -rf {} + 2>/dev/null || true
96
+ : > "$stage/.forge-installed"
97
+ rm -rf "$dest"
98
+ mv "$stage" "$dest" || { rm -rf "$stage"; return 1; }
99
+ say "$label: copied -> $dest (re-run forge install after editing)"
100
+ }
101
+
54
102
  # Antigravity loads skills only as part of a plugin — a loose directory under
55
103
  # ~/.gemini/skills is ignored (agy cannot see skills placed there at all). So forge
56
104
  # is wrapped in a minimal plugin whose skills/ entry points back at this directory.
@@ -60,14 +108,30 @@ report_opencode() {
60
108
  # not track edits to this directory automatically: re-run this installer after
61
109
  # changing the skill, or agy keeps running the version it copied.
62
110
  install_antigravity() {
63
- local label="antigravity" wrapper="$HOME/.gemini/forge-plugin"
64
- if ! command -v agy >/dev/null 2>&1; then
111
+ local label="antigravity" gemini_home="$HOME/.gemini" wrapper agy_skills has_agy=0 rc=0
112
+ if forge_is_windows && [ ! -d "$gemini_home" ] && [ -n "${USERPROFILE:-}" ]; then
113
+ gemini_home="$(forge_posix_path "$USERPROFILE")/.gemini"
114
+ fi
115
+ wrapper="$gemini_home/forge-plugin"
116
+ agy_skills="$gemini_home/config/skills"
117
+ if command -v agy >/dev/null 2>&1; then
118
+ has_agy=1
119
+ fi
120
+ if forge_is_windows && [ -d "$agy_skills" ]; then
121
+ # Windows only. Electron/Node scanners check dirent.isDirectory(), which is false for Windows
122
+ # junctions, and Antigravity loads skills directly from ~/.gemini/config/skills without
123
+ # `agy plugin install` (which hits Access is denied on Windows while Antigravity.exe watches
124
+ # ~/.gemini/config/plugins). macOS and Linux keep the plugin below.
125
+ copy_skill_dir "$agy_skills" "antigravity" || rc=1
126
+ return "$rc"
127
+ fi
128
+ if [ "$has_agy" = 0 ]; then
65
129
  say "$label: skipped (agy not on PATH)"; return
66
130
  fi
67
131
  if [ "$DRY" = 1 ]; then
68
132
  say " would: write plugin wrapper $wrapper"
69
133
  say " would: agy plugin install $wrapper"
70
- say "$label: plugin -> $wrapper"; return
134
+ say "$label: plugin -> $wrapper"; return "$rc"
71
135
  fi
72
136
  mkdir -p "$wrapper/skills" || return 1
73
137
  cat > "$wrapper/plugin.json" <<EOF
@@ -79,13 +143,22 @@ install_antigravity() {
79
143
  }
80
144
  EOF
81
145
  [ "$?" = 0 ] || return 1
82
- ln -sfn "$SKILL_DIR" "$wrapper/skills/forge" || return 1
83
- if agy plugin install "$wrapper"; then
146
+ local agy_wrapper
147
+ if forge_is_windows; then
148
+ # `agy plugin install` on Windows rejects junctions/symlinks inside the plugin bundle.
149
+ copy_skill_dir "$wrapper/skills" "antigravity" >/dev/null || return 1
150
+ agy_wrapper="$(forge_win_path "$wrapper")"
151
+ else
152
+ forge_link_dir "$SKILL_DIR" "$wrapper/skills/forge" || return 1
153
+ agy_wrapper="$wrapper"
154
+ fi
155
+ if agy plugin install "$agy_wrapper"; then
84
156
  say "$label: plugin installed (copied — re-run this script after editing the skill)"
85
157
  else
86
158
  say "$label: FAILED — try: agy plugin install $wrapper"
87
159
  return 1
88
160
  fi
161
+ return "$rc"
89
162
  }
90
163
 
91
164
  say "forge source: $SKILL_DIR"
@@ -76,7 +76,6 @@ from __future__ import annotations
76
76
  import argparse
77
77
  import contextlib
78
78
  import errno
79
- import fcntl
80
79
  import hashlib
81
80
  import importlib.util
82
81
  import json
@@ -91,6 +90,7 @@ import time
91
90
  from pathlib import Path
92
91
 
93
92
  sys.path.insert(0, str(Path(__file__).resolve().parent))
93
+ import forge_posix # noqa: E402
94
94
  from forge_registry import repo_key # noqa: E402
95
95
  import forge_identity # noqa: E402
96
96
  from forge_findings import status as record_status # noqa: E402
@@ -992,7 +992,10 @@ def _read_store(name, noun, shape, valid):
992
992
  if not stat.S_ISREG(os.lstat(path).st_mode):
993
993
  raise Fail(not_regular)
994
994
  # NOFOLLOW again for a swap after the lstat; NONBLOCK so a FIFO cannot hold the open
995
- with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as fh:
995
+ with os.fdopen(
996
+ forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK),
997
+ "rb",
998
+ ) as fh:
996
999
  if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
997
1000
  raise Fail(not_regular)
998
1001
  raw = fh.read(STORE_MAX + 1)