@giamme/forge 0.19.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 (72) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +7 -0
  3. package/SKILL.md +3 -0
  4. package/VERSION +1 -1
  5. package/docs/README.md +1 -0
  6. package/docs/commands.md +137 -5
  7. package/docs/development.md +1 -1
  8. package/docs/forge-ui.md +70 -19
  9. package/forge +8 -2
  10. package/package.json +1 -1
  11. package/references/decompose.md +20 -8
  12. package/references/memory.md +30 -5
  13. package/scripts/forge-config.py +10 -9
  14. package/scripts/forge-control.py +51 -35
  15. package/scripts/forge-findings.py +675 -0
  16. package/scripts/forge-group.py +2 -1
  17. package/scripts/forge-guard.py +71 -33
  18. package/scripts/forge-handoff.py +14 -17
  19. package/scripts/forge-issues.py +233 -99
  20. package/scripts/forge-memory.sh +471 -19
  21. package/scripts/forge-parallel.sh +24 -14
  22. package/scripts/forge-planner.py +28 -2
  23. package/scripts/forge-pre-review.py +11 -4
  24. package/scripts/forge-ripwire.py +68 -22
  25. package/scripts/forge-route.py +10 -3
  26. package/scripts/forge-runs-compact.py +3 -2
  27. package/scripts/forge-runs-rm.py +14 -14
  28. package/scripts/forge-runtime.py +36 -19
  29. package/scripts/forge-schedule.py +135 -62
  30. package/scripts/forge-shadow.py +16 -9
  31. package/scripts/forge-summarize.py +7 -3
  32. package/scripts/forge-sweep.py +206 -46
  33. package/scripts/forge-ui.py +8 -13
  34. package/scripts/forge-verify.py +29 -23
  35. package/scripts/forge_brief/__init__.py +1 -1
  36. package/scripts/forge_brief/proposals.py +7 -2
  37. package/scripts/forge_decide/budget.py +6 -1
  38. package/scripts/forge_decide/replay.py +6 -1
  39. package/scripts/forge_findings/__init__.py +17 -0
  40. package/scripts/forge_findings/apply.py +442 -0
  41. package/scripts/forge_findings/status.py +43 -0
  42. package/scripts/forge_findings/store.py +595 -0
  43. package/scripts/forge_findings/tags.py +53 -0
  44. package/scripts/forge_findings/triage.py +594 -0
  45. package/scripts/forge_flock.py +87 -0
  46. package/scripts/forge_fractal/__init__.py +7 -3
  47. package/scripts/forge_fractal/cli.py +7 -2
  48. package/scripts/forge_fractal/execution.py +14 -14
  49. package/scripts/forge_fractal/invocation.py +3 -2
  50. package/scripts/forge_fractal/pipeline.py +2 -1
  51. package/scripts/forge_fractal/selection.py +2 -1
  52. package/scripts/forge_identity.py +328 -0
  53. package/scripts/forge_locations.py +14 -4
  54. package/scripts/forge_memory_list.py +7 -3
  55. package/scripts/forge_posix.py +108 -0
  56. package/scripts/forge_proc.py +399 -0
  57. package/scripts/forge_registry.py +15 -6
  58. package/scripts/forge_retro/__init__.py +8 -2
  59. package/scripts/forge_retro/issues.py +2 -1
  60. package/scripts/forge_side/__init__.py +232 -38
  61. package/scripts/forge_storage.py +11 -1
  62. package/ui/docs/api.md +130 -12
  63. package/ui/forge_ui/control.py +693 -17
  64. package/ui/forge_ui/export.py +1 -1
  65. package/ui/forge_ui/projects.py +209 -22
  66. package/ui/forge_ui/reader.py +18 -17
  67. package/ui/forge_ui/server.py +10 -1
  68. package/ui/forge_ui/static/findingsactions.js +201 -0
  69. package/ui/forge_ui/static/index.html +2 -0
  70. package/ui/forge_ui/static/projectsview.js +600 -45
  71. package/ui/forge_ui/static/style.css +59 -0
  72. package/ui/forge_ui/static/triageview.js +423 -0
@@ -13,8 +13,9 @@ Two opt-in behaviours live here, both off by default so a plain `run` is unchang
13
13
 
14
14
  A third, ``--sweep Pn``, also per invocation: once every task has merged, the open review
15
15
  findings at Pn or worse become fix tasks (``forge-parallel.sh _sweep``, forge-sweep.py) that
16
- this run then dispatches like any other, once per plan. A fix task that fails leaves its
17
- findings for ``forge issues`` and does not fail the run.
16
+ this run then dispatches like any other: one round per invocation, each finding swept once (a
17
+ rerun that merged new findings starts the next round; ``forge-sweep.py plan --check`` says whether
18
+ there is one). A fix task that fails leaves its findings for ``forge issues`` and does not fail the run.
18
19
 
19
20
  Both numbers are per invocation, but while the scheduler runs they are mirrored into the
20
21
  plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
@@ -30,7 +31,6 @@ from __future__ import annotations
30
31
  import argparse
31
32
  import contextlib
32
33
  import errno
33
- import fcntl
34
34
  import json
35
35
  import math
36
36
  import os
@@ -49,7 +49,10 @@ import time
49
49
  # forge_infra.py sits beside this file; forge-control.py loads this module by path.
50
50
  if str(Path(__file__).resolve().parent) not in sys.path:
51
51
  sys.path.insert(0, str(Path(__file__).resolve().parent))
52
+ import forge_flock as fcntl # noqa: E402
52
53
  import forge_infra # noqa: E402
54
+ import forge_posix # noqa: E402
55
+ import forge_proc # noqa: E402
53
56
 
54
57
 
55
58
  def dataset_event(name: str, plan: Path, task: str, values: dict) -> None:
@@ -303,7 +306,10 @@ def _read_budget(plan: object, *parts: str) -> int | None:
303
306
  """A non-negative integer from a control file; None when it is missing, empty, a
304
307
  symlink or anything else, so the caller falls through to its next source."""
305
308
  try:
306
- 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
+ )
307
313
  try:
308
314
  data = os.read(fd, 65)
309
315
  finally:
@@ -320,7 +326,11 @@ def _control_lock(plan: object):
320
326
  error: warn and proceed without it (yielding False), never fail the run."""
321
327
  fd = None
322
328
  try:
323
- 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
+ )
324
334
  deadline = time.monotonic() + CONTROL_LOCK_WAIT
325
335
  while True:
326
336
  try:
@@ -357,7 +367,10 @@ def _task_dirs(plan: object, names: object) -> list[str]:
357
367
  def _read_small(plan: object, name: str) -> str | None:
358
368
  """A short plan-level control file's stripped text; None when missing or unsafe."""
359
369
  try:
360
- 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
+ )
361
374
  try:
362
375
  return os.read(fd, 65).decode('ascii').strip()
363
376
  finally:
@@ -431,15 +444,7 @@ def interrupt_grace() -> float:
431
444
 
432
445
 
433
446
  def _group_alive(pgid: int) -> bool:
434
- try:
435
- os.killpg(pgid, 0)
436
- except ProcessLookupError:
437
- return False
438
- except PermissionError:
439
- return True
440
- except OSError:
441
- return False
442
- return True
447
+ return forge_proc.group_alive(pgid)
443
448
 
444
449
 
445
450
  def stop_harnesses(plan: object, names: object, groups: object = ()) -> None:
@@ -521,7 +526,10 @@ def decision_head(plan: object, name: str) -> str:
521
526
 
522
527
  def read_request(plan: object, name: str) -> dict | None:
523
528
  try:
524
- 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
+ )
525
533
  try:
526
534
  data = os.read(fd, REQUEST_MAX + 1)
527
535
  finally:
@@ -562,7 +570,11 @@ def settle_request(plan: object, name: str, request: dict | None, outcome: str,
562
570
  'previous': None, 'request': name,
563
571
  'outcome': outcome, 'reason': reason}
564
572
  try:
565
- 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
+ )
566
578
  try:
567
579
  os.write(fd, (json.dumps(entry) + '\n').encode('utf-8'))
568
580
  finally:
@@ -643,14 +655,9 @@ def brief_writer_alive(plan: object) -> bool:
643
655
  The file is removed when the writer ends, so a missing or unreadable one means it is gone."""
644
656
  try:
645
657
  pid = int((Path(plan) / 'brief.pid').read_text().split()[0])
646
- if pid <= 0:
647
- return False
648
- os.kill(pid, 0)
649
- except PermissionError:
650
- return True
651
658
  except (OSError, ValueError, IndexError):
652
659
  return False
653
- return True
660
+ return forge_proc.pid_alive(pid)
654
661
 
655
662
 
656
663
  def brief_unanswered(plan: object, name: str) -> list:
@@ -735,10 +742,14 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
735
742
  fractal = _fractal_plan(plan)
736
743
  drain_told = False # the drained message was printed for this drain
737
744
  sweep_asked = False # this invocation already asked for the finding sweep
745
+ sweep_checked = {} # the answer of this invocation's one `plan --check`
738
746
  brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
739
747
  brief_told = set() # (task, qid or '') whose brief wait was already printed
740
748
  brief_waiting = set() # tasks the last dispatch pass held for a brief answer or the brief writer
741
- 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]
742
753
 
743
754
  def status(name: str) -> str:
744
755
  root = plan / 'tasks' / name
@@ -752,7 +763,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
752
763
  dataset_event('sched_terminal', plan, name, dict(status=state))
753
764
 
754
765
  def merge(name: str) -> None:
755
- result = subprocess.run(['/bin/bash', script, '_merge', str(plan), name])
766
+ result = subprocess.run([forge_proc.bash_executable(), script, '_merge', str(plan), name])
756
767
  if result.returncode and status(name) == 'PASS':
757
768
  mark(name, 'ERROR')
758
769
  elif brief_mode != 'off' and status(name) == 'MERGED':
@@ -880,7 +891,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
880
891
  def requeue(name: str) -> bool:
881
892
  """Prepare a retry exactly as `retry` does, then put the task at the queue head. A task at its
882
893
  attempt cap (#69) is not prepared: _prepare_retry stops it for a decision instead."""
883
- 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])
884
895
  if result.returncode:
885
896
  refused[name] = budget(name)
886
897
  return False
@@ -912,7 +923,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
912
923
  def prompt_requeue(name: str) -> bool:
913
924
  """Re-dispatch a STALE task (its prompt changed while the attempt ran, #150) with the new text. The stale
914
925
  attempt spent nothing, so no retry is counted: retries, retries.used and decided.left stay as they are."""
915
- 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'])
916
927
  if result.returncode:
917
928
  print('forge: ' + name + ' is not re-dispatched: its changed prompt could not be prepared',
918
929
  file=sys.stderr, flush=True)
@@ -939,7 +950,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
939
950
  either: _prepare_retry --resume stops it for a decision, and it leaves the queue."""
940
951
  if not _pinned(plan, name) and not at_cap(name):
941
952
  return True
942
- 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'])
943
954
  if result.returncode:
944
955
  if status(name) == 'NEEDS_DECISION':
945
956
  print('forge: ' + name + ' is not resumed: it is at its attempt cap and waits for your decision',
@@ -982,7 +993,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
982
993
  if name not in pairs_cache:
983
994
  row = row_now(name)
984
995
  qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
985
- ['/bin/bash', script, '_qa_only', str(plan), name],
996
+ [forge_proc.bash_executable(), script, '_qa_only', str(plan), name],
986
997
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
987
998
  specs = [row[5]] if qa_only or row[4] == 'script' else [row[4], row[5]]
988
999
  pairs_cache[name] = [spec_pair(registry, spec) for spec in specs]
@@ -1010,7 +1021,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1010
1021
  # The implementer's pair when it is held (a full dispatch), else the reviewer's.
1011
1022
  role = 'dwarf' if len(pairs) == 2 and any(holds(pause, pairs[:1]) for pause in holding) else 'qa'
1012
1023
  excluded = {(pause['harness'], pause['model'] or '*') for pause in pauses.values()}
1013
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
1024
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--fallback',
1014
1025
  ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', holding[0]['class']]
1015
1026
  if role == 'qa':
1016
1027
  command += ['--role', 'qa']
@@ -1063,7 +1074,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1063
1074
  return False
1064
1075
  excluded = {(info['harness'], info['model'] if scope.startswith('model:') else '*')}
1065
1076
  excluded.update((p['harness'], p['model'] or '*') for p in pauses.values())
1066
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
1077
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name, '--fallback',
1067
1078
  ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', cause]
1068
1079
  if stage == 'qa':
1069
1080
  command += ['--role', 'qa']
@@ -1099,7 +1110,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1099
1110
  def backoff() -> tuple:
1100
1111
  """The plan's infra_backoff, read at every wait so a change applies to the next one."""
1101
1112
  try:
1102
- 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
+ )
1103
1117
  try:
1104
1118
  text = os.read(fd, 4097).decode('ascii').strip()
1105
1119
  finally:
@@ -1313,7 +1327,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1313
1327
  if not _write_atomic(plan, answer + '\n', 'tasks', name, 'answer.md'):
1314
1328
  return 'refused', 'the answer could not be written to tasks/' + name + '/answer.md'
1315
1329
  # A STALE task spent no attempt: it is prepared with the new prompt, not as a failed one (#150).
1316
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (
1330
+ command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name] + (
1317
1331
  ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1318
1332
  rc = subprocess.run(command).returncode
1319
1333
  if rc == 3:
@@ -1375,7 +1389,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1375
1389
  summary_seen[name] = summary_signature(name) # before it runs: its first change must trigger
1376
1390
  except Exception:
1377
1391
  pass
1378
- if subprocess.run(['/bin/bash', script, '_waves', str(plan)]).returncode:
1392
+ if subprocess.run([forge_proc.bash_executable(), script, '_waves', str(plan)]).returncode:
1379
1393
  _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
1380
1394
  return 'applied', None
1381
1395
 
@@ -1396,7 +1410,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1396
1410
  return 'refused', ('a ' + state + ' task has no reviewer verdict to override: accept takes a FAIL, '
1397
1411
  'UNKNOWN or NEEDS_DECISION task')
1398
1412
  env = dict(os.environ, FORGE_ACCEPT_ACTOR=request.get('actor') or 'cli')
1399
- 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'],
1400
1414
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env)
1401
1415
  lines = [line for line in result.stdout.splitlines() if line.strip()]
1402
1416
  if result.returncode:
@@ -1414,19 +1428,73 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1414
1428
  """A finding sweep's fix task."""
1415
1429
  return (plan / 'tasks' / name / 'sweep.json').is_file()
1416
1430
 
1431
+ def sweep_rounds() -> list:
1432
+ """The sweep rounds this plan has, oldest first: [(number, plan.json path)]."""
1433
+ found = {}
1434
+ if (plan / 'sweep' / 'plan.json').exists():
1435
+ found[1] = plan / 'sweep' / 'plan.json'
1436
+ with contextlib.suppress(OSError):
1437
+ for path in (plan / 'sweep' / 'rounds').iterdir():
1438
+ if path.name.isdigit() and int(path.name) >= 2 and (path / 'plan.json').exists():
1439
+ found[int(path.name)] = path / 'plan.json'
1440
+ return sorted(found.items())
1441
+
1442
+ def sweep_check() -> bool:
1443
+ """Whether `forge-sweep.py plan --check` finds a finding no round swept yet; asked once per
1444
+ invocation. Nothing new is written down for the run summary (sweep/nothing.json). A check that
1445
+ fails (the integration branch cannot be read) is not a reason to plan."""
1446
+ if 'answer' not in sweep_checked:
1447
+ result = subprocess.run([sys.executable, str(Path(__file__).resolve().with_name('forge-sweep.py')), 'plan',
1448
+ str(plan), '--severity', sweep, '--max', str(sweep_max), '--check']
1449
+ + (['--plausible'] if sweep_plausible else []),
1450
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
1451
+ sweep_checked['code'] = result.returncode
1452
+ sweep_checked['answer'] = result.returncode == 0
1453
+ if result.returncode == 1:
1454
+ try:
1455
+ counts = json.loads(result.stdout)
1456
+ note = {'at': time.time(), 'attempted': int(counts['attempted']), 'left': int(counts['left'])}
1457
+ (plan / 'sweep').mkdir(exist_ok=True)
1458
+ fd, tmp = tempfile.mkstemp(dir=str(plan / 'sweep'), prefix='.nothing.json.')
1459
+ with os.fdopen(fd, 'w') as handle:
1460
+ handle.write(json.dumps(note) + '\n')
1461
+ os.replace(tmp, plan / 'sweep' / 'nothing.json')
1462
+ except (ValueError, KeyError, TypeError, OSError) as error:
1463
+ _warn('could not record that the sweep found nothing new: ' + str(error))
1464
+ return sweep_checked['answer']
1465
+
1417
1466
  def sweep_due() -> bool:
1418
- """--sweep was given, every task merged, nothing stops or holds the run, and this plan was
1419
- never swept (sweep/plan.json is the planner's record, and its marker)."""
1420
- return (bool(sweep) and not sweep_asked and not interrupted and not graceful and not paused
1421
- and not drained(plan) and not (plan / 'sweep' / 'plan.json').exists()
1422
- and all(status(name) == 'MERGED' for name in tasks))
1467
+ """--sweep was given and nothing stops or holds the run, every task of the plan merged
1468
+ (a fix task of an earlier round may have stopped), the last round's queued fix tasks are
1469
+ merged or stopped, and `plan --check` finds a finding no round tried. At most one round
1470
+ per invocation."""
1471
+ if (not sweep or sweep_asked or interrupted or graceful or paused or drained(plan)
1472
+ or not all(status(name) == 'MERGED' for name in tasks if not is_fix(name))):
1473
+ return False
1474
+ rounds = sweep_rounds()
1475
+ if rounds:
1476
+ try:
1477
+ last = json.loads((rounds[-1][1]).read_text()).get('tasks') or []
1478
+ except (OSError, ValueError, AttributeError):
1479
+ last = []
1480
+ # A crash between plan.json and the tasks.tsv append leaves the fix task with no row
1481
+ # and no status. status() would say PENDING and hold every later round; that round is lost.
1482
+ if any(status(item['id']) not in ('MERGED', 'FAIL', 'NEEDS_DECISION', 'INFRA')
1483
+ for item in last if isinstance(item, dict) and isinstance(item.get('id'), str)
1484
+ and (item['id'] in tasks or (plan / 'tasks' / item['id'] / 'status').exists())):
1485
+ return False
1486
+ return sweep_check()
1487
+ # Round 1 asks too, so nothing eligible is recorded and not planned. A check that cannot
1488
+ # be answered (the integration branch cannot be read) still starts the round.
1489
+ sweep_check()
1490
+ return sweep_checked.get('code') != 1
1423
1491
 
1424
1492
  def start_sweep() -> int:
1425
1493
  """Plan the finding sweep and queue its fix tasks; how many were queued. Whatever goes
1426
1494
  wrong here ends the run without a sweep, never with a failure."""
1427
1495
  nonlocal sweep_asked
1428
1496
  sweep_asked = True
1429
- 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)]
1430
1498
  result = subprocess.run(command + (['--plausible'] if sweep_plausible else []),
1431
1499
  stdout=subprocess.PIPE, text=True)
1432
1500
  if result.returncode:
@@ -1467,7 +1535,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1467
1535
  def gread(gid: str, name: str) -> str:
1468
1536
  """A short file of the group's dir, stripped; empty when missing or unsafe."""
1469
1537
  try:
1470
- 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
+ )
1471
1542
  try:
1472
1543
  return os.read(fd, 4097).decode('utf-8', 'replace').strip()
1473
1544
  finally:
@@ -1516,8 +1587,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1516
1587
  root.mkdir(parents=True, exist_ok=True)
1517
1588
  log = open(root / 'group.out', 'ab')
1518
1589
  process = subprocess.Popen(
1519
- ['/bin/bash', script, '_group', str(plan), gid],
1520
- 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(),
1521
1592
  )
1522
1593
  active[GROUP_KEY + gid] = process, log
1523
1594
  group_again.discard(gid)
@@ -1539,7 +1610,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1539
1610
 
1540
1611
  def group_line(gid: str) -> None:
1541
1612
  """Say what a group that waits for a person (or the next run) waits for: _group_settle's own line."""
1542
- subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1613
+ subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1543
1614
 
1544
1615
  def requeue_members(gid: str) -> None:
1545
1616
  """Every member now in AUTO_RETRY and retryable goes back through the ordinary requeue: its budget,
@@ -1551,7 +1622,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1551
1622
  def merge_group(gid: str, requeue_ok: bool = True) -> None:
1552
1623
  # _merge_group flags each merged member's dependents itself (forge_brief_stale), so a direct call
1553
1624
  # behaves the same; the scheduler does not do it a second time.
1554
- 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])
1555
1626
  if result.returncode != 0 and requeue_ok and not interrupted and not graceful:
1556
1627
  requeue_members(gid) # a member the merge invalidated, when its review is what was voided
1557
1628
 
@@ -1581,7 +1652,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1581
1652
  merge_group(gid, going)
1582
1653
  elif state == 'FAIL':
1583
1654
  if not interrupted:
1584
- 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])
1585
1656
  if result.returncode:
1586
1657
  _warn('group ' + gid + ' could not be settled (exit ' + str(result.returncode)
1587
1658
  + '); its members stay IMPLEMENTED')
@@ -1674,12 +1745,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1674
1745
  that process is gone: the run is ending and the earlier summarize of this task still holds its lock."""
1675
1746
  command = [sys.executable, os.environ.get('FORGE_SUMMARIZE') or SUMMARIZE, str(plan), '--task', name]
1676
1747
  if after is not None:
1677
- command = ['/bin/sh', '-c', 'while kill -0 "$0" 2>/dev/null; do sleep 1; done; exec "$@"',
1678
- 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
1679
1758
  out = open(plan / 'summaries.out', 'ab')
1680
1759
  try:
1681
1760
  process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
1682
- start_new_session=True)
1761
+ **forge_proc.popen_group_kwargs(detached=True))
1683
1762
  finally:
1684
1763
  out.close()
1685
1764
  summary_procs[name] = process
@@ -1789,7 +1868,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1789
1868
  if state == 'PASS':
1790
1869
  merge_group(gid)
1791
1870
  elif state == 'FAIL' and not gsettled(gid) and not interrupted:
1792
- subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1871
+ subprocess.run([forge_proc.bash_executable(), script, '_group_settle', str(plan), gid])
1793
1872
  requeue_members(gid)
1794
1873
  elif state in ('INTERRUPTED', 'INFRA', 'TIMEOUT'):
1795
1874
  group_again.add(gid)
@@ -1904,8 +1983,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1904
1983
  human.discard(name)
1905
1984
  _remove(plan, 'tasks', name, 'retry.prepared')
1906
1985
  process = subprocess.Popen(
1907
- ['/bin/bash', script, '_task', str(plan), name],
1908
- 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(),
1909
1988
  )
1910
1989
  active[name] = process, log
1911
1990
  pending.remove(name)
@@ -1948,10 +2027,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1948
2027
  reap_exited(allow_requeue=False)
1949
2028
  stopping = list(active.items())
1950
2029
  for name, (process, log) in stopping:
1951
- try:
1952
- os.killpg(process.pid, signal.SIGTERM)
1953
- except OSError:
1954
- pass
2030
+ forge_proc.kill_tree(process.pid, force=False)
1955
2031
  # The group outlives its leader while dispatch's EXIT trap stops the harness, so wait
1956
2032
  # for the group to empty, not for the leader. Reaping the leader matters too: its
1957
2033
  # zombie would keep the group alive.
@@ -1968,10 +2044,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1968
2044
  time.sleep(0.05)
1969
2045
  for name, (process, log) in stopping:
1970
2046
  if name in waiting:
1971
- try:
1972
- os.killpg(process.pid, signal.SIGKILL)
1973
- except OSError:
1974
- pass
2047
+ forge_proc.kill_tree(process.pid, force=True)
1975
2048
  try:
1976
2049
  process.wait(timeout=5)
1977
2050
  except subprocess.TimeoutExpired:
@@ -2048,7 +2121,7 @@ def main() -> None:
2048
2121
  # Who holds it, for the next command the lock refuses. exec keeps this pid.
2049
2122
  _write_atomic(plan, json.dumps(dict(pid=os.getpid(), command=command, at=time.time())) + '\n', HOLDER)
2050
2123
  env = dict(os.environ, FORGE_PLAN_LOCK=plan)
2051
- 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)
2052
2125
  parser = argparse.ArgumentParser(prog='forge-schedule.py')
2053
2126
  parser.add_argument('script')
2054
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: