@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
@@ -55,6 +55,7 @@
55
55
  """
56
56
  from __future__ import annotations
57
57
 
58
+ import datetime
58
59
  import os
59
60
  import re
60
61
  import signal
@@ -76,6 +77,7 @@ KILL_WAIT_S = 1.0
76
77
  # --- session ------------------------------------------------------------------
77
78
  def _win_session(argv: list[str]) -> int:
78
79
  _, exec_argv = forge_proc.resolve_win_command(argv)
80
+ job = forge_proc.ProcessJob()
79
81
  try:
80
82
  proc = subprocess.Popen(exec_argv)
81
83
  except FileNotFoundError:
@@ -84,7 +86,16 @@ def _win_session(argv: list[str]) -> int:
84
86
  except OSError as error:
85
87
  print('forge-guard: cannot execute %s: %s' % (argv[0], error), file=sys.stderr)
86
88
  return 126
87
- return proc.wait()
89
+ job.attach(proc.pid)
90
+ try:
91
+ rc = proc.wait()
92
+ # Keep KILL_ON_JOB_CLOSE armed while the child runs so an abrupt guardian
93
+ # termination cleans up descendants atomically; disarm on normal return so
94
+ # `reap` can still observe and record intentional orphans.
95
+ job.disarm()
96
+ return rc
97
+ finally:
98
+ job.close()
88
99
 
89
100
 
90
101
  def session(argv: list[str]) -> int:
@@ -285,9 +296,15 @@ def read_tracked(path):
285
296
  return found
286
297
 
287
298
 
299
+ def _same_start(recorded, current) -> bool:
300
+ """Whether two start times (identity, ps_table) name the same process start. Plain equality;
301
+ the Cygwin block below replaces it, since there a start older than a day is known to the day."""
302
+ return recorded == current
303
+
304
+
288
305
  def _mine(table, known):
289
306
  """The recorded processes still alive with their recorded start time (not a reused pid)."""
290
- return {pid for pid, start in known.items() if pid in table and table[pid][1] == start}
307
+ return {pid for pid, start in known.items() if pid in table and _same_start(start, table[pid][1])}
291
308
 
292
309
 
293
310
  def track(root: int, path: str, interval: float = TRACK_INTERVAL_S) -> int:
@@ -393,13 +410,24 @@ def stop_tree(root: int, wait: float) -> int:
393
410
  while left and time.monotonic() < deadline:
394
411
  time.sleep(0.2)
395
412
  now = ps_table() or {}
396
- left = {pid for pid in left if pid in now and now[pid][1] == starts[pid]}
413
+ left = {pid for pid in left if pid in now and _same_start(starts[pid], now[pid][1])}
397
414
  for pid in left:
398
415
  forge_proc.signal_pid(pid, force=True)
399
416
  print(len(targets))
400
417
  return 0
401
418
 
402
419
 
420
+ def kill_children(parent_pid: int, force: bool = False) -> int:
421
+ """Terminate descendants of `parent_pid` (used on platforms lacking `pkill -P`)."""
422
+ table = ps_table()
423
+ if table is None or parent_pid <= 1:
424
+ return 0
425
+ targets = descendants(table, {parent_pid}) - _never(table)
426
+ for pid in sorted(targets, reverse=True):
427
+ forge_proc.signal_pid(pid, force=force)
428
+ return 0
429
+
430
+
403
431
  def reap(pgid: int, orphans_file: str, tracked: str | None = None) -> int:
404
432
  count = _reap_group(pgid, orphans_file)
405
433
  extra = _reap_tracked(tracked, pgid) if tracked else []
@@ -430,6 +458,8 @@ def _ps_field(pid: int, field: str) -> str | None:
430
458
  def identity(pid: int) -> str | None:
431
459
  if forge_proc.IS_WINDOWS:
432
460
  return forge_proc.process_start_time(pid)
461
+ # On Cygwin (Windows MSYS2 mode) this is Cygwin ps's STIME made absolute (see the Cygwin
462
+ # block below). After 24 hours it is known only to the day: compare it with _same_start.
433
463
  return _ps_field(pid, 'lstart')
434
464
 
435
465
 
@@ -514,7 +544,8 @@ def stop(record: str) -> int:
514
544
  if pid > 1:
515
545
  if _pid_alive(pid):
516
546
  # A mismatch, or no way to tell, means the pid now belongs to someone else.
517
- if recorded and identity(pid) == recorded:
547
+ current = identity(pid)
548
+ if recorded and current is not None and _same_start(recorded, current):
518
549
  count = _stop_live(pid)
519
550
  else:
520
551
  count = _reap_group(pid, None)
@@ -602,12 +633,106 @@ def promises(path: str, tail_bytes: int = 3000) -> int:
602
633
  return 0
603
634
 
604
635
 
636
+ # --- Windows (MSYS2/Cygwin) -----------------------------------------------------
637
+ # procps builds each row from /proc/<pid>/stat, which Cygwin fills by asking Windows: about half
638
+ # a second per process, so one listing takes 15-20 s and outlives every timeout above, leaving
639
+ # the guards blind. Its start time is also the Windows process's, which changes when a Cygwin
640
+ # process execs a native program (a harness), so an identity recorded before the exec never
641
+ # matched again. Cygwin's own ps reads the same process table in milliseconds, keeps the start
642
+ # time across exec and hides zombies. Its STIME has one-second resolution and gives the time of
643
+ # day for the first 24 hours, then only the date: _cygwin_start makes either absolute, and
644
+ # _cygwin_same_start lets a start known to the day match one known to the second, so `stop`
645
+ # still recognises a harness after a day (to the day: a pid reused on that same day would pass).
646
+ _CYGWIN_MONTHS = {name: number for number, name in enumerate(
647
+ ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), 1)}
648
+
649
+
650
+ def _cygwin_start(stime: str, now: float | None = None) -> str:
651
+ """Cygwin ps's STIME as an absolute local start: 'YYYY-MM-DD HH:MM:SS' while ps gives the time
652
+ of day (the last 24 hours), 'YYYY-MM-DD' once it gives only the date ('Nov 19'). Text in
653
+ neither form comes back unchanged."""
654
+ today = time.localtime(time.time() if now is None else now)
655
+ parts = stime.split()
656
+ if len(parts) == 1 and re.fullmatch(r'\d\d:\d\d:\d\d', parts[0]):
657
+ day = datetime.date(today.tm_year, today.tm_mon, today.tm_mday)
658
+ if parts[0] > time.strftime('%H:%M:%S', today): # later than now: it was yesterday
659
+ day -= datetime.timedelta(days=1) # by the date: a day is not always 86400 s
660
+ return '%s %s' % (day.isoformat(), parts[0])
661
+ if len(parts) == 2 and parts[0] in _CYGWIN_MONTHS and parts[1].isdigit():
662
+ month, mday = _CYGWIN_MONTHS[parts[0]], int(parts[1])
663
+ year = today.tm_year - ((month, mday) > (today.tm_mon, today.tm_mday))
664
+ return '%04d-%02d-%02d' % (year, month, mday)
665
+ return stime
666
+
667
+
668
+ def _cygwin_same_start(recorded: str, current: str) -> bool:
669
+ """Whether two _cygwin_start values name the same start: equal, or one known only to the day
670
+ and the other on that day."""
671
+ if recorded == current:
672
+ return True
673
+ shorter, longer = sorted((recorded, current), key=len)
674
+ return len(shorter) == 10 and longer.startswith(shorter + ' ')
675
+
676
+
677
+ if sys.platform == 'cygwin':
678
+ CYGWIN_PS = '/usr/bin/ps'
679
+ _CYGWIN_ROW = re.compile(r'^\s*[A-Z]?\s*(\d+)\s+(\d+)\s+(\d+)\s+\d+\s+\S+\s+\d+\s+'
680
+ r'(\d\d:\d\d:\d\d|[A-Z][a-z]{2}\s+\d+)\s+(.*)$')
681
+ _same_start = _cygwin_same_start
682
+
683
+ def _cygwin_rows(pid: int | None = None):
684
+ """{pid: (ppid, pgid, start, executable)} of live processes, or None when ps cannot run.
685
+ LC_ALL=C keeps STIME's month names in English for _cygwin_start."""
686
+ try:
687
+ out = subprocess.run([CYGWIN_PS, '-l'] + (['-p', str(pid)] if pid else ['-a']),
688
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=30,
689
+ env=dict(os.environ, LC_ALL='C')).stdout.decode(errors='replace')
690
+ except (OSError, subprocess.SubprocessError):
691
+ return None
692
+ rows = {}
693
+ for line in out.splitlines()[1:]:
694
+ match = _CYGWIN_ROW.match(line)
695
+ if match:
696
+ rows[int(match[1])] = (int(match[2]), int(match[3]), _cygwin_start(match[4]), match[5].strip())
697
+ return rows
698
+
699
+ def _command(pid: int, fallback: str) -> str:
700
+ """The full command line where Cygwin can read it cheaply; the executable otherwise."""
701
+ try:
702
+ with open('/proc/%d/cmdline' % pid, 'rb') as handle:
703
+ return handle.read().replace(b'\0', b' ').decode(errors='replace').strip() or fallback
704
+ except OSError:
705
+ return fallback
706
+
707
+ def list_group(pgid: int):
708
+ rows = _cygwin_rows()
709
+ if rows is None:
710
+ return None
711
+ me = os.getpid()
712
+ return [(pid, _command(pid, exe)) for pid, (_ppid, group, _start, exe) in sorted(rows.items())
713
+ if group == pgid and pid != me]
714
+
715
+ def ps_table():
716
+ rows = _cygwin_rows()
717
+ if rows is None:
718
+ return None
719
+ return {pid: (ppid, start, exe) for pid, (ppid, _group, start, exe) in rows.items()}
720
+
721
+ def _ps_field(pid: int, field: str) -> str | None:
722
+ if pid <= 0:
723
+ return None
724
+ row = (_cygwin_rows(pid) or {}).get(pid)
725
+ if row is None:
726
+ return None
727
+ return {'stat': 'S', 'lstart': row[2], 'ppid': str(row[0]), 'pgid': str(row[1])}.get(field)
728
+
729
+
605
730
  # --- cli ----------------------------------------------------------------------
606
731
  def main(argv: list[str]) -> int:
607
732
  if not argv:
608
733
  print('usage: forge-guard.py ping | session -- CMD... | reap <pgid> <orphans-file> [--tracked FILE] | '
609
- 'track <pid> <file> [--interval S] | stop-tree <pid> [--wait S] | identity <pid> | '
610
- 'stop <record-file> | '
734
+ 'track <pid> <file> [--interval S] | stop-tree <pid> [--wait S] | kill-children <pid> [TERM|KILL] | '
735
+ 'identity <pid> | stop <record-file> | '
611
736
  'promises <file> [--tail-bytes N]', file=sys.stderr)
612
737
  return 2
613
738
  command, rest = argv[0], argv[1:]
@@ -639,6 +764,12 @@ def main(argv: list[str]) -> int:
639
764
  print('usage: forge-guard.py stop-tree <pid> [--wait S]', file=sys.stderr)
640
765
  return 2
641
766
  return stop_tree(int(rest[0]), max(0.0, wait))
767
+ if command == 'kill-children':
768
+ if len(rest) not in (1, 2):
769
+ print('usage: forge-guard.py kill-children <pid> [TERM|KILL]', file=sys.stderr)
770
+ return 2
771
+ force = len(rest) == 2 and rest[1].upper() == 'KILL'
772
+ return kill_children(int(rest[0]), force=force)
642
773
  if command == 'track':
643
774
  interval = TRACK_INTERVAL_S
644
775
  if '--interval' in rest:
@@ -3,7 +3,8 @@
3
3
 
4
4
  show [RUN_DIR | --repo DIR] [--json] (the default subcommand: `forge handoff RUN_DIR`)
5
5
  Everything a new session, or another harness, needs to carry a run on, in one output:
6
- the run, the choices it was launched with, whether a scheduler lives, each task, what
6
+ the run, the choices it was launched with, whether a scheduler lives, each task (and under
7
+ a task that was split, its subtasks with the sub-plan dir they are tasks of), what
7
8
  needs a person, the last human changes, tasks left RUNNING by a dead scheduler, the
8
9
  handoff notes and driver, and the exact commands to run next.
9
10
  With no RUN_DIR it picks --repo's (default: this checkout's) newest run that is live or
@@ -28,12 +29,15 @@
28
29
  resume RUN_DIR [--take-over] [--harness H] [--session S] [--json]
29
30
  Carry a decomposed run on from any harness. It claims the run first (like claim; a refused
30
31
  claim exits 3 and does nothing else), then: with a live scheduler it only says so and points
31
- at `forge control show` (nothing is started); a Fractal plan points at `forge fractal resume`;
32
+ at `forge control show` (nothing is started); a plan made with Fractal (removed in 0.23) is refused;
32
33
  otherwise each task left RUNNING by a dead scheduler has its worktree diff saved to
33
34
  tasks/<id>/interrupted-<epoch>.diff, the worktree reset and cleaned (only after it passes a
34
35
  guard: exactly <wt_root>/<id>, a git worktree on forge/<run_id>/<id>), the status set to
35
- INTERRUPTED and the attempt counter rewound when attempts.tsv has no row for it. Every
36
- INTERRUPTED task is prepared with `forge-parallel.sh retry --no-dispatch`, and the run is
36
+ INTERRUPTED and the attempt counter rewound when attempts.tsv has no row for it (unless
37
+ the attempt reached its commit: it was stopped during its review, and the retry re-runs
38
+ only that review). Every
39
+ INTERRUPTED task is prepared with `forge-parallel.sh retry --no-dispatch` (the subtasks of a split
40
+ task are recovered and prepared the same way, in the task's sub-plan), and the run is
37
41
  started again, detached, from run.flags.json (log: resume-<epoch>.log; the exit code goes to
38
42
  resume-<epoch>.done). Without run.flags.json it prints the run command to finish by hand.
39
43
  FORGE_HANDOFF_NO_START=1 prints the command and starts nothing.
@@ -67,6 +71,8 @@ SCRIPTS = Path(__file__).resolve().parent
67
71
  sys.path.insert(0, str(SCRIPTS))
68
72
  import forge_infra # noqa: E402
69
73
  import forge_registry # noqa: E402
74
+ import forge_flock # noqa: E402
75
+ import forge_legacy # noqa: E402
70
76
 
71
77
  PARALLEL = str(SCRIPTS / 'forge-parallel.sh')
72
78
  SWEEP_OK = re.compile(r'P[0-3]')
@@ -80,15 +86,17 @@ TASK_OK = frozenset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456
80
86
  OPTION_FILES = (
81
87
  'no_ripwire', 'no_memory', 'yolo_dwarf', 'yolo_qa', 'reviewer_session', 'reviewer_session_rate',
82
88
  'reviewer_session_tasks', 'implementer_session', 'fast', 'pre_review_tests', 'pre_review_parallel',
83
- 'qa_threshold', 'timeout', 'verify_retries', 'verify_cmd', 'verify_parallel', 'setup_cmd', 'final_qa',
89
+ 'qa_threshold', 'qa_test_minutes', 'timeout', 'verify_retries', 'verify_cmd', 'verify_parallel', 'setup_cmd', 'setup_before_verify', 'final_qa',
84
90
  'shadow_qa', 'shadow_rate', 'explore', 'escalate_after', 'retry_per_model', 'fail_first',
85
- 'fractal-routing.json', 'fractal-selection.json', 'jev-selection.json', 'profile.json', 'routed.json',
91
+ 'dwarf-routing.json', 'jev-selection.json', 'profile.json', 'routed.json',
92
+ # What a plan made before forge 0.23 has instead (forge_legacy.py): its tier pools and its Fractal choice.
93
+ 'fractal-routing.json', 'fractal-selection.json',
86
94
  'qa-routing.json', 'retro_mode', 'brief', 'brief_scope', 'brief_model', 'summaries', 'summaries_model',
87
95
  'groups.tsv', 'groups.frozen', 'group_max_tasks', 'group_max_diff_kb', 'after', 'max_parallel')
88
96
  FLAG_KEYS = ('retry_failed', 'infra_retries', 'sweep', 'sweep_max', 'sweep_plausible', 'sweep_ahead',
89
- 'max_parallel', 'timeout', 'verify', 'fractal', 'argv', 'at')
97
+ 'max_parallel', 'timeout', 'verify', 'argv', 'at')
90
98
  JSON_KEYS = ('run', 'choices', 'flags', 'scheduler', 'tasks', 'needs_you', 'changes', 'stale', 'notes',
91
- 'driver', 'next')
99
+ 'driver', 'next', 'subtasks')
92
100
  NOTE_MAX = 2000
93
101
  SESSION_MAX = 200
94
102
  # A different driver last seen longer ago than this is replaced without --take-over. Tests patch it.
@@ -195,6 +203,7 @@ class Plan:
195
203
  # ------------------------------------------------------------------------------------ the sections
196
204
 
197
205
  def kind_of(plan, fractal):
206
+ # 'fractal' is an old record: a plan made before forge 0.23 removed that backend (#154).
198
207
  if (plan.path / 'tasks.tsv').is_file():
199
208
  return 'fractal' if fractal else 'decomposed'
200
209
  if (plan.path / 'prompt.md').is_file() and (plan.path / 'repo').is_file():
@@ -203,8 +212,7 @@ def kind_of(plan, fractal):
203
212
 
204
213
 
205
214
  def is_fractal(plan):
206
- data = plan.json('fractal-selection.json')
207
- return bool(data and data.get('enabled'))
215
+ return forge_legacy.was_fractal(plan.path)
208
216
 
209
217
 
210
218
  def run_section(plan, kind):
@@ -277,7 +285,52 @@ def tasks_section(plan):
277
285
  return rows
278
286
 
279
287
 
280
- def needs_you_section(plan, tasks, now):
288
+ SUB_DEPTH = 8 # the depth limit of a run's decomposition tops out at 6
289
+
290
+
291
+ def split_state(plan, task):
292
+ """None for a task with no sub-plan, else `open` (its subtasks' work is not on its branch yet) or `merged`."""
293
+ if not plan.exists(f'tasks/{task}/sub/tasks.tsv'):
294
+ return None
295
+ return 'merged' if plan.exists(f'tasks/{task}/sub.merged') else 'open'
296
+
297
+
298
+ def subtasks_section(plan, tasks, prefix='', depth=0):
299
+ """The subtasks of every task that was split (#153), through every level, in tree order:
300
+ [{id, task, parent, plan, status, dwarf, split}]. `id` is the path from the run's own task (`d/a`),
301
+ `plan` the sub-plan dir the subtask is a task of: every command about it names that dir."""
302
+ rows = []
303
+ if depth >= SUB_DEPTH:
304
+ return rows
305
+ for task in tasks:
306
+ state = split_state(plan, task['id'])
307
+ if state is None:
308
+ continue
309
+ sub = Plan(plan.path / 'tasks' / task['id'] / 'sub')
310
+ children = tasks_section(sub)
311
+ plan.warnings.extend(f'{prefix}{task["id"]}/sub: {w}' for w in sub.warnings)
312
+ for child in children:
313
+ rows.append(dict(id=f'{prefix}{task["id"]}/{child["id"]}', task=child['id'], parent=prefix + task['id'],
314
+ plan=str(sub.path), status=child['status'], dwarf=child['dwarf'],
315
+ split=split_state(sub, child['id'])))
316
+ rows += subtasks_section(sub, [child], f'{prefix}{task["id"]}/', depth + 1)
317
+ return rows
318
+
319
+
320
+ def needs_you_section(plan, tasks, now, subtasks=()):
321
+ items = needs_of(plan, tasks, now)
322
+ # A subtask that waits for a person waits in its own sub-plan: the item carries that plan dir.
323
+ by_plan = {}
324
+ for row in subtasks:
325
+ by_plan.setdefault(row['plan'], []).append(row)
326
+ for where, rows in by_plan.items():
327
+ for item in needs_of(Plan(where), [dict(id=row['task'], status=row['status']) for row in rows], now):
328
+ path = next(row['id'] for row in rows if row['task'] == item['task'])
329
+ items.append(dict(item, plan=where, path=path))
330
+ return items
331
+
332
+
333
+ def needs_of(plan, tasks, now):
281
334
  items = []
282
335
  pauses = None
283
336
  for task in tasks:
@@ -354,18 +407,24 @@ def next_section(plan, run, scheduler, tasks, needs):
354
407
  live = scheduler['live']
355
408
  if live:
356
409
  steps.append(dict(command=f'forge control show {q(here)}', why='the run is live: its state and controls'))
410
+ elif open_tasks and run['kind'] == 'fractal':
411
+ steps.append(dict(command=f'forge ui open {q(here)}', why=forge_legacy.refusal('this run')))
357
412
  elif open_tasks:
358
413
  steps.append(dict(command=f'forge handoff resume {q(here)}', why='no scheduler is live and work is left'))
359
- if run['kind'] == 'fractal':
360
- steps.append(dict(command=f'forge fractal resume {q(run["run_id"] or here)}',
361
- why='a Fractal-backed run: recover its recorded executions'))
362
414
  for item in needs:
415
+ # A subtask's commands name its own sub-plan dir (#153).
416
+ where, name = q(item.get('plan') or here), item.get('path') or item['task']
417
+ verb = f'forge control retry {where} {q(item["task"])}' if live else f'{PARALLEL} retry {where} {q(item["task"])}'
363
418
  if item['kind'] == 'NEEDS_INPUT':
364
- verb = f'forge control retry {q(here)} {q(item["task"])}' if live else f'{PARALLEL} retry {q(here)} {q(item["task"])}'
365
- steps.append(dict(command=verb + ' --answer "…"', why=f'answer the question of {item["task"]}'))
366
- elif item['kind'] == 'NEEDS_DECISION' and live:
367
- steps.append(dict(command=f'forge control retry {q(here)} {q(item["task"])} --decide retry=N --reason "…" --approved',
368
- why=f'{item["task"]} needs a decision (or --decide threshold=Pn, or --dwarf SPEC)'))
419
+ steps.append(dict(command=verb + ' --answer "…"', why=f'answer the question of {name}'))
420
+ elif item['kind'] == 'NEEDS_DECISION':
421
+ if live:
422
+ steps.append(dict(command=f'forge control retry {where} {q(item["task"])} --decide retry=N --reason "…" --approved',
423
+ why=f'{name} needs a decision (or --decide threshold=Pn, or --dwarf SPEC)'))
424
+ if 'split' in [word.strip() for word in (item['reasons'] or '').replace('reasons:', '').split(',')]:
425
+ steps.append(dict(command=verb + ' --decide split --subtasks FILE --reason "…" --approved',
426
+ why=f'{name} stopped on split: split it into subtasks, only on the user\'s word '
427
+ '(FILE holds the subtasks; without a live run, --planner SPEC asks a planner instead)'))
369
428
  if tasks and not open_tasks and run['kind'] != 'solo':
370
429
  steps.append(dict(command=f'{PARALLEL} integrate {q(here)} --approved',
371
430
  why='every task is merged; run this only on the user\'s word'))
@@ -383,10 +442,14 @@ def report(path):
383
442
  run = run_section(plan, kind)
384
443
  scheduler = scheduler_section(plan)
385
444
  tasks = tasks_section(plan)
386
- needs = needs_you_section(plan, tasks, time.time())
445
+ subtasks = subtasks_section(plan, tasks) if kind != 'solo' else []
446
+ needs = needs_you_section(plan, tasks, time.time(), subtasks)
387
447
  stale = [] if scheduler['live'] else [dict(task=task['id'], note='left RUNNING with no live process')
388
448
  for task in tasks if task['status'] == 'RUNNING']
449
+ if not scheduler['live']:
450
+ stale += [dict(task=row['id'], note='left RUNNING with no live process') for row in subtasks if row['status'] == 'RUNNING']
389
451
  out = dict(run=run, choices=choices_section(plan), flags=flags_section(plan), scheduler=scheduler, tasks=tasks,
452
+ subtasks=subtasks,
390
453
  needs_you=needs, changes=changes_section(plan), stale=stale, notes=notes_section(plan),
391
454
  driver=driver_section(plan), next=next_section(plan, run, scheduler, tasks, needs))
392
455
  out['warnings'] = plan.warnings
@@ -442,20 +505,35 @@ def render(data):
442
505
  h = sched['holder']
443
506
  out.append(f' schedule.holder: {h["command"]} (pid {h["pid"]}, since {when(h["at"])})')
444
507
  head('Tasks')
508
+ below = {}
509
+ for row in data.get('subtasks') or []:
510
+ below.setdefault(row['parent'], []).append(row)
511
+
512
+ def subtasks_of(parent, depth):
513
+ # A split task's subtasks, under it: each is a task of the sub-plan dir printed on the first line.
514
+ rows = below.get(parent) or []
515
+ if rows:
516
+ out.append(f' {" " * depth}subtasks, in {rows[0]["plan"]}:')
517
+ for row in rows:
518
+ out.append(f' {" " * depth}{row["task"]:<{max(1, 24 - 2 * depth)}} {row["status"]:<15} {row["dwarf"] or "-"}')
519
+ subtasks_of(row['id'], depth + 1)
520
+
445
521
  for task in data['tasks']:
446
522
  out.append(f' {task["id"]:<24} {task["status"]:<15} {task["dwarf"] or "-"}')
523
+ subtasks_of(task['id'], 1)
447
524
  if not data['tasks']:
448
525
  out.append(' (none)')
449
526
  head('Needs you')
450
527
  for item in data['needs_you']:
528
+ name = item.get('path') or item['task']
451
529
  if item['kind'] == 'NEEDS_INPUT':
452
- out.append(f' {item["task"]}: NEEDS_INPUT, the question:')
530
+ out.append(f' {name}: NEEDS_INPUT, the question:')
453
531
  out.extend(' ' + line for line in (item['question'] or '(needs_input.md missing)').splitlines())
454
532
  elif item['kind'] == 'NEEDS_DECISION':
455
- out.append(f' {item["task"]}: NEEDS_DECISION {item["reasons"] or "(decision.md missing)"}')
533
+ out.append(f' {name}: NEEDS_DECISION {item["reasons"] or "(decision.md missing)"}')
456
534
  else:
457
535
  where = '/'.join(part for part in (item['harness'], item['model']) if part) or 'unknown'
458
- line = f' {item["task"]}: INFRA, {item["cause"]} on {where}'
536
+ line = f' {name}: INFRA, {item["cause"]} on {where}'
459
537
  if item['stage']:
460
538
  line += f' ({item["stage"]} stage)'
461
539
  if item['needs_you']:
@@ -805,10 +883,6 @@ def run_command(plan, flags):
805
883
  command += ['--timeout', str(flags['timeout'])]
806
884
  if isinstance(flags.get('verify'), str) and flags['verify']:
807
885
  command += ['--verify', flags['verify']]
808
- if flags.get('fractal') is True:
809
- command.append('--fractal')
810
- elif flags.get('fractal') is False:
811
- command.append('--no-fractal')
812
886
  return command
813
887
 
814
888
 
@@ -883,8 +957,23 @@ def save_diff(wt, dest):
883
957
  shutil.rmtree(scratch, ignore_errors=True)
884
958
 
885
959
 
886
- def attempt_rewound(ctrl, plan, task):
887
- """Write the attempt counter back by one when attempts.tsv has no row for it. Whether it did."""
960
+ def attempt_committed(ctrl, plan, task, wt, number):
961
+ """Whether attempt NUMBER reached its commit: reviewed.commit is "forge(<task>) attempt NUMBER: ...".
962
+
963
+ Such an attempt was stopped during its review. It keeps its number: the retry re-runs only the
964
+ review (forge-lib-task.sh unjudged_attempt_commit), which spends no attempt.
965
+ """
966
+ commit = (ctrl.read_file(plan, f'tasks/{task}/reviewed.commit') or '').strip()
967
+ if not commit:
968
+ return False
969
+ result = git(wt, 'log', '-1', '--format=%s', commit)
970
+ subject = result.stdout.decode('utf-8', 'replace').strip() if result.returncode == 0 else ''
971
+ return subject.startswith(f'forge({task}) attempt {number}: ')
972
+
973
+
974
+ def attempt_rewound(ctrl, plan, task, wt):
975
+ """Write the attempt counter back by one when attempts.tsv has no row for it and the attempt
976
+ never reached its commit. Whether it did."""
888
977
  text = ctrl.read_file(plan, f'tasks/{task}/attempt')
889
978
  word = (text or '').split()
890
979
  if not word or not word[0].isdigit() or int(word[0]) < 1:
@@ -895,6 +984,8 @@ def attempt_rewound(ctrl, plan, task):
895
984
  cols = row.split('\t')
896
985
  if len(cols) > 1 and cols[1].strip() == str(number):
897
986
  return False
987
+ if attempt_committed(ctrl, plan, task, wt, number):
988
+ return False
898
989
  ctrl.write_atomic(plan, f'tasks/{task}/attempt', f'{number - 1}\n')
899
990
  return True
900
991
 
@@ -965,12 +1056,86 @@ def recover_task(ctrl, plan, wt_root, run_id, task, warn):
965
1056
  try:
966
1057
  ctrl.write_atomic(str(plan), f'tasks/{task}/status', 'INTERRUPTED\n')
967
1058
  interrupted_event(plan, task)
968
- row['attempt_rewound'] = attempt_rewound(ctrl, str(plan), task)
1059
+ row['attempt_rewound'] = attempt_rewound(ctrl, str(plan), task, wt)
969
1060
  except (OSError, ctrl.Invalid) as error:
970
1061
  warn(f'{task}: could not update its status or attempt counter ({error})')
971
1062
  return row
972
1063
 
973
1064
 
1065
+ def resume_subtasks(ctrl, plan, warn, out, depth=0):
1066
+ """The same recovery one level down (#153): in the sub-plan of every split task whose subtasks' work is
1067
+ not on the task's branch yet, a subtask left RUNNING by a dead run is saved, reset and marked
1068
+ INTERRUPTED, and every INTERRUPTED subtask is prepared. Each sub-plan is worked on under its own plan
1069
+ lock; one a live run still holds is left alone, and said. Rows carry `plan`, the sub-plan dir."""
1070
+ if depth >= SUB_DEPTH:
1071
+ return
1072
+ for task in tasks_section(Plan(plan)):
1073
+ if split_state(Plan(plan), task['id']) != 'open':
1074
+ continue
1075
+ sub = os.path.join(str(plan), 'tasks', task['id'], 'sub')
1076
+ view = Plan(sub)
1077
+ wt_root, run_id = view.line('wt_root'), view.line('run_id')
1078
+ if wt_root and run_id: # else it has never run: nothing can be stale in it
1079
+ lock = take_plan_lock(sub)
1080
+ if lock is None:
1081
+ warn(f'{task["id"]}: its subtasks ({sub}) are locked by {lock_holder(sub)}; nothing there was recovered')
1082
+ continue
1083
+ try:
1084
+ if scheduler_section(Plan(sub))['live']:
1085
+ warn(f'{task["id"]}: a run of its subtasks ({sub}) is live; nothing there was recovered')
1086
+ continue
1087
+ for child in tasks_section(Plan(sub)):
1088
+ if child['status'] == 'RUNNING':
1089
+ row = recover_task(ctrl, sub, wt_root, run_id, child['id'], warn)
1090
+ if row is not None:
1091
+ out['recovered'].append(dict(row, plan=sub))
1092
+ finally:
1093
+ try:
1094
+ forge_flock.flock(lock, forge_flock.LOCK_UN)
1095
+ except (OSError, ValueError):
1096
+ pass
1097
+ lock.close()
1098
+ for child in tasks_section(Plan(sub)):
1099
+ if child['status'] == 'INTERRUPTED':
1100
+ result = dict(prepare_task(sub, child['id']), plan=sub)
1101
+ out['prepared'].append(result)
1102
+ if not result['ok']:
1103
+ warn(f'{task["id"]}/{child["id"]}: could not be prepared for a retry: {result["message"]}')
1104
+ resume_subtasks(ctrl, sub, warn, out, depth + 1)
1105
+
1106
+
1107
+ def take_plan_lock(plan):
1108
+ """schedule.lock, the plan lock every forge-parallel.sh command that changes a plan holds (#157).
1109
+
1110
+ The open file while it is held, else None (another command holds it, or it cannot be taken). Held
1111
+ while stale tasks are reset, so a `run` started meanwhile is refused at the lock instead of racing
1112
+ the git reset and the status write; released before `retry --no-dispatch`, which takes it itself.
1113
+ """
1114
+ try:
1115
+ handle = open(os.path.join(str(plan), 'schedule.lock'), 'a')
1116
+ except OSError:
1117
+ return None
1118
+ try:
1119
+ forge_flock.flock(handle, forge_flock.LOCK_EX | forge_flock.LOCK_NB)
1120
+ except (OSError, ValueError):
1121
+ handle.close()
1122
+ return None
1123
+ return handle
1124
+
1125
+
1126
+ def lock_holder(plan):
1127
+ """Who holds the plan lock, in words, from schedule.holder (written by each command that takes it)."""
1128
+ try:
1129
+ with open(os.path.join(str(plan), 'schedule.holder'), encoding='utf-8') as handle:
1130
+ holder = json.loads(handle.read(READ_CAP))
1131
+ except (OSError, ValueError):
1132
+ holder = None
1133
+ if isinstance(holder, dict) and isinstance(holder.get('command'), str) and holder['command'].isidentifier() \
1134
+ and type(holder.get('pid')) is int and pid_alive(holder['pid']):
1135
+ return f'forge-parallel.sh {holder["command"]} (pid {holder["pid"]})'
1136
+ return 'another forge command'
1137
+
1138
+
974
1139
  def prepare_task(plan, task):
975
1140
  """forge-parallel.sh retry PLAN TASK --no-dispatch. {task, ok, message}."""
976
1141
  command = forge_proc.bash_cmd(parallel_script(), 'retry', str(plan), task, '--no-dispatch')
@@ -1007,7 +1172,7 @@ def cmd_resume(args):
1007
1172
  if not (Path(plan) / 'tasks.tsv').is_file():
1008
1173
  raise Usage(f'{plan}: resume needs a decomposed run (tasks.tsv)') # before the claim: a solo run is not marked
1009
1174
  claim_run(plan, args.harness, session, args.take_over) # Held (a refused claim) exits 3 before anything else
1010
- out = dict(live=False, recovered=[], prepared=[], started=None, command=[])
1175
+ out = dict(live=False, locked=False, recovered=[], prepared=[], started=None, command=[])
1011
1176
  view = Plan(plan)
1012
1177
  scheduler = scheduler_section(view)
1013
1178
  quote = shlex.quote
@@ -1025,22 +1190,39 @@ def cmd_resume(args):
1025
1190
  return finish(f'the run is live (scheduler pid {scheduler["pid"]}) and is being followed; nothing was started',
1026
1191
  f'forge control show {quote(plan)}')
1027
1192
  if is_fractal(view):
1028
- run_id = view.line('run_id')
1029
- return finish('a Fractal plan is not restarted here; recover its recorded executions:',
1030
- f'forge fractal resume {quote(run_id or plan)}')
1193
+ return finish(forge_legacy.refusal('this plan'))
1031
1194
 
1032
1195
  ctrl, wt_root, run_id = control(), view.line('wt_root'), view.line('run_id')
1033
- for task in tasks_section(view):
1034
- if task['status'] == 'RUNNING':
1035
- row = recover_task(ctrl, plan, wt_root, run_id, task['id'], warn)
1036
- if row is not None:
1037
- out['recovered'].append(row)
1196
+ # The plan lock first (#157): a command that holds it is working on the plan, and nothing here may
1197
+ # reset its worktrees or restart it. Held through the resets, so no scheduler can start meanwhile.
1198
+ lock = take_plan_lock(plan)
1199
+ if lock is None:
1200
+ out['locked'] = True
1201
+ return finish(f'the plan is locked by {lock_holder(plan)}; nothing was recovered or started. '
1202
+ 'Run this again once it has finished.', f'forge control show {quote(plan)}')
1203
+ try:
1204
+ if scheduler_section(Plan(plan))['live']:
1205
+ out['live'] = True
1206
+ return finish('a scheduler started while resume was starting; nothing was changed or started',
1207
+ f'forge control show {quote(plan)}')
1208
+ for task in tasks_section(Plan(plan)):
1209
+ if task['status'] == 'RUNNING':
1210
+ row = recover_task(ctrl, plan, wt_root, run_id, task['id'], warn)
1211
+ if row is not None:
1212
+ out['recovered'].append(row)
1213
+ finally:
1214
+ try:
1215
+ forge_flock.flock(lock, forge_flock.LOCK_UN)
1216
+ except (OSError, ValueError):
1217
+ pass
1218
+ lock.close()
1038
1219
  for task in tasks_section(Plan(plan)):
1039
1220
  if task['status'] == 'INTERRUPTED':
1040
1221
  result = prepare_task(plan, task['id'])
1041
1222
  out['prepared'].append(result)
1042
1223
  if not result['ok']:
1043
1224
  warn(f'{task["id"]}: could not be prepared for a retry: {result["message"]}')
1225
+ resume_subtasks(ctrl, plan, warn, out)
1044
1226
 
1045
1227
  flags_view = Plan(plan)
1046
1228
  flags = flags_view.json('run.flags.json')