@giamme/forge 0.18.0 → 0.20.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 (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -13,12 +13,18 @@ Two opt-in behaviours live here, both off by default so a plain `run` is unchang
13
13
 
14
14
  A third, ``--sweep Pn``, also per invocation: once every task has merged, the open review
15
15
  findings at Pn or worse become fix tasks (``forge-parallel.sh _sweep``, forge-sweep.py) that
16
- this run then dispatches like any other, once per plan. A fix task that fails leaves its
17
- findings for ``forge issues`` and does not fail the run.
16
+ this run then dispatches like any other: one round per invocation, each finding swept once (a
17
+ rerun that merged new findings starts the next round; ``forge-sweep.py plan --check`` says whether
18
+ there is one). A fix task that fails leaves its findings for ``forge issues`` and does not fail the run.
18
19
 
19
20
  Both numbers are per invocation, but while the scheduler runs they are mirrored into the
20
21
  plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
21
22
  decision, so `forge control` can change them mid-run. See "live control files" below.
23
+
24
+ Group review (#140) is opt-in through groups.tsv: the members of a `review=group` group stop at
25
+ IMPLEMENTED, and once all are, the scheduler runs the group as one unit of work (`_group`, keyed
26
+ `group:<gid>` in `active`), then merges a PASS (`_merge_group`) or sends the implicated members back
27
+ (`_group_settle`, then the ordinary requeue). A plan without such a group never reaches that code.
22
28
  """
23
29
  from __future__ import annotations
24
30
 
@@ -201,8 +207,12 @@ def load_registry() -> list:
201
207
  def spec_pair(registry: list, spec: str) -> tuple | None:
202
208
  """(harness, model) for a spec, resolved the way forge-dispatch.sh's lookup does: an
203
209
  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:
210
+ unknown alias with a harness is a literal model id. None when it cannot be resolved.
211
+
212
+ `script` is a task kind (it runs tasks/<id>/run), not a model. It is none even when a
213
+ registry alias is named script, so a pause on that alias's harness cannot hold the task
214
+ through its implementer."""
215
+ if not spec or spec in ('-', 'UNASSIGNED', 'script') or ',' in spec:
206
216
  return None
207
217
  parts = spec.split(':')
208
218
  alias, harness = parts[0], ':'.join(parts[2:])
@@ -268,7 +278,7 @@ def _write_atomic(plan: object, text: str, *parts: str) -> bool:
268
278
  try:
269
279
  path = _resolve(plan, *parts)
270
280
  fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.' + parts[-1] + '.')
271
- with os.fdopen(fd, 'w') as handle:
281
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
272
282
  os.fchmod(handle.fileno(), 0o644)
273
283
  handle.write(text)
274
284
  os.replace(tmp, path)
@@ -433,21 +443,23 @@ def _group_alive(pgid: int) -> bool:
433
443
  return True
434
444
 
435
445
 
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."""
446
+ def stop_harnesses(plan: object, names: object, groups: object = ()) -> None:
447
+ """Run the guard's identity-checked `stop` on every harness record of these tasks (and the
448
+ review harness of these groups, #140), all at once, so the bound does not grow with the
449
+ number of tasks. Never raises."""
439
450
  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))
451
+ targets = [(name, ('tasks', name), role) for name in names for role in HARNESS_ROLES]
452
+ targets += [('group ' + gid, ('groups', gid), 'qa') for gid in groups]
453
+ for name, where, role in targets:
454
+ try:
455
+ record = _resolve(plan, *where, role + '.harness')
456
+ if not os.path.lexists(record):
457
+ continue
458
+ stopping.append((name, role, subprocess.Popen(
459
+ [sys.executable, GUARD, 'stop', record], stdin=subprocess.DEVNULL,
460
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)))
461
+ except (OSError, ValueError) as error:
462
+ _warn('could not stop the ' + role + ' harness of ' + name + ': ' + str(error))
451
463
  deadline = time.monotonic() + GUARD_STOP_WAIT
452
464
  for name, role, process in stopping:
453
465
  try:
@@ -467,8 +479,10 @@ def stop_harnesses(plan: object, names: object) -> None:
467
479
  # only while scheduler.live says a scheduler reads them. The scheduler applies or refuses each,
468
480
  # logs one outcome line with the same `request` id, and removes it. live_stop settles whatever
469
481
  # is left after it withdraws liveness, under the same lock, so no request outlives its run.
482
+ GROUP_KEY = 'group:' # the `active` key of a running group review: a prefix no task id takes (#140)
470
483
  REQUESTS = 'control.requests'
471
484
  REQUEST_MAX = 64 * 1024
485
+ ANSWER_MAX = 8000 # characters of a NEEDS_INPUT answer a request may carry (#147)
472
486
  # What `forge control retry --decide` may carry: retry=N (1 to 20) or threshold=Pn.
473
487
  DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
474
488
  # NEEDS_INPUT is in neither: a task stopped for the user's answer resumes only through
@@ -476,7 +490,9 @@ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
476
490
  # a task whose reviews do not converge, or that the retry policy cannot move to a stronger model,
477
491
  # resumes only through a person's `retry --decide` (or `--dwarf`) with a reason and --approved.
478
492
  # 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')
493
+ # STALE (the prompt changed while the attempt ran, #150) is retryable by hand, but it is not in AUTO_RETRY:
494
+ # its path is prompt_requeue, which spends no retry.
495
+ RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED', 'STALE')
480
496
  # What --retry-failed retries on its own. INVALIDATED only for a review voided while the committed
481
497
  # work stayed as it was (tasks/<id>/invalidated.reason is `review`): that retry is a fresh review.
482
498
  AUTO_RETRY = ('FAIL', 'UNKNOWN', 'INVALIDATED')
@@ -529,6 +545,9 @@ def read_request(plan: object, name: str) -> dict | None:
529
545
  return None
530
546
  if not isinstance(request.get('approved', False), bool):
531
547
  return None
548
+ answer = request.get('answer')
549
+ if answer is not None and (not isinstance(answer, str) or not 1 <= len(answer) <= ANSWER_MAX or '\0' in answer):
550
+ return None
532
551
  actor = request.get('actor')
533
552
  if actor is not None and actor not in ('ui', 'cli'):
534
553
  return None
@@ -540,7 +559,8 @@ def settle_request(plan: object, name: str, request: dict | None, outcome: str,
540
559
  verb = request.get('verb') if request else None
541
560
  task = request.get('task') if request else None
542
561
  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,
562
+ 'value': ('answer' if request.get('answer') is not None else request.get('dwarf')) if request else None,
563
+ 'previous': None, 'request': name,
544
564
  'outcome': outcome, 'reason': reason}
545
565
  try:
546
566
  fd = os.open(_resolve(plan, 'control.log'), os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
@@ -560,13 +580,15 @@ def refuse_requests(plan: object, reason: str) -> None:
560
580
  settle_request(plan, name, read_request(plan, name), 'refused', reason)
561
581
 
562
582
 
563
- def live_start(plan: object, names: object, retry_failed: int, infra_retries: int) -> None:
583
+ def live_start(plan: object, names: object, retry_failed: int, infra_retries: int, groups: object = ()) -> None:
564
584
  """Publish the flags and that this scheduler is live. Stale per-task overrides and
565
- usage counters from an earlier invocation go first."""
585
+ usage counters from an earlier invocation go first, and so does a review group's."""
566
586
  with _control_lock(plan):
567
587
  for name in _task_dirs(plan, names):
568
588
  _remove(plan, 'tasks', name, 'retry_budget')
569
589
  _remove(plan, 'tasks', name, 'retries.used')
590
+ for gid in groups:
591
+ _remove(plan, 'groups', gid, 'retries.used')
570
592
  _remove(plan, 'infra.paused')
571
593
  _remove(plan, 'infra.last')
572
594
  _remove(plan, 'drain')
@@ -665,10 +687,28 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
665
687
  if not _task_id_ok(name):
666
688
  raise ValueError('invalid task ID: ' + name)
667
689
  (plan / 'tasks' / name).mkdir(parents=True, exist_ok=True)
668
- active = {}
690
+ # Opt-in group review (#140): the review=group groups of groups.tsv. Without one, nothing below changes.
691
+ rgroups = {} # gid -> its Group
692
+ if (plan / 'groups.tsv').is_file():
693
+ import forge_groups
694
+ try:
695
+ rgroups = {g.id: g for g in forge_groups.load(plan) if g.review == 'group'}
696
+ except forge_groups.GroupError as error:
697
+ raise ValueError(str(error))
698
+ for g in rgroups.values():
699
+ absent = [m for m in g.members if m not in tasks]
700
+ if absent:
701
+ raise ValueError('group ' + g.id + ' has members tasks.tsv does not: ' + ', '.join(absent))
702
+ if GROUP_KEY + g.id in tasks:
703
+ raise ValueError('task ' + GROUP_KEY + g.id + ' clashes with group ' + g.id)
704
+ group_of = {m: g.id for g in rgroups.values() for m in g.members} # member -> its review group
705
+ active = {} # task id, or GROUP_KEY + gid for a running group review
669
706
  pending = list(tasks)
670
707
  interrupted = False
708
+ group_again = set() # groups to review once more whatever their status says (a resume, an UNKNOWN)
709
+ group_used = {} # gid -> re-reviews of an UNKNOWN verdict used this run
671
710
  retries = {} # automatic reviewer-driven retries used per task, this run
711
+ per_model_seen = {} # task -> the per-model answer that allowed its latest automatic retry
672
712
  refused = {} # task -> budget at the time its retry could not be prepared
673
713
  retried = set() # tasks whose next dispatch is a retry (FORGE_FRACTAL_RETRY=1)
674
714
  offsets = {} # how much of each task.out was already echoed under --output full
@@ -696,6 +736,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
696
736
  fractal = _fractal_plan(plan)
697
737
  drain_told = False # the drained message was printed for this drain
698
738
  sweep_asked = False # this invocation already asked for the finding sweep
739
+ sweep_checked = {} # the answer of this invocation's one `plan --check`
699
740
  brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
700
741
  brief_told = set() # (task, qid or '') whose brief wait was already printed
701
742
  brief_waiting = set() # tasks the last dispatch pass held for a brief answer or the brief writer
@@ -784,15 +825,51 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
784
825
  stop) hands them to the next one."""
785
826
  return _read_budget(plan, 'tasks', name, 'decided.left')
786
827
 
828
+ def per_model_limit() -> int | None:
829
+ """<plan>/retry_per_model as an integer from 1 to 99, else None (missing or not that)."""
830
+ try:
831
+ text = (plan / 'retry_per_model').read_text(encoding='utf-8').strip()
832
+ except OSError:
833
+ return None
834
+ if not re.fullmatch(r'[0-9]{1,9}', text):
835
+ return None
836
+ value = int(text)
837
+ return value if 1 <= value <= 99 else None
838
+
839
+ def per_model_allows(name: str) -> bool:
840
+ """Whether forge-route.py per-model says this task may be attempted again. A failing or
841
+ unparsable call is a no. The parsed answer is kept for the retry line."""
842
+ try:
843
+ result = subprocess.run(
844
+ [sys.executable, ROUTE, 'per-model', '--plan', str(plan), '--task', name],
845
+ capture_output=True, text=True)
846
+ data = json.loads(result.stdout) if result.stdout.strip() else None
847
+ except (OSError, subprocess.SubprocessError, json.JSONDecodeError, ValueError):
848
+ per_model_seen[name] = None
849
+ return False
850
+ if result.returncode != 0 or not isinstance(data, dict):
851
+ per_model_seen[name] = None
852
+ return False
853
+ per_model_seen[name] = data
854
+ return data.get('retry') is True
855
+
856
+ def automatic_retry(name: str) -> bool:
857
+ """Without retry_per_model, the run's retry budget. With it, any budget above 0 and the
858
+ route's answer: N failures on the current rung, then a stronger one, until none is left."""
859
+ if per_model_limit() is not None:
860
+ return budget(name) > 0 and per_model_allows(name)
861
+ return retries.get(name, 0) < budget(name)
862
+
787
863
  def retryable(name: str) -> bool:
788
864
  root = plan / 'tasks' / name
789
865
  left = granted(name)
790
866
  return (
791
867
  status(name) in AUTO_RETRY
792
868
  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))
869
+ # After a decision the person's count rules, over and under the budget and over a
870
+ # per-model answer of no: `retry=3` is three attempts even with a budget of 0, and
871
+ # `retry=1` is one even with 3.
872
+ and (left > 0 if left is not None else automatic_retry(name))
796
873
  # A task that produced no new work (empty diff, byte-identical retry) would
797
874
  # only repeat itself; its marker says so and it is left for a human.
798
875
  and not (root / 'noretry').exists()
@@ -823,8 +900,30 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
823
900
  print('forge: retrying ' + name + ' (decided retry, ' + str(left) + ' more after this)',
824
901
  file=sys.stderr, flush=True)
825
902
  else:
826
- print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
827
- + str(budget(name)) + ')', file=sys.stderr, flush=True)
903
+ if per_model_limit() is not None:
904
+ info = per_model_seen.get(name) or {}
905
+ print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + ', '
906
+ + str(info.get('failed_on_rung', '')) + ' of ' + str(info.get('per_model', ''))
907
+ + ' failed on ' + str(info.get('rung', '')) + ')',
908
+ file=sys.stderr, flush=True)
909
+ else:
910
+ print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
911
+ + str(budget(name)) + ')', file=sys.stderr, flush=True)
912
+ return True
913
+
914
+ def prompt_requeue(name: str) -> bool:
915
+ """Re-dispatch a STALE task (its prompt changed while the attempt ran, #150) with the new text. The stale
916
+ attempt spent nothing, so no retry is counted: retries, retries.used and decided.left stay as they are."""
917
+ result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--prompt'])
918
+ if result.returncode:
919
+ print('forge: ' + name + ' is not re-dispatched: its changed prompt could not be prepared',
920
+ file=sys.stderr, flush=True)
921
+ return False
922
+ pairs_cache.pop(name, None)
923
+ if name not in pending:
924
+ pending.insert(0, name)
925
+ print('forge: ' + name + ': re-dispatching with the changed prompt (no attempt spent)',
926
+ file=sys.stderr, flush=True)
828
927
  return True
829
928
 
830
929
  def at_cap(name: str) -> bool:
@@ -854,11 +953,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
854
953
  return False
855
954
  return True
856
955
 
857
- def echo_output(name: str) -> None:
956
+ def echo_output(name: str, file: Path | None = None) -> None:
858
957
  # task.out is opened in append mode, so a retried task's file keeps its earlier
859
- # attempts; print only what is new.
958
+ # attempts; print only what is new. (A group review's own file is group.out.)
860
959
  try:
861
- data = (plan / 'tasks' / name / 'task.out').read_bytes()
960
+ data = (file or plan / 'tasks' / name / 'task.out').read_bytes()
862
961
  except OSError:
863
962
  return
864
963
  start = offsets.get(name, 0)
@@ -878,13 +977,17 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
878
977
 
879
978
  def next_pairs(name: str) -> list:
880
979
  """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."""
980
+ resume (decided by forge-parallel.sh's own check), the implementer and QA otherwise.
981
+
982
+ A scripted task has no implementer model, so only its reviewer is in the list: a pause
983
+ holds it only through that reviewer, and a lateral move can only move the reviewer."""
882
984
  if name not in pairs_cache:
883
985
  row = row_now(name)
884
986
  qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
885
987
  ['/bin/bash', script, '_qa_only', str(plan), name],
886
988
  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]])]
989
+ specs = [row[5]] if qa_only or row[4] == 'script' else [row[4], row[5]]
990
+ pairs_cache[name] = [spec_pair(registry, spec) for spec in specs]
888
991
  return pairs_cache[name]
889
992
 
890
993
  def scope_held(name: str) -> bool:
@@ -1177,9 +1280,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1177
1280
  return 'refused', 'the task is merged'
1178
1281
  if state == 'INFRA':
1179
1282
  return 'refused', 'an infrastructure stop is resumed by the scheduler itself'
1180
- if state == 'NEEDS_INPUT':
1283
+ answer = request.get('answer')
1284
+ if answer is not None:
1285
+ # A NEEDS_INPUT task's answer (#147), the text `forge-parallel.sh retry --answer` takes.
1286
+ if state != 'NEEDS_INPUT':
1287
+ return 'refused', (name + ' is ' + state + ', not waiting for an answer; an answer only resumes a '
1288
+ + 'NEEDS_INPUT task')
1289
+ if dwarf or request.get('decide'):
1290
+ return 'refused', 'an answer is not combined with --dwarf or --decide'
1291
+ elif state == 'NEEDS_INPUT':
1181
1292
  return 'refused', (name + ' is waiting for an answer: forge-parallel.sh retry ' + str(plan)
1182
- + ' ' + name + ' --answer \u2026')
1293
+ + ' ' + name + ' --answer \u2026 (on a live run: forge control retry ' + str(plan)
1294
+ + ' ' + name + ' --answer \u2026)')
1183
1295
  decide, reason, approved = request.get('decide'), request.get('reason'), request.get('approved') is True
1184
1296
  if decide and state != 'NEEDS_DECISION':
1185
1297
  return 'refused', name + ' is ' + state + ', not waiting for a decision; --decide only decides a NEEDS_DECISION task'
@@ -1193,9 +1305,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1193
1305
  if not (reason or '').strip() or not approved:
1194
1306
  return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
1195
1307
  decision = (['--decide', decide] if decide else []) + ['--reason', reason, '--approved']
1196
- elif state not in RETRYABLE:
1308
+ elif state != 'NEEDS_INPUT' and state not in RETRYABLE:
1197
1309
  return 'refused', 'a ' + state + ' task is not retried'
1198
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (['--dwarf', dwarf] if dwarf else []) + decision
1310
+ if state == 'STALE' and dwarf:
1311
+ return 'refused', name + ' is STALE: it re-runs with the changed prompt on the same implementer; --dwarf does not apply'
1312
+ if answer is not None:
1313
+ # Atomic, and before the preparation: it takes the answer only when it is newer than the question,
1314
+ # and keeps it when it then refuses, so the same answer can be retried.
1315
+ if not _write_atomic(plan, answer + '\n', 'tasks', name, 'answer.md'):
1316
+ return 'refused', 'the answer could not be written to tasks/' + name + '/answer.md'
1317
+ # A STALE task spent no attempt: it is prepared with the new prompt, not as a failed one (#150).
1318
+ command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (
1319
+ ['--prompt'] if state == 'STALE' else (['--dwarf', dwarf] if dwarf else []) + decision)
1199
1320
  rc = subprocess.run(command).returncode
1200
1321
  if rc == 3:
1201
1322
  try:
@@ -1215,7 +1336,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1215
1336
  # A decision sets how many attempts follow it: retry=N is N in all (this one and N-1
1216
1337
  # automatic ones), any other choice is this one. A plain retry leaves the budget in charge.
1217
1338
  # (retry_decided wrote decided.left for a decision.) A plain retry ends what a decision allowed.
1218
- if state != 'NEEDS_DECISION':
1339
+ if state not in ('NEEDS_DECISION', 'STALE'):
1219
1340
  _remove(plan, 'tasks', name, 'decided.left')
1220
1341
  retried.add(name)
1221
1342
  human.add(name)
@@ -1295,12 +1416,66 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1295
1416
  """A finding sweep's fix task."""
1296
1417
  return (plan / 'tasks' / name / 'sweep.json').is_file()
1297
1418
 
1419
+ def sweep_rounds() -> list:
1420
+ """The sweep rounds this plan has, oldest first: [(number, plan.json path)]."""
1421
+ found = {}
1422
+ if (plan / 'sweep' / 'plan.json').exists():
1423
+ found[1] = plan / 'sweep' / 'plan.json'
1424
+ with contextlib.suppress(OSError):
1425
+ for path in (plan / 'sweep' / 'rounds').iterdir():
1426
+ if path.name.isdigit() and int(path.name) >= 2 and (path / 'plan.json').exists():
1427
+ found[int(path.name)] = path / 'plan.json'
1428
+ return sorted(found.items())
1429
+
1430
+ def sweep_check() -> bool:
1431
+ """Whether `forge-sweep.py plan --check` finds a finding no round swept yet; asked once per
1432
+ invocation. Nothing new is written down for the run summary (sweep/nothing.json). A check that
1433
+ fails (the integration branch cannot be read) is not a reason to plan."""
1434
+ if 'answer' not in sweep_checked:
1435
+ result = subprocess.run([sys.executable, str(Path(__file__).resolve().with_name('forge-sweep.py')), 'plan',
1436
+ str(plan), '--severity', sweep, '--max', str(sweep_max), '--check']
1437
+ + (['--plausible'] if sweep_plausible else []),
1438
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
1439
+ sweep_checked['code'] = result.returncode
1440
+ sweep_checked['answer'] = result.returncode == 0
1441
+ if result.returncode == 1:
1442
+ try:
1443
+ counts = json.loads(result.stdout)
1444
+ note = {'at': time.time(), 'attempted': int(counts['attempted']), 'left': int(counts['left'])}
1445
+ (plan / 'sweep').mkdir(exist_ok=True)
1446
+ fd, tmp = tempfile.mkstemp(dir=str(plan / 'sweep'), prefix='.nothing.json.')
1447
+ with os.fdopen(fd, 'w') as handle:
1448
+ handle.write(json.dumps(note) + '\n')
1449
+ os.replace(tmp, plan / 'sweep' / 'nothing.json')
1450
+ except (ValueError, KeyError, TypeError, OSError) as error:
1451
+ _warn('could not record that the sweep found nothing new: ' + str(error))
1452
+ return sweep_checked['answer']
1453
+
1298
1454
  def sweep_due() -> bool:
1299
- """--sweep was given, every task merged, nothing stops or holds the run, and this plan was
1300
- never swept (sweep/plan.json is the planner's record, and its marker)."""
1301
- return (bool(sweep) and not sweep_asked and not interrupted and not graceful and not paused
1302
- and not drained(plan) and not (plan / 'sweep' / 'plan.json').exists()
1303
- and all(status(name) == 'MERGED' for name in tasks))
1455
+ """--sweep was given and nothing stops or holds the run, every task of the plan merged
1456
+ (a fix task of an earlier round may have stopped), the last round's queued fix tasks are
1457
+ merged or stopped, and `plan --check` finds a finding no round tried. At most one round
1458
+ per invocation."""
1459
+ if (not sweep or sweep_asked or interrupted or graceful or paused or drained(plan)
1460
+ or not all(status(name) == 'MERGED' for name in tasks if not is_fix(name))):
1461
+ return False
1462
+ rounds = sweep_rounds()
1463
+ if rounds:
1464
+ try:
1465
+ last = json.loads((rounds[-1][1]).read_text()).get('tasks') or []
1466
+ except (OSError, ValueError, AttributeError):
1467
+ last = []
1468
+ # A crash between plan.json and the tasks.tsv append leaves the fix task with no row
1469
+ # and no status. status() would say PENDING and hold every later round; that round is lost.
1470
+ if any(status(item['id']) not in ('MERGED', 'FAIL', 'NEEDS_DECISION', 'INFRA')
1471
+ for item in last if isinstance(item, dict) and isinstance(item.get('id'), str)
1472
+ and (item['id'] in tasks or (plan / 'tasks' / item['id'] / 'status').exists())):
1473
+ return False
1474
+ return sweep_check()
1475
+ # Round 1 asks too, so nothing eligible is recorded and not planned. A check that cannot
1476
+ # be answered (the integration branch cannot be read) still starts the round.
1477
+ sweep_check()
1478
+ return sweep_checked.get('code') != 1
1304
1479
 
1305
1480
  def start_sweep() -> int:
1306
1481
  """Plan the finding sweep and queue its fix tasks; how many were queued. Whatever goes
@@ -1340,6 +1515,152 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1340
1515
  with _control_lock(plan):
1341
1516
  settle_request(plan, name, request, outcome, reason)
1342
1517
 
1518
+ # --- group review (#140) ---------------------------------------------------------------
1519
+ # A member of a review=group group ends its attempt IMPLEMENTED. Once every member is, the group is one unit
1520
+ # of work: `_group` reviews it, then (by its status) `_merge_group` merges it or `_group_settle` sends the
1521
+ # implicated members back through the ordinary retry. Nothing here runs for a plan without such a group.
1522
+
1523
+ def gread(gid: str, name: str) -> str:
1524
+ """A short file of the group's dir, stripped; empty when missing or unsafe."""
1525
+ try:
1526
+ fd = os.open(_resolve(plan, 'groups', gid, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1527
+ try:
1528
+ return os.read(fd, 4097).decode('utf-8', 'replace').strip()
1529
+ finally:
1530
+ os.close(fd)
1531
+ except OSError:
1532
+ return ''
1533
+
1534
+ def gstate(gid: str) -> str:
1535
+ return gread(gid, 'status').split('\n')[0].strip()
1536
+
1537
+ def gmerged(gid: str) -> bool:
1538
+ return (plan / 'groups' / gid / 'merged').exists()
1539
+
1540
+ def gsettled(gid: str) -> bool:
1541
+ """The group's FAIL of its current round was settled (`_group_settle` wrote settled.round)."""
1542
+ rnd = gread(gid, 'round')
1543
+ return bool(rnd) and gread(gid, 'settled.round') == rnd
1544
+
1545
+ def gbudget() -> int:
1546
+ """Re-reviews of an UNKNOWN verdict a group may use: the run's --retry-failed, as `forge control` has it."""
1547
+ value = _read_budget(plan, 'retry_budget')
1548
+ return retry_failed if value is None else value
1549
+
1550
+ def group_set(gid: str, state: str) -> None:
1551
+ _write_atomic(plan, state + '\n', 'groups', gid, 'status')
1552
+
1553
+ def group_ready(gid: str) -> bool:
1554
+ """Every member is IMPLEMENTED, nothing runs or merged it, and its status does not stop it: a group
1555
+ waiting for a person (NEEDS_DECISION, CONFLICT, ERROR) is left, an INFRA or TIMEOUT one is reviewed by the
1556
+ next run, a PASS one is merged. A FAIL whose members came back is the next round; one not yet settled
1557
+ waits for its settle."""
1558
+ if GROUP_KEY + gid in active or gmerged(gid):
1559
+ return False
1560
+ if not all(status(m) == 'IMPLEMENTED' for m in rgroups[gid].members):
1561
+ return False
1562
+ if gid in group_again:
1563
+ return True
1564
+ state = gstate(gid)
1565
+ return state in ('', 'WAITING') or (state == 'FAIL' and gsettled(gid))
1566
+
1567
+ def ready_groups() -> list:
1568
+ return [gid for gid in rgroups if group_ready(gid)]
1569
+
1570
+ def start_group(gid: str) -> None:
1571
+ root = plan / 'groups' / gid
1572
+ root.mkdir(parents=True, exist_ok=True)
1573
+ log = open(root / 'group.out', 'ab')
1574
+ process = subprocess.Popen(
1575
+ ['/bin/bash', script, '_group', str(plan), gid],
1576
+ stdout=log, stderr=subprocess.STDOUT, start_new_session=True,
1577
+ )
1578
+ active[GROUP_KEY + gid] = process, log
1579
+ group_again.discard(gid)
1580
+ print('forge: reviewing group ' + gid + ' (' + ', '.join(rgroups[gid].members) + ')',
1581
+ file=sys.stderr, flush=True)
1582
+
1583
+ def start_ready_groups() -> None:
1584
+ """Start the review of every ready group a free slot allows, on the same terms as a task: nothing
1585
+ new while stopping, draining or paused for infrastructure. A group takes one slot, and has no file
1586
+ overlap with a task: it touches only its own candidate worktree."""
1587
+ if not rgroups or interrupted or graceful or paused or drained(plan):
1588
+ return
1589
+ cap = live_capacity(plan, capacity)
1590
+ for gid in rgroups:
1591
+ if len(active) >= cap:
1592
+ return
1593
+ if group_ready(gid):
1594
+ start_group(gid)
1595
+
1596
+ def group_line(gid: str) -> None:
1597
+ """Say what a group that waits for a person (or the next run) waits for: _group_settle's own line."""
1598
+ subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1599
+
1600
+ def requeue_members(gid: str) -> None:
1601
+ """Every member now in AUTO_RETRY and retryable goes back through the ordinary requeue: its budget,
1602
+ escalation, decision and pin apply to it alone, as for a task reviewed by itself."""
1603
+ for member in rgroups[gid].members:
1604
+ if member not in pending and member not in active and status(member) in AUTO_RETRY and retryable(member):
1605
+ requeue(member)
1606
+
1607
+ def merge_group(gid: str, requeue_ok: bool = True) -> None:
1608
+ # _merge_group flags each merged member's dependents itself (forge_brief_stale), so a direct call
1609
+ # behaves the same; the scheduler does not do it a second time.
1610
+ result = subprocess.run(['/bin/bash', script, '_merge_group', str(plan), gid])
1611
+ if result.returncode != 0 and requeue_ok and not interrupted and not graceful:
1612
+ requeue_members(gid) # a member the merge invalidated, when its review is what was voided
1613
+
1614
+ def rereview(gid: str) -> bool:
1615
+ """An UNKNOWN verdict is reviewed again once per unit of the group's own budget (--retry-failed N),
1616
+ counted in groups/<gid>/retries.used; no member attempt is spent. False when the budget is spent."""
1617
+ used = group_used.get(gid, 0)
1618
+ if used >= gbudget():
1619
+ return False
1620
+ group_used[gid] = used + 1
1621
+ _write_atomic(plan, str(used + 1), 'groups', gid, 'retries.used')
1622
+ group_again.add(gid)
1623
+ print('forge: group ' + gid + ' got no verdict; reviewing it again (re-review ' + str(used + 1) + '/'
1624
+ + str(gbudget()) + ', no attempt spent)', file=sys.stderr, flush=True)
1625
+ return True
1626
+
1627
+ def reap_group(gid: str, allow_requeue: bool) -> None:
1628
+ """What a finished group review does, by its status. Like a task, a PASS is merged however the run ends;
1629
+ every other outcome is kept once the run is interrupted, and nothing is requeued while it stops."""
1630
+ state = gstate(gid)
1631
+ going = allow_requeue and not interrupted and not graceful
1632
+ if state == 'REVIEWING':
1633
+ group_set(gid, 'ERROR')
1634
+ print('forge: group ' + gid + ' ended without a result; marked ERROR (see ' + str(plan / 'groups' / gid
1635
+ / 'group.out') + ')', file=sys.stderr, flush=True)
1636
+ elif state == 'PASS':
1637
+ merge_group(gid, going)
1638
+ elif state == 'FAIL':
1639
+ if not interrupted:
1640
+ result = subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1641
+ if result.returncode:
1642
+ _warn('group ' + gid + ' could not be settled (exit ' + str(result.returncode)
1643
+ + '); its members stay IMPLEMENTED')
1644
+ elif going:
1645
+ requeue_members(gid)
1646
+ elif state in ('NEEDS_DECISION', 'CONFLICT', 'ERROR'):
1647
+ group_line(gid)
1648
+ elif state == 'UNKNOWN':
1649
+ if not (going and rereview(gid)):
1650
+ group_line(gid)
1651
+ elif state in ('INVALIDATED', 'WAITING') and going:
1652
+ requeue_members(gid)
1653
+
1654
+ def report_waiting_groups() -> None:
1655
+ """Members left IMPLEMENTED are not failures, and no dependent of theirs ran: say which group each waits for."""
1656
+ for gid, group in rgroups.items():
1657
+ if gmerged(gid):
1658
+ continue
1659
+ for member in group.members:
1660
+ if status(member) == 'IMPLEMENTED':
1661
+ print('forge: ' + member + ' is implemented, waiting for group ' + gid + ' (' + (gstate(gid) or 'not reviewed')
1662
+ + ')', file=sys.stderr, flush=True)
1663
+
1343
1664
  def reap_exited(into: set[str] | None = None, *, allow_requeue: bool = True) -> None:
1344
1665
  """Reap every active task whose process has already exited.
1345
1666
 
@@ -1361,6 +1682,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1361
1682
  into.add(name)
1362
1683
  log.close()
1363
1684
  del active[name]
1685
+ if name.startswith(GROUP_KEY) and name not in tasks:
1686
+ gid = name[len(GROUP_KEY):]
1687
+ if os.environ.get('FORGE_OUTPUT') == 'full':
1688
+ echo_output(name, plan / 'groups' / gid / 'group.out')
1689
+ reap_group(gid, allow_requeue)
1690
+ continue
1364
1691
  if os.environ.get('FORGE_OUTPUT') == 'full':
1365
1692
  echo_output(name)
1366
1693
  state = status(name)
@@ -1373,6 +1700,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1373
1700
  elif allow_requeue and not interrupted and not graceful \
1374
1701
  and state in AUTO_RETRY and retryable(name):
1375
1702
  requeue(name)
1703
+ elif state == 'STALE' and allow_requeue and not interrupted and not graceful:
1704
+ prompt_requeue(name)
1705
+ elif state == 'IMPLEMENTED' and allow_requeue and name in group_of:
1706
+ start_ready_groups() # the last member in: its group is reviewed now, with no wave barrier
1376
1707
  if not reaped:
1377
1708
  return
1378
1709
 
@@ -1479,7 +1810,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1479
1810
  signal.signal(signal.SIGTERM, stop)
1480
1811
  signal.signal(signal.SIGINT, stop)
1481
1812
  try:
1482
- live_start(plan, tasks, retry_failed, infra_retries)
1813
+ live_start(plan, tasks, retry_failed, infra_retries, rgroups)
1483
1814
  summaries_on_change()
1484
1815
  # Failures require an explicit retry unless this run asked for automatic ones.
1485
1816
  # Saved PASS results use the same fingerprint checks without paying for
@@ -1487,7 +1818,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1487
1818
  # is simply dispatched again.
1488
1819
  # RUNNING at start means a scheduler was killed without its cleanup: its tasks'
1489
1820
  # harnesses may still be running and editing their worktrees.
1490
- stop_harnesses(plan, [name for name in pending if status(name) == 'RUNNING'])
1821
+ stop_harnesses(plan, [name for name in pending if status(name) == 'RUNNING'],
1822
+ [gid for gid in rgroups if gstate(gid) == 'REVIEWING'])
1491
1823
  for name in pending[:]:
1492
1824
  state = status(name)
1493
1825
  if state == 'PASS':
@@ -1496,13 +1828,34 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1496
1828
  mark(name, 'INTERRUPTED')
1497
1829
  if state in AUTO_RETRY and not interrupted and retryable(name):
1498
1830
  requeue(name)
1831
+ if state == 'STALE' and not interrupted:
1832
+ prompt_requeue(name) # left by an interrupted run; the task is PENDING again, so it stays in pending
1499
1833
  if state == 'INFRA' and not interrupted and not resume(name):
1500
1834
  pending.remove(name)
1501
1835
  continue
1502
1836
  if status(name) not in ('PENDING', 'BLOCKED', 'INFRA'):
1503
- pending.remove(name)
1837
+ pending.remove(name) # an IMPLEMENTED member is not implemented again: its group is reviewed
1838
+ for gid in rgroups:
1839
+ if gmerged(gid):
1840
+ continue
1841
+ state = gstate(gid)
1842
+ if state == 'REVIEWING': # a scheduler died mid-review; its harness was stopped above
1843
+ group_set(gid, 'INTERRUPTED')
1844
+ state = 'INTERRUPTED'
1845
+ if state == 'PASS':
1846
+ merge_group(gid)
1847
+ elif state == 'FAIL' and not gsettled(gid) and not interrupted:
1848
+ subprocess.run(['/bin/bash', script, '_group_settle', str(plan), gid])
1849
+ requeue_members(gid)
1850
+ elif state in ('INTERRUPTED', 'INFRA', 'TIMEOUT'):
1851
+ group_again.add(gid)
1852
+ elif state == 'INVALIDATED' and gread(gid, 'invalidated.reason') not in ('integration-moved', 'integration-dirty'):
1853
+ group_again.add(gid)
1854
+ elif state == 'UNKNOWN':
1855
+ if not rereview(gid):
1856
+ group_line(gid)
1504
1857
  swept = time.monotonic()
1505
- while pending or active or waiting_scopes() or sweep_due():
1858
+ while pending or active or waiting_scopes() or sweep_due() or ready_groups():
1506
1859
  # Reap before honouring the stop. A signal during the sleep, and a task
1507
1860
  # that exits while another merge is still running, have already written
1508
1861
  # a result; breaking first used to skip them and mark them INTERRUPTED.
@@ -1570,9 +1923,13 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1570
1923
  cap = live_capacity(plan, capacity)
1571
1924
  draining = drained(plan) # again: the infrastructure wait above can last minutes
1572
1925
  brief_waiting.clear()
1926
+ start_ready_groups()
1573
1927
  for name in pending[:]:
1574
1928
  if paused or len(active) >= cap or interrupted or graceful or draining:
1575
1929
  break
1930
+ if rgroups and status(name) == 'IMPLEMENTED':
1931
+ pending.remove(name) # a member waiting for its group is never dispatched again
1932
+ continue
1576
1933
  deps = [d for d in tasks[name][1].split(',') if d and d != '-']
1577
1934
  if any(status(dep) != 'MERGED' for dep in deps):
1578
1935
  continue
@@ -1580,7 +1937,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1580
1937
  # A wait, not a stop: the rest of the plan runs, and the run does not end while it lasts.
1581
1938
  brief_waiting.add(name)
1582
1939
  continue
1583
- if any(overlap(tasks[name][3], tasks[other][3]) for other in active):
1940
+ if any(overlap(tasks[name][3], tasks[other][3]) for other in active if other in tasks):
1584
1941
  continue
1585
1942
  if pauses and scope_held(name):
1586
1943
  # Each move changes the models it is held on: the implementer, then the reviewer, in one pass,
@@ -1614,7 +1971,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1614
1971
  print('forge: stopped by forge control stop; ' + str(len(pending)) + ' task(s) not started',
1615
1972
  file=sys.stderr, flush=True)
1616
1973
  break
1617
- if not active and draining and (pending or waiting_scopes()):
1974
+ if not active and draining and (pending or waiting_scopes() or ready_groups()):
1618
1975
  if not drain_told:
1619
1976
  drain_told = True
1620
1977
  print('forge: drained — ' + str(len(pending)) + ' task(s) waiting; forge control resume '
@@ -1628,9 +1985,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1628
1985
  if not pending and sweep_due() and start_sweep():
1629
1986
  continue
1630
1987
  for name in pending:
1631
- mark(name, 'BLOCKED')
1988
+ if status(name) != 'IMPLEMENTED': # waiting for its group, not blocked
1989
+ mark(name, 'BLOCKED')
1632
1990
  break
1633
1991
  time.sleep(0.05)
1992
+ report_waiting_groups()
1634
1993
  finally:
1635
1994
  try:
1636
1995
  held_record()
@@ -1674,8 +2033,14 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1674
2033
  except subprocess.TimeoutExpired:
1675
2034
  pass
1676
2035
  log.close()
1677
- stop_harnesses(plan, [name for name, _ in stopping])
2036
+ stopped_groups = [name[len(GROUP_KEY):] for name, _ in stopping if name.startswith(GROUP_KEY) and name not in tasks]
2037
+ stop_harnesses(plan, [name for name, _ in stopping if name in tasks], stopped_groups)
1678
2038
  for name, _ in stopping:
2039
+ if name.startswith(GROUP_KEY) and name not in tasks:
2040
+ # A group left REVIEWING is INTERRUPTED; one that wrote its outcome before the stop keeps it.
2041
+ if gstate(name[len(GROUP_KEY):]) == 'REVIEWING':
2042
+ group_set(name[len(GROUP_KEY):], 'INTERRUPTED')
2043
+ continue
1679
2044
  try:
1680
2045
  mark(name, 'INTERRUPTED')
1681
2046
  except OSError as error: