@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
@@ -10,9 +10,15 @@ import shutil
10
10
  import signal
11
11
  import subprocess
12
12
  import tempfile
13
+ import threading
13
14
  import time
14
15
  import sys
15
16
 
17
+ _SCRIPTS = str(Path(__file__).resolve().parent)
18
+ if _SCRIPTS not in sys.path:
19
+ sys.path.insert(0, _SCRIPTS)
20
+ import forge_proc # noqa: E402
21
+
16
22
 
17
23
  def resolve():
18
24
  binary = shutil.which('ripwire')
@@ -22,40 +28,80 @@ def resolve():
22
28
  return str(Path(binary).resolve()) if binary else None
23
29
 
24
30
 
31
+ def _bounded_windows(process, deadline, limit):
32
+ output = [bytearray(), bytearray()]
33
+ exceeded = threading.Event()
34
+
35
+ def _drain(idx, pipe):
36
+ try:
37
+ fd = pipe.fileno()
38
+ while True:
39
+ chunk = os.read(fd, 4096)
40
+ if not chunk:
41
+ break
42
+ output[idx].extend(chunk)
43
+ if sum(map(len, output)) > limit:
44
+ exceeded.set()
45
+ break
46
+ except OSError:
47
+ pass
48
+
49
+ threads = [
50
+ threading.Thread(target=_drain, args=(0, process.stdout), daemon=True),
51
+ threading.Thread(target=_drain, args=(1, process.stderr), daemon=True),
52
+ ]
53
+ for t in threads:
54
+ t.start()
55
+ while any(t.is_alive() for t in threads) or process.poll() is None:
56
+ if exceeded.is_set():
57
+ raise RuntimeError('excessive output')
58
+ remaining = deadline - time.monotonic()
59
+ if remaining <= 0:
60
+ raise RuntimeError('timeout')
61
+ time.sleep(min(remaining, 0.05))
62
+ for t in threads:
63
+ t.join(timeout=0.5)
64
+ if exceeded.is_set():
65
+ raise RuntimeError('excessive output')
66
+ return output
67
+
68
+
25
69
  def bounded(command, cwd, deadline, limit=16384):
26
70
  process = subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL,
27
71
  stdout=subprocess.PIPE, stderr=subprocess.PIPE,
28
- start_new_session=True)
29
- streams = selectors.DefaultSelector()
72
+ **forge_proc.popen_group_kwargs())
73
+ streams = None if forge_proc.IS_WINDOWS else selectors.DefaultSelector()
30
74
  output = [bytearray(), bytearray()]
31
- for i, pipe in enumerate((process.stdout, process.stderr)):
32
- os.set_blocking(pipe.fileno(), False)
33
- streams.register(pipe, selectors.EVENT_READ, i)
75
+ if streams is not None:
76
+ for i, pipe in enumerate((process.stdout, process.stderr)):
77
+ os.set_blocking(pipe.fileno(), False)
78
+ streams.register(pipe, selectors.EVENT_READ, i)
34
79
  try:
35
- while streams.get_map() or process.poll() is None:
36
- remaining = deadline - time.monotonic()
37
- if remaining <= 0:
38
- raise RuntimeError('timeout')
39
- for key, _ in streams.select(min(remaining, .1)):
40
- chunk = os.read(key.fileobj.fileno(), 4096)
41
- if not chunk:
42
- streams.unregister(key.fileobj)
43
- else:
44
- output[key.data].extend(chunk)
45
- if sum(map(len, output)) > limit:
46
- raise RuntimeError('excessive output')
80
+ if streams is None:
81
+ output = _bounded_windows(process, deadline, limit)
82
+ else:
83
+ while streams.get_map() or process.poll() is None:
84
+ remaining = deadline - time.monotonic()
85
+ if remaining <= 0:
86
+ raise RuntimeError('timeout')
87
+ for key, _ in streams.select(min(remaining, .1)):
88
+ chunk = os.read(key.fileobj.fileno(), 4096)
89
+ if not chunk:
90
+ streams.unregister(key.fileobj)
91
+ else:
92
+ output[key.data].extend(chunk)
93
+ if sum(map(len, output)) > limit:
94
+ raise RuntimeError('excessive output')
47
95
  if process.returncode:
48
96
  detail = output[1].decode('utf-8', 'replace').strip().replace('\n', ' ')[:180]
49
97
  raise RuntimeError(f'exit {process.returncode}: {detail}')
50
98
  return bytes(output[0]).decode('utf-8', 'replace')
51
99
  finally:
52
100
  # Also kill descendants that closed their pipes before the parent exited.
53
- try:
54
- os.killpg(process.pid, signal.SIGKILL)
55
- except (ProcessLookupError, PermissionError): # macOS: EPERM for a group of zombies only
56
- pass
101
+ forge_proc.kill_tree(process.pid, force=True)
57
102
  process.wait()
58
- streams.close()
103
+ if streams is not None:
104
+ streams.close()
59
105
  process.stdout.close()
60
106
  process.stderr.close()
61
107
 
@@ -99,7 +99,6 @@ from __future__ import annotations
99
99
  import argparse
100
100
  import contextlib
101
101
  import errno
102
- import fcntl
103
102
  import hashlib
104
103
  import json
105
104
  import math
@@ -116,6 +115,10 @@ from pathlib import Path
116
115
 
117
116
  TIERS = ('low', 'medium', 'high')
118
117
  SCRIPTS = Path(__file__).resolve().parent
118
+ if str(SCRIPTS) not in sys.path:
119
+ sys.path.insert(0, str(SCRIPTS))
120
+ import forge_flock as fcntl # noqa: E402
121
+ import forge_posix # noqa: E402
119
122
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
120
123
  FAILED = ('FAIL', 'TIMEOUT', 'BOUNCED', 'INCOMPLETE') # a judgment against the spec that ran
121
124
  NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT', 'NEEDS_DECISION', 'STALE') # say nothing about it
@@ -938,7 +941,11 @@ def _task_dir(plan: Path, task: str):
938
941
 
939
942
  @contextlib.contextmanager
940
943
  def _control_lock(plan: Path):
941
- fd = os.open(str(plan / 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644)
944
+ fd = forge_posix.open_nofollow(
945
+ str(plan / 'control.lock'),
946
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_CLOEXEC,
947
+ 0o644,
948
+ )
942
949
  try:
943
950
  if not stat.S_ISREG(os.fstat(fd).st_mode):
944
951
  raise OSError(errno.EINVAL, 'control.lock is not a regular file')
@@ -1155,7 +1162,7 @@ def _record(args, name: str, after=None) -> int:
1155
1162
  parent, _leaf = control._open_parent(plan, rel)
1156
1163
  if parent is None:
1157
1164
  return 1
1158
- os.close(parent)
1165
+ forge_posix.close_dir(parent)
1159
1166
  if args.probe:
1160
1167
  control.probe(plan, rel)
1161
1168
  else:
@@ -49,6 +49,7 @@ import time
49
49
  SKILL = Path(__file__).resolve().parent.parent
50
50
  sys.path.insert(0, str(SKILL / 'scripts'))
51
51
 
52
+ import forge_proc # noqa: E402
52
53
  import forge_storage # noqa: E402
53
54
 
54
55
  OK, REFUSED, BUSY, FAILED = 0, 2, 3, 4
@@ -293,8 +294,8 @@ def start_check(args) -> int:
293
294
  if args.exclude:
294
295
  argv += ['--exclude', args.exclude]
295
296
  with open(log, 'ab') as sink:
296
- subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=sink, stderr=sink, start_new_session=True,
297
- close_fds=True)
297
+ subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=sink, stderr=sink,
298
+ close_fds=True, **forge_proc.popen_group_kwargs(detached=True))
298
299
  except Exception: # noqa: BLE001 -- a run never fails over its storage check
299
300
  pass
300
301
  return OK
@@ -45,7 +45,6 @@ from __future__ import annotations
45
45
 
46
46
  import argparse
47
47
  import errno
48
- import fcntl
49
48
  import hashlib
50
49
  import itertools
51
50
  import json
@@ -59,6 +58,13 @@ import sys
59
58
  import time
60
59
  from pathlib import Path
61
60
 
61
+ _SCRIPTS = str(Path(__file__).resolve().parent)
62
+ if _SCRIPTS not in sys.path:
63
+ sys.path.insert(0, _SCRIPTS)
64
+ import forge_flock as fcntl # noqa: E402
65
+ import forge_posix # noqa: E402
66
+ import forge_proc # noqa: E402
67
+
62
68
  SKILL = Path(__file__).resolve().parent.parent
63
69
  sys.path.insert(0, str(SKILL / 'scripts'))
64
70
 
@@ -210,7 +216,7 @@ def locate(arg):
210
216
  def read_text(path, cap=READ_MAX):
211
217
  """A run file's text: None if absent, Refused if it is not a plain readable file. Never follows a link."""
212
218
  try:
213
- fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
219
+ fd = forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NONBLOCK | forge_posix.O_NOFOLLOW)
214
220
  except FileNotFoundError:
215
221
  return None
216
222
  except OSError as error:
@@ -324,23 +330,17 @@ def scheduler_pid(run):
324
330
  pid = json.loads(read_text(os.path.join(run.path, 'scheduler.live'), 64 * 1024) or '')['pid']
325
331
  except (ValueError, KeyError, TypeError, Refused):
326
332
  return None
327
- if type(pid) is not int or pid <= 0:
328
- return None
329
- try:
330
- os.kill(pid, 0)
331
- except ProcessLookupError:
332
- return None
333
- except PermissionError:
334
- return pid
335
- except (OSError, OverflowError):
336
- return None
337
- return pid
333
+ return pid if forge_proc.pid_alive(pid) else None
338
334
 
339
335
 
340
336
  def take_lock(run):
341
337
  """The run's operation lock, non-blocking, as the runners take it. Returns the open fd."""
342
338
  try:
343
- fd = os.open(run.lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o644)
339
+ fd = forge_posix.open_nofollow(
340
+ run.lock_path,
341
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
342
+ 0o644,
343
+ )
344
344
  except OSError as error:
345
345
  raise Failed('cannot open %s: %s' % (run.lock_path, error.strerror or error))
346
346
  try:
@@ -15,6 +15,11 @@ import sys
15
15
  import time
16
16
  import uuid
17
17
 
18
+ _SCRIPTS = str(Path(__file__).resolve().parent)
19
+ if _SCRIPTS not in sys.path:
20
+ sys.path.insert(0, _SCRIPTS)
21
+ import forge_proc # noqa: E402
22
+
18
23
 
19
24
  def write_json(path: Path, value: dict) -> None:
20
25
  temporary = path.with_name(path.name + '.' + uuid.uuid4().hex)
@@ -42,7 +47,7 @@ def _dataset(hook: str, *args) -> None:
42
47
 
43
48
 
44
49
  def capability_help(cache: str, registry: str, recipe: str, command: list[str]) -> str:
45
- binary = Path(command[0]).resolve()
50
+ binary, exec_command = forge_proc.resolve_win_command(command)
46
51
  stat = binary.stat()
47
52
  identity = [
48
53
  str(binary), stat.st_dev, stat.st_ino, stat.st_size,
@@ -56,7 +61,7 @@ def capability_help(cache: str, registry: str, recipe: str, command: list[str])
56
61
  path = root / key
57
62
  if path.exists():
58
63
  return path.read_text()
59
- result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
64
+ result = subprocess.run(exec_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
60
65
  if result.returncode:
61
66
  raise RuntimeError(result.stdout.decode(errors='replace'))
62
67
  temporary = root / (key + '.' + uuid.uuid4().hex)
@@ -65,10 +70,20 @@ def capability_help(cache: str, registry: str, recipe: str, command: list[str])
65
70
  return result.stdout.decode(errors='replace')
66
71
 
67
72
 
73
+ def shared_clock() -> float:
74
+ """Seconds from a point every process on this machine shares. begin and each phase run as separate
75
+ processes and subtract each other's readings, which time.monotonic() does not promise: on macOS,
76
+ Python 3.9 starts it at zero in every process, so every phase there measured about 0s."""
77
+ try:
78
+ return time.clock_gettime(time.CLOCK_MONOTONIC)
79
+ except (AttributeError, OSError): # Windows has no clock_gettime; its monotonic() is system-wide
80
+ return time.monotonic()
81
+
82
+
68
83
  def begin(root: str, role: str) -> Path:
69
84
  attempt = Path(root) / 'attempts' / (role + '-' + uuid.uuid4().hex)
70
85
  attempt.mkdir(parents=True)
71
- now = time.monotonic()
86
+ now = shared_clock()
72
87
  write_json(attempt / 'metrics.json', {
73
88
  'role': role, 'started': now, 'wall_started': time.time(),
74
89
  'phase': 'preparation', 'phase_started': now,
@@ -87,7 +102,7 @@ def begin(root: str, role: str) -> Path:
87
102
  def phase(attempt: str, name: str, rc: str | None = None) -> None:
88
103
  path = Path(attempt) / 'metrics.json'
89
104
  data = json.loads(path.read_text())
90
- now = time.monotonic()
105
+ now = shared_clock()
91
106
  previous = data['phase']
92
107
  duration = now - data['phase_started']
93
108
  data['elapsed_s'][previous] = data['elapsed_s'].get(previous, 0) + duration
@@ -124,17 +139,15 @@ def clock(log: str, out: str, every: str | None = None) -> None:
124
139
  def sample() -> None:
125
140
  nonlocal last
126
141
  # A TERM waits until the line is whole: it is delivered when the mask is lifted.
127
- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
128
- try:
129
- size = os.stat(log).st_size
130
- if size != last:
131
- with open(out, 'a') as stream:
132
- stream.write('%.3f %d\n' % (time.time(), size))
133
- last = size
134
- except OSError:
135
- pass
136
- finally:
137
- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGTERM})
142
+ with forge_proc.mask_sigterm():
143
+ try:
144
+ size = os.stat(log).st_size
145
+ if size != last:
146
+ with open(out, 'a') as stream:
147
+ stream.write('%.3f %d\n' % (time.time(), size))
148
+ last = size
149
+ except OSError:
150
+ pass
138
151
 
139
152
  try:
140
153
  while os.getppid() == parent and not os.path.exists(stop_file):
@@ -792,12 +805,16 @@ def settle(log: str, grace: str, pid: str) -> None:
792
805
  poll = min(SETTLE_POLL_S, max(grace_s / 4, 0.05))
793
806
  size, since, judged = None, time.monotonic(), None
794
807
  while True:
795
- try:
796
- os.kill(target, 0)
797
- except ProcessLookupError:
798
- sys.exit(1)
799
- except PermissionError:
800
- pass
808
+ if forge_proc.IS_WINDOWS:
809
+ if not forge_proc.pid_alive(target):
810
+ sys.exit(1)
811
+ else:
812
+ try:
813
+ os.kill(target, 0)
814
+ except ProcessLookupError:
815
+ sys.exit(1)
816
+ except PermissionError:
817
+ pass
801
818
  try:
802
819
  now = os.stat(log).st_size
803
820
  except OSError: