@giamme/forge 0.18.0 → 0.19.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 (78) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +16 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +81 -14
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +84 -15
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +20 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +621 -33
  17. package/references/harnesses.md +18 -3
  18. package/references/planning.md +43 -14
  19. package/references/ui.md +53 -6
  20. package/registry.tsv +8 -3
  21. package/scripts/forge-brief.py +88 -3
  22. package/scripts/forge-compare.py +4 -3
  23. package/scripts/forge-contract.py +202 -27
  24. package/scripts/forge-control.py +117 -5
  25. package/scripts/forge-dispatch.sh +34 -5
  26. package/scripts/forge-group.py +496 -0
  27. package/scripts/forge-groups.py +89 -0
  28. package/scripts/forge-handoff.py +1128 -0
  29. package/scripts/forge-lib-group.sh +641 -0
  30. package/scripts/forge-lib-plans.sh +339 -3
  31. package/scripts/forge-lib-task.sh +197 -4
  32. package/scripts/forge-memory.sh +245 -3
  33. package/scripts/forge-parallel.sh +715 -34
  34. package/scripts/forge-planner.py +104 -8
  35. package/scripts/forge-route.py +190 -12
  36. package/scripts/forge-runs.py +9 -5
  37. package/scripts/forge-schedule.py +354 -45
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-worktrees.py +243 -0
  40. package/scripts/forge_brief/__init__.py +294 -50
  41. package/scripts/forge_brief/answers.py +58 -11
  42. package/scripts/forge_brief/proposals.py +1630 -0
  43. package/scripts/forge_dataset/efforts.py +4 -3
  44. package/scripts/forge_dataset/export.py +24 -12
  45. package/scripts/forge_dataset/facts.py +5 -3
  46. package/scripts/forge_dataset/forecast.py +8 -18
  47. package/scripts/forge_dataset/harvest.py +204 -9
  48. package/scripts/forge_dataset/history.py +11 -6
  49. package/scripts/forge_dataset/importer.py +65 -1
  50. package/scripts/forge_dataset/names.py +66 -0
  51. package/scripts/forge_dataset/reviewers.py +5 -2
  52. package/scripts/forge_dataset/risk.py +6 -3
  53. package/scripts/forge_dataset/routing.py +6 -1
  54. package/scripts/forge_groups/__init__.py +308 -0
  55. package/scripts/forge_groups/attribute.py +289 -0
  56. package/scripts/forge_groups/review.py +286 -0
  57. package/scripts/forge_owner.py +152 -0
  58. package/scripts/forge_side/__init__.py +12 -7
  59. package/ui/docs/api.md +173 -17
  60. package/ui/forge_ui/control.py +361 -2
  61. package/ui/forge_ui/executions.py +8 -1
  62. package/ui/forge_ui/export.py +31 -4
  63. package/ui/forge_ui/groups.py +264 -0
  64. package/ui/forge_ui/models.py +70 -8
  65. package/ui/forge_ui/reader.py +262 -19
  66. package/ui/forge_ui/server.py +4 -0
  67. package/ui/forge_ui/static/app.js +93 -13
  68. package/ui/forge_ui/static/briefview.js +350 -47
  69. package/ui/forge_ui/static/diffview.js +86 -1
  70. package/ui/forge_ui/static/groupsview.js +332 -0
  71. package/ui/forge_ui/static/index.html +1 -0
  72. package/ui/forge_ui/static/panel.js +127 -7
  73. package/ui/forge_ui/static/projectsview.js +189 -10
  74. package/ui/forge_ui/static/runmodel.js +14 -3
  75. package/ui/forge_ui/static/storageview.js +91 -10
  76. package/ui/forge_ui/static/style.css +79 -5
  77. package/ui/forge_ui/static/worktreesview.js +233 -12
  78. package/ui/forge_ui/storage.py +14 -0
@@ -19,6 +19,11 @@ findings for ``forge issues`` and does not fail the run.
19
19
  Both numbers are per invocation, but while the scheduler runs they are mirrored into the
20
20
  plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
21
21
  decision, so `forge control` can change them mid-run. See "live control files" below.
