@giamme/forge 0.22.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 (153) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +19 -12
  3. package/SKILL.md +137 -216
  4. package/VERSION +1 -1
  5. package/docs/README.md +2 -3
  6. package/docs/add-ons.md +5 -3
  7. package/docs/artifacts.md +17 -2
  8. package/docs/commands.md +85 -63
  9. package/docs/decomposed-runs.md +195 -21
  10. package/docs/development.md +11 -9
  11. package/docs/forge-ui.md +33 -4
  12. package/docs/install.md +37 -5
  13. package/docs/memory.md +6 -1
  14. package/docs/models.md +36 -10
  15. package/docs/reviews.md +44 -25
  16. package/docs/safety.md +27 -2
  17. package/docs/troubleshooting.md +7 -10
  18. package/forge +25 -4
  19. package/package.json +2 -1
  20. package/references/dataset.md +10 -9
  21. package/references/decompose-integration.md +337 -0
  22. package/references/decompose-opt-in.md +527 -0
  23. package/references/decompose-recovery.md +569 -0
  24. package/references/decompose-review.md +256 -0
  25. package/references/decompose.md +99 -1606
  26. package/references/findings.md +68 -0
  27. package/references/harnesses.md +7 -12
  28. package/references/memory.md +13 -2
  29. package/references/planning.md +48 -18
  30. package/references/ripwire.md +38 -13
  31. package/references/runtime.md +22 -33
  32. package/references/setup.md +90 -0
  33. package/references/solo.md +13 -42
  34. package/references/ui.md +12 -5
  35. package/registry.tsv +40 -22
  36. package/scripts/forge-artifact.sh +143 -12
  37. package/scripts/forge-compare.py +5 -15
  38. package/scripts/forge-config.py +14 -1
  39. package/scripts/forge-contract.py +216 -53
  40. package/scripts/forge-control.py +777 -54
  41. package/scripts/forge-dispatch.sh +95 -12
  42. package/scripts/forge-du.py +13 -3
  43. package/scripts/forge-handoff.py +221 -39
  44. package/scripts/forge-install-ripwire.sh +100 -24
  45. package/scripts/forge-install.sh +18 -32
  46. package/scripts/forge-issues.py +6 -4
  47. package/scripts/forge-jev-options.sh +3 -5
  48. package/scripts/forge-lib-adopt.sh +169 -5
  49. package/scripts/forge-lib-attribute.sh +10 -3
  50. package/scripts/forge-lib-decompose.sh +454 -0
  51. package/scripts/forge-lib-env.sh +21 -0
  52. package/scripts/forge-lib-group.sh +4 -1
  53. package/scripts/forge-lib-plans.sh +30 -18
  54. package/scripts/forge-lib-review.sh +28 -8
  55. package/scripts/forge-lib-task.sh +225 -56
  56. package/scripts/forge-lib-verify.sh +59 -10
  57. package/scripts/forge-memory.sh +81 -4
  58. package/scripts/forge-metrics.sh +4 -2
  59. package/scripts/forge-parallel-options.sh +23 -4
  60. package/scripts/forge-parallel.sh +447 -175
  61. package/scripts/forge-plan-check.py +71 -8
  62. package/scripts/forge-planner.py +303 -17
  63. package/scripts/forge-pr.py +9 -1
  64. package/scripts/forge-prompt.py +2 -2
  65. package/scripts/forge-review-links.py +248 -0
  66. package/scripts/forge-ripwire.py +234 -16
  67. package/scripts/forge-route.py +19 -27
  68. package/scripts/forge-runs-rm.py +92 -21
  69. package/scripts/forge-runs.py +46 -5
  70. package/scripts/forge-runtime.py +37 -12
  71. package/scripts/forge-schedule.py +124 -33
  72. package/scripts/forge-setup-stale.py +236 -0
  73. package/scripts/forge-setup.py +804 -0
  74. package/scripts/forge-shadow.py +2 -20
  75. package/scripts/forge-solo-lock.py +46 -0
  76. package/scripts/forge-solo.sh +33 -56
  77. package/scripts/forge-sweep.py +2 -1
  78. package/scripts/forge-ui.py +8 -1
  79. package/scripts/forge-update.sh +2 -2
  80. package/scripts/forge-verify.py +16 -1
  81. package/scripts/forge-version.py +13 -1
  82. package/scripts/forge-watch.py +7 -2
  83. package/scripts/forge_dataset/__init__.py +1 -1
  84. package/scripts/forge_dataset/capture.py +0 -34
  85. package/scripts/forge_dataset/checks.py +0 -1
  86. package/scripts/forge_dataset/cli.py +5 -1
  87. package/scripts/forge_dataset/export.py +28 -6
  88. package/scripts/forge_dataset/facts.py +1 -2
  89. package/scripts/forge_dataset/forecast.py +1 -1
  90. package/scripts/forge_dataset/harvest.py +107 -7
  91. package/scripts/forge_dataset/importer.py +3 -2
  92. package/scripts/forge_dataset/pairs.py +3 -3
  93. package/scripts/forge_dataset/reviewers.py +4 -3
  94. package/scripts/forge_dataset/routing.py +6 -3
  95. package/scripts/forge_dataset/tiers.py +1 -1
  96. package/scripts/forge_decide/__init__.py +1 -1
  97. package/scripts/forge_decide/profiles.py +11 -14
  98. package/scripts/forge_decompose.py +987 -0
  99. package/scripts/forge_groups/review.py +6 -1
  100. package/scripts/forge_jev/__init__.py +1 -1
  101. package/scripts/forge_jev/cli.py +10 -1
  102. package/scripts/forge_jev/gates.py +10 -1
  103. package/scripts/forge_jev/verify.py +10 -2
  104. package/scripts/forge_legacy.py +86 -0
  105. package/scripts/forge_memory_home.py +57 -0
  106. package/scripts/forge_models.py +151 -0
  107. package/scripts/forge_prefs.py +138 -0
  108. package/scripts/forge_side/__init__.py +10 -0
  109. package/scripts/forge_storage.py +28 -15
  110. package/ui/README.md +22 -10
  111. package/ui/docs/api.md +121 -99
  112. package/ui/forge_ui/control.py +46 -14
  113. package/ui/forge_ui/export.py +0 -10
  114. package/ui/forge_ui/models.py +15 -2
  115. package/ui/forge_ui/projects.py +4 -1
  116. package/ui/forge_ui/reader.py +456 -59
  117. package/ui/forge_ui/server.py +0 -10
  118. package/ui/forge_ui/static/app.js +28 -9
  119. package/ui/forge_ui/static/checksview.js +12 -3
  120. package/ui/forge_ui/static/controls.js +147 -11
  121. package/ui/forge_ui/static/convo.js +5 -2
  122. package/ui/forge_ui/static/diffview.js +4 -5
  123. package/ui/forge_ui/static/panel.js +180 -77
  124. package/ui/forge_ui/static/projectsview.js +16 -2
  125. package/ui/forge_ui/static/runmodel.js +18 -4
  126. package/ui/forge_ui/static/scene3d.js +29 -29
  127. package/ui/forge_ui/static/settings.js +1 -1
  128. package/ui/forge_ui/static/storageview.js +2 -2
  129. package/ui/forge_ui/static/style.css +23 -6
  130. package/ui/forge_ui/static/worktreesview.js +8 -4
  131. package/ui/forge_ui/transcripts.py +6 -0
  132. package/ui/forge_ui/worktrees.py +13 -1
  133. package/docs/fractal.md +0 -181
  134. package/references/fractal-dashboard.md +0 -21
  135. package/references/fractal.md +0 -307
  136. package/scripts/forge-fractal-dispatch.sh +0 -4
  137. package/scripts/forge-fractal-options.sh +0 -54
  138. package/scripts/forge-fractal.py +0 -6
  139. package/scripts/forge-install-fractal.sh +0 -4
  140. package/scripts/forge_fractal/__init__.py +0 -88
  141. package/scripts/forge_fractal/bridge.py +0 -46
  142. package/scripts/forge_fractal/cli.py +0 -224
  143. package/scripts/forge_fractal/dashboard.css +0 -138
  144. package/scripts/forge_fractal/dashboard.html +0 -41
  145. package/scripts/forge_fractal/dashboard.js +0 -687
  146. package/scripts/forge_fractal/decomposition.py +0 -262
  147. package/scripts/forge_fractal/execution.py +0 -659
  148. package/scripts/forge_fractal/inspection.py +0 -261
  149. package/scripts/forge_fractal/install.py +0 -158
  150. package/scripts/forge_fractal/invocation.py +0 -95
  151. package/scripts/forge_fractal/pipeline.py +0 -125
  152. package/scripts/forge_fractal/selection.py +0 -180
  153. package/ui/forge_ui/fractal.py +0 -582
@@ -261,10 +261,58 @@ class Run:
261
261
  self.removable = set() # paths of the worktrees --worktrees removes (or prunes, when missing on disk)
262
262
  self.wt_root = None
263
263
  self.owners = {} # worktree path -> forge_worktrees kind (None: foreign), for the dataset events
264
+ # The run and, after it, every sub-plan under it (#153: the subtasks of a split task run as a plan of
265
+ # their own, with its own run id, branches and worktree folder): dict(run_id, tasks, wt_root, path).
266
+ self.members = []
267
+
268
+
269
+ SUB_DEPTH = 8 # the depth limit of a run's decomposition tops out at 6
270
+
271
+
272
+ def plan_tasks(path, ignored=None):
273
+ """The task ids of a plan dir's tasks.tsv that are safe as file names and ref components."""
274
+ tasks, seen = [], set()
275
+ for line in (read_text(os.path.join(path, 'tasks.tsv')) or '').splitlines():
276
+ if not line.strip() or line.startswith('#'):
277
+ continue
278
+ task = line.split('\t', 1)[0]
279
+ if not TASK_ID.fullmatch(task):
280
+ if ignored is not None:
281
+ ignored.append(task)
282
+ elif task not in seen:
283
+ seen.add(task)
284
+ tasks.append(task)
285
+ return tasks
286
+
287
+
288
+ def sub_members(run, path, tasks, depth=0):
289
+ """The sub-plans under a plan dir, as members. One whose run id is not safe, or whose worktree folder
290
+ would overlap the run dir, is left out: nothing of it is touched."""
291
+ found = []
292
+ if depth >= SUB_DEPTH:
293
+ return found
294
+ for task in tasks:
295
+ sub = os.path.join(path, 'tasks', task, 'sub')
296
+ if os.path.islink(sub) or not os.path.isfile(os.path.join(sub, 'tasks.tsv')):
297
+ continue
298
+ run_id = first_line(os.path.join(sub, 'run_id')) or ''
299
+ if not RUN_ID.fullmatch(run_id) or not run_id.startswith(run.run_id + '--'):
300
+ continue
301
+ root = forge_worktrees.wt_root(run.repo, run_id)
302
+ if contains(run.path, root) or contains(root, run.path):
303
+ continue
304
+ below = plan_tasks(sub)
305
+ found.append(dict(run_id=run_id, tasks=below, wt_root=root, path=sub))
306
+ found += sub_members(run, sub, below, depth + 1)
307
+ return found
264
308
 
