@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
@@ -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:
@@ -703,6 +709,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
703
709
  raise ValueError('task ' + GROUP_KEY + g.id + ' clashes with group ' + g.id)
704
710
  group_of = {m: g.id for g in rgroups.values() for m in g.members} # member -> its review group
705
711
  active = {} # task id, or GROUP_KEY + gid for a running group review
712
+ task_jobs: dict[str, forge_proc.ProcessJob] = {}
713
+
714
+ def _track_job(key: str, pid: int) -> None:
715
+ job = forge_proc.ProcessJob()
716
+ if job.attach(pid):
717
+ task_jobs[key] = job
706
718
  pending = list(tasks)
707
719
  interrupted = False
708
720
  group_again = set() # groups to review once more whatever their status says (a resume, an UNKNOWN)
@@ -740,7 +752,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
740
752
  brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
741
753
  brief_told = set() # (task, qid or '') whose brief wait was already printed
742
754
  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
755
+ # When the writer was last looked at, and what was seen. -inf, not 0.0: time.monotonic() has no
756
+ # defined start, and where it is small (seen with Python 3.9 on a macOS runner) the first look
757
+ # was skipped and a task dispatched as if the writer had already gone.
758
+ brief_alive = [float('-inf'), False]
744
759
 
745
760
  def status(name: str) -> str:
746
761
  root = plan / 'tasks' / name
@@ -754,7 +769,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
754
769
  dataset_event('sched_terminal', plan, name, dict(status=state))
755
770
 
756
771
  def merge(name: str) -> None:
757
- result = subprocess.run(['/bin/bash', script, '_merge', str(plan), name])
772
+ result = subprocess.run([forge_proc.bash_executable(), script, '_merge', str(plan), name])
758
773
  if result.returncode and status(name) == 'PASS':
759
774
  mark(name, 'ERROR')
760
775
  elif brief_mode != 'off' and status(name) == 'MERGED':
@@ -882,7 +897,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
882
897
  def requeue(name: str) -> bool:
883
898
  """Prepare a retry exactly as `retry` does, then put the task at the queue head. A task at its
884
899
  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])
900
+ result = subprocess.run([forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name])
886
901
  if result.returncode:
887
902
  refused[name] = budget(name)
888
903
  return False
@@ -914,7 +929,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
914
929
  def prompt_requeue(name: str) -> bool:
915
930
  """Re-dispatch a STALE task (its prompt changed while the attempt ran, #150) with the new text. The stale
916
931
  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'])
932
+ result = subprocess.run([forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--prompt'])
918
933
  if result.returncode:
919
934
  print('forge: ' + name + ' is not re-dispatched: its changed prompt could not be prepared',
920
935
  file=sys.stderr, flush=True)
@@ -941,7 +956,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
941
956
  either: _prepare_retry --resume stops it for a decision, and it leaves the queue."""
942
957
  if not _pinned(plan, name) and not at_cap(name):
943
958
  return True
944
- result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--resume'])
959
+ result = subprocess.run([forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--resume'])
945
960
  if result.returncode:
946
961
  if status(name) == 'NEEDS_DECISION':
947
962
  print('forge: ' + name + ' is not resumed: it is at its attempt cap and waits for your decision',
@@ -984,7 +999,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
984
999
  if name not in pairs_cache:
985
1000
  row = row_now(name)
986
1001
  qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
987
- ['/bin/bash', script, '_qa_only', str(plan), name],
1002
+ [forge_proc.bash_executable(), script, '_qa_only', str(plan), name],
988
1003
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
989
1004
  specs = [row[5]] if qa_only or row[4] == 'script' else [row[4], row[5]]
990
1005
  pairs_cache[name] = [spec_pair(registry, spec) for spec in specs]
@@ -1012,7 +1027,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1012
1027
  # The implementer's pair when it is held (a full dispatch), else the reviewer's.
1013
1028
  role = 'dwarf' if len(pairs) == 2 and any(holds(pause, pairs[:1]) for pause in holding) else 'qa'
1014
1029
  excluded = {(pause['harness'], pause['model'] or '*') for pause in pauses.values()}
1015
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
1030
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--fallback',
1016
1031
  ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', holding[0]['class']]
1017
1032
  if role == 'qa':
1018
1033
  command += ['--role', 'qa']
@@ -1065,7 +1080,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1065
1080
  return False
1066
1081
  excluded = {(info['harness'], info['model'] if scope.startswith('model:') else '*')}
1067
1082
  excluded.update((p['harness'], p['model'] or '*') for p in pauses.values())
1068
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
1083
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--fallback',
1069
1084
  ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', cause]
1070
1085
  if stage == 'qa':
1071
1086
  command += ['--role', 'qa']
@@ -1101,7 +1116,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1101
1116
  def backoff() -> tuple:
1102
1117
  """The plan's infra_backoff, read at every wait so a change applies to the next one."""
1103
1118
  try:
1104
- fd = os.open(_resolve(plan, 'infra_backoff'), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1119
+ fd = forge_posix.open_nofollow(
1120
+ _resolve(plan, 'infra_backoff'),
1121
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
1122
+ )
1105
1123
  try:
1106
1124
  text = os.read(fd, 4097).decode('ascii').strip()
1107
1125
  finally:
@@ -1315,7 +1333,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1315
1333
  if not _write_atomic(plan, answer + '\n', 'tasks', name, 'answer.md'):
1316
1334
  return 'refused', 'the answer could not be written to tasks/' + name + '/answer.md'
1317
1335
  # 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] + (
1336
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name] + (
1319
1337
  ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1320
1338
  rc = subprocess.run(command).returncode
1321
1339
  if rc == 3:
@@ -1377,7 +1395,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1377
1395
  summary_seen[name] = summary_signature(name) # before it runs: its first change must trigger
1378
1396
  except Exception:
1379
1397
  pass
1380
- if subprocess.run(['/bin/bash', script, '_waves', str(plan)]).returncode:
1398
+ if subprocess.run([forge_proc.bash_executable(), script, '_waves', str(plan)]).returncode:
1381
1399
  _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
1382
1400
  return 'applied', None
1383
1401
 
@@ -1398,7 +1416,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1398
1416
  return 'refused', ('a ' + state + ' task has no reviewer verdict to override: accept takes a FAIL, '
1399
1417
  'UNKNOWN or NEEDS_DECISION task')
1400
1418
  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'],
1419
+ result = subprocess.run([forge_proc.bash_executable(), script, '_accept', str(plan), name, '--reason', reason, '--approved'],
1402
1420
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env)
1403
1421
  lines = [line for line in result.stdout.splitlines() if line.strip()]
1404
1422
  if result.returncode:
@@ -1482,7 +1500,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1482
1500
  wrong here ends the run without a sweep, never with a failure."""
1483
1501
  nonlocal sweep_asked
1484
1502
  sweep_asked = True
1485
- command = ['/bin/bash', script, '_sweep', str(plan), '--severity', sweep, '--max', str(sweep_max)]
1503
+ command = [forge_proc.bash_executable(), script, '_sweep', str(plan), '--severity', sweep, '--max', str(sweep_max)]
1486
1504
  result = subprocess.run(command + (['--plausible'] if sweep_plausible else []),
1487
1505
  stdout=subprocess.PIPE, text=True)
1488
1506
  if result.returncode:
@@ -1523,7 +1541,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1523
1541
  def gread(gid: str, name: str) -> str:
1524
1542
  """A short file of the group's dir, stripped; empty when missing or unsafe."""
1525
1543
  try:
1526
- fd = os.open(_resolve(plan, 'groups', gid, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1544
+ fd = forge_posix.open_nofollow(
1545
+ _resolve(plan, 'groups', gid, name),
1546
+ os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
1547
+ )
1527
1548
  try:
1528
1549
  return os.read(fd, 4097).decode('utf-8', 'replace').strip()
1529
1550
  finally:
@@ -1572,10 +1593,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1572
1593
  root.mkdir(parents=True, exist_ok=True)
1573
1594
  log = open(root / 'group.out', 'ab')
1574
1595
  process = subprocess.Popen(
1575
- ['/bin/bash', script, '_group', str(plan), gid],
1576
- stdout=log, stderr=subprocess.STDOUT, start_new_session=True,
1596
+ forge_proc.bash_cmd(script, '_group', str(plan), gid),
1597
+ stdout=log, stderr=subprocess.STDOUT, **forge_proc.popen_group_kwargs(),
1577
1598
  )
1578
1599
  active[GROUP_KEY + gid] = process, log
1600
+ _track_job(GROUP_KEY + gid, process.pid)
1579
1601
  group_again.discard(gid)
1580
1602
  print('forge: reviewing group ' + gid + ' (' + ', '.join(rgroups[gid].members) + ')',
1581
1603
  file=sys.stderr, flush=True)
@@ -1595,7 +1617,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1595
1617
 
1596
1618
  def group_line(gid: str) -> None:
1597
1619
  """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])
1620
+ subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1599
1621
 
1600
1622
  def requeue_members(gid: str) -> None:
1601
1623
  """Every member now in AUTO_RETRY and retryable goes back through the ordinary requeue: its budget,
@@ -1607,7 +1629,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1607
1629
  def merge_group(gid: str, requeue_ok: bool = True) -> None:
1608
1630
  # _merge_group flags each merged member's dependents itself (forge_brief_stale), so a direct call
1609
1631
  # behaves the same; the scheduler does not do it a second time.
1610
- result = subprocess.run(['/bin/bash', script, '_merge_group', str(plan), gid])
1632
+ result = subprocess.run([forge_proc.bash_executable(), script, '_merge_group', str(plan), gid])
1611
1633
  if result.returncode != 0 and requeue_ok and not interrupted and not graceful:
1612
1634
  requeue_members(gid) # a member the merge invalidated, when its review is what was voided
1613
1635
 
@@ -1637,7 +1659,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1637
1659
  merge_group(gid, going)
1638
1660
  elif state == 'FAIL':
1639
1661
  if not interrupted:
1640
- result = subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1662
+ result = subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1641
1663
  if result.returncode:
1642
1664
  _warn('group ' + gid + ' could not be settled (exit ' + str(result.returncode)
1643
1665
  + '); its members stay IMPLEMENTED')
@@ -1682,6 +1704,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1682
1704
  into.add(name)
1683
1705
  log.close()
1684
1706
  del active[name]
1707
+ job = task_jobs.pop(name, None)
1708
+ if job is not None:
1709
+ job.disarm()
1710
+ job.close()
1685
1711
  if name.startswith(GROUP_KEY) and name not in tasks:
1686
1712
  gid = name[len(GROUP_KEY):]
1687
1713
  if os.environ.get('FORGE_OUTPUT') == 'full':
@@ -1730,12 +1756,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1730
1756
  that process is gone: the run is ending and the earlier summarize of this task still holds its lock."""
1731
1757
  command = [sys.executable, os.environ.get('FORGE_SUMMARIZE') or SUMMARIZE, str(plan), '--task', name]
1732
1758
  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
1759
+ if forge_proc.IS_WINDOWS:
1760
+ waiter = ('import os, subprocess, sys, time; sys.path.insert(0, sys.argv[1]); '
1761
+ 'import forge_proc\n'
1762
+ 'pid = int(sys.argv[2])\n'
1763
+ 'while forge_proc.pid_alive(pid): time.sleep(1)\n'
1764
+ 'sys.exit(subprocess.run(sys.argv[3:]).returncode)')
1765
+ command = [sys.executable, '-c', waiter, str(Path(__file__).resolve().parent), str(after), *command]
1766
+ else:
1767
+ command = ['/bin/sh', '-c', 'while kill -0 "$0" 2>/dev/null; do sleep 1; done; exec "$@"',
1768
+ str(after)] + command
1735
1769
  out = open(plan / 'summaries.out', 'ab')
1736
1770
  try:
1737
1771
  process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
1738
- start_new_session=True)
1772
+ **forge_proc.popen_group_kwargs(detached=True))
1739
1773
  finally:
1740
1774
  out.close()
1741
1775
  summary_procs[name] = process
@@ -1809,6 +1843,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1809
1843
 
1810
1844
  signal.signal(signal.SIGTERM, stop)
1811
1845
  signal.signal(signal.SIGINT, stop)
1846
+ forge_proc.install_signal(forge_proc.SIGBREAK, stop)
1812
1847
  try:
1813
1848
  live_start(plan, tasks, retry_failed, infra_retries, rgroups)
1814
1849
  summaries_on_change()
@@ -1845,7 +1880,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1845
1880
  if state == 'PASS':
1846
1881
  merge_group(gid)
1847
1882
  elif state == 'FAIL' and not gsettled(gid) and not interrupted:
1848
- subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1883
+ subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1849
1884
  requeue_members(gid)
1850
1885
  elif state in ('INTERRUPTED', 'INFRA', 'TIMEOUT'):
1851
1886
  group_again.add(gid)
@@ -1948,7 +1983,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1948
1983
  continue
1949
1984
  root = plan / 'tasks' / name
1950
1985
  if not (root / 'base_ref').exists():
1951
- worktree = Path((plan / 'wt_root').read_text().strip()) / '_integration'
1986
+ worktree = Path(forge_posix.host_path((plan / 'wt_root').read_text().strip())) / '_integration'
1952
1987
  base = subprocess.check_output(['git', '-C', str(worktree), 'rev-parse', 'HEAD'])
1953
1988
  (root / 'base_ref').write_bytes(base)
1954
1989
  log = open(root / 'task.out', 'ab')
@@ -1960,10 +1995,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1960
1995
  human.discard(name)
1961
1996
  _remove(plan, 'tasks', name, 'retry.prepared')
1962
1997
  process = subprocess.Popen(
1963
- ['/bin/bash', script, '_task', str(plan), name],
1964
- stdout=log, stderr=subprocess.STDOUT, start_new_session=True, env=env,
1998
+ forge_proc.bash_cmd(script, '_task', str(plan), name),
1999
+ stdout=log, stderr=subprocess.STDOUT, env=env, **forge_proc.popen_group_kwargs(),
1965
2000
  )
1966
2001
  active[name] = process, log
2002
+ _track_job(name, process.pid)
1967
2003
  pending.remove(name)
1968
2004
  print('forge: dispatched ' + name + ' -> ' + str(root), file=sys.stderr, flush=True)
1969
2005
  if not active and graceful:
@@ -2004,10 +2040,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2004
2040
  reap_exited(allow_requeue=False)
2005
2041
  stopping = list(active.items())
2006
2042
  for name, (process, log) in stopping:
2007
- try:
2008
- os.killpg(process.pid, signal.SIGTERM)
2009
- except OSError:
2010
- pass
2043
+ forge_proc.kill_tree(process.pid, force=False)
2011
2044
  # The group outlives its leader while dispatch's EXIT trap stops the harness, so wait
2012
2045
  # for the group to empty, not for the leader. Reaping the leader matters too: its
2013
2046
  # zombie would keep the group alive.
@@ -2024,10 +2057,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2024
2057
  time.sleep(0.05)
2025
2058
  for name, (process, log) in stopping:
2026
2059
  if name in waiting:
2027
- try:
2028
- os.killpg(process.pid, signal.SIGKILL)
2029
- except OSError:
2030
- pass
2060
+ forge_proc.kill_tree(process.pid, force=True)
2061
+ job = task_jobs.pop(name, None)
2062
+ if job is not None:
2063
+ job.terminate()
2064
+ job.close()
2031
2065
  try:
2032
2066
  process.wait(timeout=5)
2033
2067
  except subprocess.TimeoutExpired:
@@ -2104,7 +2138,7 @@ def main() -> None:
2104
2138
  # Who holds it, for the next command the lock refuses. exec keeps this pid.
2105
2139
  _write_atomic(plan, json.dumps(dict(pid=os.getpid(), command=command, at=time.time())) + '\n', HOLDER)
2106
2140
  env = dict(os.environ, FORGE_PLAN_LOCK=plan)
2107
- os.execve('/bin/bash', ['/bin/bash', script, command, plan, *args], env)
2141
+ forge_proc.exec_or_exit(forge_proc.bash_cmd(script, command, plan, *args), env=env, inherit_fds=True)
2108
2142
  parser = argparse.ArgumentParser(prog='forge-schedule.py')
2109
2143
  parser.add_argument('script')
2110
2144
  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)
@@ -48,6 +48,10 @@
48
48
  set -uo pipefail
49
49
 
50
50
  SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
51
+ # Windows: re-run inside MSYS2 when started from Git Bash (no-op elsewhere).
52
+ . "$SKILL_DIR/scripts/forge-win.sh"
53
+ source "$SKILL_DIR/scripts/forge-lib-env.sh"
54
+ forge_ensure_python3
51
55
  DISPATCH="$SKILL_DIR/scripts/forge-dispatch.sh"
52
56
  MEMORY="$SKILL_DIR/scripts/forge-memory.sh"
53
57
  source "$SKILL_DIR/scripts/forge-artifact.sh"
@@ -229,7 +233,7 @@ RUN="$(cd "$RUN" && pwd)"
229
233
  # The frozen copy, atomically. Only the process that holds the run's lock writes it (a refused
230
234
  # second start, or a dry run, must not change what an active run froze): the first pass above
231
235
  # only read and checked, and the re-exec under the lock chooses again from the same arguments.
232
- if [ "$DRY" != 1 ] && [ "${FORGE_SOLO_LOCK:-}" = "$RUN" ]; then
236
+ if [ "$DRY" != 1 ] && [ "$(forge_posix_path "${FORGE_SOLO_LOCK:-}")" = "$RUN" ]; then
233
237
  forge_profile_py solo "$RUN" --repo "$REPO" --no-validate --write ${pf_args[@]+"${pf_args[@]}"} >/dev/null || exit $?
234
238
  fi
235
239
  [ -z "$PF_LINE" ] || [ -n "${FORGE_SOLO_LOCK:-}" ] || echo "$PF_LINE"
@@ -239,7 +243,7 @@ fi
239
243
  REPO="$(cd "$REPO" && pwd)"
240
244
  # Before any decision-model step: the privacy floor and the run budget read these.
241
245
  [ "$JEV_OPTS" = 1 ] && forge_decide_env "$REPO" "$RUN"
242
- if [ "$DRY" != 1 ] && [ "${FORGE_SOLO_LOCK:-}" != "$RUN" ]; then
246
+ if [ "$DRY" != 1 ] && [ "$(forge_posix_path "${FORGE_SOLO_LOCK:-}")" != "$RUN" ]; then
243
247
  exec python3 "$SKILL_DIR/scripts/forge-fractal.py" _lock "$RUN" "$0" "${ORIGINAL_ARGS[@]}"
244
248
  fi
245
249
  # After the lock re-exec, so the process that dispatches is the one that writes it.
@@ -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:
@@ -254,7 +259,7 @@ class Context:
254
259
  def __init__(self, plan: Path):
255
260
  self.plan = plan
256
261
  self.repo = read(plan / 'repo')
257
- wt_root = read(plan / 'wt_root')
262
+ wt_root = forge_posix.host_path(read(plan / 'wt_root'))
258
263
  self.integration = os.path.join(wt_root, '_integration') if wt_root else ''
259
264
  rc, tip = git(self.integration, 'rev-parse', 'HEAD') if self.integration else (1, b'')
260
265
  self.tip = tip.decode().strip() if not rc else ''
@@ -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
@@ -2,6 +2,9 @@
2
2
  # Update the canonical checkout, then refresh each harness through the installer.
3
3
  set -uo pipefail
4
4
 
5
+ source "$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)/forge-lib-env.sh"
6
+ forge_ensure_python3
7
+
5
8
  main() {
6
9
  local source_dir dry=0 local_only=0 upstream remote branch before after changes
7
10
  source_dir="$(cd -P "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" || return 2
@@ -24,7 +27,9 @@ main() {
24
27
  fi
25
28
  echo "forge: update source: $source_dir"
26
29
  if [ "$local_only" = 0 ]; then
27
- if [ "$(git -C "$source_dir" rev-parse --show-toplevel 2>/dev/null)" != "$source_dir" ]; then
30
+ local git_top
31
+ git_top="$(git -C "$source_dir" rev-parse --show-toplevel 2>/dev/null || true)"
32
+ if [ "$(forge_posix_path "$git_top")" != "$(forge_posix_path "$source_dir")" ]; then
28
33
  case "$source_dir" in
29
34
  */node_modules/*)
30
35
  # @latest, because older npm updated a global package within ^version: never 0.7 -> 0.8.