@giamme/forge 0.21.0 → 0.23.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 (165) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +25 -15
  3. package/SKILL.md +137 -216
  4. package/VERSION +1 -1
  5. package/bin/forge.js +104 -0
  6. package/docs/README.md +2 -3
  7. package/docs/add-ons.md +5 -3
  8. package/docs/artifacts.md +17 -2
  9. package/docs/commands.md +85 -63
  10. package/docs/decomposed-runs.md +195 -21
  11. package/docs/development.md +12 -10
  12. package/docs/forge-ui.md +33 -4
  13. package/docs/install.md +127 -6
  14. package/docs/memory.md +6 -1
  15. package/docs/models.md +36 -10
  16. package/docs/reviews.md +50 -29
  17. package/docs/safety.md +27 -2
  18. package/docs/troubleshooting.md +8 -11
  19. package/forge +29 -4
  20. package/forge.cmd +56 -0
  21. package/package.json +6 -3
  22. package/references/dataset.md +10 -9
  23. package/references/decompose-integration.md +337 -0
  24. package/references/decompose-opt-in.md +527 -0
  25. package/references/decompose-recovery.md +569 -0
  26. package/references/decompose-review.md +256 -0
  27. package/references/decompose.md +99 -1606
  28. package/references/findings.md +68 -0
  29. package/references/harnesses.md +7 -12
  30. package/references/memory.md +13 -2
  31. package/references/planning.md +48 -18
  32. package/references/ripwire.md +38 -13
  33. package/references/runtime.md +22 -33
  34. package/references/setup.md +90 -0
  35. package/references/solo.md +13 -42
  36. package/references/ui.md +12 -5
  37. package/registry.tsv +40 -22
  38. package/scripts/forge-artifact.sh +148 -13
  39. package/scripts/forge-compare.py +5 -15
  40. package/scripts/forge-config.py +14 -1
  41. package/scripts/forge-contract.py +216 -53
  42. package/scripts/forge-control.py +781 -51
  43. package/scripts/forge-dispatch.sh +202 -42
  44. package/scripts/forge-du.py +13 -3
  45. package/scripts/forge-guard.py +137 -6
  46. package/scripts/forge-handoff.py +221 -39
  47. package/scripts/forge-install-ripwire.sh +100 -24
  48. package/scripts/forge-install.sh +100 -41
  49. package/scripts/forge-issues.py +6 -4
  50. package/scripts/forge-jev-options.sh +3 -5
  51. package/scripts/forge-lib-adopt.sh +169 -5
  52. package/scripts/forge-lib-attribute.sh +10 -3
  53. package/scripts/forge-lib-decompose.sh +454 -0
  54. package/scripts/forge-lib-env.sh +179 -0
  55. package/scripts/forge-lib-group.sh +9 -6
  56. package/scripts/forge-lib-plans.sh +38 -21
  57. package/scripts/forge-lib-review.sh +28 -8
  58. package/scripts/forge-lib-task.sh +263 -69
  59. package/scripts/forge-lib-verify.sh +59 -10
  60. package/scripts/forge-memory.sh +83 -4
  61. package/scripts/forge-metrics.sh +10 -3
  62. package/scripts/forge-parallel-options.sh +23 -4
  63. package/scripts/forge-parallel.sh +602 -217
  64. package/scripts/forge-plan-check.py +71 -8
  65. package/scripts/forge-planner.py +303 -17
  66. package/scripts/forge-pr.py +9 -1
  67. package/scripts/forge-prompt.py +2 -2
  68. package/scripts/forge-review-links.py +248 -0
  69. package/scripts/forge-ripwire.py +234 -16
  70. package/scripts/forge-route.py +19 -27
  71. package/scripts/forge-runs-rm.py +92 -21
  72. package/scripts/forge-runs.py +46 -5
  73. package/scripts/forge-runtime.py +39 -14
  74. package/scripts/forge-schedule.py +141 -33
  75. package/scripts/forge-setup-stale.py +236 -0
  76. package/scripts/forge-setup.py +804 -0
  77. package/scripts/forge-shadow.py +2 -20
  78. package/scripts/forge-solo-lock.py +46 -0
  79. package/scripts/forge-solo.sh +39 -58
  80. package/scripts/forge-sweep.py +3 -2
  81. package/scripts/forge-ui.py +8 -1
  82. package/scripts/forge-update.sh +8 -3
  83. package/scripts/forge-verify.py +17 -1
  84. package/scripts/forge-version.py +13 -1
  85. package/scripts/forge-watch.py +7 -2
  86. package/scripts/forge-win.sh +156 -0
  87. package/scripts/forge_brief/__init__.py +6 -1
  88. package/scripts/forge_brief/proposals.py +6 -1
  89. package/scripts/forge_dataset/__init__.py +1 -1
  90. package/scripts/forge_dataset/capture.py +0 -34
  91. package/scripts/forge_dataset/checks.py +0 -1
  92. package/scripts/forge_dataset/cli.py +5 -1
  93. package/scripts/forge_dataset/export.py +28 -6
  94. package/scripts/forge_dataset/facts.py +1 -2
  95. package/scripts/forge_dataset/forecast.py +1 -1
  96. package/scripts/forge_dataset/harvest.py +107 -7
  97. package/scripts/forge_dataset/importer.py +3 -2
  98. package/scripts/forge_dataset/pairs.py +3 -3
  99. package/scripts/forge_dataset/reviewers.py +4 -3
  100. package/scripts/forge_dataset/routing.py +6 -3
  101. package/scripts/forge_dataset/tiers.py +1 -1
  102. package/scripts/forge_decide/__init__.py +1 -1
  103. package/scripts/forge_decide/budget.py +12 -7
  104. package/scripts/forge_decide/profiles.py +11 -14
  105. package/scripts/forge_decide/replay.py +9 -4
  106. package/scripts/forge_decompose.py +987 -0
  107. package/scripts/forge_flock.py +17 -2
  108. package/scripts/forge_groups/review.py +6 -1
  109. package/scripts/forge_jev/__init__.py +1 -1
  110. package/scripts/forge_jev/cli.py +10 -1
  111. package/scripts/forge_jev/gates.py +10 -1
  112. package/scripts/forge_jev/verify.py +10 -2
  113. package/scripts/forge_legacy.py +86 -0
  114. package/scripts/forge_memory_home.py +57 -0
  115. package/scripts/forge_models.py +151 -0
  116. package/scripts/forge_posix.py +17 -0
  117. package/scripts/forge_prefs.py +138 -0
  118. package/scripts/forge_proc.py +108 -0
  119. package/scripts/forge_registry.py +2 -2
  120. package/scripts/forge_side/__init__.py +23 -4
  121. package/scripts/forge_storage.py +28 -15
  122. package/ui/README.md +22 -10
  123. package/ui/docs/api.md +121 -99
  124. package/ui/forge_ui/control.py +53 -16
  125. package/ui/forge_ui/export.py +0 -10
  126. package/ui/forge_ui/models.py +15 -2
  127. package/ui/forge_ui/projects.py +4 -1
  128. package/ui/forge_ui/reader.py +462 -60
  129. package/ui/forge_ui/server.py +0 -10
  130. package/ui/forge_ui/static/app.js +28 -9
  131. package/ui/forge_ui/static/checksview.js +12 -3
  132. package/ui/forge_ui/static/controls.js +147 -11
  133. package/ui/forge_ui/static/convo.js +5 -2
  134. package/ui/forge_ui/static/diffview.js +4 -5
  135. package/ui/forge_ui/static/panel.js +180 -77
  136. package/ui/forge_ui/static/projectsview.js +16 -2
  137. package/ui/forge_ui/static/runmodel.js +18 -4
  138. package/ui/forge_ui/static/scene3d.js +52 -31
  139. package/ui/forge_ui/static/settings.js +1 -1
  140. package/ui/forge_ui/static/storageview.js +2 -2
  141. package/ui/forge_ui/static/style.css +23 -6
  142. package/ui/forge_ui/static/worktreesview.js +8 -4
  143. package/ui/forge_ui/transcripts.py +6 -0
  144. package/ui/forge_ui/worktrees.py +13 -1
  145. package/docs/fractal.md +0 -181
  146. package/references/fractal-dashboard.md +0 -21
  147. package/references/fractal.md +0 -307
  148. package/scripts/forge-fractal-dispatch.sh +0 -4
  149. package/scripts/forge-fractal-options.sh +0 -54
  150. package/scripts/forge-fractal.py +0 -6
  151. package/scripts/forge-install-fractal.sh +0 -4
  152. package/scripts/forge_fractal/__init__.py +0 -88
  153. package/scripts/forge_fractal/bridge.py +0 -46
  154. package/scripts/forge_fractal/cli.py +0 -224
  155. package/scripts/forge_fractal/dashboard.css +0 -138
  156. package/scripts/forge_fractal/dashboard.html +0 -41
  157. package/scripts/forge_fractal/dashboard.js +0 -687
  158. package/scripts/forge_fractal/decomposition.py +0 -262
  159. package/scripts/forge_fractal/execution.py +0 -659
  160. package/scripts/forge_fractal/inspection.py +0 -261
  161. package/scripts/forge_fractal/install.py +0 -158
  162. package/scripts/forge_fractal/invocation.py +0 -95
  163. package/scripts/forge_fractal/pipeline.py +0 -125
  164. package/scripts/forge_fractal/selection.py +0 -180
  165. package/ui/forge_ui/fractal.py +0 -582
@@ -49,6 +49,7 @@ 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_decompose # noqa: E402
52
53
  import forge_flock as fcntl # noqa: E402
53
54
  import forge_infra # noqa: E402
54
55
  import forge_posix # noqa: E402
@@ -389,22 +390,6 @@ def drained(plan: object) -> bool:
389
390
  return _read_small(plan, 'drain') is not None
390
391
 
391
392
 
392
- def _fractal_plan(plan: object) -> bool:
393
- """fractal-selection.json enabled (unreadable counts: fail closed, as forge-control does)."""
394
- try:
395
- text = Path(_resolve(plan, 'fractal-selection.json')).read_text()
396
- except FileNotFoundError:
397
- return False
398
- except OSError:
399
- return True
400
- if not text.strip():
401
- return False
402
- try:
403
- return bool(json.loads(text).get('enabled'))
404
- except (ValueError, AttributeError):
405
- return True
406
-
407
-
408
393
  def live_capacity(plan: object, default: int) -> int:
409
394
  """`forge control set max-parallel` (1-64), else the argument the run started with."""
410
395
  text = _read_small(plan, 'max_parallel')
@@ -488,7 +473,8 @@ REQUESTS = 'control.requests'
488
473
  REQUEST_MAX = 64 * 1024
489
474
  ANSWER_MAX = 8000 # characters of a NEEDS_INPUT answer a request may carry (#147)
490
475
  # What `forge control retry --decide` may carry: retry=N (1 to 20) or threshold=Pn.
491
- DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
476
+ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]|split(?:=keep|=fresh)?|files\+=[^\s,]+(?:,[^\s,]+)*')
477
+ SPLIT_DECISIONS = ('split', 'split=keep', 'split=fresh') # #153: the task becomes a sub-plan of subtasks
492
478
  # NEEDS_INPUT is in neither: a task stopped for the user's answer resumes only through
493
479
  # `retry <plan> <id> --answer`, whose preparation refuses without one. Nor is NEEDS_DECISION (#69):
494
480
  # a task whose reviews do not converge, or that the retry policy cannot move to a stronger model,
@@ -524,6 +510,26 @@ def decision_head(plan: object, name: str) -> str:
524
510
  return ' '.join(line.strip() for line in lines[:3] if line.strip())[:300]
525
511
 
526
512
 
513
+ def waiting_line(plan: object, name: str, state: str) -> str | None:
514
+ """The line `run` prints when a task stops for the user while the run goes on (#193), in the form of its
515
+ `dispatched` and `retrying` lines: `forge: needs you: <task> <STATUS> (<why>) -> <file to read>`. An
516
+ INFRA stop needs no one unless its pause says so, so it reads `forge: stopped: …`. None for any other state."""
517
+ root = Path(plan) / 'tasks' / name
518
+ if state == 'NEEDS_DECISION':
519
+ try:
520
+ first = (root / 'decision.md').read_text(errors='replace').splitlines()[:1]
521
+ except OSError:
522
+ first = []
523
+ reasons = first[0][len('reasons: '):].strip() if first and first[0].startswith('reasons: ') else ''
524
+ return 'forge: needs you: %s NEEDS_DECISION (%s) -> %s' % (name, reasons or 'see decision.md', root / 'decision.md')
525
+ if state == 'NEEDS_INPUT':
526
+ return 'forge: needs you: %s NEEDS_INPUT (a question to answer) -> %s' % (name, root / 'needs_input.md')
527
+ if state == 'INFRA':
528
+ cause = forge_infra.cause_of(infra_info(root).get('class'))
529
+ return 'forge: stopped: %s INFRA (%s, no attempt spent) -> %s' % (name, cause, root / 'infra.txt')
530
+ return None
531
+
532
+
527
533
  def read_request(plan: object, name: str) -> dict | None:
528
534
  try:
529
535
  fd = forge_posix.open_nofollow(
@@ -709,6 +715,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
709
715
  raise ValueError('task ' + GROUP_KEY + g.id + ' clashes with group ' + g.id)
710
716
  group_of = {m: g.id for g in rgroups.values() for m in g.members} # member -> its review group
711
717
  active = {} # task id, or GROUP_KEY + gid for a running group review
718
+ task_jobs: dict[str, forge_proc.ProcessJob] = {}
719
+
720
+ def _track_job(key: str, pid: int) -> None:
721
+ job = forge_proc.ProcessJob()
722
+ if job.attach(pid):
723
+ task_jobs[key] = job
712
724
  pending = list(tasks)
713
725
  interrupted = False
714
726
  group_again = set() # groups to review once more whatever their status says (a resume, an UNKNOWN)
@@ -716,7 +728,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
716
728
  retries = {} # automatic reviewer-driven retries used per task, this run
717
729
  per_model_seen = {} # task -> the per-model answer that allowed its latest automatic retry
718
730
  refused = {} # task -> budget at the time its retry could not be prepared
719
- retried = set() # tasks whose next dispatch is a retry (FORGE_FRACTAL_RETRY=1)
731
+ retried = set() # tasks whose next dispatch is a retry
720
732
  offsets = {} # how much of each task.out was already echoed under --output full
721
733
  infra_seen = [] # tasks stopped by an infrastructure failure, awaiting resume
722
734
  held = set() # INFRA tasks not resumed: their pin could not be applied
@@ -735,11 +747,27 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
735
747
  backoff_warned = [] # an invalid infra_backoff file is reported once
736
748
  graceful = False # `forge control stop`: start nothing more, end once running tasks are done
737
749
  human = set() # tasks whose next dispatch is a `forge control retry` (dataset trigger human)
750
+ # One --max-parallel for a run and every sub-plan run under it (#153): each task that works holds
751
+ # a slot of the root plan's tree.slots. A split task waiting for its subtasks holds none.
752
+ try:
753
+ tree_root = forge_decompose.root_of(plan)
754
+ except Exception:
755
+ tree_root = plan
756
+ tree_slots = forge_decompose.Slots(tree_root)
757
+ slot_of = {} # task -> the slot it holds
758
+
759
+ def split_open(name: str) -> bool:
760
+ try:
761
+ return forge_decompose.is_open(plan, name)
762
+ except Exception:
763
+ return False
764
+
765
+ def give_slot(name: str) -> None:
766
+ forge_decompose.Slots.give(slot_of.pop(name, None))
738
767
  for name in tasks: # `retry --no-dispatch` (#118) prepared it for this run: still a person's retry
739
768
  if (plan / 'tasks' / name / 'retry.prepared').exists():
740
769
  retried.add(name)
741
770
  human.add(name)
742
- fractal = _fractal_plan(plan)
743
771
  drain_told = False # the drained message was printed for this drain
744
772
  sweep_asked = False # this invocation already asked for the finding sweep
745
773
  sweep_checked = {} # the answer of this invocation's one `plan --check`
@@ -955,6 +983,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
955
983
  if status(name) == 'NEEDS_DECISION':
956
984
  print('forge: ' + name + ' is not resumed: it is at its attempt cap and waits for your decision',
957
985
  file=sys.stderr, flush=True)
986
+ print(waiting_line(plan, name, 'NEEDS_DECISION'), file=sys.stderr, flush=True)
958
987
  return False
959
988
  held.add(name)
960
989
  print('forge: ' + name + ' is not resumed: its escalation pin could not be applied',
@@ -1007,7 +1036,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1007
1036
  implementer to the next healthy model of its tier, or, when only its reviewer is held, the reviewer
1008
1037
  to a peer. Tried once for each set of pauses and models: a move changes the models, so a task with
1009
1038
  both on the paused harness moves its implementer, then its reviewer. True when the task moved."""
1010
- if interrupted or graceful or fractal or _read_small(plan, 'infra_fallback') != 'on':
1039
+ if interrupted or graceful or _read_small(plan, 'infra_fallback') != 'on':
1011
1040
  return False
1012
1041
  pairs = next_pairs(name)
1013
1042
  seen = (frozenset(pauses), tuple(pairs))
@@ -1065,7 +1094,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1065
1094
  exhausted pair is excluded (and a harness stop excludes the whole harness); a pool all
1066
1095
  stopped cannot bounce the task forever. True when the task moved, and so left the pause."""
1067
1096
  stage = info.get('stage')
1068
- if interrupted or graceful or fractal or _read_small(plan, 'infra_fallback') != 'on':
1097
+ if interrupted or graceful or _read_small(plan, 'infra_fallback') != 'on':
1069
1098
  return False
1070
1099
  # A pin waits for the next full retry, which a review's move is not.
1071
1100
  if stage not in ('dwarf', 'qa') or (stage == 'dwarf' and _pinned(plan, name)):
@@ -1279,7 +1308,23 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1279
1308
  file=sys.stderr, flush=True)
1280
1309
  write_paused()
1281
1310
 
1311
+ STORED_SUBTASKS = re.compile(r'split\.request\.[0-9]+-[0-9]+\.json')
1312
+
1282
1313
  def apply_retry(request: dict) -> tuple:
1314
+ """_apply_retry, and a split's stored subtasks never outlive a request that was refused."""
1315
+ outcome = _apply_retry(request)
1316
+ stored = request.get('subtasks')
1317
+ if isinstance(stored, str) and STORED_SUBTASKS.fullmatch(stored) and isinstance(request.get('task'), str) \
1318
+ and request['task'] in tasks:
1319
+ leftovers = [stored] + ([forge_decompose.PROPOSAL] if outcome[0] == 'refused' else [])
1320
+ for leftover in leftovers:
1321
+ try:
1322
+ (plan / 'tasks' / request['task'] / leftover).unlink()
1323
+ except OSError:
1324
+ pass
1325
+ return outcome
1326
+
1327
+ def _apply_retry(request: dict) -> tuple:
1283
1328
  name, dwarf = request['task'], request.get('dwarf')
1284
1329
  if name not in tasks:
1285
1330
  return 'refused', 'this run does not know task ' + name
@@ -1305,14 +1350,31 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1305
1350
  + ' ' + name + ' --answer \u2026 (on a live run: forge control retry ' + str(plan)
1306
1351
  + ' ' + name + ' --answer \u2026)')
1307
1352
  decide, reason, approved = request.get('decide'), request.get('reason'), request.get('approved') is True
1308
- if decide and state != 'NEEDS_DECISION':
1353
+ splitting = decide in SPLIT_DECISIONS
1354
+ if decide and state != 'NEEDS_DECISION' and not splitting:
1309
1355
  return 'refused', name + ' is ' + state + ', not waiting for a decision; --decide only decides a NEEDS_DECISION task'
1310
1356
  decision = []
1311
- if state == 'NEEDS_DECISION':
1357
+ if splitting:
1358
+ # A split (#153): any task that has not passed, with a reason and --approved. Its subtasks were
1359
+ # checked and stored by `forge control retry --decide split`.
1360
+ if dwarf:
1361
+ return 'refused', 'a split does not take --dwarf: the subtasks are routed with the plan\'s pools'
1362
+ if not (reason or '').strip() or not approved:
1363
+ return 'refused', 'a split needs --reason and --approved'
1364
+ stored = request.get('subtasks')
1365
+ if not isinstance(stored, str) or not STORED_SUBTASKS.fullmatch(stored):
1366
+ return 'refused', 'a split needs its subtasks: forge control retry ' + str(plan) + ' ' + name \
1367
+ + ' --decide split --subtasks FILE'
1368
+ try:
1369
+ os.replace(plan / 'tasks' / name / stored, plan / 'tasks' / name / forge_decompose.PROPOSAL)
1370
+ except OSError:
1371
+ return 'refused', 'the subtasks of this split are no longer stored; ask again'
1372
+ decision = ['--decide', decide, '--reason', reason, '--approved']
1373
+ elif state == 'NEEDS_DECISION':
1312
1374
  # Only a person's explicit decision resumes it: a choice, a reason, and --approved.
1313
1375
  if not decide and not dwarf:
1314
1376
  return 'refused', (name + ' is waiting for your decision, and only a decision resumes it: '
1315
- + decision_head(plan, name) + ' (retry --decide retry=N | threshold=Pn, or --dwarf SPEC,'
1377
+ + decision_head(plan, name) + ' (retry --decide retry=N | threshold=Pn | files+=PATH, or --dwarf SPEC,'
1316
1378
  + ' with --reason and --approved)')
1317
1379
  if not (reason or '').strip() or not approved:
1318
1380
  return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
@@ -1330,6 +1392,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1330
1392
  command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name] + (
1331
1393
  ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1332
1394
  rc = subprocess.run(command).returncode
1395
+ if rc and splitting:
1396
+ return 'refused', 'the task was not split (exit ' + str(rc) + '; the run output says why)'
1397
+ if rc == 6:
1398
+ return 'refused', ('the paths were not added to its files: another task declares one, or it owns them '
1399
+ 'already (the run output says which); nothing was written')
1333
1400
  if rc == 3:
1334
1401
  try:
1335
1402
  why = (plan / 'tasks' / name / 'split.suggested').read_text().strip()
@@ -1591,6 +1658,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1591
1658
  stdout=log, stderr=subprocess.STDOUT, **forge_proc.popen_group_kwargs(),
1592
1659
  )
1593
1660
  active[GROUP_KEY + gid] = process, log
1661
+ _track_job(GROUP_KEY + gid, process.pid)
1594
1662
  group_again.discard(gid)
1595
1663
  print('forge: reviewing group ' + gid + ' (' + ', '.join(rgroups[gid].members) + ')',
1596
1664
  file=sys.stderr, flush=True)
@@ -1697,6 +1765,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1697
1765
  into.add(name)
1698
1766
  log.close()
1699
1767
  del active[name]
1768
+ give_slot(name)
1769
+ job = task_jobs.pop(name, None)
1770
+ if job is not None:
1771
+ job.disarm()
1772
+ job.close()
1700
1773
  if name.startswith(GROUP_KEY) and name not in tasks:
1701
1774
  gid = name[len(GROUP_KEY):]
1702
1775
  if os.environ.get('FORGE_OUTPUT') == 'full':
@@ -1719,9 +1792,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1719
1792
  prompt_requeue(name)
1720
1793
  elif state == 'IMPLEMENTED' and allow_requeue and name in group_of:
1721
1794
  start_ready_groups() # the last member in: its group is reviewed now, with no wave barrier
1795
+ announce_wait(name)
1722
1796
  if not reaped:
1723
1797
  return
1724
1798
 
1799
+ def announce_wait(name: str) -> None:
1800
+ """#193: say at once that a task stopped for the user, so the agent driving the run can put it to them while
1801
+ the other tasks go on. An INFRA stop dispatched again at once, or a task already queued again, says nothing."""
1802
+ state = status(name)
1803
+ if state == 'INFRA' and name in pending:
1804
+ return
1805
+ line = waiting_line(plan, name, state)
1806
+ if line:
1807
+ print(line, file=sys.stderr, flush=True)
1808
+
1725
1809
  summary_seen = {} # task -> what the scheduler last saw of it (status, attempt trail, verdict, retries)
1726
1810
  summary_due = set() # tasks that changed and wait for a summarize
1727
1811
  summary_procs = {} # task -> its detached forge-summarize.py, polled only to reap it
@@ -1832,6 +1916,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1832
1916
 
1833
1917
  signal.signal(signal.SIGTERM, stop)
1834
1918
  signal.signal(signal.SIGINT, stop)
1919
+ forge_proc.install_signal(forge_proc.SIGBREAK, stop)
1835
1920
  try:
1836
1921
  live_start(plan, tasks, retry_failed, infra_retries, rgroups)
1837
1922
  summaries_on_change()
@@ -1943,6 +2028,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1943
2028
  write_paused()
1944
2029
  end_scoped_waits()
1945
2030
  handle_requests()
2031
+ # A running task that has become a split task (run --auto-split) waits for its subtasks
2032
+ # now: they need its slot.
2033
+ for name in list(slot_of):
2034
+ if name in active and split_open(name):
2035
+ give_slot(name)
1946
2036
  cap = live_capacity(plan, capacity)
1947
2037
  draining = drained(plan) # again: the infrastructure wait above can last minutes
1948
2038
  brief_waiting.clear()
@@ -1969,16 +2059,25 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1969
2059
  pass
1970
2060
  if scope_held(name):
1971
2061
  continue
2062
+ # The tree's bound, last of the checks: a task that will only run its subtasks takes no
2063
+ # slot, they do. None means every slot of the tree is taken, here or in another plan of it.
2064
+ slot = False if split_open(name) else tree_slots.take(live_capacity(tree_root, capacity))
2065
+ if slot is None:
2066
+ break
1972
2067
  root = plan / 'tasks' / name
1973
- if not (root / 'base_ref').exists():
1974
- worktree = Path((plan / 'wt_root').read_text().strip()) / '_integration'
1975
- base = subprocess.check_output(['git', '-C', str(worktree), 'rev-parse', 'HEAD'])
1976
- (root / 'base_ref').write_bytes(base)
1977
- log = open(root / 'task.out', 'ab')
1978
- # A retried task runs with the same environment `retry` gives it, so the
1979
- # no-progress guard (byte-identical diff) applies under Fractal too.
1980
- env = (dict(os.environ, FORGE_FRACTAL_RETRY='1',
1981
- FORGE_DATASET_TRIGGER='human' if name in human else 'auto')
2068
+ try:
2069
+ if not (root / 'base_ref').exists():
2070
+ worktree = Path(forge_posix.host_path((plan / 'wt_root').read_text().strip())) / '_integration'
2071
+ base = subprocess.check_output(['git', '-C', str(worktree), 'rev-parse', 'HEAD'])
2072
+ (root / 'base_ref').write_bytes(base)
2073
+ log = open(root / 'task.out', 'ab')
2074
+ except BaseException:
2075
+ forge_decompose.Slots.give(slot)
2076
+ raise
2077
+ if slot:
2078
+ slot_of[name] = slot
2079
+ # A retried task runs with the dataset trigger `retry` gives it.
2080
+ env = (dict(os.environ, FORGE_DATASET_TRIGGER='human' if name in human else 'auto')
1982
2081
  if name in retried else None)
1983
2082
  human.discard(name)
1984
2083
  _remove(plan, 'tasks', name, 'retry.prepared')
@@ -1987,6 +2086,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1987
2086
  stdout=log, stderr=subprocess.STDOUT, env=env, **forge_proc.popen_group_kwargs(),
1988
2087
  )
1989
2088
  active[name] = process, log
2089
+ _track_job(name, process.pid)
1990
2090
  pending.remove(name)
1991
2091
  print('forge: dispatched ' + name + ' -> ' + str(root), file=sys.stderr, flush=True)
1992
2092
  if not active and graceful:
@@ -2045,11 +2145,16 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2045
2145
  for name, (process, log) in stopping:
2046
2146
  if name in waiting:
2047
2147
  forge_proc.kill_tree(process.pid, force=True)
2148
+ job = task_jobs.pop(name, None)
2149
+ if job is not None:
2150
+ job.terminate()
2151
+ job.close()
2048
2152
  try:
2049
2153
  process.wait(timeout=5)
2050
2154
  except subprocess.TimeoutExpired:
2051
2155
  pass
2052
2156
  log.close()
2157
+ give_slot(name)
2053
2158
  stopped_groups = [name[len(GROUP_KEY):] for name, _ in stopping if name.startswith(GROUP_KEY) and name not in tasks]
2054
2159
  stop_harnesses(plan, [name for name, _ in stopping if name in tasks], stopped_groups)
2055
2160
  for name, _ in stopping:
@@ -2068,6 +2173,9 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2068
2173
  if paused or any(live_pause(pause) for pause in pauses.values()) \
2069
2174
  or any(status(name) == 'INFRA' for name in tasks):
2070
2175
  return INFRA_EXIT
2176
+ # A split task whose subtasks paused on an infrastructure failure (#153): the same pause, one level down.
2177
+ if any(status(name) == 'BLOCKED' and (plan / 'tasks' / name / 'sub.infra').exists() for name in tasks):
2178
+ return INFRA_EXIT
2071
2179
  # A fix task that did not merge leaves its findings for `forge issues`; the run's own work is done.
2072
2180
  return 0 if all(status(name) == 'MERGED' for name in tasks if not is_fix(name)) else 5
2073
2181
 
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env python3
2
+ """Track worktree setup commits and detect stale generated inputs before verify."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import fnmatch
8
+ import posixpath
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ DEFAULT_LOCKFILES = frozenset(
14
+ {
15
+ "package-lock.json",
16
+ "pnpm-lock.yaml",
17
+ "yarn.lock",
18
+ "bun.lock",
19
+ "bun.lockb",
20
+ "npm-shrinkwrap.json",
21
+ "poetry.lock",
22
+ "uv.lock",
23
+ "Pipfile.lock",
24
+ "Cargo.lock",
25
+ "go.sum",
26
+ "Gemfile.lock",
27
+ "composer.lock",
28
+ "Package.resolved",
29
+ "Podfile.lock",
30
+ "mix.lock",
31
+ "pubspec.lock",
32
+ "flake.lock",
33
+ "gradle.lockfile",
34
+ }
35
+ )
36
+
37
+
38
+ def _git_stdout(checkout: Path, *args: str) -> bytes | None:
39
+ res = subprocess.run(
40
+ ["git", "-C", str(checkout), *args],
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.DEVNULL,
43
+ check=False,
44
+ )
45
+ if res.returncode != 0:
46
+ return None
47
+ return res.stdout
48
+
49
+
50
+ def _git_text(checkout: Path, *args: str) -> str:
51
+ raw = _git_stdout(checkout, *args)
52
+ if raw is None:
53
+ return ""
54
+ return raw.decode("utf-8", "surrogateescape").strip()
55
+
56
+
57
+ def _git_dir(checkout: Path) -> Path | None:
58
+ gdir = _git_text(checkout, "rev-parse", "--git-dir")
59
+ if not gdir:
60
+ return None
61
+ p = Path(gdir)
62
+ if not p.is_absolute():
63
+ p = checkout / p
64
+ return p
65
+
66
+
67
+ def _write_lf(path: Path, text: str) -> None:
68
+ path.parent.mkdir(parents=True, exist_ok=True)
69
+ path.write_bytes(text.encode("utf-8", "surrogateescape"))
70
+
71
+
72
+ def cmd_record_commit(args: argparse.Namespace) -> int:
73
+ checkout = Path(args.checkout)
74
+ head = _git_text(checkout, "rev-parse", "HEAD")
75
+ if not head:
76
+ return 0
77
+ gdir = _git_dir(checkout)
78
+ if gdir is not None:
79
+ _write_lf(gdir / "forge-setup-commit", head + "\n")
80
+ if args.out:
81
+ _write_lf(Path(args.out), head + "\n")
82
+ return 0
83
+
84
+
85
+ def _strip_dot_slash(path: str) -> str:
86
+ while path.startswith("./"):
87
+ path = path[2:]
88
+ return path
89
+
90
+
91
+ def _load_setup_inputs(wt: Path, repo: Path) -> list[str] | None:
92
+ for candidate in (wt / ".forge" / "setup-inputs", repo / ".forge" / "setup-inputs"):
93
+ if candidate.is_file():
94
+ raw = candidate.read_bytes().decode("utf-8", "surrogateescape")
95
+ patterns: list[str] = []
96
+ for line in raw.splitlines():
97
+ stripped = line.strip()
98
+ if stripped and not stripped.startswith("#"):
99
+ patterns.append(_strip_dot_slash(stripped.replace("\\", "/")))
100
+ return patterns
101
+ return None
102
+
103
+
104
+ def _matches_pattern(rel_path: str, pattern: str) -> bool:
105
+ rel_path = _strip_dot_slash(rel_path.replace("\\", "/"))
106
+ if not pattern:
107
+ return False
108
+ if pattern.endswith("/"):
109
+ return rel_path.startswith(pattern)
110
+ if pattern.endswith("/**"):
111
+ prefix = pattern[:-3].rstrip("/")
112
+ return rel_path == prefix or rel_path.startswith(prefix + "/")
113
+ has_glob = any(ch in pattern for ch in "*?[")
114
+ if has_glob:
115
+ if "/" in pattern:
116
+ return fnmatch.fnmatch(rel_path, pattern)
117
+ return fnmatch.fnmatch(rel_path, pattern) or fnmatch.fnmatch(
118
+ posixpath.basename(rel_path), pattern
119
+ )
120
+ if "/" in pattern:
121
+ return rel_path == pattern or rel_path.startswith(pattern + "/")
122
+ return (
123
+ rel_path == pattern
124
+ or rel_path.startswith(pattern + "/")
125
+ or posixpath.basename(rel_path) == pattern
126
+ )
127
+
128
+
129
+ def _changed_files(wt: Path, base_commit: str, head_commit: str) -> list[str]:
130
+ raw = _git_stdout(
131
+ wt, "diff", "--name-only", "-z", base_commit, head_commit, "--", "."
132
+ )
133
+ if not raw:
134
+ return []
135
+ items = [p.decode("utf-8", "surrogateescape") for p in raw.split(b"\x00") if p]
136
+ return [p.replace("\\", "/") for p in items]
137
+
138
+
139
+ def _resolve_setup_commit(wt: Path, override_path: str | None) -> str:
140
+ if override_path:
141
+ p = Path(override_path)
142
+ if p.is_file():
143
+ val = p.read_bytes().decode("utf-8", "surrogateescape").strip()
144
+ if val:
145
+ return val
146
+ gdir = _git_dir(wt)
147
+ if gdir is not None:
148
+ marker = gdir / "forge-setup-commit"
149
+ if marker.is_file():
150
+ val = marker.read_bytes().decode("utf-8", "surrogateescape").strip()
151
+ if val:
152
+ return val
153
+ return ""
154
+
155
+
156
+ def _emit(status: str, matched: list[str]) -> int:
157
+ summary = ", ".join(matched[:5])
158
+ if len(matched) > 5:
159
+ summary += f" (+{len(matched) - 5} more)"
160
+ line = f"{status}\t{summary}\n"
161
+ sys.stdout.buffer.write(line.encode("utf-8", "surrogateescape"))
162
+ return 0
163
+
164
+
165
+ def cmd_check(args: argparse.Namespace) -> int:
166
+ plan = Path(args.plan)
167
+ wt = Path(args.wt)
168
+ repo = Path(args.repo)
169
+
170
+ setup_commit = _resolve_setup_commit(wt, args.setup_commit)
171
+ if not setup_commit:
172
+ # No successful setup on record (it failed, or the worktree predates the record):
173
+ # with the flag on that is the case a re-run helps most.
174
+ if (plan / "setup_before_verify").is_file():
175
+ return _emit("RERUN", ["no successful setup recorded for this checkout"])
176
+ return _emit("OK", [])
177
+ head_commit = _git_text(wt, "rev-parse", "HEAD")
178
+ if not head_commit or setup_commit == head_commit:
179
+ return _emit("OK", [])
180
+
181
+ changed = _changed_files(wt, setup_commit, head_commit)
182
+ if not changed:
183
+ return _emit("OK", [])
184
+
185
+ patterns = _load_setup_inputs(wt, repo)
186
+ setup_before_verify = (plan / "setup_before_verify").is_file()
187
+
188
+ if setup_before_verify:
189
+ if patterns is not None:
190
+ matched = [
191
+ p
192
+ for p in changed
193
+ if p in (".forge/setup", ".forge/setup-inputs")
194
+ or any(_matches_pattern(p, pat) for pat in patterns)
195
+ ]
196
+ if matched:
197
+ return _emit("RERUN", matched)
198
+ return _emit("OK", [])
199
+ return _emit("RERUN", changed)
200
+
201
+ matched_stale: list[str] = []
202
+ for p in changed:
203
+ base = posixpath.basename(p)
204
+ is_lock = base in DEFAULT_LOCKFILES
205
+ is_declared = patterns is not None and any(
206
+ _matches_pattern(p, pat) for pat in patterns
207
+ )
208
+ if is_lock or is_declared or p == ".forge/setup":
209
+ matched_stale.append(p)
210
+ if matched_stale:
211
+ return _emit("STALE", matched_stale)
212
+ return _emit("OK", [])
213
+
214
+
215
+ def main(argv: list[str] | None = None) -> int:
216
+ parser = argparse.ArgumentParser(description="Check or record setup commit staleness.")
217
+ sub = parser.add_subparsers(dest="cmd", required=True)
218
+
219
+ p_rec = sub.add_parser("record-commit")
220
+ p_rec.add_argument("checkout")
221
+ p_rec.add_argument("--out", default=None)
222
+ p_rec.set_defaults(func=cmd_record_commit)
223
+
224
+ p_chk = sub.add_parser("check")
225
+ p_chk.add_argument("plan")
226
+ p_chk.add_argument("wt")
227
+ p_chk.add_argument("repo")
228
+ p_chk.add_argument("--setup-commit", default=None)
229
+ p_chk.set_defaults(func=cmd_check)
230
+
231
+ args = parser.parse_args(argv)
232
+ return args.func(args)
233
+
234
+
235
+ if __name__ == "__main__":
236
+ raise SystemExit(main())