265
309
 
266
310
  def identify(target):
267
311
  path = target.path
312
+ if os.path.basename(path) == 'sub' and os.path.basename(os.path.dirname(os.path.dirname(path))) == 'tasks' \
313
+ and os.path.isfile(os.path.join(path, 'parent.json')):
314
+ raise Refused('%s holds the subtasks of a split task: it is deleted with the run it belongs to, not by itself'
315
+ % path)
268
316
  if path == '/' or any(contains(path, home) for home in homes()):
269
317
  raise Refused('refusing to delete %s: it is, or contains, the home directory' % path)
270
318
  if os.path.lexists(os.path.join(path, '.git')):
@@ -286,20 +334,14 @@ def identify(target):
286
334
  if contains(path, run.repo_real) or contains(path, os.path.abspath(run.repo)):
287
335
  raise Refused('refusing to delete %s: it is, or contains, the run\'s repo %s' % (path, run.repo))
288
336
  if run.kind == 'plan':
289
- seen = set()
290
- for line in (read_text(os.path.join(path, 'tasks.tsv')) or '').splitlines():
291
- if not line.strip() or line.startswith('#'):
292
- continue
293
- task = line.split('\t', 1)[0]
294
- if not TASK_ID.fullmatch(task):
295
- run.ignored_tasks.append(task)
296
- elif task not in seen:
297
- seen.add(task)
298
- run.tasks.append(task)
337
+ run.tasks = plan_tasks(path, run.ignored_tasks)
299
338
  # forge-parallel.sh: wt_root="$(cd "$REPO/.." && pwd)/.forge-worktrees/$run_id", a logical cd
300
339
  run.wt_root = forge_worktrees.wt_root(run.repo, run.run_id)
301
340
  if contains(path, run.wt_root) or contains(run.wt_root, path):
302
341
  raise Refused('refusing to delete %s: it overlaps the run\'s worktree root %s' % (path, run.wt_root))
342
+ run.members = [dict(run_id=run.run_id, tasks=run.tasks, wt_root=run.wt_root, path=path)]
343
+ if run.kind == 'plan':
344
+ run.members += sub_members(run, path, run.tasks)
303
345
  return run
304
346
 
305
347
 
@@ -444,17 +486,24 @@ def inspect_git(run):
444
486
  except Failed as error:
445
487
  run.git_error = str(error)
446
488
  return
447
- branch_refs = {'refs/heads/forge/%s/%s' % (run.run_id, task) for task in run.tasks}
448
- branch_refs.add('refs/heads/forge/%s-integration' % run.run_id)
489
+ # The run's own branches and those of every sub-plan under it (a split task's subtasks, #153).
490
+ branch_refs = set()
491
+ for member in run.members:
492
+ branch_refs |= {'refs/heads/forge/%s/%s' % (member['run_id'], task) for task in member['tasks']}
493
+ branch_refs.add('refs/heads/forge/%s-integration' % member['run_id'])
449
494
  for wt in listed:
450
495
  real = os.path.realpath(wt['path'])
451
- in_root = real != run.wt_root and contains(run.wt_root, real)
496
+ in_root = any(real != member['wt_root'] and contains(member['wt_root'], real) for member in run.members)
452
497
  ours = wt['branch'] in branch_refs
453
498
  if not in_root and not ours:
454
499
  continue # the main worktree, or another run's: not this command's business
455
500
  # forge_worktrees.owner is the rule forge-ui's Worktrees screen uses too: a task or integration branch in
456
501
  # the run's folder, or a scratch worktree integrate or the culprit search left there.
457
- kind = forge_worktrees.owner(wt['path'], wt['branch'], run.run_id, run.tasks, run.wt_root)
502
+ kind = None
503
+ for member in run.members:
504
+ kind = forge_worktrees.owner(wt['path'], wt['branch'], member['run_id'], member['tasks'], member['wt_root'])
505
+ if kind:
506
+ break
458
507
  run.owners[wt['path']] = kind
459
508
  entry = dict(path=wt['path'], branch=(wt['branch'] or '').replace('refs/heads/', '', 1) or None,
460
509
  kind='run' if kind else 'foreign', dirty=None, removed=False, note='')
@@ -486,6 +535,21 @@ def inspect_git(run):
486
535
  run.branches.append(dict(name=ref.replace('refs/heads/', '', 1), sha=sha, merged=merged,
487
536
  status='merged' if merged else 'UNMERGED', checked_out=checked_out.get(ref),
488
537
  stays_checked_out=checked_out.get(ref), deleted=False, note=''))
538
+ # What a split that started over set aside (retry --decide split=fresh): refs, not branches, listed and
539
+ # deleted with them under their full name.
540
+ for member in run.members:
541
+ code, out, err = git(run.repo, 'for-each-ref', '--format=%(refname) %(objectname)',
542
+ 'refs/forge/kept/%s/' % member['run_id'])
543
+ if code != 0:
544
+ run.git_error = 'git for-each-ref failed in %s: %s' % (run.repo, err or 'exit %d' % code)
545
+ return
546
+ for line in sorted(out.splitlines()):
547
+ ref, _, sha = line.rpartition(' ')
548
+ if ref.rsplit('/', 1)[-1] not in member['tasks']:
549
+ continue
550
+ merged = git(run.repo, 'merge-base', '--is-ancestor', sha, 'HEAD')[0] == 0
551
+ run.branches.append(dict(name=ref, sha=sha, merged=merged, status='merged' if merged else 'UNMERGED',
552
+ checked_out=None, stays_checked_out=None, deleted=False, note=''))
489
553
 
490
554
 
491
555
  # ------------------------------------------------------------------------------ the steps
@@ -607,11 +671,13 @@ def remove_worktrees(run):
607
671
  code, _, err = git(run.repo, 'worktree', 'prune')
608
672
  if code != 0:
609
673
  problems.append('git worktree prune: ' + (err or 'exit %d' % code))
610
- if os.path.isdir(run.wt_root) and not os.path.islink(run.wt_root):
611
- try:
612
- os.rmdir(run.wt_root) # only succeeds when it is empty: a foreign worktree keeps it
613
- except OSError:
614
- pass
674
+ for member in run.members:
675
+ root = member['wt_root']
676
+ if os.path.isdir(root) and not os.path.islink(root):
677
+ try:
678
+ os.rmdir(root) # only succeeds when it is empty: a foreign worktree keeps it
679
+ except OSError:
680
+ pass
615
681
  return '; '.join(problems) or None
616
682
 
617
683
 
@@ -624,10 +690,15 @@ def delete_branches(run):
624
690
  if where:
625
691
  branch['note'] = 'kept: checked out in ' + where
626
692
  continue
627
- code, _, err = git(run.repo, 'branch', '-D', branch['name'])
693
+ if branch['name'].startswith('refs/'):
694
+ code, _, err = git(run.repo, 'update-ref', '-d', branch['name'], branch['sha'])
695
+ restore = 'git update-ref %s %s' % (branch['name'], branch['sha'])
696
+ else:
697
+ code, _, err = git(run.repo, 'branch', '-D', branch['name'])
698
+ restore = 'git branch %s %s' % (branch['name'], branch['sha'])
628
699
  if code == 0:
629
700
  branch['deleted'] = True
630
- branch['note'] = 'was %s; restore with: git branch %s %s' % (branch['sha'][:12], branch['name'], branch['sha'])
701
+ branch['note'] = 'was %s; restore with: %s' % (branch['sha'][:12], restore)
631
702
  else:
632
703
  branch['note'] = err or 'git branch -D exit %d' % code
633
704
  problems.append('%s: %s' % (branch['name'], branch['note']))
@@ -2,8 +2,9 @@
2
2
  """forge runs [--repo DIR | --all] [--limit N] [--json]: this repo's recent runs, in the terminal.
3
3
 
4
4
  Every solo run, `plan` and `run` registers its run dir (forge_registry.py); this lists them newest
5
- first, one line each (run id, kind, age, task states, verification, final review, goal, and
6
- `after <run>` when the plan was chained) with the run dir under it, so you can see what happened
5
+ first, one line each (run id, kind, age, task states, verification, final review, goal,
6
+ `after <run>` when the plan was chained, and `made with Fractal, removed in v0.23` for a run of
7
+ that removed backend) with the run dir under it, so you can see what happened
7
8
  without a browser and get the dir to resume, retry or open with `forge ui open`. The repo is the
8
9
  Git top level of the current directory unless
9
10
  `--repo` names one; `--all` lists the runs of every repo. It reads the same run summaries as
@@ -15,6 +16,11 @@ deletes a run, after its traces are in the dataset and an archive exists (script
15
16
  keeps every run and takes back what it holds for nothing: leftover review snapshots and, with
16
17
  --logs, gzipped log copies (scripts/forge-runs-compact.py). Both change things; listing never does.
17
18
 
19
+ `forge runs tree <run-dir> [--json]` prints a run's tasks and, under each task that was split, its subtasks
20
+ through every level, with the decision recorded for each (split, kept whole, or kept whole at a limit) and
21
+ the run's limits. A split task's subtasks are a plan of their own under it, `<run-dir>/tasks/<id>/sub`:
22
+ the list above counts them on the run's line and never lists them as runs.
23
+
18
24
  `forge runs rerun <run-dir> --dwarf SPEC` and `forge runs compare <run-dir-A> <run-dir-B>` (scripts/forge-compare.py)
19
25
  run a plan again under another implementer, from the same starting commit and never merging, and set two runs
20
26
  side by side per task. Starting the rerun spends tokens, so it takes `--run --yes` after it has shown the forecast.
@@ -37,7 +43,7 @@ import forge_registry # noqa: E402
37
43
  from forge_ui import reader # noqa: E402
38
44
 
39
45
  FIELDS = ('key', 'run_id', 'kind', 'goal', 'repo', 'path', 'created', 'updated', 'task_count', 'counts',
40
- 'verification_status', 'final_review', 'after')
46
+ 'verification_status', 'final_review', 'after', 'removed', 'decomposition')
41
47
 
42
48
 
43
49
  def repo_of(start: Path) -> Path:
@@ -97,7 +103,14 @@ def line(run: dict, now: float, with_repo: bool = False) -> str:
97
103
  if len(goal) > 72:
98
104
  goal = goal[:71] + '…'
99
105
  repo = f" {Path(run['repo']).name or run['repo']}" if with_repo and run.get('repo') else ''
100
- return f"{run['run_id'] or run['key']} {run['kind']}{repo} {age(run['updated'], now)} {counts}{checks}{chain} {goal}\n {run['path']}"
106
+ # A run of a backend forge no longer has (Fractal): still listed and readable, never run again.
107
+ gone = run.get('removed') or {}
108
+ removed = f" made with {gone.get('name')}, removed in v{gone.get('since')}" if gone else ''
109
+ # Tasks that were split (#153): their subtasks are plans of their own under the run dir, counted here.
110
+ tree = run.get('decomposition') or {}
111
+ split = f" {tree['subtasks']} subtasks in {tree['split']} split task{'' if tree['split'] == 1 else 's'}" if tree.get('split') else ''
112
+ return (f"{run['run_id'] or run['key']} {run['kind']}{repo} {age(run['updated'], now)} {counts}{split}{checks}{chain}{removed}"
113
+ f" {goal}\n {run['path']}")
101
114
 
102
115
 
103
116
  def remove(argv) -> int:
@@ -130,16 +143,44 @@ def compare_runs(argv) -> int:
130
143
  return module.main(argv)
131
144
 
132
145
 
146
+ def tree(argv) -> int:
147
+ """`forge runs tree <run-dir> [--json]`: the run's tasks and, under each task that was split, its
148
+ subtasks through every level (#153), with the decision recorded for each and the run's limits."""
149
+ import forge_decompose
150
+ parser = argparse.ArgumentParser(prog='forge runs tree', description="A run's tasks and the subtasks of every task that was "
151
+ 'split, through every level, with the decision recorded for each. Read-only.')
152
+ parser.add_argument('run_dir', type=Path, metavar='RUN_DIR', help='the plan dir (the one with tasks.tsv)')
153
+ parser.add_argument('--json', action='store_true', help='print {limits, nodes} as JSON, for scripts and agents')
154
+ args = parser.parse_args(argv)
155
+ if not (args.run_dir / 'tasks.tsv').is_file():
156
+ parser.error(f'{args.run_dir} is not a plan dir (no tasks.tsv); a solo run has one task and no tree')
157
+ nodes = forge_decompose.tree(args.run_dir)
158
+ limits = dict(forge_decompose.limits(args.run_dir), frozen=forge_decompose.is_frozen(args.run_dir))
159
+ if args.json:
160
+ json.dump(dict(limits=limits, nodes=nodes), sys.stdout, indent=2)
161
+ sys.stdout.write('\n')
162
+ return 0
163
+ print('decomposition limits: ' + forge_decompose.describe(limits) + (' (frozen)' if limits['frozen'] else ''))
164
+ print(forge_decompose.render(args.run_dir))
165
+ for node in nodes:
166
+ if node['children']:
167
+ print(f"subtasks of {node['id']}: {forge_decompose.sub_dir(node['plan'], node['task'])}")
168
+ return 0
169
+
170
+
133
171
  def main(argv=None) -> int:
134
172
  argv = sys.argv[1:] if argv is None else list(argv)
135
173
  if argv[:1] == ['rm']:
136
174
  return remove(argv[1:])
175
+ if argv[:1] == ['tree']:
176
+ return tree(argv[1:])
137
177
  if argv[:1] == ['compact']:
138
178
  return compact(argv[1:])
139
179
  if argv[:1] in (['rerun'], ['compare']):
140
180
  return compare_runs(argv)
141
181
  parser = argparse.ArgumentParser(prog='forge runs', description="This repo's recent forge runs, newest first. Listing is read-only.",
142
- epilog='Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help). Take back the space runs '
182
+ epilog='The subtasks of a run\'s split tasks: forge runs tree <run-dir>. '
183
+ 'Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help). Take back the space runs '
143
184
  'hold for nothing, keeping every run: forge runs compact --help. Rerun a plan with another '
144
185
  'implementer and compare: forge runs rerun --help, forge runs compare --help')
145
186
  which = parser.add_mutually_exclusive_group()
@@ -796,14 +796,32 @@ def settled_result(text: str) -> dict | None:
796
796
  return found
797
797
 
798
798
 
799
- def settle(log: str, grace: str, pid: str) -> None:
799
+ def open_background(text: str) -> bool:
800
+ """Whether the session's last list of background tasks (system/background_tasks_changed) names any. A log
801
+ that never lists them has none open."""
802
+ tasks = []
803
+ for event in _events(text)[0]:
804
+ if event.get('type') == 'system' and event.get('subtype') == 'background_tasks_changed':
805
+ tasks = event.get('tasks') if isinstance(event.get('tasks'), list) else []
806
+ return bool(tasks)
807
+
808
+
809
+ def settle(log: str, grace: str, pid: str, quick: str = '') -> None:
800
810
  """Returns once the harness log ends in a settled result (settled_result) and has not grown for `grace`
801
811
  seconds of the machine's awake time; exits 1 once process `pid`, the harness, is gone. dispatch then ends
802
812
  the harness: its answer is in, and only a background task keeps it open. An idle log whose last turn is
803
- still under way (a long command) is never ended here; that is the watchdog's."""
813
+ still under way (a long command) is never ended here; that is the watchdog's.
814
+
815
+ `quick` (live steering, #252): a CLI whose input forge holds open never exits after its result, so with no
816
+ background task open the wait is `quick` seconds instead. A grace of 0 then means only the quick path.
817
+ Prints which wait ended it: quick or grace."""
804
818
  grace_s, target = float(grace), int(pid)
805
- poll = min(SETTLE_POLL_S, max(grace_s / 4, 0.05))
806
- size, since, judged = None, time.monotonic(), None
819
+ quick_s = float(quick) if quick else None
820
+ waits = [w for w in (grace_s if grace_s > 0 else None, quick_s) if w is not None]
821
+ if not waits:
822
+ raise ValueError('settle needs a grace or a quick grace')
823
+ poll = min(SETTLE_POLL_S, max(min(waits) / 4, 0.05))
824
+ size, since, verdict = None, time.monotonic(), None # verdict: (settled, background open) of this size
807
825
  while True:
808
826
  if forge_proc.IS_WINDOWS:
809
827
  if not forge_proc.pid_alive(target):
@@ -820,14 +838,21 @@ def settle(log: str, grace: str, pid: str) -> None:
820
838
  except OSError:
821
839
  now = None
822
840
  if now != size:
823
- size, since = now, time.monotonic()
824
- elif judged != size and time.monotonic() - since >= grace_s:
825
- judged = size # read once per size: an idle log mid-turn is not read again and again
826
- try:
827
- text = Path(log).read_text(errors='replace')
828
- except OSError:
829
- text = ''
830
- if settled_result(text) is not None:
841
+ size, since, verdict = now, time.monotonic(), None
842
+ elif time.monotonic() - since >= min(waits):
843
+ if verdict is None: # read once per size: an idle log mid-turn is not read again and again
844
+ try:
845
+ text = Path(log).read_text(errors='replace')
846
+ except OSError:
847
+ text = ''
848
+ settled = settled_result(text) is not None
849
+ verdict = (settled, settled and open_background(text))
850
+ idle = time.monotonic() - since
851
+ if verdict[0] and quick_s is not None and idle >= quick_s and not verdict[1]:
852
+ print('quick')
853
+ return
854
+ if verdict[0] and grace_s > 0 and idle >= grace_s:
855
+ print('grace')
831
856
  return
832
857
  time.sleep(poll)
833
858
 
@@ -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(
@@ -722,7 +728,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
722
728
  retries = {} # automatic reviewer-driven retries used per task, this run
723
729
  per_model_seen = {} # task -> the per-model answer that allowed its latest automatic retry
724
730
  refused = {} # task -> budget at the time its retry could not be prepared
725
- retried = set() # tasks whose next dispatch is a retry (FORGE_FRACTAL_RETRY=1)
731
+ retried = set() # tasks whose next dispatch is a retry
726
732
  offsets = {} # how much of each task.out was already echoed under --output full
727
733
  infra_seen = [] # tasks stopped by an infrastructure failure, awaiting resume
728
734
  held = set() # INFRA tasks not resumed: their pin could not be applied
@@ -741,11 +747,27 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
741
747
  backoff_warned = [] # an invalid infra_backoff file is reported once
742
748
  graceful = False # `forge control stop`: start nothing more, end once running tasks are done
743
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))
744
767
  for name in tasks: # `retry --no-dispatch` (#118) prepared it for this run: still a person's retry
745
768
  if (plan / 'tasks' / name / 'retry.prepared').exists():
746
769
  retried.add(name)
747
770
  human.add(name)
748
- fractal = _fractal_plan(plan)
749
771
  drain_told = False # the drained message was printed for this drain
750
772
  sweep_asked = False # this invocation already asked for the finding sweep
751
773
  sweep_checked = {} # the answer of this invocation's one `plan --check`
@@ -961,6 +983,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
961
983
  if status(name) == 'NEEDS_DECISION':
962
984
  print('forge: ' + name + ' is not resumed: it is at its attempt cap and waits for your decision',
963
985
  file=sys.stderr, flush=True)
986
+ print(waiting_line(plan, name, 'NEEDS_DECISION'), file=sys.stderr, flush=True)
964
987
  return False
965
988
  held.add(name)
966
989
  print('forge: ' + name + ' is not resumed: its escalation pin could not be applied',
@@ -1013,7 +1036,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1013
1036
  implementer to the next healthy model of its tier, or, when only its reviewer is held, the reviewer
1014
1037
  to a peer. Tried once for each set of pauses and models: a move changes the models, so a task with
1015
1038
  both on the paused harness moves its implementer, then its reviewer. True when the task moved."""
1016
- 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':
1017
1040
  return False
1018
1041
  pairs = next_pairs(name)
1019
1042
  seen = (frozenset(pauses), tuple(pairs))
@@ -1071,7 +1094,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1071
1094
  exhausted pair is excluded (and a harness stop excludes the whole harness); a pool all
1072
1095
  stopped cannot bounce the task forever. True when the task moved, and so left the pause."""
1073
1096
  stage = info.get('stage')
1074
- 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':
1075
1098
  return False
1076
1099
  # A pin waits for the next full retry, which a review's move is not.
1077
1100
  if stage not in ('dwarf', 'qa') or (stage == 'dwarf' and _pinned(plan, name)):
@@ -1285,7 +1308,23 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1285
1308
  file=sys.stderr, flush=True)
1286
1309
  write_paused()
1287
1310
 
1311
+ STORED_SUBTASKS = re.compile(r'split\.request\.[0-9]+-[0-9]+\.json')
1312
+
1288
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:
1289
1328
  name, dwarf = request['task'], request.get('dwarf')
1290
1329
  if name not in tasks:
1291
1330
  return 'refused', 'this run does not know task ' + name
@@ -1311,14 +1350,31 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1311
1350
  + ' ' + name + ' --answer \u2026 (on a live run: forge control retry ' + str(plan)
1312
1351
  + ' ' + name + ' --answer \u2026)')
1313
1352
  decide, reason, approved = request.get('decide'), request.get('reason'), request.get('approved') is True
1314
- if decide and state != 'NEEDS_DECISION':
1353
+ splitting = decide in SPLIT_DECISIONS
1354
+ if decide and state != 'NEEDS_DECISION' and not splitting:
1315
1355
  return 'refused', name + ' is ' + state + ', not waiting for a decision; --decide only decides a NEEDS_DECISION task'
1316
1356
  decision = []
1317
- 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':
1318
1374
  # Only a person's explicit decision resumes it: a choice, a reason, and --approved.
1319
1375
  if not decide and not dwarf:
1320
1376
  return 'refused', (name + ' is waiting for your decision, and only a decision resumes it: '
1321
- + 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,'
1322
1378
  + ' with --reason and --approved)')
1323
1379
  if not (reason or '').strip() or not approved:
1324
1380
  return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
@@ -1336,6 +1392,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1336
1392
  command = [forge_proc.bash_executable(), script, '_prepare_retry', str(plan), name] + (
1337
1393
  ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1338
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')
1339
1400
  if rc == 3:
1340
1401
  try:
1341
1402
  why = (plan / 'tasks' / name / 'split.suggested').read_text().strip()
@@ -1704,6 +1765,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1704
1765
  into.add(name)
1705
1766
  log.close()
1706
1767
  del active[name]
1768
+ give_slot(name)
1707
1769
  job = task_jobs.pop(name, None)
1708
1770
  if job is not None:
1709
1771
  job.disarm()
@@ -1730,9 +1792,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1730
1792
  prompt_requeue(name)
1731
1793
  elif state == 'IMPLEMENTED' and allow_requeue and name in group_of:
1732
1794
  start_ready_groups() # the last member in: its group is reviewed now, with no wave barrier
1795
+ announce_wait(name)
1733
1796
  if not reaped:
1734
1797
  return
1735
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
+
1736
1809
  summary_seen = {} # task -> what the scheduler last saw of it (status, attempt trail, verdict, retries)
1737
1810
  summary_due = set() # tasks that changed and wait for a summarize
1738
1811
  summary_procs = {} # task -> its detached forge-summarize.py, polled only to reap it
@@ -1955,6 +2028,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1955
2028
  write_paused()
1956
2029
  end_scoped_waits()
1957
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)
1958
2036
  cap = live_capacity(plan, capacity)
1959
2037
  draining = drained(plan) # again: the infrastructure wait above can last minutes
1960
2038
  brief_waiting.clear()
@@ -1981,16 +2059,25 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1981
2059
  pass
1982
2060
  if scope_held(name):
1983
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
1984
2067
  root = plan / 'tasks' / name
1985
- if not (root / 'base_ref').exists():
1986
- worktree = Path(forge_posix.host_path((plan / 'wt_root').read_text().strip())) / '_integration'
1987
- base = subprocess.check_output(['git', '-C', str(worktree), 'rev-parse', 'HEAD'])
1988
- (root / 'base_ref').write_bytes(base)
1989
- log = open(root / 'task.out', 'ab')
1990
- # A retried task runs with the same environment `retry` gives it, so the
1991
- # no-progress guard (byte-identical diff) applies under Fractal too.
1992
- env = (dict(os.environ, FORGE_FRACTAL_RETRY='1',
1993
- 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')
1994
2081
  if name in retried else None)
1995
2082
  human.discard(name)
1996
2083
  _remove(plan, 'tasks', name, 'retry.prepared')
@@ -2067,6 +2154,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2067
2154
  except subprocess.TimeoutExpired:
2068
2155
  pass
2069
2156
  log.close()
2157
+ give_slot(name)
2070
2158
  stopped_groups = [name[len(GROUP_KEY):] for name, _ in stopping if name.startswith(GROUP_KEY) and name not in tasks]
2071
2159
  stop_harnesses(plan, [name for name, _ in stopping if name in tasks], stopped_groups)
2072
2160
  for name, _ in stopping:
@@ -2085,6 +2173,9 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
2085
2173
  if paused or any(live_pause(pause) for pause in pauses.values()) \
2086
2174
  or any(status(name) == 'INFRA' for name in tasks):
2087
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
2088
2179
  # A fix task that did not merge leaves its findings for `forge issues`; the run's own work is done.
2089
2180
  return 0 if all(status(name) == 'MERGED' for name in tasks if not is_fix(name)) else 5
2090
2181