@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
@@ -36,7 +36,6 @@ does not keep running after `run` returns.
36
36
  """
37
37
  from __future__ import annotations
38
38
 
39
- import fcntl
40
39
  import os
41
40
  from pathlib import Path
42
41
  import re
@@ -45,10 +44,14 @@ import stat
45
44
  import subprocess
46
45
  import sys
47
46
 
47
+ SCRIPTS = Path(__file__).resolve().parent.parent
48
+ if str(SCRIPTS) not in sys.path:
49
+ sys.path.insert(0, str(SCRIPTS))
50
+ import forge_flock as fcntl # noqa: E402
51
+ import forge_proc # noqa: E402
48
52
  from forge_decide import load_user
49
53
  from forge_decide.providers import privacy_floor
50
54
 
51
- SCRIPTS = Path(__file__).resolve().parent.parent
52
55
  DISPATCH = SCRIPTS / 'forge-dispatch.sh'
53
56
 
54
57
  KINDS = ('brief', 'brief-change', 'summary', 'triage')
@@ -478,6 +481,9 @@ def _finish(plan, task, kind, spec, ok, last, directory, reason) -> dict:
478
481
 
479
482
  def _signal_group(pgid: int, sig: int, proc: subprocess.Popen) -> None:
480
483
  """Signal the dispatch's session. Never this process's own group."""
484
+ if forge_proc.IS_WINDOWS:
485
+ forge_proc.kill_tree(proc.pid, force=(sig == forge_proc.SIGKILL))
486
+ return
481
487
  if pgid == os.getpgrp():
482
488
  try:
483
489
  proc.send_signal(sig)
@@ -505,17 +511,20 @@ def _stop_dispatch(proc: subprocess.Popen) -> None:
505
511
  trap as well.
506
512
  """
507
513
  try:
508
- try:
509
- pgid = os.getpgid(proc.pid)
510
- except OSError:
514
+ if forge_proc.IS_WINDOWS:
511
515
  pgid = proc.pid
516
+ else:
517
+ try:
518
+ pgid = os.getpgid(proc.pid)
519
+ except OSError:
520
+ pgid = proc.pid
512
521
  _signal_group(pgid, signal.SIGTERM, proc)
513
522
  try:
514
523
  proc.wait(timeout=_STOP_GRACE_S)
515
524
  except subprocess.TimeoutExpired:
516
525
  pass
517
526
  # The shell can be gone while a preflight child is still in the session.
518
- _signal_group(pgid, signal.SIGKILL, proc)
527
+ _signal_group(pgid, forge_proc.SIGKILL, proc)
519
528
  try:
520
529
  proc.wait(timeout=_STOP_GRACE_S)
521
530
  except subprocess.TimeoutExpired:
@@ -539,14 +548,14 @@ def _dispatch_and_wait(dest: Path, repo, prompt, spec, limit: int, event_dir, ta
539
548
  return _finish(event_dir, task, kind, spec, False, None, dest, 'error')
540
549
  if not repo:
541
550
  return _finish(event_dir, task, kind, spec, False, None, dest, 'error')
542
- argv = ['/bin/bash', str(DISPATCH), 'side', '' if spec is None else str(spec),
543
- '--repo', str(repo), '--run-dir', str(dest), '--prompt-file', str(dest / 'prompt.txt'),
544
- '--timeout', str(max(0, limit))]
551
+ argv = forge_proc.bash_cmd(DISPATCH, 'side', '' if spec is None else str(spec),
552
+ '--repo', str(repo), '--run-dir', str(dest), '--prompt-file', str(dest / 'prompt.txt'),
553
+ '--timeout', str(max(0, limit)))
545
554
  # Own session, so a timeout can stop the preflight with the shell.
546
555
  try:
547
556
  proc = subprocess.Popen(
548
557
  argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
549
- start_new_session=True, close_fds=True)
558
+ close_fds=True, **forge_proc.popen_group_kwargs())
550
559
  except (OSError, subprocess.SubprocessError):
551
560
  return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'error')
552
561
  wait = None if limit <= 0 else limit + _DISPATCH_GRACE_S
@@ -36,9 +36,15 @@ import os
36
36
  import re
37
37
  import shutil
38
38
  import stat
39
+ import sys
39
40
  import time
40
41
  from pathlib import Path
41
42
 
43
+ _SCRIPTS = str(Path(__file__).resolve().parent)
44
+ if _SCRIPTS not in sys.path:
45
+ sys.path.insert(0, _SCRIPTS)
46
+ import forge_posix # noqa: E402
47
+
42
48
  DEP_DIRS = frozenset('node_modules bower_components .venv venv vendor .bundle Pods deps _build .dart_tool elm-stuff .build'.split())
43
49
  LOG_MIN = 64 << 10 # a smaller log gains next to nothing from gzip
44
50
  LOG_ROLES = ('dwarf', 'qa')
@@ -241,7 +247,11 @@ def compress_log(path) -> tuple[int, str | None]:
241
247
  except OSError as error:
242
248
  return 0, 'cannot remove %s: %s' % (part, error.strerror or error)
243
249
  try:
244
- fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, stat.S_IMODE(before.st_mode))
250
+ fd = forge_posix.open_nofollow(
251
+ part,
252
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | forge_posix.O_NOFOLLOW,
253
+ stat.S_IMODE(before.st_mode),
254
+ )
245
255
  with os.fdopen(fd, 'wb') as raw, open(path, 'rb') as source:
246
256
  with gzip.GzipFile(filename=os.path.basename(path), mode='wb', fileobj=raw, compresslevel=6,
247
257
  mtime=int(before.st_mtime)) as packed:
@@ -17,11 +17,22 @@ import re
17
17
  import shutil
18
18
  import signal
19
19
  import subprocess
20
+ import sys
20
21
  import tempfile
21
22
  import threading
22
23
  import time
23
24
  import urllib.parse
24
25
 
26
+ _SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'scripts')
27
+ _inserted = _SCRIPTS not in sys.path
28
+ if _inserted:
29
+ sys.path.insert(0, _SCRIPTS)
30
+ try:
31
+ import forge_proc # noqa: E402
32
+ finally:
33
+ if _inserted and _SCRIPTS in sys.path:
34
+ sys.path.remove(_SCRIPTS)
35
+
25
36
 
26
37
  TIMEOUT_S = 60 # one CLI call; a test sets a shorter one
27
38
  TERM_WAIT_S = 5 # between SIGTERM and SIGKILL of a timed-out call's process group
@@ -63,6 +74,7 @@ MAX_DECIDE_VALUE = 256
63
74
  # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
64
75
  # at 64 KiB by the server; this caps the stdin text itself, which a re-encode can make larger.
65
76
  MAX_PROFILE_BODY = 64 * 1024
77
+ MAX_PROFILE_DEPTH = 64 # a profile is a few levels deep
66
78
  # A brief answer, in characters. The CLI then keeps the leading 4 KiB of what remains after it
67
79
  # strips control characters; this bound is the one the route enforces before that call.
68
80
  MAX_ANSWER = 4096
@@ -160,6 +172,9 @@ class CliResult:
160
172
 
161
173
 
162
174
  def _signal_group(pgid, sig):
175
+ if forge_proc.IS_WINDOWS:
176
+ forge_proc.kill_tree(pgid, force=(sig == forge_proc.SIGKILL))
177
+ return
163
178
  try:
164
179
  os.killpg(pgid, sig)
165
180
  except (ProcessLookupError, PermissionError):
@@ -180,7 +195,7 @@ def run_cli(argv, timeout, stdin=None):
180
195
  try:
181
196
  proc = subprocess.Popen(argv, stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
182
197
  stdout=subprocess.PIPE, stderr=subprocess.PIPE,
183
- start_new_session=True, close_fds=True, env=env)
198
+ close_fds=True, env=env, **forge_proc.popen_group_kwargs())
184
199
  except OSError as exc:
185
200
  return CliResult(error=f'cannot run the forge CLI: {exc.strerror or exc}')
186
201
  try:
@@ -192,14 +207,14 @@ def run_cli(argv, timeout, stdin=None):
192
207
  while proc.poll() is None and time.monotonic() < deadline:
193
208
  time.sleep(0.05)
194
209
  # Children that outlive the leader (or ignore SIGTERM) die here; the leader is reaped by wait().
195
- _signal_group(pgid, signal.SIGKILL)
210
+ _signal_group(pgid, forge_proc.SIGKILL)
196
211
  proc.wait()
197
212
  for pipe in (proc.stdin, proc.stdout, proc.stderr):
198
213
  if pipe:
199
214
  pipe.close()
200
215
  return CliResult(timed_out=True)
201
216
  except BaseException:
202
- _signal_group(proc.pid, signal.SIGKILL)
217
+ _signal_group(proc.pid, forge_proc.SIGKILL)
203
218
  proc.wait()
204
219
  raise
205
220
  return CliResult(code=proc.returncode, stdout=out.decode('utf-8', 'replace'), stderr=err.decode('utf-8', 'replace'))
@@ -838,10 +853,26 @@ def _profile_value(value):
838
853
  return value
839
854
 
840
855
 
856
+ def _nested_deeper_than(value, limit):
857
+ """Whether lists and objects nest more than `limit` levels, checked without recursion."""
858
+ stack = [(value, 1)]
859
+ while stack:
860
+ item, depth = stack.pop()
861
+ if isinstance(item, (dict, list)):
862
+ if depth > limit:
863
+ return True
864
+ stack.extend((child, depth + 1) for child in (item.values() if isinstance(item, dict) else item))
865
+ return False
866
+
867
+
841
868
  def _profile_stdin(value):
842
869
  """The bytes `--file -` reads. A re-encode can be larger than the HTTP body, so it is capped on its own."""
843
870
  if not isinstance(value, dict):
844
871
  raise BadBody('body must be a JSON object')