22
+
23
+ Group review (#140) is opt-in through groups.tsv: the members of a `review=group` group stop at
24
+ IMPLEMENTED, and once all are, the scheduler runs the group as one unit of work (`_group`, keyed
25
+ `group:<gid>` in `active`), then merges a PASS (`_merge_group`) or sends the implicated members back
26
+ (`_group_settle`, then the ordinary requeue). A plan without such a group never reaches that code.
22
27
  """
23
28
  from __future__ import annotations
24
29
 
@@ -201,8 +206,12 @@ def load_registry() -> list:
201
206
  def spec_pair(registry: list, spec: str) -> tuple | None:
202
207
  """(harness, model) for a spec, resolved the way forge-dispatch.sh's lookup does: an
203
208
  alias's first row is its default harness, alias:effort:harness picks that row, and an
204
- unknown alias with a harness is a literal model id. None when it cannot be resolved."""
205
- if not spec or spec in ('-', 'UNASSIGNED') or ',' in spec:
209
+ unknown alias with a harness is a literal model id. None when it cannot be resolved.
210
+
211
+ `script` is a task kind (it runs tasks/<id>/run), not a model. It is none even when a
212
+ registry alias is named script, so a pause on that alias's harness cannot hold the task
213
+ through its implementer."""
214
+ if not spec or spec in ('-', 'UNASSIGNED', 'script') or ',' in spec:
206
215
  return None
207
216
  parts = spec.split(':')
208
217
  alias, harness = parts[0], ':'.join(parts[2:])
@@ -268,7 +277,7 @@ def _write_atomic(plan: object, text: str, *parts: str) -> bool:
268
277
  try:
269
278
  path = _resolve(plan, *parts)
270
279
  fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.' + parts[-1] + '.')
271
- with os.fdopen(fd, 'w') as handle:
280
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
272
281
  os.fchmod(handle.fileno(), 0o644)
273
282
  handle.write(text)
274
283
  os.replace(tmp, path)
@@ -433,21 +442,23 @@ def _group_alive(pgid: int) -> bool:
433
442
  return True
434
443
 
435
444
 
436
- def stop_harnesses(plan: object, names: object) -> None:
437
- """Run the guard's identity-checked `stop` on every harness record of these tasks, all
438
- at once, so the bound does not grow with the number of tasks. Never raises."""
445
+ def stop_harnesses(plan: object, names: object, groups: object = ()) -> None:
446
+ """Run the guard's identity-checked `stop` on every harness record of these tasks (and the
447
+ review harness of these groups, #140), all at once, so the bound does not grow with the
448
+ number of tasks. Never raises."""
439
449
  stopping = []
440
- for name in names:
441
- for role in HARNESS_ROLES:
442
- try:
443
- record = _resolve(plan, 'tasks', name, role + '.harness')
444
- if not os.path.lexists(record):
445
- continue
446
- stopping.append((name, role, subprocess.Popen(
447
- [sys.executable, GUARD, 'stop', record], stdin=subprocess.DEVNULL,
448
- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)))
449
- except (OSError, ValueError) as error:
450
- _warn('could not stop the ' + role + ' harness of ' + name + ': ' + str(error))
450
+ targets = [(name, ('tasks', name), role) for name in names for role in HARNESS_ROLES]
451
+ targets += [('group ' + gid, ('groups', gid), 'qa') for gid in groups]
452
+ for name, where, role in targets:
453
+ try:
454
+ record = _resolve(plan, *where, role + '.harness')
455
+ if not os.path.lexists(record):
456
+ continue
457
+ stopping.append((name, role, subprocess.Popen(
458
+ [sys.executable, GUARD, 'stop', record], stdin=subprocess.DEVNULL,
459
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)))
460
+ except (OSError, ValueError) as error:
461
+ _warn('could not stop the ' + role + ' harness of ' + name + ': ' + str(error))
451
462
  deadline = time.monotonic() + GUARD_STOP_WAIT
452
463
  for name, role, process in stopping:
453
464
  try:
@@ -467,8 +478,10 @@ def stop_harnesses(plan: object, names: object) -> None:
467
478
  # only while scheduler.live says a scheduler reads them. The scheduler applies or refuses each,
468
479
  # logs one outcome line with the same `request` id, and removes it. live_stop settles whatever
469
480
  # is left after it withdraws liveness, under the same lock, so no request outlives its run.
481
+ GROUP_KEY = 'group:' # the `active` key of a running group review: a prefix no task id takes (#140)
470
482
  REQUESTS = 'control.requests'
471
483
  REQUEST_MAX = 64 * 1024
484
+ ANSWER_MAX = 8000 # characters of a NEEDS_INPUT answer a request may carry (#147)
472
485
  # What `forge control retry --decide` may carry: retry=N (1 to 20) or threshold=Pn.
473
486
  DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
474
487
  # NEEDS_INPUT is in neither: a task stopped for the user's answer resumes only through
@@ -476,7 +489,9 @@ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
476
489
  # a task whose reviews do not converge, or that the retry policy cannot move to a stronger model,
477
490
  # resumes only through a person's `retry --decide` (or `--dwarf`) with a reason and --approved.
478
491
  # No budget, pin or sweep reaches it, because every automatic path asks for a status in AUTO_RETRY.
479
- RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED')
492
+ # STALE (the prompt changed while the attempt ran, #150) is retryable by hand, but it is not in AUTO_RETRY:
493
+ # its path is prompt_requeue, which spends no retry.
494
+ RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED', 'STALE')
480
495
  # What --retry-failed retries on its own. INVALIDATED only for a review voided while the committed
481
496
  # work stayed as it was (tasks/<id>/invalidated.reason is `review`): that retry is a fresh review.
482
497
  AUTO_RETRY = ('FAIL', 'UNKNOWN', 'INVALIDATED')
@@ -529,6 +544,9 @@ def read_request(plan: object, name: str) -> dict | None:
529
544
  return None
530
545
  if not isinstance(request.get('approved', False), bool):
531
546
  return None
547
+ answer = request.get('answer')
548
+ if answer is not None and (not isinstance(answer, str) or not 1 <= len(answer) <= ANSWER_MAX or '\0' in answer):
549
+ return None
532
550
  actor = request.get('actor')
533
551
  if actor is not None and actor not in ('ui', 'cli'):
534
552
  return None
@@ -540,7 +558,8 @@ def settle_request(plan: object, name: str, request: dict | None, outcome: str,
540
558
  verb = request.get('verb') if request else None
541
559
  task = request.get('task') if request else None
542
560
  entry = {'at': time.time(), 'actor': 'scheduler', 'action': verb, 'task': task, 'key': None,
543
- 'value': request.get('dwarf') if request else None, 'previous': None, 'request': name,
561
+ 'value': ('answer' if request.get('answer') is not None else request.get('dwarf')) if request else None,
562
+ 'previous': None, 'request': name,
544
563
  'outcome': outcome, 'reason': reason}
545
564
  try:
546
565
  fd = os.open(_resolve(plan, 'control.log'), os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
@@ -560,13 +579,15 @@ def refuse_requests(plan: object, reason: str) -> None:
560
579
  settle_request(plan, name, read_request(plan, name), 'refused', reason)
561
580
 
562
581
 
563
- def live_start(plan: object, names: object, retry_failed: int, infra_retries: int) -> None:
582
+ def live_start(plan: object, names: object, retry_failed: int, infra_retries: int, groups: object = ()) -> None:
564
583
  """Publish the flags and that this scheduler is live. Stale per-task overrides and
565
- usage counters from an earlier invocation go first."""
584
+ usage counters from an earlier invocation go first, and so does a review group's."""
566
585
  with _control_lock(plan):
567
586
  for name in _task_dirs(plan, names):
568
587
  _remove(plan, 'tasks', name, 'retry_budget')
569
588
  _remove(plan, 'tasks', name, 'retries.used')
589
+ for gid in groups:
590
+ _remove(plan, 'groups', gid, 'retries.used')
570
591
  _remove(plan, 'infra.paused')
571
592
  _remove(plan, 'infra.last')
572
593
  _remove(plan, 'drain')
@@ -665,10 +686,28 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
665
686
  if not _task_id_ok(name):
666
687
  raise ValueError('invalid task ID: ' + name)
667
688
  (plan / 'tasks' / name).mkdir(parents=True, exist_ok=True)
668
- active = {}
689
+ # Opt-in group review (#140): the review=group groups of groups.tsv. Without one, nothing below changes.
690
+ rgroups = {} # gid -> its Group
691
+ if (plan / 'groups.tsv').is_file():
692
+ import forge_groups
693
+ try:
694
+ rgroups = {g.id: g for g in forge_groups.load(plan) if g.review == 'group'}
695
+ except forge_groups.GroupError as error:
696
+ raise ValueError(str(error))
697
+ for g in rgroups.values():
698
+ absent = [m for m in g.members if m not in tasks]
699
+ if absent:
700
+ raise ValueError('group ' + g.id + ' has members tasks.tsv does not: ' + ', '.join(absent))
701
+ if GROUP_KEY + g.id in tasks:
702
+ raise ValueError('task ' + GROUP_KEY + g.id + ' clashes with group ' + g.id)
703
+ group_of = {m: g.id for g in rgroups.values() for m in g.members} # member -> its review group
704
+ active = {} # task id, or GROUP_KEY + gid for a running group review
669
705
  pending = list(tasks)
670
706
  interrupted = False
707
+ group_again = set() # groups to review once more whatever their status says (a resume, an UNKNOWN)
708
+ group_used = {} # gid -> re-reviews of an UNKNOWN verdict used this run
671
709
  retries = {} # automatic reviewer-driven retries used per task, this run
710
+ per_model_seen = {} # task -> the per-model answer that allowed its latest automatic retry
672
711
  refused = {} # task -> budget at the time its retry could not be prepared
673
712
  retried = set() # tasks whose next dispatch is a retry (FORGE_FRACTAL_RETRY=1)
674
713
  offsets = {} # how much of each task.out was already echoed under --output full
@@ -784,15 +823,51 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
784
823
  stop) hands them to the next one."""
785
824
  return _read_budget(plan, 'tasks', name, 'decided.left')
786
825
 
826
+ def per_model_limit() -> int | None:
827
+ """<plan>/retry_per_model as an integer from 1 to 99, else None (missing or not that)."""
828
+ try:
829
+ text = (plan / 'retry_per_model').read_text(encoding='utf-8').strip()
830
+ except OSError:
831
+ return None
832
+ if not re.fullmatch(r'[0-9]{1,9}', text):
833
+ return None
834
+ value = int(text)
835
+ return value if 1 <= value <= 99 else None
836
+
837
+ def per_model_allows(name: str) -> bool:
838
+ """Whether forge-route.py per-model says this task may be attempted again. A failing or
839
+ unparsable call is a no. The parsed answer is kept for the retry line."""
840
+ try:
841
+ result = subprocess.run(
842
+ [sys.executable, ROUTE, 'per-model', '--plan', str(plan), '--task', name],
843
+ capture_output=True, text=True)
844
+ data = json.loads(result.stdout) if result.stdout.strip() else None
845
+ except (OSError, subprocess.SubprocessError, json.JSONDecodeError, ValueError):
846
+ per_model_seen[name] = None
847
+ return False
848
+ if result.returncode != 0 or not isinstance(data, dict):
849
+ per_model_seen[name] = None
850
+ return False
851
+ per_model_seen[name] = data
852
+ return data.get('retry') is True
853
+
854
+ def automatic_retry(name: str) -> bool:
855
+ """Without retry_per_model, the run's retry budget. With it, any budget above 0 and the
856
+ route's answer: N failures on the current rung, then a stronger one, until none is left."""
857
+ if per_model_limit() is not None:
858
+ return budget(name) > 0 and per_model_allows(name)
859
+ return retries.get(name, 0) < budget(name)
860
+
787
861
  def retryable(name: str) -> bool:
788
862
  root = plan / 'tasks' / name
789
863
  left = granted(name)
790
864
  return (
791
865
  status(name) in AUTO_RETRY
792
866
  and (status(name) != 'INVALIDATED' or review_voided(name))
793
- # After a decision the person's count rules, over and under the budget: `retry=3`
794
- # is three attempts even with a budget of 0, and `retry=1` is one even with 3.
795
- and (left > 0 if left is not None else retries.get(name, 0) < budget(name))
867
+ # After a decision the person's count rules, over and under the budget and over a
868
+ # per-model answer of no: `retry=3` is three attempts even with a budget of 0, and
869
+ # `retry=1` is one even with 3.
870
+ and (left > 0 if left is not None else automatic_retry(name))
796
871
  # A task that produced no new work (empty diff, byte-identical retry) would
797
872
  # only repeat itself; its marker says so and it is left for a human.
798
873
  and not (root / 'noretry').exists()
@@ -823,8 +898,30 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
823
898
  print('forge: retrying ' + name + ' (decided retry, ' + str(left) + ' more after this)',
824
899
  file=sys.stderr, flush=True)
825
900
  else:
826
- print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
827
- + str(budget(name)) + ')', file=sys.stderr, flush=True)
901
+ if per_model_limit() is not None:
902
+ info = per_model_seen.get(name) or {}
903
+ print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + ', '
904
+ + str(info.get('failed_on_rung', '')) + ' of ' + str(info.get('per_model', ''))
905
+ + ' failed on ' + str(info.get('rung', '')) + ')',
906
+ file=sys.stderr, flush=True)
907
+ else:
908
+ print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
909
+ + str(budget(name)) + ')', file=sys.stderr, flush=True)
910
+ return True
911
+
912
+ def prompt_requeue(name: str) -> bool:
913
+ """Re-dispatch a STALE task (its prompt changed while the attempt ran, #150) with the new text. The stale
914
+ attempt spent nothing, so no retry is counted: retries, retries.used and decided.left stay as they are."""
915
+ result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--prompt'])
916
+ if result.returncode:
917
+ print('forge: ' + name + ' is not re-dispatched: its changed prompt could not be prepared',
918
+ file=sys.stderr, flush=True)
919
+ return False
920
+ pairs_cache.pop(name, None)
921
+ if name not in pending:
922
+ pending.insert(0, name)
923
+ print('forge: ' + name + ': re-dispatching with the changed prompt (no attempt spent)',
924
+ file=sys.stderr, flush=True)
828
925
  return True
829
926
 
830
927
  def at_cap(name: str) -> bool:
@@ -854,11 +951,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
854
951
  return False
855
952
  return True
856
953
 
857
- def echo_output(name: str) -> None:
954
+ def echo_output(name: str, file: Path | None = None) -> None:
858
955
  # task.out is opened in append mode, so a retried task's file keeps its earlier
859
- # attempts; print only what is new.
956
+ # attempts; print only what is new. (A group review's own file is group.out.)
860
957
  try:
861
- data = (plan / 'tasks' / name / 'task.out').read_bytes()
958
+ data = (file or plan / 'tasks' / name / 'task.out').read_bytes()
862
959
  except OSError:
863
960
  return
864
961
  start = offsets.get(name, 0)
@@ -878,13 +975,17 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
878
975
 
879
976
  def next_pairs(name: str) -> list:
880
977
  """The pairs the task's next dispatch uses: QA only when its next entry is a QA-only
881
- resume (decided by forge-parallel.sh's own check), the implementer and QA otherwise."""
978
+ resume (decided by forge-parallel.sh's own check), the implementer and QA otherwise.
979
+
980
+ A scripted task has no implementer model, so only its reviewer is in the list: a pause
981
+ holds it only through that reviewer, and a lateral move can only move the reviewer."""
882
982
  if name not in pairs_cache:
883
983
  row = row_now(name)
884
984
  qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
885
985
  ['/bin/bash', script, '_qa_only', str(plan), name],
886
986
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
887
- pairs_cache[name] = [spec_pair(registry, spec) for spec in ([row[5]] if qa_only else [row[4], row[5]])]
987
+ specs = [row[5]] if qa_only or row[4] == 'script' else [row[4], row[5]]
988
+ pairs_cache[name] = [spec_pair(registry, spec) for spec in specs]
888
989
  return pairs_cache[name]
889
990
 
890
991
  def scope_held(name: str) -> bool:
@@ -1177,9 +1278,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1177
1278
  return 'refused', 'the task is merged'
1178
1279
  if state == 'INFRA':
1179
1280
  return 'refused', 'an infrastructure stop is resumed by the scheduler itself'
1180
- if state == 'NEEDS_INPUT':
1281
+ answer = request.get('answer')
1282
+ if answer is not None:
1283
+ # A NEEDS_INPUT task's answer (#147), the text `forge-parallel.sh retry --answer` takes.
1284
+ if state != 'NEEDS_INPUT':
1285
+ return 'refused', (name + ' is ' + state + ', not waiting for an answer; an answer only resumes a '
1286
+ + 'NEEDS_INPUT task')
1287
+ if dwarf or request.get('decide'):
1288
+ return 'refused', 'an answer is not combined with --dwarf or --decide'
1289
+ elif state == 'NEEDS_INPUT':
1181
1290
  return 'refused', (name + ' is waiting for an answer: forge-parallel.sh retry ' + str(plan)
1182
- + ' ' + name + ' --answer \u2026')
1291
+ + ' ' + name + ' --answer \u2026 (on a live run: forge control retry ' + str(plan)
1292
+ + ' ' + name + ' --answer \u2026)')
1183
1293
  decide, reason, approved = request.get('decide'), request.get('reason'), request.get('approved') is True
1184
1294
  if decide and state != 'NEEDS_DECISION':
1185
1295
  return 'refused', name + ' is ' + state + ', not waiting for a decision; --decide only decides a NEEDS_DECISION task'
@@ -1193,9 +1303,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1193
1303
  if not (reason or '').strip() or not approved:
1194
1304
  return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
1195
1305
  decision = (['--decide', decide] if decide else []) + ['--reason', reason, '--approved']
1196
- elif state not in RETRYABLE:
1306
+ elif state != 'NEEDS_INPUT' and state not in RETRYABLE:
1197
1307
  return 'refused', 'a ' + state + ' task is not retried'
1198
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (['--dwarf', dwarf] if dwarf else []) + decision
1308
+ if state == 'STALE' and dwarf:
1309
+ return 'refused', name + ' is STALE: it re-runs with the changed prompt on the same implementer; --dwarf does not apply'
1310
+ if answer is not None:
1311
+ # Atomic, and before the preparation: it takes the answer only when it is newer than the question,
1312
+ # and keeps it when it then refuses, so the same answer can be retried.
1313
+ if not _write_atomic(plan, answer + '\n', 'tasks', name, 'answer.md'):
1314
+ return 'refused', 'the answer could not be written to tasks/' + name + '/answer.md'
1315
+ # A STALE task spent no attempt: it is prepared with the new prompt, not as a failed one (#150).
1316
+ command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (
1317
+ ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1199
1318
  rc = subprocess.run(command).returncode
1200
1319
  if rc == 3:
1201
1320
  try:
@@ -1215,7 +1334,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1215
1334
  # A decision sets how many attempts follow it: retry=N is N in all (this one and N-1
1216
1335
  # automatic ones), any other choice is this one. A plain retry leaves the budget in charge.
1217
1336
  # (retry_decided wrote decided.left for a decision.) A plain retry ends what a decision allowed.
1218
- if state != 'NEEDS_DECISION':
1337
+ if state not in ('NEEDS_DECISION', 'STALE'):
1219
1338
  _remove(plan, 'tasks', name, 'decided.left')
1220
1339
  retried.add(name)
1221
1340
  human.add(name)
@@ -1340,6 +1459,152 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1340
1459
  with _control_lock(plan):
1341
1460
  settle_request(plan, name, request, outcome, reason)
1342
1461
 
1462
+ # --- group review (#140) ---------------------------------------------------------------
1463
+ # A member of a review=group group ends its attempt IMPLEMENTED. Once every member is, the group is one unit
1464
+ # of work: `_group` reviews it, then (by its status) `_merge_group` merges it or `_group_settle` sends the
1465
+ # implicated members back through the ordinary retry. Nothing here runs for a plan without such a group.
1466
+
1467
+ def gread(gid: str, name: str) -> str:
1468
+ """A short file of the group's dir, stripped; empty when missing or unsafe."""
1469
+ try:
1470
+ fd = os.open(_resolve(plan, 'groups', gid, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1471
+ try:
1472
+ return os.read(fd, 4097).decode('utf-8', 'replace').strip()
1473
+ finally:
1474
+ os.close(fd)
1475
+ except OSError:
1476
+ return ''
1477
+
1478
+ def gstate(gid: str) -> str:
1479
+ return gread(gid, 'status').split('\n')[0].strip()
1480
+
1481
+ def gmerged(gid: str) -> bool:
1482
+ return (plan / 'groups' / gid / 'merged').exists()
1483
+
1484
+ def gsettled(gid: str) -> bool:
1485
+ """The group's FAIL of its current round was settled (`_group_settle` wrote settled.round)."""
1486
+ rnd = gread(gid, 'round')
1487
+ return bool(rnd) and gread(gid, 'settled.round') == rnd
1488
+
1489
+ def gbudget() -> int:
1490
+ """Re-reviews of an UNKNOWN verdict a group may use: the run's --retry-failed, as `forge control` has it."""
1491
+ value = _read_budget(plan, 'retry_budget')
1492
+ return retry_failed if value is None else value
1493
+
1494
+ def group_set(gid: str, state: str) -> None:
1495
+ _write_atomic(plan, state + '\n', 'groups', gid, 'status')
1496
+
1497
+ def group_ready(gid: str) -> bool:
1498
+ """Every member is IMPLEMENTED, nothing runs or merged it, and its status does not stop it: a group
1499
+ waiting for a person (NEEDS_DECISION, CONFLICT, ERROR) is left, an INFRA or TIMEOUT one is reviewed by the
1500
+ next run, a PASS one is merged. A FAIL whose members came back is the next round; one not yet settled
1501
+ waits for its settle."""
1502
+ if GROUP_KEY + gid in active or gmerged(gid):
1503
+ return False
1504
+ if not all(status(m) == 'IMPLEMENTED' for m in rgroups[gid].members):
1505
+ return False
1506
+ if gid in group_again:
1507
+ return True
1508
+ state = gstate(gid)
1509
+ return state in ('', 'WAITING') or (state == 'FAIL' and gsettled(gid))
1510
+
1511
+ def ready_groups() -> list:
1512
+ return [gid for gid in rgroups if group_ready(gid)]
1513
+
1514
+ def start_group(gid: str) -> None:
1515
+ root = plan / 'groups' / gid
1516
+ root.mkdir(parents=True, exist_ok=True)
1517
+ log = open(root / 'group.out', 'ab')
1518
+ process = subprocess.Popen(
1519
+ ['/bin/bash', script, '_group', str(plan), gid],
1520
+ stdout=log, stderr=subprocess.STDOUT, start_new_session=True,
1521
+ )
1522
+ active[GROUP_KEY + gid] = process, log
1523
+ group_again.discard(gid)
1524
+ print('forge: reviewing group ' + gid + ' (' + ', '.join(rgroups[gid].members) + ')',
1525
+ file=sys.stderr, flush=True)
1526
+
1527
+ def start_ready_groups() -> None:
1528
+ """Start the review of every ready group a free slot allows, on the same terms as a task: nothing
1529
+ new while stopping, draining or paused for infrastructure. A group takes one slot, and has no file
1530
+ overlap with a task: it touches only its own candidate worktree."""
1531
+ if not rgroups or interrupted or graceful or paused or drained(plan):
1532
+ return
1533
+ cap = live_capacity(plan, capacity)
1534
+ for gid in rgroups:
1535
+ if len(active) >= cap:
1536
+ return
1537
+ if group_ready(gid):
1538
+ start_group(gid)
1539
+
1540
+ def group_line(gid: str) -> None:
1541
+ """Say what a group that waits for a person (or the next run) waits for: _group_settle's own line."""
1542
+ subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1543
+
1544
+ def requeue_members(gid: str) -> None:
1545
+ """Every member now in AUTO_RETRY and retryable goes back through the ordinary requeue: its budget,
1546
+ escalation, decision and pin apply to it alone, as for a task reviewed by itself."""
1547
+ for member in rgroups[gid].members:
1548
+ if member not in pending and member not in active and status(member) in AUTO_RETRY and retryable(member):
1549
+ requeue(member)
1550
+
1551
+ def merge_group(gid: str, requeue_ok: bool = True) -> None:
1552
+ # _merge_group flags each merged member's dependents itself (forge_brief_stale), so a direct call
1553
+ # behaves the same; the scheduler does not do it a second time.
1554
+ result = subprocess.run(['/bin/bash', script, '_merge_group', str(plan), gid])
1555
+ if result.returncode != 0 and requeue_ok and not interrupted and not graceful:
1556
+ requeue_members(gid) # a member the merge invalidated, when its review is what was voided
1557
+
1558
+ def rereview(gid: str) -> bool:
1559
+ """An UNKNOWN verdict is reviewed again once per unit of the group's own budget (--retry-failed N),
1560
+ counted in groups/<gid>/retries.used; no member attempt is spent. False when the budget is spent."""
1561
+ used = group_used.get(gid, 0)
1562
+ if used >= gbudget():
1563
+ return False
1564
+ group_used[gid] = used + 1
1565
+ _write_atomic(plan, str(used + 1), 'groups', gid, 'retries.used')
1566
+ group_again.add(gid)
1567
+ print('forge: group ' + gid + ' got no verdict; reviewing it again (re-review ' + str(used + 1) + '/'
1568
+ + str(gbudget()) + ', no attempt spent)', file=sys.stderr, flush=True)
1569
+ return True
1570
+
1571
+ def reap_group(gid: str, allow_requeue: bool) -> None:
1572
+ """What a finished group review does, by its status. Like a task, a PASS is merged however the run ends;
1573
+ every other outcome is kept once the run is interrupted, and nothing is requeued while it stops."""
1574
+ state = gstate(gid)
1575
+ going = allow_requeue and not interrupted and not graceful
1576
+ if state == 'REVIEWING':
1577
+ group_set(gid, 'ERROR')
1578
+ print('forge: group ' + gid + ' ended without a result; marked ERROR (see ' + str(plan / 'groups' / gid
1579
+ / 'group.out') + ')', file=sys.stderr, flush=True)
1580
+ elif state == 'PASS':
1581
+ merge_group(gid, going)
1582
+ elif state == 'FAIL':
1583
+ if not interrupted:
1584
+ result = subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1585
+ if result.returncode:
1586
+ _warn('group ' + gid + ' could not be settled (exit ' + str(result.returncode)
1587
+ + '); its members stay IMPLEMENTED')
1588
+ elif going:
1589
+ requeue_members(gid)
1590
+ elif state in ('NEEDS_DECISION', 'CONFLICT', 'ERROR'):
1591
+ group_line(gid)
1592
+ elif state == 'UNKNOWN':
1593
+ if not (going and rereview(gid)):
1594
+ group_line(gid)
1595
+ elif state in ('INVALIDATED', 'WAITING') and going:
1596
+ requeue_members(gid)
1597
+
1598
+ def report_waiting_groups() -> None:
1599
+ """Members left IMPLEMENTED are not failures, and no dependent of theirs ran: say which group each waits for."""
1600
+ for gid, group in rgroups.items():
1601
+ if gmerged(gid):
1602
+ continue
1603
+ for member in group.members:
1604
+ if status(member) == 'IMPLEMENTED':
1605
+ print('forge: ' + member + ' is implemented, waiting for group ' + gid + ' (' + (gstate(gid) or 'not reviewed')
1606
+ + ')', file=sys.stderr, flush=True)
1607
+
1343
1608
  def reap_exited(into: set[str] | None = None, *, allow_requeue: bool = True) -> None:
1344
1609
  """Reap every active task whose process has already exited.
1345
1610
 
@@ -1361,6 +1626,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1361
1626
  into.add(name)
1362
1627
  log.close()
1363
1628
  del active[name]
1629
+ if name.startswith(GROUP_KEY) and name not in tasks:
1630
+ gid = name[len(GROUP_KEY):]
1631
+ if os.environ.get('FORGE_OUTPUT') == 'full':
1632
+ echo_output(name, plan / 'groups' / gid / 'group.out')
1633
+ reap_group(gid, allow_requeue)
1634
+ continue
1364
1635
  if os.environ.get('FORGE_OUTPUT') == 'full':
1365
1636
  echo_output(name)
1366
1637
  state = status(name)
@@ -1373,6 +1644,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1373
1644
  elif allow_requeue and not interrupted and not graceful \
1374
1645
  and state in AUTO_RETRY and retryable(name):
1375
1646
  requeue(name)
1647
+ elif state == 'STALE' and allow_requeue and not interrupted and not graceful:
1648
+ prompt_requeue(name)
1649
+ elif state == 'IMPLEMENTED' and allow_requeue and name in group_of:
1650
+ start_ready_groups() # the last member in: its group is reviewed now, with no wave barrier
1376
1651
  if not reaped:
1377
1652
  return
1378
1653
 
@@ -1479,7 +1754,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1479
1754
  signal.signal(signal.SIGTERM, stop)
1480
1755
  signal.signal(signal.SIGINT, stop)
1481
1756
  try:
1482
- live_start(plan, tasks, retry_failed, infra_retries)
1757
+ live_start(plan, tasks, retry_failed, infra_retries, rgroups)
1483
1758
  summaries_on_change()
1484
1759
  # Failures require an explicit retry unless this run asked for automatic ones.
1485
1760
  # Saved PASS results use the same fingerprint checks without paying for
@@ -1487,7 +1762,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1487
1762
  # is simply dispatched again.
1488
1763
  # RUNNING at start means a scheduler was killed without its cleanup: its tasks'
1489
1764
  # harnesses may still be running and editing their worktrees.
1490
- stop_harnesses(plan, [name for name in pending if status(name) == 'RUNNING'])
1765
+ stop_harnesses(plan, [name for name in pending if status(name) == 'RUNNING'],
1766
+ [gid for gid in rgroups if gstate(gid) == 'REVIEWING'])
1491
1767
  for name in pending[:]:
1492
1768
  state = status(name)
1493
1769
  if state == 'PASS':
@@ -1496,13 +1772,34 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1496
1772
  mark(name, 'INTERRUPTED')
1497
1773
  if state in AUTO_RETRY and not interrupted and retryable(name):
1498
1774
  requeue(name)
1775
+ if state == 'STALE' and not interrupted:
1776
+ prompt_requeue(name) # left by an interrupted run; the task is PENDING again, so it stays in pending
1499
1777
  if state == 'INFRA' and not interrupted and not resume(name):
1500
1778
  pending.remove(name)
1501
1779
  continue
1502
1780
  if status(name) not in ('PENDING', 'BLOCKED', 'INFRA'):
1503
- pending.remove(name)
1781
+ pending.remove(name) # an IMPLEMENTED member is not implemented again: its group is reviewed
1782
+ for gid in rgroups:
1783
+ if gmerged(gid):
1784
+ continue
1785
+ state = gstate(gid)
1786
+ if state == 'REVIEWING': # a scheduler died mid-review; its harness was stopped above
1787
+ group_set(gid, 'INTERRUPTED')
1788
+ state = 'INTERRUPTED'
1789
+ if state == 'PASS':
1790
+ merge_group(gid)
1791
+ elif state == 'FAIL' and not gsettled(gid) and not interrupted:
1792
+ subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1793
+ requeue_members(gid)
1794
+ elif state in ('INTERRUPTED', 'INFRA', 'TIMEOUT'):
1795
+ group_again.add(gid)
1796
+ elif state == 'INVALIDATED' and gread(gid, 'invalidated.reason') not in ('integration-moved', 'integration-dirty'):
1797
+ group_again.add(gid)
1798
+ elif state == 'UNKNOWN':
1799
+ if not rereview(gid):
1800
+ group_line(gid)
1504
1801
  swept = time.monotonic()
1505
- while pending or active or waiting_scopes() or sweep_due():
1802
+ while pending or active or waiting_scopes() or sweep_due() or ready_groups():
1506
1803
  # Reap before honouring the stop. A signal during the sleep, and a task
1507
1804
  # that exits while another merge is still running, have already written
1508
1805
  # a result; breaking first used to skip them and mark them INTERRUPTED.
@@ -1570,9 +1867,13 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1570
1867
  cap = live_capacity(plan, capacity)
1571
1868
  draining = drained(plan) # again: the infrastructure wait above can last minutes
1572
1869
  brief_waiting.clear()
1870
+ start_ready_groups()
1573
1871
  for name in pending[:]:
1574
1872
  if paused or len(active) >= cap or interrupted or graceful or draining:
1575
1873
  break
1874
+ if rgroups and status(name) == 'IMPLEMENTED':
1875
+ pending.remove(name) # a member waiting for its group is never dispatched again
1876
+ continue
1576
1877
  deps = [d for d in tasks[name][1].split(',') if d and d != '-']
1577
1878
  if any(status(dep) != 'MERGED' for dep in deps):
1578
1879
  continue
@@ -1580,7 +1881,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1580
1881
  # A wait, not a stop: the rest of the plan runs, and the run does not end while it lasts.
1581
1882
  brief_waiting.add(name)
1582
1883
  continue
1583
- if any(overlap(tasks[name][3], tasks[other][3]) for other in active):
1884
+ if any(overlap(tasks[name][3], tasks[other][3]) for other in active if other in tasks):
1584
1885
  continue
1585
1886
  if pauses and scope_held(name):
1586
1887
  # Each move changes the models it is held on: the implementer, then the reviewer, in one pass,
@@ -1614,7 +1915,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1614
1915
  print('forge: stopped by forge control stop; ' + str(len(pending)) + ' task(s) not started',
1615
1916
  file=sys.stderr, flush=True)
1616
1917
  break
1617
- if not active and draining and (pending or waiting_scopes()):
1918
+ if not active and draining and (pending or waiting_scopes() or ready_groups()):
1618
1919
  if not drain_told:
1619
1920
  drain_told = True
1620
1921
  print('forge: drained — ' + str(len(pending)) + ' task(s) waiting; forge control resume '
@@ -1628,9 +1929,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1628
1929
  if not pending and sweep_due() and start_sweep():
1629
1930
  continue
1630
1931
  for name in pending:
1631
- mark(name, 'BLOCKED')
1932
+ if status(name) != 'IMPLEMENTED': # waiting for its group, not blocked
1933
+ mark(name, 'BLOCKED')
1632
1934
  break
1633
1935
  time.sleep(0.05)
1936
+ report_waiting_groups()
1634
1937
  finally:
1635
1938
  try:
1636
1939
  held_record()
@@ -1674,8 +1977,14 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1674
1977
  except subprocess.TimeoutExpired:
1675
1978
  pass
1676
1979
  log.close()
1677
- stop_harnesses(plan, [name for name, _ in stopping])
1980
+ stopped_groups = [name[len(GROUP_KEY):] for name, _ in stopping if name.startswith(GROUP_KEY) and name not in tasks]
1981
+ stop_harnesses(plan, [name for name, _ in stopping if name in tasks], stopped_groups)
1678
1982
  for name, _ in stopping:
1983
+ if name.startswith(GROUP_KEY) and name not in tasks:
1984
+ # A group left REVIEWING is INTERRUPTED; one that wrote its outcome before the stop keeps it.
1985
+ if gstate(name[len(GROUP_KEY):]) == 'REVIEWING':
1986
+ group_set(name[len(GROUP_KEY):], 'INTERRUPTED')
1987
+ continue
1679
1988
  try:
1680
1989
  mark(name, 'INTERRUPTED')
1681
1990
  except OSError as error:
@@ -356,6 +356,8 @@ git -C "$REPO" diff --binary "$START" "$END" -- . ':(exclude).forge' > "$RUN/cha
356
356
  if [ ! -s "$RUN/changes.diff" ]; then
357
357
  # An exit-0 harness with an empty final message and no changes never really ran.
358
358
  grep -qx 'class=empty' "$RUN/dwarf.infra" 2>/dev/null && die "the dwarf returned nothing (empty output, no changes) — an infrastructure failure, not a refusal; fix the cause and run again (see $RUN/dwarf.infra)" 8
359
+ # Nor did one its CLI cancelled before it changed anything.
360
+ grep -qx 'class=cancelled' "$RUN/dwarf.infra" 2>/dev/null && die "the dwarf was cancelled by its CLI before it changed anything — an infrastructure failure, not a refusal: $(sed -n 's/^detail=//p' "$RUN/dwarf.infra"); fix the cause and run again (see $RUN/dwarf.infra)" 8
359
361
  note "the dwarf produced no changes at all — see $RUN/dwarf.last for what it said"
360
362
  echo NOCHANGES > "$RUN/verdict"
361
363
  exit 5