@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
@@ -31,7 +31,6 @@ from __future__ import annotations
31
31
  import argparse
32
32
  import contextlib
33
33
  import errno
34
- import fcntl
35
34
  import json
36
35
  import math
37
36
  import os
@@ -50,7 +49,10 @@ import time
50
49
  # forge_infra.py sits beside this file; forge-control.py loads this module by path.
51
50
  if str(Path(__file__).resolve().parent) not in sys.path:
52
51
  sys.path.insert(0, str(Path(__file__).resolve().parent))
52
+ import forge_flock as fcntl # noqa: E402
53
53
  import forge_infra # noqa: E402
54
+ import forge_posix # noqa: E402
55
+ import forge_proc # noqa: E402
54
56
 
55
57
 
56
58
  def dataset_event(name: str, plan: Path, task: str, values: dict) -> None:
@@ -304,7 +306,10 @@ def _read_budget(plan: object, *parts: str) -> int | None:
304
306
  """A non-negative integer from a control file; None when it is missing, empty, a
305
307
  symlink or anything else, so the caller falls through to its next source."""
306
308
  try:
307
- fd = os.open(_resolve(plan, *parts), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
309
+ fd = forge_posix.open_nofollow(
310
+ _resolve(plan, *parts),
311
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
312
+ )
308
313
  try:
309
314
  data = os.read(fd, 65)
310
315
  finally:
@@ -321,7 +326,11 @@ def _control_lock(plan: object):
321
326
  error: warn and proceed without it (yielding False), never fail the run."""
322
327
  fd = None
323
328
  try:
324
- fd = os.open(_resolve(plan, 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644)
329
+ fd = forge_posix.open_nofollow(
330
+ _resolve(plan, 'control.lock'),
331
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW,
332
+ 0o644,
333
+ )
325
334
  deadline = time.monotonic() + CONTROL_LOCK_WAIT
326
335
  while True:
327
336
  try:
@@ -358,7 +367,10 @@ def _task_dirs(plan: object, names: object) -> list[str]:
358
367
  def _read_small(plan: object, name: str) -> str | None:
359
368
  """A short plan-level control file's stripped text; None when missing or unsafe."""
360
369
  try:
361
- fd = os.open(_resolve(plan, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
370
+ fd = forge_posix.open_nofollow(
371
+ _resolve(plan, name),
372
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
373
+ )
362
374
  try:
363
375
  return os.read(fd, 65).decode('ascii').strip()
364
376
  finally:
@@ -432,15 +444,7 @@ def interrupt_grace() -> float:
432
444
 
433
445
 
434
446
  def _group_alive(pgid: int) -> bool:
435
- try:
436
- os.killpg(pgid, 0)
437
- except ProcessLookupError:
438
- return False
439
- except PermissionError:
440
- return True
441
- except OSError:
442
- return False
443
- return True
447
+ return forge_proc.group_alive(pgid)
444
448
 
445
449
 
446
450
  def stop_harnesses(plan: object, names: object, groups: object = ()) -> None:
@@ -522,7 +526,10 @@ def decision_head(plan: object, name: str) -> str:
522
526
 
523
527
  def read_request(plan: object, name: str) -> dict | None:
524
528
  try:
525
- fd = os.open(_resolve(plan, REQUESTS, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
529
+ fd = forge_posix.open_nofollow(
530
+ _resolve(plan, REQUESTS, name),
531
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
532
+ )
526
533
  try:
527
534
  data = os.read(fd, REQUEST_MAX + 1)
528
535
  finally:
@@ -563,7 +570,11 @@ def settle_request(plan: object, name: str, request: dict | None, outcome: str,
563
570
  'previous': None, 'request': name,
564
571
  'outcome': outcome, 'reason': reason}
565
572
  try:
566
- fd = os.open(_resolve(plan, 'control.log'), os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
573
+ fd = forge_posix.open_nofollow(
574
+ _resolve(plan, 'control.log'),
575
+ os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW,
576
+ 0o644,
577
+ )
567
578
  try:
568
579
  os.write(fd, (json.dumps(entry) + '\n').encode('utf-8'))
569
580
  finally:
@@ -644,14 +655,9 @@ def brief_writer_alive(plan: object) -> bool:
644
655
  The file is removed when the writer ends, so a missing or unreadable one means it is gone."""
645
656
  try:
646
657
  pid = int((Path(plan) / 'brief.pid').read_text().split()[0])
647
- if pid <= 0:
648
- return False
649
- os.kill(pid, 0)
650
- except PermissionError:
651
- return True
652
658
  except (OSError, ValueError, IndexError):
653
659
  return False
654
- return True
660
+ return forge_proc.pid_alive(pid)
655
661
 
656
662
 
657
663
  def brief_unanswered(plan: object, name: str) -> list:
@@ -740,7 +746,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
740
746
  brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
741
747
  brief_told = set() # (task, qid or '') whose brief wait was already printed
742
748
  brief_waiting = set() # tasks the last dispatch pass held for a brief answer or the brief writer
743
- brief_alive = [0.0, False] # when the writer was last looked at, and what was seen
749
+ # When the writer was last looked at, and what was seen. -inf, not 0.0: time.monotonic() has no
750
+ # defined start, and where it is small (seen with Python 3.9 on a macOS runner) the first look
751
+ # was skipped and a task dispatched as if the writer had already gone.
752
+ brief_alive = [float('-inf'), False]
744
753
 
745
754
  def status(name: str) -> str:
746
755
  root = plan / 'tasks' / name
@@ -754,7 +763,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
754
763
  dataset_event('sched_terminal', plan, name, dict(status=state))
755
764
 
756
765
  def merge(name: str) -> None:
757
- result = subprocess.run(['/bin/bash', script, '_merge', str(plan), name])
766
+ result = subprocess.run([forge_proc.bash_executable(), script, '_merge', str(plan), name])
758
767
  if result.returncode and status(name) == 'PASS':
759
768
  mark(name, 'ERROR')
760
769
  elif brief_mode != 'off' and status(name) == 'MERGED':
@@ -882,7 +891,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
882
891
  def requeue(name: str) -> bool:
883
892
  """Prepare a retry exactly as `retry` does, then put the task at the queue head. A task at its
884
893
  attempt cap (#69) is not prepared: _prepare_retry stops it for a decision instead."""
885
- result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name])
894
+ result = subprocess.run([forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name])
886
895
  if result.returncode:
887
896
  refused[name] = budget(name)
888
897
  return False
@@ -914,7 +923,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
914
923
  def prompt_requeue(name: str) -> bool:
915
924
  """Re-dispatch a STALE task (its prompt changed while the attempt ran, #150) with the new text. The stale
916
925
  attempt spent nothing, so no retry is counted: retries, retries.used and decided.left stay as they are."""
917
- result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--prompt'])
926
+ result = subprocess.run([forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--prompt'])
918
927
  if result.returncode:
919
928
  print('forge: ' + name + ' is not re-dispatched: its changed prompt could not be prepared',
920
929
  file=sys.stderr, flush=True)
@@ -941,7 +950,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
941
950
  either: _prepare_retry --resume stops it for a decision, and it leaves the queue."""
942
951
  if not _pinned(plan, name) and not at_cap(name):
943
952
  return True
944
- result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--resume'])
953
+ result = subprocess.run([forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--resume'])
945
954
  if result.returncode:
946
955
  if status(name) == 'NEEDS_DECISION':
947
956
  print('forge: ' + name + ' is not resumed: it is at its attempt cap and waits for your decision',
@@ -984,7 +993,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
984
993
  if name not in pairs_cache:
985
994
  row = row_now(name)
986
995
  qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
987
- ['/bin/bash', script, '_qa_only', str(plan), name],
996
+ [forge_proc.bash_executable(), script, '_qa_only', str(plan), name],
988
997
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
989
998
  specs = [row[5]] if qa_only or row[4] == 'script' else [row[4], row[5]]
990
999
  pairs_cache[name] = [spec_pair(registry, spec) for spec in specs]
@@ -1012,7 +1021,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1012
1021
  # The implementer's pair when it is held (a full dispatch), else the reviewer's.
1013
1022
  role = 'dwarf' if len(pairs) == 2 and any(holds(pause, pairs[:1]) for pause in holding) else 'qa'
1014
1023
  excluded = {(pause['harness'], pause['model'] or '*') for pause in pauses.values()}
1015
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
1024
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--fallback',
1016
1025
  ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', holding[0]['class']]
1017
1026
  if role == 'qa':
1018
1027
  command += ['--role', 'qa']
@@ -1065,7 +1074,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1065
1074
  return False
1066
1075
  excluded = {(info['harness'], info['model'] if scope.startswith('model:') else '*')}
1067
1076
  excluded.update((p['harness'], p['model'] or '*') for p in pauses.values())
1068
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
1077
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--fallback',
1069
1078
  ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', cause]
1070
1079
  if stage == 'qa':
1071
1080
  command += ['--role', 'qa']
@@ -1101,7 +1110,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1101
1110
  def backoff() -> tuple:
1102
1111
  """The plan's infra_backoff, read at every wait so a change applies to the next one."""
1103
1112
  try:
1104
- fd = os.open(_resolve(plan, 'infra_backoff'), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1113
+ fd = forge_posix.open_nofollow(
1114
+ _resolve(plan, 'infra_backoff'),
1115
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
1116
+ )
1105
1117
  try:
1106
1118
  text = os.read(fd, 4097).decode('ascii').strip()
1107
1119
  finally:
@@ -1315,7 +1327,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1315
1327
  if not _write_atomic(plan, answer + '\n', 'tasks', name, 'answer.md'):
1316
1328
  return 'refused', 'the answer could not be written to tasks/' + name + '/answer.md'
1317
1329
  # A STALE task spent no attempt: it is prepared with the new prompt, not as a failed one (#150).
1318
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (
1330
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name] + (
1319
1331
  ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1320
1332
  rc = subprocess.run(command).returncode
1321
1333
  if rc == 3:
@@ -1377,7 +1389,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1377
1389
  summary_seen[name] = summary_signature(name) # before it runs: its first change must trigger
1378
1390
  except Exception:
1379
1391
  pass
1380
- if subprocess.run(['/bin/bash', script, '_waves', str(plan)]).returncode:
1392
+ if subprocess.run([forge_proc.bash_executable(), script, '_waves', str(plan)]).returncode:
1381
1393
  _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
1382
1394
  return 'applied', None
1383
1395
 
@@ -1398,7 +1410,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1398
1410
  return 'refused', ('a ' + state + ' task has no reviewer verdict to override: accept takes a FAIL, '
1399
1411
  'UNKNOWN or NEEDS_DECISION task')
1400
1412
  env = dict(os.environ, FORGE_ACCEPT_ACTOR=request.get('actor') or 'cli')
1401
- result = subprocess.run(['/bin/bash', script, '_accept', str(plan), name, '--reason', reason, '--approved'],
1413
+ result = subprocess.run([forge_proc.bash_executable(), script, '_accept', str(plan), name, '--reason', reason, '--approved'],
1402
1414
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env)
1403
1415
  lines = [line for line in result.stdout.splitlines() if line.strip()]
1404
1416
  if result.returncode:
@@ -1482,7 +1494,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1482
1494
  wrong here ends the run without a sweep, never with a failure."""
1483
1495
  nonlocal sweep_asked
1484
1496
  sweep_asked = True
1485
- command = ['/bin/bash', script, '_sweep', str(plan), '--severity', sweep, '--max', str(sweep_max)]
1497
+ command = [forge_proc.bash_executable(), script, '_sweep', str(plan), '--severity', sweep, '--max', str(sweep_max)]
1486
1498
  result = subprocess.run(command + (['--plausible'] if sweep_plausible else []),
1487
1499
  stdout=subprocess.PIPE, text=True)
1488
1500
  if result.returncode:
@@ -1523,7 +1535,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1523
1535
  def gread(gid: str, name: str) -> str:
1524
1536
  """A short file of the group's dir, stripped; empty when missing or unsafe."""
1525
1537
  try:
1526
- fd = os.open(_resolve(plan, 'groups', gid, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1538
+ fd = forge_posix.open_nofollow(
1539
+ _resolve(plan, 'groups', gid, name),
1540
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
1541
+ )
1527
1542
  try:
1528
1543
  return os.read(fd, 4097).decode('utf-8', 'replace').strip()
1529
1544
  finally:
@@ -1572,8 +1587,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1572
1587
  root.mkdir(parents=True, exist_ok=True)
1573
1588
  log = open(root / 'group.out', 'ab')
1574
1589
  process = subprocess.Popen(
1575
- ['/bin/bash', script, '_group', str(plan), gid],
1576
- stdout=log, stderr=subprocess.STDOUT, start_new_session=True,
1590
+ forge_proc.bash_cmd(script, '_group', str(plan), gid),
1591
+ stdout=log, stderr=subprocess.STDOUT, **forge_proc.popen_group_kwargs(),
1577
1592
  )
1578
1593
  active[GROUP_KEY + gid] = process, log
1579
1594
  group_again.discard(gid)
@@ -1595,7 +1610,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1595
1610
 
1596
1611
  def group_line(gid: str) -> None:
1597
1612
  """Say what a group that waits for a person (or the next run) waits for: _group_settle's own line."""
1598
- subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1613
+ subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1599
1614
 
1600
1615
  def requeue_members(gid: str) -> None:
1601
1616
  """Every member now in AUTO_RETRY and retryable goes back through the ordinary requeue: its budget,
@@ -1607,7 +1622,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1607
1622
  def merge_group(gid: str, requeue_ok: bool = True) -> None:
1608
1623
  # _merge_group flags each merged member's dependents itself (forge_brief_stale), so a direct call
1609
1624
  # behaves the same; the scheduler does not do it a second time.
1610
- result = subprocess.run(['/bin/bash', script, '_merge_group', str(plan), gid])
1625
+ result = subprocess.run([forge_proc.bash_executable(), script, '_merge_group', str(plan), gid])
1611
1626
  if result.returncode != 0 and requeue_ok and not interrupted and not graceful:
1612
1627
  requeue_members(gid) # a member the merge invalidated, when its review is what was voided
1613
1628
 
@@ -1637,7 +1652,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1637
1652
  merge_group(gid, going)
1638
1653
  elif state == 'FAIL':
1639
1654
  if not interrupted:
1640
- result = subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1655
+ result = subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1641
1656
  if result.returncode:
1642
1657
  _warn('group ' + gid + ' could not be settled (exit ' + str(result.returncode)
1643
1658
  + '); its members stay IMPLEMENTED')
@@ -1730,12 +1745,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1730
1745
  that process is gone: the run is ending and the earlier summarize of this task still holds its lock."""
1731
1746
  command = [sys.executable, os.environ.get('FORGE_SUMMARIZE') or SUMMARIZE, str(plan), '--task', name]
1732
1747
  if after is not None:
1733
- command = ['/bin/sh', '-c', 'while kill -0 "$0" 2>/dev/null; do sleep 1; done; exec "$@"',
1734
- str(after)] + command
1748
+ if forge_proc.IS_WINDOWS:
1749
+ waiter = ('import os, subprocess, sys, time; sys.path.insert(0, sys.argv[1]); '
1750
+ 'import forge_proc\n'
1751
+ 'pid = int(sys.argv[2])\n'
1752
+ 'while forge_proc.pid_alive(pid): time.sleep(1)\n'
1753
+ 'sys.exit(subprocess.run(sys.argv[3:]).returncode)')
1754
+ command = [sys.executable, '-c', waiter, str(Path(__file__).resolve().parent), str(after), *command]
1755
+ else:
1756
+ command = ['/bin/sh', '-c', 'while kill -0 "$0" 2>/dev/null; do sleep 1; done; exec "$@"',
1757
+ str(after)] + command
1735
1758
  out = open(plan / 'summaries.out', 'ab')
1736
1759
  try:
1737
1760
  process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
1738
- start_new_session=True)
1761
+ **forge_proc.popen_group_kwargs(detached=True))
1739
1762
  finally:
1740
1763
  out.close()
1741
1764
  summary_procs[name] = process
@@ -1845,7 +1868,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1845
1868
  if state == 'PASS':
1846
1869
  merge_group(gid)
1847
1870
  elif state == 'FAIL' and not gsettled(gid) and not interrupted:
1848
- subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1871
+ subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1849
1872
  requeue_members(gid)
1850
1873
  elif state in ('INTERRUPTED', 'INFRA', 'TIMEOUT'):
1851
1874
  group_again.add(gid)
@@ -1960,8 +1983,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1960
1983
  human.discard(name)
1961
1984
  _remove(plan, 'tasks', name, 'retry.prepared')
1962
1985
  process = subprocess.Popen(
1963
- ['/bin/bash', script, '_task', str(plan), name],
1964
- stdout=log, stderr=subprocess.STDOUT, start_new_session=True, env=env,
1986
+ forge_proc.bash_cmd(script, '_task', str(plan), name),
1987
+ stdout=log, stderr=subprocess.STDOUT, env=env, **forge_proc.popen_group_kwargs(),
1965
1988
  )
1966
1989
  active[name] = process, log
1967
1990
  pending.remove(name)
@@ -2004,10 +2027,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2004
2027
  reap_exited(allow_requeue=False)
2005
2028
  stopping = list(active.items())
2006
2029
  for name, (process, log) in stopping:
2007
- try:
2008
- os.killpg(process.pid, signal.SIGTERM)
2009
- except OSError:
2010
- pass
2030
+ forge_proc.kill_tree(process.pid, force=False)
2011
2031
  # The group outlives its leader while dispatch's EXIT trap stops the harness, so wait
2012
2032
  # for the group to empty, not for the leader. Reaping the leader matters too: its
2013
2033
  # zombie would keep the group alive.
@@ -2024,10 +2044,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2024
2044
  time.sleep(0.05)
2025
2045
  for name, (process, log) in stopping:
2026
2046
  if name in waiting:
2027
- try:
2028
- os.killpg(process.pid, signal.SIGKILL)
2029
- except OSError:
2030
- pass
2047
+ forge_proc.kill_tree(process.pid, force=True)
2031
2048
  try:
2032
2049
  process.wait(timeout=5)
2033
2050
  except subprocess.TimeoutExpired:
@@ -2104,7 +2121,7 @@ def main() -> None:
2104
2121
  # Who holds it, for the next command the lock refuses. exec keeps this pid.
2105
2122
  _write_atomic(plan, json.dumps(dict(pid=os.getpid(), command=command, at=time.time())) + '\n', HOLDER)
2106
2123
  env = dict(os.environ, FORGE_PLAN_LOCK=plan)
2107
- os.execve('/bin/bash', ['/bin/bash', script, command, plan, *args], env)
2124
+ forge_proc.exec_or_exit(forge_proc.bash_cmd(script, command, plan, *args), env=env, inherit_fds=True)
2108
2125
  parser = argparse.ArgumentParser(prog='forge-schedule.py')
2109
2126
  parser.add_argument('script')
2110
2127
  parser.add_argument('plan')
@@ -46,6 +46,11 @@ import tempfile
46
46
  import time
47
47
  from pathlib import Path
48
48
 
49
+ _SCRIPTS = str(Path(__file__).resolve().parent)
50
+ if _SCRIPTS not in sys.path:
51
+ sys.path.insert(0, _SCRIPTS)
52
+ import forge_proc # noqa: E402
53
+
49
54
  SCRIPTS = Path(__file__).resolve().parent
50
55
  DISPATCH = SCRIPTS / 'forge-dispatch.sh'
51
56
  ARTIFACT = SCRIPTS / 'forge-artifact.sh'
@@ -125,8 +130,9 @@ def resolution(spec: str) -> tuple | None:
125
130
  prompt = Path(tmp) / 'input'
126
131
  prompt.write_text('Offline resolution')
127
132
  try:
128
- out = subprocess.run(['/bin/bash', str(DISPATCH), 'qa', spec, '--run-dir', tmp, '--prompt-file',
129
- str(prompt), '--dry-run'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
133
+ out = subprocess.run(forge_proc.bash_cmd(DISPATCH, 'qa', spec, '--run-dir', tmp, '--prompt-file',
134
+ prompt, '--dry-run'),
135
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
130
136
  timeout=60, text=True)
131
137
  except (OSError, subprocess.SubprocessError):
132
138
  return None
@@ -183,7 +189,7 @@ def fresh_dir(base: Path, attempt: str) -> Path:
183
189
 
184
190
 
185
191
  def bash(function: str, *args) -> subprocess.CompletedProcess:
186
- return subprocess.run(['/bin/bash', '-c', 'source "$1"; shift; "$@"', '_', str(ARTIFACT), function, *args],
192
+ return subprocess.run(forge_proc.bash_cmd('-c', 'source "$1"; shift; "$@"', '_', str(ARTIFACT), function, *args),
187
193
  stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=PREPARE_TIMEOUT_S)
188
194
 
189
195
 
@@ -229,7 +235,7 @@ def _stop(_signum, _frame):
229
235
  def run(args) -> int:
230
236
  # First, before anything slow: the task may signal that its review finished at any time,
231
237
  # and SIGUSR1's default action would kill a launcher that is still preparing.
232
- signal.signal(signal.SIGUSR1, _primary_done)
238
+ forge_proc.install_signal(forge_proc.SIGUSR1, _primary_done)
233
239
  signal.signal(signal.SIGTERM, _stop)
234
240
  plan = Path(args.plan)
235
241
  parent = os.getppid()
@@ -254,10 +260,11 @@ def run(args) -> int:
254
260
  shutil.copyfile(Path(args.tdir) / 'qa.input', out / 'qa.input')
255
261
  env = dict(os.environ, FORGE_SHADOW='1', FORGE_SHADOW_ATTEMPT=args.attempt,
256
262
  FORGE_SHADOW_REVIEWED=args.reviewed, FORGE_SHADOW_FROM=args.qa)
257
- argv = ['/bin/bash', str(DISPATCH), 'qa', spec, '--repo', str(review), '--run-dir', str(out),
258
- '--review-base', (out / 'review.base').read_text().strip(),
259
- '--ripwire-query-file', str(Path(args.tdir) / 'prompt.md'), '--prompt-file', str(out / 'qa.input'),
260
- '--output', 'summary']
263
+ argv = forge_proc.bash_cmd(DISPATCH, 'qa', spec, '--repo', str(review), '--run-dir', str(out),
264
+ '--review-base', (out / 'review.base').read_text().strip(),
265
+ '--ripwire-query-file', str(Path(args.tdir) / 'prompt.md'),
266
+ '--prompt-file', str(out / 'qa.input'),
267
+ '--output', 'summary')
261
268
  if args.yolo:
262
269
  argv.append('--yolo')
263
270
  argv.extend(service_tier_args(plan, 'qa'))
@@ -331,7 +338,7 @@ def preflight(args) -> int:
331
338
  flags = ['--yolo'] if (plan / 'yolo_qa').exists() else []
332
339
  flags.extend(service_tier_args(plan, 'qa'))
333
340
  try:
334
- result = subprocess.run(['/bin/bash', str(DISPATCH), 'doctor', '--spec', spec, '--role', 'qa', *flags],
341
+ result = subprocess.run(forge_proc.bash_cmd(DISPATCH, 'doctor', '--spec', spec, '--role', 'qa', *flags),
335
342
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=120, text=True)
336
343
  except (OSError, subprocess.SubprocessError):
337
344
  print('forge: shadow review spec %s is not usable here; it is skipped' % spec, file=sys.stderr)
@@ -29,9 +29,9 @@ import sys
29
29
  import tempfile
30
30
  import time
31
31
 
32
- import fcntl
33
-
34
32
  sys.path.insert(0, str(Path(__file__).resolve().parent))
33
+ import forge_flock as fcntl # noqa: E402
34
+ import forge_posix # noqa: E402
35
35
  import forge_side # noqa: E402
36
36
 
37
37
  # The facts the model sees. 8 KB, the same cut forge uses for a reply it carries forward.
@@ -576,7 +576,11 @@ def _lock(task_dir: Path):
576
576
  """
577
577
  task_dir.mkdir(parents=True, exist_ok=True)
578
578
  try:
579
- fd = os.open(task_dir / 'summary.lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o644)
579
+ fd = forge_posix.open_nofollow(
580
+ task_dir / 'summary.lock',
581
+ os.O_CREAT | os.O_RDWR | forge_posix.O_NOFOLLOW,
582
+ 0o644,
583
+ )
580
584
  except OSError:
581
585
  return None
582
586
  try:
@@ -48,7 +48,6 @@ from __future__ import annotations
48
48
 
49
49
  import argparse
50
50
  import contextlib
51
- import fcntl
52
51
  import importlib.util
53
52
  import json
54
53
  import os
@@ -63,6 +62,8 @@ import time
63
62
  SCRIPTS = Path(__file__).resolve().parent
64
63
  if str(SCRIPTS) not in sys.path:
65
64
  sys.path.insert(0, str(SCRIPTS))
65
+ import forge_flock as fcntl # noqa: E402
66
+ import forge_posix # noqa: E402
66
67
  SEVERITIES = ('P0', 'P1', 'P2', 'P3')
67
68
  DEFAULT_MAX = 5 # fix tasks one sweep may add
68
69
  GROUP_CAP = 8 # findings one fix task is given; the rest of its file stays for forge issues
@@ -127,7 +128,11 @@ def write_atomic(path: Path, text: str) -> None:
127
128
  def control_lock(plan: Path):
128
129
  """The plan's control.lock, as `forge control` takes it, around a tasks.tsv rewrite. Busy for
129
130
  LOCK_WAIT seconds: proceed without it, as the scheduler does."""
130
- fd = os.open(str(plan / 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644)
131
+ fd = forge_posix.open_nofollow(
132
+ str(plan / 'control.lock'),
133
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW,
134
+ 0o644,
135
+ )
131
136
  try:
132
137
  deadline = time.monotonic() + LOCK_WAIT
133
138
  while True:
@@ -17,7 +17,6 @@ from __future__ import annotations
17
17
 
18
18
  import argparse
19
19
  import errno
20
- import fcntl
21
20
  import http.client
22
21
  import json
23
22
  import os
@@ -36,6 +35,9 @@ SKILL = Path(__file__).resolve().parent.parent
36
35
  # `-I` keeps the script's own directory off sys.path, so both are added by hand.
37
36
  sys.path.insert(0, str(SKILL / 'scripts'))
38
37
  sys.path.insert(0, str(SKILL / 'ui'))
38
+ import forge_flock as fcntl # noqa: E402
39
+ import forge_posix # noqa: E402
40
+ import forge_proc # noqa: E402
39
41
 
40
42
  HOST = '127.0.0.1'
41
43
  LISTENING = re.compile(r'^forge-ui on http://127\.0\.0\.1:(\d+)/', re.M)
@@ -71,15 +73,7 @@ def _env_int(name, default):
71
73
 
72
74
 
73
75
  def pid_alive(pid) -> bool:
74
- if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 1:
75
- return False
76
- try:
77
- os.kill(pid, 0)
78
- except (ProcessLookupError, OverflowError): # OverflowError: no process can have that pid
79
- return False
80
- except PermissionError:
81
- return True
82
- return True
76
+ return forge_proc.pid_alive(pid, min_pid=2)
83
77
 
84
78
 
85
79
  def wait_dead(pid, seconds) -> bool:
@@ -114,7 +108,7 @@ def open_regular(path, flags):
114
108
 
115
109
  O_NONBLOCK: a FIFO or device planted at one of our paths must fail, never block.
116
110
  """
117
- fd = os.open(path, flags | os.O_NONBLOCK | os.O_CLOEXEC, 0o644)
111
+ fd = os.open(path, flags | forge_posix.O_NONBLOCK | forge_posix.O_CLOEXEC, 0o644)
118
112
  if not stat.S_ISREG(os.fstat(fd).st_mode):
119
113
  os.close(fd)
120
114
  raise OSError(errno.EINVAL, 'not a regular file', str(path))
@@ -216,7 +210,7 @@ def _spawn(state, port, registry, idle, read_only=False, cli_env=None):
216
210
  command.append('--read-only')
217
211
  with os.fdopen(open_regular(log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 'w') as out:
218
212
  proc = subprocess.Popen(command, cwd=str(state), stdin=subprocess.DEVNULL, stdout=out, stderr=out,
219
- start_new_session=True, close_fds=True, env=env)
213
+ close_fds=True, env=env, **forge_proc.popen_group_kwargs(detached=True))
220
214
  deadline = time.monotonic() + START_WAIT_S
221
215
  while time.monotonic() < deadline:
222
216
  try:
@@ -263,7 +257,8 @@ def launch_browser(url):
263
257
  command = [sys.executable, '-I', str(Path(__file__).resolve()), '_browse', url]
264
258
  try:
265
259
  proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
266
- stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True)
260
+ stderr=subprocess.DEVNULL, close_fds=True,
261
+ **forge_proc.popen_group_kwargs(detached=True))
267
262
  proc.wait(BROWSER_WAIT_S)
268
263
  except subprocess.TimeoutExpired:
269
264
  pass # still starting its browser: leave it