872
+ # Up to Python 3.11 json.dumps raises RecursionError on a deep enough value; from 3.12 it
873
+ # goes much deeper, so the limit is explicit.
874
+ if _nested_deeper_than(value, MAX_PROFILE_DEPTH):
875
+ raise BadBody(f'body is nested more than {MAX_PROFILE_DEPTH} levels deep')
845
876
  try:
846
877
  raw = json.dumps(value, allow_nan=False).encode('utf-8')
847
878
  except (TypeError, ValueError, RecursionError):
@@ -1416,15 +1447,7 @@ def _scheduler_live(path):
1416
1447
  pid = json.load(handle).get('pid')
1417
1448
  except (OSError, ValueError, AttributeError, RecursionError):
1418
1449
  return False
1419
- if type(pid) is not int or pid <= 0:
1420
- return False
1421
- try:
1422
- os.kill(pid, 0)
1423
- except PermissionError:
1424
- return True
1425
- except (OSError, OverflowError):
1426
- return False
1427
- return True
1450
+ return forge_proc.pid_alive(pid)
1428
1451
 
1429
1452
 
1430
1453
  def _task_answer(ctx):
@@ -14,6 +14,17 @@ import sys
14
14
  import time
15
15
  import urllib.parse
16
16
 
17
+ _SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'scripts')
18
+ _inserted = _SCRIPTS not in sys.path
19
+ if _inserted:
20
+ sys.path.insert(0, _SCRIPTS)
21
+ try:
22
+ import forge_posix # noqa: E402
23
+ import forge_proc # noqa: E402
24
+ finally:
25
+ if _inserted and _SCRIPTS in sys.path:
26
+ sys.path.remove(_SCRIPTS)
27
+
17
28
  from forge_ui import checks, diffs, executions, findings, fractal, groups, links, repos, transcripts
18
29
  from forge_ui.findings import verdict as _verdict
19
30
 
@@ -702,15 +713,7 @@ def _scheduler(reader):
702
713
  """RunDetail.scheduler: whether a scheduler runs this plan now, and, while one does, what holds it: a drain, a
703
714
  stop, infrastructure pauses (scheduler-written infra.paused) and the capacity it dispatches up to."""
704
715
  pid = (reader.object('scheduler.live') or {}).get('pid') if reader.exists('scheduler.live') else None
705
- live = False
706
- if type(pid) is int and pid > 0:
707
- try:
708
- os.kill(pid, 0)
709
- live = True
710
- except PermissionError:
711
- live = True
712
- except (OSError, OverflowError):
713
- live = False
716
+ live = forge_proc.pid_alive(pid)
714
717
  result = dict(live=live, drained=False, stopping=None, pauses=[], max_parallel=None)
715
718
  if not live:
716
719
  return result
@@ -955,14 +958,9 @@ def _brief_writer_alive(reader):
955
958
  """brief.pid names a running process: the question writer `run` started has not finished."""
956
959
  try:
957
960
  pid = int((reader.text('brief.pid') or '').split()[0])
958
- if pid > 0:
959
- os.kill(pid, 0)
960
- return True
961
- except PermissionError:
962
- return True
963
961
  except (OSError, ValueError, IndexError):
964
- pass
965
- return False
962
+ return False
963
+ return forge_proc.pid_alive(pid)
966
964
 
967
965
 
968
966
  def _brief_wait(reader, ident):
@@ -3287,7 +3285,10 @@ def _log_name(lane, k, retry=False):
3287
3285
  def _open_log(path, name):
3288
3286
  """The open log and its stat, or None: a missing file, a symlink, anything not regular."""
3289
3287
  try:
3290
- fd = os.open(os.path.join(os.path.realpath(path), name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
3288
+ fd = forge_posix.open_nofollow(
3289
+ os.path.join(os.path.realpath(path), name),
3290
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
3291
+ )
3291
3292
  except OSError:
3292
3293
  return None
3293
3294
  try:
@@ -15,6 +15,7 @@ import os
15
15
  from pathlib import Path
16
16
  import re
17
17
  import secrets
18
+ import socketserver
18
19
  import sys
19
20
  import threading
20
21
  import time
@@ -460,8 +461,16 @@ class Handler(BaseHTTPRequestHandler):
460
461
  pass # the client hung up (BrokenPipeError, ConnectionResetError, ...): nothing to tell it
461
462
 
462
463
 
464
+ class _Server(ThreadingHTTPServer):
465
+ def server_bind(self):
466
+ # HTTPServer.server_bind sets server_name from socket.getfqdn(host), a reverse DNS lookup
467
+ # that can take many seconds on macOS. forge-ui serves loopback only and never reads it.
468
+ socketserver.TCPServer.server_bind(self)
469
+ self.server_name, self.server_port = self.server_address[:2]
470
+
471
+
463
472
  def make_server(catalog, host='127.0.0.1', port=0, static_dir=None, quiet=False, read_only=False):
464
- server = ThreadingHTTPServer((host, port), Handler)
473
+ server = _Server((host, port), Handler)
465
474
  server.catalog = catalog
466
475
  server.read_only = read_only
467
476
  server.token = secrets.token_urlsafe(32) # per process; only the page this process serves carries it