@giamme/forge 0.17.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -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
 
@@ -30,6 +35,7 @@ import json
30
35
  import math
31
36
  import os
32
37
  import re
38
+ import shlex
33
39
  from pathlib import Path
34
40
  import posixpath
35
41
  import signal
@@ -37,6 +43,7 @@ import stat
37
43
  import subprocess
38
44
  import sys
39
45
  import tempfile
46
+ import threading
40
47
  import time
41
48
 
42
49
  # forge_infra.py sits beside this file; forge-control.py loads this module by path.
@@ -199,8 +206,12 @@ def load_registry() -> list:
199
206
  def spec_pair(registry: list, spec: str) -> tuple | None:
200
207
  """(harness, model) for a spec, resolved the way forge-dispatch.sh's lookup does: an
201
208
  alias's first row is its default harness, alias:effort:harness picks that row, and an
202
- unknown alias with a harness is a literal model id. None when it cannot be resolved."""
203
- 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:
204
215
  return None
205
216
  parts = spec.split(':')
206
217
  alias, harness = parts[0], ':'.join(parts[2:])
@@ -266,7 +277,7 @@ def _write_atomic(plan: object, text: str, *parts: str) -> bool:
266
277
  try:
267
278
  path = _resolve(plan, *parts)
268
279
  fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.' + parts[-1] + '.')
269
- with os.fdopen(fd, 'w') as handle:
280
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
270
281
  os.fchmod(handle.fileno(), 0o644)
271
282
  handle.write(text)
272
283
  os.replace(tmp, path)
@@ -401,6 +412,11 @@ def _pinned(plan: object, name: str) -> bool:
401
412
  # dispatch that died too early left behind.
402
413
  GUARD = str(Path(__file__).resolve().parent / 'forge-guard.py')
403
414
  ROUTE = str(Path(__file__).resolve().parent / 'forge-route.py')
415
+ # FORGE_SUMMARIZE names another script for the same job; tests stand a stub in.
416
+ SUMMARIZE = str(Path(__file__).resolve().parent / 'forge-summarize.py')
417
+ # the dwarf's reply (it ends before the status moves), an attempt ended, a verdict, a retry queued
418
+ SUMMARY_FILES = ('dwarf.last', 'attempts.tsv', 'qa.last', 'retries.used')
419
+ SUMMARY_JOIN = 3.0 # seconds the scheduler's end waits for admission checks to start their summarize
404
420
  HARNESS_ROLES = ('dwarf', 'qa')
405
421
  GUARD_STOP_WAIT = 15.0 # seconds; the guard's own bound is about 3 s plus two ps calls
406
422
 
@@ -426,21 +442,23 @@ def _group_alive(pgid: int) -> bool:
426
442
  return True
427
443
 
428
444
 
429
- def stop_harnesses(plan: object, names: object) -> None:
430
- """Run the guard's identity-checked `stop` on every harness record of these tasks, all
431
- 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."""
432
449
  stopping = []
433
- for name in names:
434
- for role in HARNESS_ROLES:
435
- try:
436
- record = _resolve(plan, 'tasks', name, role + '.harness')
437
- if not os.path.lexists(record):
438
- continue
439
- stopping.append((name, role, subprocess.Popen(
440
- [sys.executable, GUARD, 'stop', record], stdin=subprocess.DEVNULL,
441
- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)))
442
- except (OSError, ValueError) as error:
443
- _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))
444
462
  deadline = time.monotonic() + GUARD_STOP_WAIT
445
463
  for name, role, process in stopping:
446
464
  try:
@@ -456,12 +474,14 @@ def stop_harnesses(plan: object, names: object) -> None:
456
474
 
457
475
 
458
476
  # --- control requests ----------------------------------------------------------------------
459
- # `forge control retry|add` queue one JSON file each in control.requests/, under control.lock and
477
+ # `forge control retry|add|accept` queue one JSON file each in control.requests/, under control.lock and
460
478
  # only while scheduler.live says a scheduler reads them. The scheduler applies or refuses each,
461
479
  # logs one outcome line with the same `request` id, and removes it. live_stop settles whatever
462
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)
463
482
  REQUESTS = 'control.requests'
464
483
  REQUEST_MAX = 64 * 1024
484
+ ANSWER_MAX = 8000 # characters of a NEEDS_INPUT answer a request may carry (#147)
465
485
  # What `forge control retry --decide` may carry: retry=N (1 to 20) or threshold=Pn.
466
486
  DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
467
487
  # NEEDS_INPUT is in neither: a task stopped for the user's answer resumes only through
@@ -469,7 +489,9 @@ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
469
489
  # a task whose reviews do not converge, or that the retry policy cannot move to a stronger model,
470
490
  # resumes only through a person's `retry --decide` (or `--dwarf`) with a reason and --approved.
471
491
  # No budget, pin or sweep reaches it, because every automatic path asks for a status in AUTO_RETRY.
472
- 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')
473
495
  # What --retry-failed retries on its own. INVALIDATED only for a review voided while the committed
474
496
  # work stayed as it was (tasks/<id>/invalidated.reason is `review`): that retry is a fresh review.
475
497
  AUTO_RETRY = ('FAIL', 'UNKNOWN', 'INVALIDATED')
@@ -507,7 +529,7 @@ def read_request(plan: object, name: str) -> dict | None:
507
529
  request = json.loads(data.decode('utf-8'))
508
530
  except (OSError, ValueError, UnicodeDecodeError):
509
531
  return None
510
- if len(data) > REQUEST_MAX or not isinstance(request, dict) or request.get('verb') not in ('retry', 'add'):
532
+ if len(data) > REQUEST_MAX or not isinstance(request, dict) or request.get('verb') not in ('retry', 'add', 'accept'):
511
533
  return None
512
534
  task, dwarf = request.get('task'), request.get('dwarf')
513
535
  if not isinstance(task, str) or not _task_id_ok(task):
@@ -522,6 +544,12 @@ def read_request(plan: object, name: str) -> dict | None:
522
544
  return None
523
545
  if not isinstance(request.get('approved', False), bool):
524
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
550
+ actor = request.get('actor')
551
+ if actor is not None and actor not in ('ui', 'cli'):
552
+ return None
525
553
  return request
526
554
 
527
555
 
@@ -530,7 +558,8 @@ def settle_request(plan: object, name: str, request: dict | None, outcome: str,
530
558
  verb = request.get('verb') if request else None
531
559
  task = request.get('task') if request else None
532
560
  entry = {'at': time.time(), 'actor': 'scheduler', 'action': verb, 'task': task, 'key': None,
533
- '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,
534
563
  'outcome': outcome, 'reason': reason}
535
564
  try:
536
565
  fd = os.open(_resolve(plan, 'control.log'), os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
@@ -550,13 +579,15 @@ def refuse_requests(plan: object, reason: str) -> None:
550
579
  settle_request(plan, name, read_request(plan, name), 'refused', reason)
551
580
 
552
581
 
553
- 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:
554
583
  """Publish the flags and that this scheduler is live. Stale per-task overrides and
555
- usage counters from an earlier invocation go first."""
584
+ usage counters from an earlier invocation go first, and so does a review group's."""
556
585
  with _control_lock(plan):
557
586
  for name in _task_dirs(plan, names):
558
587
  _remove(plan, 'tasks', name, 'retry_budget')
559
588
  _remove(plan, 'tasks', name, 'retries.used')
589
+ for gid in groups:
590
+ _remove(plan, 'groups', gid, 'retries.used')
560
591
  _remove(plan, 'infra.paused')
561
592
  _remove(plan, 'infra.last')
562
593
  _remove(plan, 'drain')
@@ -586,6 +617,54 @@ def live_stop(plan: object, names: object) -> None:
586
617
  _warn('could not withdraw the live control files: ' + str(error))
587
618
 
588
619
 
620
+ def brief_level(plan: object) -> str:
621
+ """The plan's effective brief level (off, advisory, gated, strict). Off when settings cannot be read:
622
+ a broken brief must never hold a run."""
623
+ try:
624
+ import forge_side
625
+ return str(forge_side.settings(plan)['brief']['level'])
626
+ except Exception:
627
+ return 'off'
628
+
629
+
630
+ def _json_object(path: Path) -> dict | None:
631
+ try:
632
+ value = json.loads(path.read_text(encoding='utf-8'))
633
+ except (OSError, ValueError):
634
+ return None
635
+ return value if isinstance(value, dict) else None
636
+
637
+
638
+ BRIEF_PID_CHECK = 0.5 # seconds a writer liveness answer is reused
639
+
640
+
641
+ def brief_writer_alive(plan: object) -> bool:
642
+ """Whether the brief writer `run` started is still running: brief.pid names a live process.
643
+ The file is removed when the writer ends, so a missing or unreadable one means it is gone."""
644
+ try:
645
+ pid = int((Path(plan) / 'brief.pid').read_text().split()[0])
646
+ if pid <= 0:
647
+ return False
648
+ os.kill(pid, 0)
649
+ except PermissionError:
650
+ return True
651
+ except (OSError, ValueError, IndexError):
652
+ return False
653
+ return True
654
+
655
+
656
+ def brief_unanswered(plan: object, name: str) -> list:
657
+ """The ids of the task's `must_answer` questions that have no entry in brief.answers.json."""
658
+ root = Path(plan) / 'tasks' / name
659
+ brief = _json_object(root / 'brief.json')
660
+ if brief is None or not isinstance(brief.get('questions'), list):
661
+ return []
662
+ answers = _json_object(root / 'brief.answers.json') or {}
663
+ return [q['id'] for q in brief['questions']
664
+ if isinstance(q, dict) and q.get('must_answer') is True
665
+ and isinstance(q.get('id'), str) and q['id'] and q['id'] not in answers]
666
+
667
+
589
668
  def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
590
669
  infra_retries: int = 0, sweep: str | None = None, sweep_max: int = 5,
591
670
  sweep_plausible: bool = False) -> int:
@@ -607,10 +686,28 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
607
686
  if not _task_id_ok(name):
608
687
  raise ValueError('invalid task ID: ' + name)
609
688
  (plan / 'tasks' / name).mkdir(parents=True, exist_ok=True)
610
- 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
611
705
  pending = list(tasks)
612
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
613
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
614
711
  refused = {} # task -> budget at the time its retry could not be prepared
615
712
  retried = set() # tasks whose next dispatch is a retry (FORGE_FRACTAL_RETRY=1)
616
713
  offsets = {} # how much of each task.out was already echoed under --output full
@@ -638,6 +735,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
638
735
  fractal = _fractal_plan(plan)
639
736
  drain_told = False # the drained message was printed for this drain
640
737
  sweep_asked = False # this invocation already asked for the finding sweep
738
+ brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
739
+ brief_told = set() # (task, qid or '') whose brief wait was already printed
740
+ brief_waiting = set() # tasks the last dispatch pass held for a brief answer or the brief writer
741
+ brief_alive = [0.0, False] # when the writer was last looked at, and what was seen
641
742
 
642
743
  def status(name: str) -> str:
643
744
  root = plan / 'tasks' / name
@@ -654,6 +755,47 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
654
755
  result = subprocess.run(['/bin/bash', script, '_merge', str(plan), name])
655
756
  if result.returncode and status(name) == 'PASS':
656
757
  mark(name, 'ERROR')
758
+ elif brief_mode != 'off' and status(name) == 'MERGED':
759
+ brief_stale(name)
760
+
761
+ def brief_stale(name: str) -> None:
762
+ """Flag the open questions of the tasks that depend on a merge that touched undeclared files.
763
+ A failure is one warning line and changes nothing else."""
764
+ try:
765
+ result = subprocess.run([sys.executable, str(Path(__file__).resolve().with_name('forge-brief.py')),
766
+ 'stale', str(plan), name], stdin=subprocess.DEVNULL,
767
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, timeout=120)
768
+ failed = result.returncode != 0
769
+ detail = result.stderr.strip().splitlines()[-1:] if failed else []
770
+ except (OSError, subprocess.SubprocessError) as error:
771
+ failed, detail = True, [str(error)]
772
+ if failed:
773
+ _warn('brief: could not flag the dependents of ' + name + ' as possibly stale'
774
+ + (' (' + detail[0] + ')' if detail else ''))
775
+
776
+ def brief_held(name: str) -> bool:
777
+ """Under gated only: the task has a must_answer question nobody answered, or no brief.json yet while
778
+ the writer still runs. Prints one line the first time a question holds it."""
779
+ if brief_mode != 'gated':
780
+ return False
781
+ open_ids = brief_unanswered(plan, name)
782
+ if open_ids:
783
+ if (name, open_ids[0]) not in brief_told:
784
+ brief_told.add((name, open_ids[0]))
785
+ print('forge: ' + name + ' waits for your answer to ' + open_ids[0] + ': forge brief answer '
786
+ + shlex.quote(str(plan)) + ' ' + name + ' ' + open_ids[0] + ' "…"', file=sys.stderr, flush=True)
787
+ return True
788
+ if (plan / 'tasks' / name / 'brief.json').exists():
789
+ return False
790
+ now = time.monotonic()
791
+ if now - brief_alive[0] >= BRIEF_PID_CHECK:
792
+ brief_alive[:] = [now, brief_writer_alive(plan)]
793
+ if not brief_alive[1]:
794
+ return False
795
+ if (name, '') not in brief_told:
796
+ brief_told.add((name, ''))
797
+ print('forge: ' + name + ' waits for its brief questions to be written', file=sys.stderr, flush=True)
798
+ return True
657
799
 
658
800
  def budget(name: str) -> int:
659
801
  """Automatic retries this task may use. Read at every decision, never cached: the
@@ -681,15 +823,51 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
681
823
  stop) hands them to the next one."""
682
824
  return _read_budget(plan, 'tasks', name, 'decided.left')
683
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
+
684
861
  def retryable(name: str) -> bool:
685
862
  root = plan / 'tasks' / name
686
863
  left = granted(name)
687
864
  return (
688
865
  status(name) in AUTO_RETRY
689
866
  and (status(name) != 'INVALIDATED' or review_voided(name))
690
- # After a decision the person's count rules, over and under the budget: `retry=3`
691
- # is three attempts even with a budget of 0, and `retry=1` is one even with 3.
692
- 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))
693
871
  # A task that produced no new work (empty diff, byte-identical retry) would
694
872
  # only repeat itself; its marker says so and it is left for a human.
695
873
  and not (root / 'noretry').exists()
@@ -720,8 +898,30 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
720
898
  print('forge: retrying ' + name + ' (decided retry, ' + str(left) + ' more after this)',
721
899
  file=sys.stderr, flush=True)
722
900
  else:
723
- print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
724
- + 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)
725
925
  return True
726
926
 
727
927
  def at_cap(name: str) -> bool:
@@ -751,11 +951,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
751
951
  return False
752
952
  return True
753
953
 
754
- def echo_output(name: str) -> None:
954
+ def echo_output(name: str, file: Path | None = None) -> None:
755
955
  # task.out is opened in append mode, so a retried task's file keeps its earlier
756
- # attempts; print only what is new.
956
+ # attempts; print only what is new. (A group review's own file is group.out.)
757
957
  try:
758
- data = (plan / 'tasks' / name / 'task.out').read_bytes()
958
+ data = (file or plan / 'tasks' / name / 'task.out').read_bytes()
759
959
  except OSError:
760
960
  return
761
961
  start = offsets.get(name, 0)
@@ -775,13 +975,17 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
775
975
 
776
976
  def next_pairs(name: str) -> list:
777
977
  """The pairs the task's next dispatch uses: QA only when its next entry is a QA-only
778
- 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."""
779
982
  if name not in pairs_cache:
780
983
  row = row_now(name)
781
984
  qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
782
985
  ['/bin/bash', script, '_qa_only', str(plan), name],
783
986
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
784
- 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]
785
989
  return pairs_cache[name]
786
990
 
787
991
  def scope_held(name: str) -> bool:
@@ -1074,9 +1278,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1074
1278
  return 'refused', 'the task is merged'
1075
1279
  if state == 'INFRA':
1076
1280
  return 'refused', 'an infrastructure stop is resumed by the scheduler itself'
1077
- 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':
1078
1290
  return 'refused', (name + ' is waiting for an answer: forge-parallel.sh retry ' + str(plan)
1079
- + ' ' + name + ' --answer \u2026')
1291
+ + ' ' + name + ' --answer \u2026 (on a live run: forge control retry ' + str(plan)
1292
+ + ' ' + name + ' --answer \u2026)')
1080
1293
  decide, reason, approved = request.get('decide'), request.get('reason'), request.get('approved') is True
1081
1294
  if decide and state != 'NEEDS_DECISION':
1082
1295
  return 'refused', name + ' is ' + state + ', not waiting for a decision; --decide only decides a NEEDS_DECISION task'
@@ -1090,9 +1303,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1090
1303
  if not (reason or '').strip() or not approved:
1091
1304
  return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
1092
1305
  decision = (['--decide', decide] if decide else []) + ['--reason', reason, '--approved']
1093
- elif state not in RETRYABLE:
1306
+ elif state != 'NEEDS_INPUT' and state not in RETRYABLE:
1094
1307
  return 'refused', 'a ' + state + ' task is not retried'
1095
- 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)
1096
1318
  rc = subprocess.run(command).returncode
1097
1319
  if rc == 3:
1098
1320
  try:
@@ -1112,7 +1334,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1112
1334
  # A decision sets how many attempts follow it: retry=N is N in all (this one and N-1
1113
1335
  # automatic ones), any other choice is this one. A plain retry leaves the budget in charge.
1114
1336
  # (retry_decided wrote decided.left for a decision.) A plain retry ends what a decision allowed.
1115
- if state != 'NEEDS_DECISION':
1337
+ if state not in ('NEEDS_DECISION', 'STALE'):
1116
1338
  _remove(plan, 'tasks', name, 'decided.left')
1117
1339
  retried.add(name)
1118
1340
  human.add(name)
@@ -1149,10 +1371,45 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1149
1371
  return 'refused', 'tasks/' + name + ' could not be created: ' + str(error)
1150
1372
  tasks[name] = found[0]
1151
1373
  pending.append(name)
1374
+ try:
1375
+ summary_seen[name] = summary_signature(name) # before it runs: its first change must trigger
1376
+ except Exception:
1377
+ pass
1152
1378
  if subprocess.run(['/bin/bash', script, '_waves', str(plan)]).returncode:
1153
1379
  _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
1154
1380
  return 'applied', None
1155
1381
 
1382
+ def apply_accept(request: dict) -> tuple:
1383
+ """A person's accept of a reviewed task (#138): what `forge-parallel.sh accept` does, run
1384
+ here because this scheduler holds the plan lock it needs. Its dependents start once it merges."""
1385
+ name, reason = request['task'], (request.get('reason') or '').strip()
1386
+ if name not in tasks:
1387
+ return 'refused', 'this run does not know task ' + name
1388
+ if not reason or request.get('approved') is not True:
1389
+ return 'refused', 'an accept needs --reason and --approved'
1390
+ if name in active:
1391
+ return 'refused', 'the task is running'
1392
+ if name in pending:
1393
+ return 'refused', 'the task is already waiting to run'
1394
+ state = status(name)
1395
+ if state not in ('FAIL', 'UNKNOWN', 'NEEDS_DECISION'):
1396
+ return 'refused', ('a ' + state + ' task has no reviewer verdict to override: accept takes a FAIL, '
1397
+ 'UNKNOWN or NEEDS_DECISION task')
1398
+ env = dict(os.environ, FORGE_ACCEPT_ACTOR=request.get('actor') or 'cli')
1399
+ result = subprocess.run(['/bin/bash', script, '_accept', str(plan), name, '--reason', reason, '--approved'],
1400
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env)
1401
+ lines = [line for line in result.stdout.splitlines() if line.strip()]
1402
+ if result.returncode:
1403
+ said = [line[len('forge: '):] for line in lines if line.startswith('forge: ')]
1404
+ return 'refused', (said[-1] if said else 'the accept failed (exit ' + str(result.returncode) + ')')
1405
+ for line in lines:
1406
+ print('forge: ' + line, file=sys.stderr, flush=True)
1407
+ pairs_cache.pop(name, None)
1408
+ refused.pop(name, None)
1409
+ if brief_mode != 'off' and status(name) == 'MERGED':
1410
+ brief_stale(name)
1411
+ return 'applied', None
1412
+
1156
1413
  def is_fix(name: str) -> bool:
1157
1414
  """A finding sweep's fix task."""
1158
1415
  return (plan / 'tasks' / name / 'sweep.json').is_file()
@@ -1195,11 +1452,159 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1195
1452
  outcome, reason = 'refused', 'run is stopping'
1196
1453
  elif request['verb'] == 'retry':
1197
1454
  outcome, reason = apply_retry(request)
1455
+ elif request['verb'] == 'accept':
1456
+ outcome, reason = apply_accept(request)
1198
1457
  else:
1199
1458
  outcome, reason = apply_add(request)
1200
1459
  with _control_lock(plan):
1201
1460
  settle_request(plan, name, request, outcome, reason)
1202
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
+
1203
1608
  def reap_exited(into: set[str] | None = None, *, allow_requeue: bool = True) -> None:
1204
1609
  """Reap every active task whose process has already exited.
1205
1610
 
@@ -1221,6 +1626,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1221
1626
  into.add(name)
1222
1627
  log.close()
1223
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
1224
1635
  if os.environ.get('FORGE_OUTPUT') == 'full':
1225
1636
  echo_output(name)
1226
1637
  state = status(name)
@@ -1233,9 +1644,109 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1233
1644
  elif allow_requeue and not interrupted and not graceful \
1234
1645
  and state in AUTO_RETRY and retryable(name):
1235
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
1236
1651
  if not reaped:
1237
1652
  return
1238
1653
 
1654
+ summary_seen = {} # task -> what the scheduler last saw of it (status, attempt trail, verdict, retries)
1655
+ summary_due = set() # tasks that changed and wait for a summarize
1656
+ summary_procs = {} # task -> its detached forge-summarize.py, polled only to reap it
1657
+ summary_starters = {} # task -> the thread that is checking admission and starting one
1658
+ summary_checks = {} # task -> (that thread's abandon flag, the pid it waits for)
1659
+ summary_warned = [] # a failure to start one is reported once
1660
+
1661
+ def summary_signature(name: str) -> tuple:
1662
+ root = plan / 'tasks' / name
1663
+ parts = [status(name)]
1664
+ for file in SUMMARY_FILES:
1665
+ try:
1666
+ found = os.stat(root / file)
1667
+ parts.append((found.st_size, found.st_mtime_ns))
1668
+ except OSError:
1669
+ parts.append(None)
1670
+ return tuple(parts)
1671
+
1672
+ def summary_spawn(name: str, after: int | None) -> None:
1673
+ """Start the detached summarize of one task, in its own session. With after (a pid), it begins once
1674
+ that process is gone: the run is ending and the earlier summarize of this task still holds its lock."""
1675
+ command = [sys.executable, os.environ.get('FORGE_SUMMARIZE') or SUMMARIZE, str(plan), '--task', name]
1676
+ if after is not None:
1677
+ command = ['/bin/sh', '-c', 'while kill -0 "$0" 2>/dev/null; do sleep 1; done; exec "$@"',
1678
+ str(after)] + command
1679
+ out = open(plan / 'summaries.out', 'ab')
1680
+ try:
1681
+ process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
1682
+ start_new_session=True)
1683
+ finally:
1684
+ out.close()
1685
+ summary_procs[name] = process
1686
+
1687
+ def summary_run(name: str, after: int | None, abandoned: threading.Event) -> None:
1688
+ """Thread body: forge_side.allowed() takes a blocking lock, so it never runs on the scheduler's
1689
+ loop. An abandoned check (the scheduler is ending and handed the task on) starts nothing."""
1690
+ try:
1691
+ import forge_side
1692
+ if not forge_side.allowed('summary', plan, name)[0] or abandoned.is_set():
1693
+ return
1694
+ summary_spawn(name, after)
1695
+ except Exception as error: # a summary is never worth the run
1696
+ if not summary_warned:
1697
+ summary_warned.append(error)
1698
+ _warn('summaries not started: ' + str(error))
1699
+
1700
+ def summaries_on_change(final: bool = False) -> None:
1701
+ """Start a detached `forge-summarize.py <plan> --task <id>` for every task whose status, dwarf reply,
1702
+ attempt trail, verdict or retry count changed since the last look: once per change, never on a timer,
1703
+ one at a time per task, and only where forge_side.allowed() says summaries are on. The first look at a
1704
+ task only remembers it. Nothing here can change a task or the run, or wait for one."""
1705
+ try:
1706
+ for name in list(summary_procs):
1707
+ if summary_procs[name].poll() is not None:
1708
+ del summary_procs[name]
1709
+ for name in list(summary_starters):
1710
+ if not summary_starters[name].is_alive():
1711
+ del summary_starters[name]
1712
+ for name in tasks:
1713
+ signature = summary_signature(name)
1714
+ if name in summary_seen and summary_seen[name] != signature:
1715
+ summary_due.add(name)
1716
+ summary_seen[name] = signature
1717
+ deadline = time.monotonic() + SUMMARY_JOIN
1718
+ if final: # let the admission checks that are under way finish, for a bounded time
1719
+ for starter in list(summary_starters.values()):
1720
+ starter.join(max(0.0, deadline - time.monotonic()))
1721
+ for name in sorted(summary_due):
1722
+ starter = summary_starters.get(name)
1723
+ running = summary_procs.get(name)
1724
+ running = running if running is not None and running.poll() is None else None
1725
+ if (starter is not None and starter.is_alive()) or (running is not None and not final):
1726
+ continue # still summarising: the change waits for it to end
1727
+ summary_due.discard(name)
1728
+ after = running.pid if running else None
1729
+ abandoned = threading.Event()
1730
+ thread = threading.Thread(target=summary_run, args=(name, after, abandoned), daemon=True)
1731
+ summary_starters[name] = thread
1732
+ summary_checks[name] = (abandoned, after)
1733
+ thread.start()
1734
+ if final:
1735
+ for starter in list(summary_starters.values()):
1736
+ starter.join(max(0.0, deadline - time.monotonic()))
1737
+ # A check still blocked at the deadline (the side lock is held) was past the switch tests,
1738
+ # which never block: summaries are on. The thread dies with the scheduler, so the detached
1739
+ # summarize takes it over and makes the whole admission check itself.
1740
+ for name, starter in list(summary_starters.items()):
1741
+ if starter.is_alive():
1742
+ abandoned, after = summary_checks[name]
1743
+ abandoned.set()
1744
+ summary_spawn(name, after)
1745
+ except Exception as error: # a summary is never worth the run
1746
+ if not summary_warned:
1747
+ summary_warned.append(error)
1748
+ _warn('summaries not started: ' + str(error))
1749
+
1239
1750
  def stop(signum: int, frame: object) -> None:
1240
1751
  nonlocal interrupted
1241
1752
  interrupted = True
@@ -1243,14 +1754,16 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1243
1754
  signal.signal(signal.SIGTERM, stop)
1244
1755
  signal.signal(signal.SIGINT, stop)
1245
1756
  try:
1246
- live_start(plan, tasks, retry_failed, infra_retries)
1757
+ live_start(plan, tasks, retry_failed, infra_retries, rgroups)
1758
+ summaries_on_change()
1247
1759
  # Failures require an explicit retry unless this run asked for automatic ones.
1248
1760
  # Saved PASS results use the same fingerprint checks without paying for
1249
1761
  # implementation or QA again; an INFRA stop is not a failure of the work, so it
1250
1762
  # is simply dispatched again.
1251
1763
  # RUNNING at start means a scheduler was killed without its cleanup: its tasks'
1252
1764
  # harnesses may still be running and editing their worktrees.
1253
- 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'])
1254
1767
  for name in pending[:]:
1255
1768
  state = status(name)
1256
1769
  if state == 'PASS':
@@ -1259,13 +1772,34 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1259
1772
  mark(name, 'INTERRUPTED')
1260
1773
  if state in AUTO_RETRY and not interrupted and retryable(name):
1261
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
1262
1777
  if state == 'INFRA' and not interrupted and not resume(name):
1263
1778
  pending.remove(name)
1264
1779
  continue
1265
1780
  if status(name) not in ('PENDING', 'BLOCKED', 'INFRA'):
1266
- 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)
1267
1801
  swept = time.monotonic()
1268
- while pending or active or waiting_scopes() or sweep_due():
1802
+ while pending or active or waiting_scopes() or sweep_due() or ready_groups():
1269
1803
  # Reap before honouring the stop. A signal during the sleep, and a task
1270
1804
  # that exits while another merge is still running, have already written
1271
1805
  # a result; breaking first used to skip them and mark them INTERRUPTED.
@@ -1276,6 +1810,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1276
1810
  interrupted = True
1277
1811
  graceful = graceful or mode == 'graceful'
1278
1812
  reap_exited(ended)
1813
+ summaries_on_change()
1279
1814
  if interrupted:
1280
1815
  break
1281
1816
  draining = drained(plan)
@@ -1331,13 +1866,22 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1331
1866
  handle_requests()
1332
1867
  cap = live_capacity(plan, capacity)
1333
1868
  draining = drained(plan) # again: the infrastructure wait above can last minutes
1869
+ brief_waiting.clear()
1870
+ start_ready_groups()
1334
1871
  for name in pending[:]:
1335
1872
  if paused or len(active) >= cap or interrupted or graceful or draining:
1336
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
1337
1877
  deps = [d for d in tasks[name][1].split(',') if d and d != '-']
1338
1878
  if any(status(dep) != 'MERGED' for dep in deps):
1339
1879
  continue
1340
- if any(overlap(tasks[name][3], tasks[other][3]) for other in active):
1880
+ if brief_held(name):
1881
+ # A wait, not a stop: the rest of the plan runs, and the run does not end while it lasts.
1882
+ brief_waiting.add(name)
1883
+ continue
1884
+ if any(overlap(tasks[name][3], tasks[other][3]) for other in active if other in tasks):
1341
1885
  continue
1342
1886
  if pauses and scope_held(name):
1343
1887
  # Each move changes the models it is held on: the implementer, then the reviewer, in one pass,
@@ -1371,12 +1915,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1371
1915
  print('forge: stopped by forge control stop; ' + str(len(pending)) + ' task(s) not started',
1372
1916
  file=sys.stderr, flush=True)
1373
1917
  break
1374
- if not active and draining and (pending or waiting_scopes()):
1918
+ if not active and draining and (pending or waiting_scopes() or ready_groups()):
1375
1919
  if not drain_told:
1376
1920
  drain_told = True
1377
1921
  print('forge: drained — ' + str(len(pending)) + ' task(s) waiting; forge control resume '
1378
1922
  + str(plan) + ' continues', file=sys.stderr, flush=True)
1379
- elif not active and not waiting_scopes():
1923
+ elif not active and not waiting_scopes() and not brief_waiting:
1380
1924
  if paused or held or any(live_pause(pause) for pause in pauses.values()):
1381
1925
  # Infrastructure stop: leave everything not yet run PENDING. Marking it
1382
1926
  # BLOCKED would turn "the provider was down" into a recorded failure.
@@ -1385,9 +1929,11 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1385
1929
  if not pending and sweep_due() and start_sweep():
1386
1930
  continue
1387
1931
  for name in pending:
1388
- mark(name, 'BLOCKED')
1932
+ if status(name) != 'IMPLEMENTED': # waiting for its group, not blocked
1933
+ mark(name, 'BLOCKED')
1389
1934
  break
1390
1935
  time.sleep(0.05)
1936
+ report_waiting_groups()
1391
1937
  finally:
1392
1938
  try:
1393
1939
  held_record()
@@ -1431,12 +1977,19 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1431
1977
  except subprocess.TimeoutExpired:
1432
1978
  pass
1433
1979
  log.close()
1434
- 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)
1435
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
1436
1988
  try:
1437
1989
  mark(name, 'INTERRUPTED')
1438
1990
  except OSError as error:
1439
1991
  _warn('could not mark ' + name + ' INTERRUPTED: ' + str(error))
1992
+ summaries_on_change(final=True) # the last merges and stops; the children outlive the scheduler
1440
1993
  if interrupted or (graceful and not all(status(name) == 'MERGED' for name in tasks)):
1441
1994
  return 130
1442
1995
  if paused or any(live_pause(pause) for pause in pauses.values()) \
@@ -1446,6 +1999,31 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1446
1999
  return 0 if all(status(name) == 'MERGED' for name in tasks if not is_fix(name)) else 5
1447
2000
 
1448
2001
 
2002
+ HOLDER = 'schedule.holder' # the forge command holding schedule.lock: written by each one that takes it
2003
+
2004
+
2005
+ def lock_refusal(plan: Path, command: str) -> str:
2006
+ """What a command the plan lock refuses says (#138): who holds the lock, and what to do instead."""
2007
+ holder = _json_object(plan / HOLDER) or {}
2008
+ pid, held_by, since = holder.get('pid'), holder.get('command'), holder.get('at')
2009
+ who = 'another forge command'
2010
+ if isinstance(held_by, str) and held_by.isidentifier() and type(pid) is int:
2011
+ who = 'forge-parallel.sh ' + held_by + ' (pid ' + str(pid) + ')'
2012
+ if isinstance(since, (int, float)):
2013
+ try:
2014
+ who += ', since ' + time.strftime('%H:%M', time.localtime(since))
2015
+ except (ValueError, OverflowError, OSError):
2016
+ pass
2017
+ text = 'forge: ' + command + ': the plan ' + str(plan) + ' is locked by ' + who + '.'
2018
+ if held_by == 'run' or (plan / 'scheduler.live').exists():
2019
+ live = ('forge control accept ' + str(plan) + ' <task> --reason TEXT --approved'
2020
+ if command == 'accept' else 'forge control (retry, accept, add, set, drain, stop)')
2021
+ text += ' A run is live: change it with ' + live + ', or wait for the run to end.'
2022
+ else:
2023
+ text += ' Wait for it to finish, then run forge-parallel.sh ' + command + ' again.'
2024
+ return text
2025
+
2026
+
1449
2027
  def main() -> None:
1450
2028
  try:
1451
2029
  if sys.argv[1] == 'backoff-check':
@@ -1461,8 +2039,14 @@ def main() -> None:
1461
2039
  # The shell inherits the lock for its entire operation, including
1462
2040
  # preflight, setup, scheduling, verification and cleanup.
1463
2041
  lock = open(Path(plan) / 'schedule.lock', 'a')
1464
- fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
2042
+ try:
2043
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
2044
+ except BlockingIOError:
2045
+ print(lock_refusal(Path(plan), command), file=sys.stderr)
2046
+ sys.exit(3)
1465
2047
  os.set_inheritable(lock.fileno(), True)
2048
+ # Who holds it, for the next command the lock refuses. exec keeps this pid.
2049
+ _write_atomic(plan, json.dumps(dict(pid=os.getpid(), command=command, at=time.time())) + '\n', HOLDER)
1466
2050
  env = dict(os.environ, FORGE_PLAN_LOCK=plan)
1467
2051
  os.execve('/bin/bash', ['/bin/bash', script, command, plan, *args], env)
1468
2052
  parser = argparse.ArgumentParser(prog='forge-schedule.py')