@giamme/forge 0.13.1 → 0.14.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 (47) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -0
  5. package/docs/commands.md +121 -7
  6. package/docs/development.md +3 -0
  7. package/docs/reviews.md +2 -0
  8. package/docs/troubleshooting.md +5 -1
  9. package/forge +28 -1
  10. package/package.json +1 -1
  11. package/references/dataset.md +3 -1
  12. package/references/decompose.md +199 -61
  13. package/references/runtime.md +29 -0
  14. package/references/ui.md +10 -0
  15. package/scripts/forge-compare.py +491 -0
  16. package/scripts/forge-config.py +3 -3
  17. package/scripts/forge-contract.py +34 -8
  18. package/scripts/forge-control.py +105 -13
  19. package/scripts/forge-dispatch.sh +9 -5
  20. package/scripts/forge-jev-options.sh +17 -4
  21. package/scripts/forge-ledger.py +387 -0
  22. package/scripts/forge-lib-plans.sh +11 -2
  23. package/scripts/forge-lib-task.sh +390 -28
  24. package/scripts/forge-parallel-options.sh +20 -4
  25. package/scripts/forge-parallel.sh +116 -12
  26. package/scripts/forge-plan-check.py +68 -3
  27. package/scripts/forge-pr.py +276 -0
  28. package/scripts/forge-route.py +350 -34
  29. package/scripts/forge-runs.py +18 -1
  30. package/scripts/forge-runtime.py +23 -7
  31. package/scripts/forge-schedule.py +303 -46
  32. package/scripts/forge-verify-failed.py +111 -0
  33. package/scripts/forge-watch.py +372 -0
  34. package/scripts/forge_dataset/harvest.py +3 -1
  35. package/scripts/forge_fractal/cli.py +23 -6
  36. package/scripts/forge_infra.py +274 -0
  37. package/scripts/forge_jev/client.py +13 -9
  38. package/ui/docs/api.md +51 -8
  39. package/ui/forge_ui/export.py +6 -2
  40. package/ui/forge_ui/reader.py +172 -6
  41. package/ui/forge_ui/static/app.js +2 -2
  42. package/ui/forge_ui/static/checksview.js +20 -7
  43. package/ui/forge_ui/static/controls.js +6 -3
  44. package/ui/forge_ui/static/panel.js +69 -4
  45. package/ui/forge_ui/static/runmodel.js +30 -4
  46. package/ui/forge_ui/static/scene3d.js +3 -2
  47. package/ui/forge_ui/static/style.css +11 -4
@@ -348,7 +348,10 @@ INFRA_PATTERNS = (
348
348
  _P(r"\b(?:no|missing) api[ _-]?key\b|\bcould not resolve authentication method\b", re.I),
349
349
  _P(_HTTP_CODE % '40[13]' + r"|\b40[13]\b\W{0,3}(?:unauthori[sz]ed|forbidden)\b", re.I),
350
350
  )),
351
- ('quota', (
351
+ # Order is priority: the first class with a matching phrase wins (auth > usage_limit > budget >
352
+ # capacity > rate_limit > provider_down > network). A usage limit that also mentions credits
353
+ # is a usage limit: the window resets, the money does not run out.
354
+ ('usage_limit', (
352
355
  _P(r"\busage[ _-]?limit\b", re.I),
353
356
  # "You've hit your limit", "hit your session limit", "reached the weekly limit"; but not
354
357
  # "reached the context limit", which is the model's problem rather than the account's.
@@ -356,31 +359,44 @@ INFRA_PATTERNS = (
356
359
  r"5-hour|five-hour|spend\w*|credit|token|message|request|plan|org\w*) )?limits?\b", re.I),
357
360
  _P(r"(?<!context )(?<!rate )(?<!rate-)(?<!rate_)\blimit (?:reached|exceeded)\b", re.I),
358
361
  _P(r"\b(?:session|weekly|daily|monthly|5-hour|five-hour) limit\b", re.I),
362
+ )),
363
+ # Money that is gone. A bare "billing" is not a phrase: it would match "billing.ts" in a stack trace.
364
+ ('budget', (
359
365
  _P(r"\bquota (?:exceeded|exhausted|reached)\b|\bexceeded (?:your |the )?(?:current )?quota\b|\binsufficient[ _-]quota\b|\bout of (?:credits|quota)\b", re.I),
360
366
  _P(r"\binsufficient (?:balance|credits?|funds)\b", re.I),
361
367
  _P(r"\bcredit balance (?:is )?too low\b", re.I),
362
368
  _P(r"\bpayment required\b|\bbilling (?:hard )?limit\b|\bbilling (?:issue|error|details|not active)\b|\bcheck your (?:plan and )?billing\b", re.I),
369
+ _P(_HTTP_CODE % '402', re.I),
363
370
  )),
371
+ # A model at capacity for everyone who asks it.
372
+ ('capacity', (
373
+ _P(r"\boverloaded\b", re.I),
374
+ _P(r"\bat capacity\b", re.I),
375
+ _P(_HTTP_CODE % '529', re.I),
376
+ )),
377
+ # An account sending too fast.
364
378
  ('rate_limit', (
365
379
  _P(r"\brate[ _-]?limit(?:s|ed|ing)?\b", re.I),
366
380
  _P(r"\btoo many requests\b", re.I),
367
- _P(r"\boverloaded\b", re.I),
368
- _P(r"\bat capacity\b", re.I),
369
381
  _P(_HTTP_CODE % '429' + r"|\b429\b\W{0,3}too many\b", re.I),
370
382
  )),
383
+ # One provider failing, while the connection itself works.
384
+ ('provider_down', (
385
+ _P(r"\bbad gateway\b|\bservice unavailable\b|\bgateway time-?out\b", re.I),
386
+ _P(_HTTP_CODE % '50[234]', re.I),
387
+ )),
371
388
  ('network', (
372
389
  _P(r"\b(?:ECONNRESET|ETIMEDOUT|ENOTFOUND|ECONNREFUSED|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|ENETDOWN)\b"),
373
390
  _P(r"\bgetaddrinfo\b", re.I),
374
391
  _P(r"\bconnection (?:refused|reset|timed out)\b|\bnetwork is unreachable\b|\bsocket hang up\b", re.I),
375
392
  _P(r"\bcan['’]?t reach the api server\b|\bunable to connect\b|\bfailed to connect\b|\bfetch failed\b", re.I),
376
393
  _P(r"\btemporary failure in name resolution\b|\bname or service not known\b", re.I),
377
- _P(r"\bbad gateway\b|\bservice unavailable\b|\bgateway time-?out\b", re.I),
378
394
  _P(r"\binvalid peer certificate\b", re.I),
379
395
  )),
380
396
  )
381
397
  # api_error_status as claude reports it, used only when the text itself matched nothing.
382
- STATUS_CLASS = {401: 'auth', 403: 'auth', 402: 'quota', 429: 'rate_limit', 529: 'rate_limit',
383
- 502: 'network', 503: 'network', 504: 'network'}
398
+ STATUS_CLASS = {401: 'auth', 403: 'auth', 402: 'budget', 429: 'rate_limit', 529: 'capacity',
399
+ 502: 'provider_down', 503: 'provider_down', 504: 'provider_down'}
384
400
 
385
401
  _MONTHS = {m: i + 1 for i, m in enumerate(
386
402
  ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'))}
@@ -470,7 +486,7 @@ def _one_line(text: str, limit: int = DETAIL_MAX) -> str:
470
486
 
471
487
 
472
488
  def classify_text(text: str, status: object = None, now: float | None = None):
473
- """(class, retry_after_or_None, detail) for failure text, or None. auth > quota > rate_limit > network."""
489
+ """(class, retry_after_or_None, detail) for failure text, or None. The order is INFRA_PATTERNS'."""
474
490
  for name, patterns in INFRA_PATTERNS:
475
491
  for pattern in patterns:
476
492
  match = pattern.search(text)
@@ -27,6 +27,7 @@ import contextlib
27
27
  import errno
28
28
  import fcntl
29
29
  import json
30
+ import math
30
31
  import os
31
32
  import re
32
33
  from pathlib import Path
@@ -38,6 +39,11 @@ import sys
38
39
  import tempfile
39
40
  import time
40
41
 
42
+ # forge_infra.py sits beside this file; forge-control.py loads this module by path.
43
+ if str(Path(__file__).resolve().parent) not in sys.path:
44
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
45
+ import forge_infra # noqa: E402
46
+
41
47
 
42
48
  def dataset_event(name: str, plan: Path, task: str, values: dict) -> None:
43
49
  """Record a status only the scheduler sets (INTERRUPTED, BLOCKED, ERROR) in the run
@@ -64,7 +70,7 @@ def overlap(a: str, b: str) -> bool:
64
70
 
65
71
  INFRA_EXIT = 8
66
72
  # A parsed retry-after beyond this is not a pause worth waiting for inside one run.
67
- INFRA_WAIT_CAP = 6 * 3600
73
+ INFRA_WAIT_CAP = forge_infra.WAIT_CAP_S
68
74
 
69
75
 
70
76
  def infra_info(root: Path) -> dict:
@@ -143,18 +149,39 @@ def infra_wait(info: dict, cycle: int, backoff: tuple | None = None) -> tuple:
143
149
 
144
150
 
145
151
  # --- pause scopes ----------------------------------------------------------------------
146
- # A capacity error on one model says nothing about another, and a quota or auth stop is one
147
- # harness's account; only the remaining classes (network, empty output, ...) stop everything.
152
+ # What a stop holds back follows its cause (forge_infra.CAUSES): a capacity or rate-limit error
153
+ # on one model says nothing about another, a usage limit, budget or auth stop is one harness's
154
+ # account, and only the remaining causes (network, ...) stop everything. A stored class from
155
+ # before the split (`quota`) is read as the cause it became.
148
156
  def infra_scope(info: dict) -> tuple:
149
157
  """(scope, harness, model) for a stop's infra.txt."""
150
- cls, harness, model = info.get('class', ''), info.get('harness', ''), info.get('model', '')
151
- if cls == 'rate_limit' and harness and model:
158
+ harness, model = info.get('harness', ''), info.get('model', '')
159
+ scope = forge_infra.entry(info.get('class'))['scope']
160
+ if scope == 'model' and harness and model:
152
161
  return 'model:%s/%s' % (harness, model), harness, model
153
- if cls in ('quota', 'auth') and harness:
162
+ if scope == 'harness' and harness:
154
163
  return 'harness:' + harness, harness, ''
155
164
  return 'all', harness, model
156
165
 
157
166
 
167
+ def _epoch(value: object) -> float | int | None:
168
+ """A finite non-negative number from an infra.txt value, else None."""
169
+ try:
170
+ number = float(value)
171
+ except (TypeError, ValueError):
172
+ return None
173
+ if not math.isfinite(number) or number < 0:
174
+ return None
175
+ return int(number) if number == int(number) else number
176
+
177
+
178
+ def _reset_of(info: dict) -> float | int | None:
179
+ """When a stop's limit resets: its reset_at, else its retry-after from now; None when unknown."""
180
+ at = _epoch(info.get('reset_at'))
181
+ after = _epoch(info.get('retry_after'))
182
+ return at if at is not None or after is None else time.time() + after
183
+
184
+
158
185
  def load_registry() -> list:
159
186
  path = os.environ.get('FORGE_REGISTRY') or str(Path(__file__).resolve().parent.parent / 'registry.tsv')
160
187
  rows = []
@@ -373,6 +400,7 @@ def _pinned(plan: object, name: str) -> bool:
373
400
  # lets that trap finish; the guard's `stop` then acts on whatever <role>.harness record a
374
401
  # dispatch that died too early left behind.
375
402
  GUARD = str(Path(__file__).resolve().parent / 'forge-guard.py')
403
+ ROUTE = str(Path(__file__).resolve().parent / 'forge-route.py')
376
404
  HARNESS_ROLES = ('dwarf', 'qa')
377
405
  GUARD_STOP_WAIT = 15.0 # seconds; the guard's own bound is about 3 s plus two ps calls
378
406
 
@@ -434,8 +462,13 @@ def stop_harnesses(plan: object, names: object) -> None:
434
462
  # is left after it withdraws liveness, under the same lock, so no request outlives its run.
435
463
  REQUESTS = 'control.requests'
436
464
  REQUEST_MAX = 64 * 1024
465
+ # What `forge control retry --decide` may carry: retry=N (1 to 20) or threshold=Pn.
466
+ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
437
467
  # NEEDS_INPUT is in neither: a task stopped for the user's answer resumes only through
438
- # `retry <plan> <id> --answer`, whose preparation refuses without one.
468
+ # `retry <plan> <id> --answer`, whose preparation refuses without one. Nor is NEEDS_DECISION (#69):
469
+ # a task whose reviews do not converge, or that the retry policy cannot move to a stronger model,
470
+ # resumes only through a person's `retry --decide` (or `--dwarf`) with a reason and --approved.
471
+ # No budget, pin or sweep reaches it, because every automatic path asks for a status in AUTO_RETRY.
439
472
  RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED')
440
473
  # What --retry-failed retries on its own. INVALIDATED only for a review voided while the committed
441
474
  # work stayed as it was (tasks/<id>/invalidated.reason is `review`): that retry is a fresh review.
@@ -455,6 +488,15 @@ def list_requests(plan: object) -> list:
455
488
  return []
456
489
 
457
490
 
491
+ def decision_head(plan: object, name: str) -> str:
492
+ """The first lines of a NEEDS_DECISION task's decision.md, on one line."""
493
+ try:
494
+ lines = (Path(plan) / 'tasks' / name / 'decision.md').read_text().splitlines()
495
+ except OSError:
496
+ return 'see decision.md'
497
+ return ' '.join(line.strip() for line in lines[:3] if line.strip())[:300]
498
+
499
+
458
500
  def read_request(plan: object, name: str) -> dict | None:
459
501
  try:
460
502
  fd = os.open(_resolve(plan, REQUESTS, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
@@ -473,6 +515,13 @@ def read_request(plan: object, name: str) -> dict | None:
473
515
  if dwarf is not None and (not isinstance(dwarf, str) or not dwarf or dwarf.startswith('-')
474
516
  or any(c.isspace() or c == ',' for c in dwarf)):
475
517
  return None
518
+ decide, reason = request.get('decide'), request.get('reason')
519
+ if decide is not None and (not isinstance(decide, str) or not DECISION.fullmatch(decide)):
520
+ return None
521
+ if reason is not None and (not isinstance(reason, str) or len(reason) > 2000):
522
+ return None
523
+ if not isinstance(request.get('approved', False), bool):
524
+ return None
476
525
  return request
477
526
 
478
527
 
@@ -509,6 +558,7 @@ def live_start(plan: object, names: object, retry_failed: int, infra_retries: in
509
558
  _remove(plan, 'tasks', name, 'retry_budget')
510
559
  _remove(plan, 'tasks', name, 'retries.used')
511
560
  _remove(plan, 'infra.paused')
561
+ _remove(plan, 'infra.last')
512
562
  _remove(plan, 'drain')
513
563
  _remove(plan, 'stop')
514
564
  # Queued for a scheduler that died: never applied to this run.
@@ -569,10 +619,13 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
569
619
  infra_cycles = 0 # how many times this run already waited out an infrastructure pause
570
620
  paused = False # an `all`-scope infrastructure failure was seen: dispatch nothing new
571
621
  resume_at = 0.0
572
- all_class = '' # the class of the first `all`-scope stop, for infra.paused
622
+ all_class = '' # the cause of the first `all`-scope stop, for infra.paused
623
+ all_reset = None # when that stop said its limit resets, for infra.paused
624
+ retried_stops = set() # (task, cause) already re-dispatched once at once (the `retry` move)
573
625
  pauses = {} # scope -> its pause, for model: and harness: scopes; `all` is the above
574
626
  scope_waits = {} # scope -> waits it already completed this run
575
627
  pairs_cache = {} # task -> (harness, model) pairs its next dispatch uses
628
+ held_tries = {} # task -> the paused scopes and its pairs when a sideways move before dispatch was last tried
576
629
  registry = load_registry()
577
630
  paused_text = None # what infra.paused holds now
578
631
  backoff_warned = [] # an invalid infra_backoff file is reported once
@@ -618,12 +671,21 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
618
671
  except OSError:
619
672
  return False
620
673
 
674
+ def granted(name: str) -> int | None:
675
+ """Automatic retries left from a person's decision, which replaces the budget; None when no
676
+ decision governs. A file (decided.left), so a run that ended before they were used (a quota
677
+ stop) hands them to the next one."""
678
+ return _read_budget(plan, 'tasks', name, 'decided.left')
679
+
621
680
  def retryable(name: str) -> bool:
622
681
  root = plan / 'tasks' / name
682
+ left = granted(name)
623
683
  return (
624
684
  status(name) in AUTO_RETRY
625
685
  and (status(name) != 'INVALIDATED' or review_voided(name))
626
- and retries.get(name, 0) < budget(name)
686
+ # After a decision the person's count rules, over and under the budget: `retry=3`
687
+ # is three attempts even with a budget of 0, and `retry=1` is one even with 3.
688
+ and (left > 0 if left is not None else retries.get(name, 0) < budget(name))
627
689
  # A task that produced no new work (empty diff, byte-identical retry) would
628
690
  # only repeat itself; its marker says so and it is left for a human.
629
691
  and not (root / 'noretry').exists()
@@ -634,7 +696,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
634
696
  )
635
697
 
636
698
  def requeue(name: str) -> bool:
637
- """Prepare a retry exactly as `retry` does, then put the task at the queue head."""
699
+ """Prepare a retry exactly as `retry` does, then put the task at the queue head. A task at its
700
+ attempt cap (#69) is not prepared: _prepare_retry stops it for a decision instead."""
638
701
  result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name])
639
702
  if result.returncode:
640
703
  refused[name] = budget(name)
@@ -646,18 +709,38 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
646
709
  retried.add(name)
647
710
  if name not in pending:
648
711
  pending.insert(0, name)
649
- print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
650
- + str(budget(name)) + ')', file=sys.stderr, flush=True)
712
+ left = granted(name)
713
+ if left is not None:
714
+ left = max(left - 1, 0)
715
+ _write_atomic(plan, str(left), 'tasks', name, 'decided.left')
716
+ print('forge: retrying ' + name + ' (decided retry, ' + str(left) + ' more after this)',
717
+ file=sys.stderr, flush=True)
718
+ else:
719
+ print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
720
+ + str(budget(name)) + ')', file=sys.stderr, flush=True)
651
721
  return True
652
722
 
723
+ def at_cap(name: str) -> bool:
724
+ """The task has spent its attempt cap (#69): `forge-route.py attempt-cap` prints "<used> <cap>"."""
725
+ result = subprocess.run([sys.executable, ROUTE, 'attempt-cap', '--plan', str(plan), '--task', name],
726
+ capture_output=True, text=True)
727
+ used, _, cap = result.stdout.strip().partition(' ')
728
+ return result.returncode == 0 and used.isdigit() and cap.isdigit() and int(used) >= int(cap)
729
+
653
730
  def resume(name: str) -> bool:
654
731
  """Prepare an INFRA task's next entry. Not a retry, so nothing is counted, but a
655
732
  pending pin applies when that entry is a full implementer attempt. False when a
656
- claimed pin could not be put in place: the task then stays INFRA, as `retry` would."""
657
- if not _pinned(plan, name):
733
+ claimed pin could not be put in place: the task then stays INFRA, as `retry` would. A task already
734
+ at its attempt cap (#69; the cap may have been set or lowered after the stop) is not resumed
735
+ either: _prepare_retry --resume stops it for a decision, and it leaves the queue."""
736
+ if not _pinned(plan, name) and not at_cap(name):
658
737
  return True
659
738
  result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--resume'])
660
739
  if result.returncode:
740
+ if status(name) == 'NEEDS_DECISION':
741
+ print('forge: ' + name + ' is not resumed: it is at its attempt cap and waits for your decision',
742
+ file=sys.stderr, flush=True)
743
+ return False
661
744
  held.add(name)
662
745
  print('forge: ' + name + ' is not resumed: its escalation pin could not be applied',
663
746
  file=sys.stderr, flush=True)
@@ -700,6 +783,52 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
700
783
  def scope_held(name: str) -> bool:
701
784
  return any(holds(pause, next_pairs(name)) for pause in pauses.values())
702
785
 
786
+ def move_held(name: str) -> bool:
787
+ """A pending task a pause holds back moves sideways before its dispatch, as a stopped one does: the
788
+ implementer to the next healthy model of its tier, or, when only its reviewer is held, the reviewer
789
+ to a peer. Tried once for each set of pauses and models: a move changes the models, so a task with
790
+ both on the paused harness moves its implementer, then its reviewer. True when the task moved."""
791
+ if interrupted or graceful or fractal or _read_small(plan, 'infra_fallback') != 'on':
792
+ return False
793
+ pairs = next_pairs(name)
794
+ seen = (frozenset(pauses), tuple(pairs))
795
+ if held_tries.get(name) == seen:
796
+ return False
797
+ held_tries[name] = seen
798
+ holding = [pause for pause in pauses.values() if holds(pause, pairs)]
799
+ moves = [pause for pause in holding if forge_infra.entry(pause['class'])['move'] in ('lateral', 'retry')]
800
+ if not holding or len(moves) < len(holding):
801
+ return False
802
+ # The implementer's pair when it is held (a full dispatch), else the reviewer's.
803
+ role = 'dwarf' if len(pairs) == 2 and any(holds(pause, pairs[:1]) for pause in holding) else 'qa'
804
+ excluded = {(pause['harness'], pause['model'] or '*') for pause in pauses.values()}
805
+ command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
806
+ ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', holding[0]['class']]
807
+ if role == 'qa':
808
+ command += ['--role', 'qa']
809
+ if subprocess.run(command).returncode:
810
+ return False
811
+ pairs_cache.pop(name, None)
812
+ return True
813
+
814
+ def held_record() -> None:
815
+ """infra.last: the pauses still holding work when the scheduler ends, each with the pending tasks it
816
+ holds back (`held`). infra.paused goes with the scheduler; the run summary and forge-ui read this
817
+ one to say who must act. The next run's start removes it."""
818
+ scopes = []
819
+ if paused:
820
+ scopes.append({'scope': 'all', 'class': all_class or None, 'harness': None, 'model': None,
821
+ 'tasks': list(infra_seen), 'held': list(pending), 'needs_you': False, 'hint': None,
822
+ 'reset_at': all_reset})
823
+ for pause in pauses.values():
824
+ if live_pause(pause):
825
+ record = {key: pause[key] for key in ('scope', 'class', 'harness', 'model', 'tasks', 'needs_you',
826
+ 'hint', 'reset_at')}
827
+ record['held'] = [name for name in pending if holds(pause, next_pairs(name))]
828
+ scopes.append(record)
829
+ if scopes:
830
+ _write_atomic(plan, json.dumps({'scopes': scopes}), 'infra.last')
831
+
703
832
  def live_pause(pause: dict) -> bool:
704
833
  """A pause still holding something: its own stopped tasks, or a pending task on its pair.
705
834
  One whose tasks all fell back to another model holds nothing."""
@@ -708,23 +837,34 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
708
837
  def waiting_scopes() -> bool:
709
838
  return any(not pause['exhausted'] and live_pause(pause) for pause in pauses.values())
710
839
 
711
- def fall_back(name: str, info: dict, scope: str) -> None:
712
- """--infra-fallback: a dwarf-stage capacity stop moves to the next healthy model of its
713
- tier pool. The stop was already recorded as its scope's pause, so every paused or
714
- exhausted pair is excluded and a pool all at capacity cannot bounce the task forever."""
715
- if interrupted or graceful or fractal or _read_small(plan, 'infra_fallback') != 'on' or _pinned(plan, name):
716
- return
717
- if info.get('stage') != 'dwarf' or info.get('class') != 'rate_limit' or not scope.startswith('model:'):
718
- return
719
- excluded = {(info['harness'], info['model'])}
840
+ def fall_back(name: str, info: dict, scope: str, cause: str) -> bool:
841
+ """The lateral move: a stop on a model or harness scope moves to the next healthy model of its
842
+ tier pool, when --infra-fallback is on. A dwarf-stage stop takes the implementer pool's next
843
+ model; a QA-stage stop takes a peer reviewer from the plan's qa-routing.json (never the model
844
+ that wrote the work, and none for a plan without that file), keeping its attempt and its
845
+ QA-only resume. The stop was already recorded as its scope's pause, so every paused or
846
+ exhausted pair is excluded (and a harness stop excludes the whole harness); a pool all
847
+ stopped cannot bounce the task forever. True when the task moved, and so left the pause."""
848
+ stage = info.get('stage')
849
+ if interrupted or graceful or fractal or _read_small(plan, 'infra_fallback') != 'on':
850
+ return False
851
+ # A pin waits for the next full retry, which a review's move is not.
852
+ if stage not in ('dwarf', 'qa') or (stage == 'dwarf' and _pinned(plan, name)):
853
+ return False
854
+ if not scope.startswith(('model:', 'harness:')):
855
+ return False
856
+ excluded = {(info['harness'], info['model'] if scope.startswith('model:') else '*')}
720
857
  excluded.update((p['harness'], p['model'] or '*') for p in pauses.values())
721
858
  command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
722
- ','.join(sorted(h + '/' + m for h, m in excluded))]
859
+ ','.join(sorted(h + '/' + m for h, m in excluded)), '--cause', cause]
860
+ if stage == 'qa':
861
+ command += ['--role', 'qa']
723
862
  if subprocess.run(command).returncode:
724
- return
863
+ return False
725
864
  pauses[scope]['tasks'].remove(name)
726
865
  pairs_cache.pop(name, None)
727
866
  pending.insert(0, name)
867
+ return True
728
868
 
729
869
  def write_paused(until_all: float | None = None) -> None:
730
870
  """infra.paused for forge-ui and `forge control show`; gone when nothing is paused."""
@@ -733,10 +873,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
733
873
  if paused:
734
874
  scopes.append({'scope': 'all', 'class': all_class or None, 'harness': None, 'model': None,
735
875
  'tasks': list(infra_seen), 'cycle': infra_cycles + (1 if until_all else 0),
736
- 'until': until_all, 'exhausted': not until_all and infra_cycles >= infra_budget()})
876
+ 'until': until_all, 'exhausted': not until_all and infra_cycles >= infra_budget(),
877
+ 'needs_you': False, 'hint': None, 'reset_at': all_reset})
737
878
  for pause in pauses.values():
738
879
  scopes.append({key: pause[key] for key in
739
- ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')})
880
+ ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted',
881
+ 'needs_you', 'hint', 'reset_at')})
740
882
  text = json.dumps({'scopes': scopes}) if scopes else None
741
883
  if text == paused_text:
742
884
  return
@@ -770,11 +912,14 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
770
912
  _warn('infra_backoff ignored, using the default: ' + problem)
771
913
  return default_backoff()
772
914
 
915
+ def scope_where(pause: dict) -> str:
916
+ return pause['harness'] + ('/' + pause['model'] if pause['model'] else '')
917
+
773
918
  def start_wait(pause: dict, info: dict, name: str) -> None:
774
919
  """Begin the scope's next wait, or mark it exhausted when its budget is spent."""
775
920
  done, budget = scope_waits.get(pause['scope'], 0), infra_budget()
776
- where = pause['harness'] + ('/' + pause['model'] if pause['model'] else '')
777
- head = 'forge: infrastructure failure (' + pause['class'] + ') on ' + where + ' for ' + name
921
+ head = 'forge: infrastructure failure (' + pause['class'] + ') on ' + scope_where(pause) + ' for ' + name
922
+ pause.update(needs_you=False, hint=None, reset_at=_epoch(info.get('reset_at')))
778
923
  if done >= budget:
779
924
  pause.update(cycle=done, until=None, exhausted=True)
780
925
  print(head + '; its waits are used up (' + str(done) + ' of ' + str(budget)
@@ -786,37 +931,117 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
786
931
  + str(done + 1) + ' of ' + str(budget) + '); other tasks continue (no attempt spent)',
787
932
  file=sys.stderr, flush=True)
788
933
 
934
+ def ask(pause: dict, info: dict, cause: str, name: str) -> None:
935
+ """A cause only a person clears: the pause is exhausted at once, with no wait spent. It takes
936
+ over the stop's cause, so a wait it was in is replaced and its hint is the cause's own."""
937
+ hint = forge_infra.hint(cause, pause['harness'])
938
+ pause.update({'class': cause, 'info': info, 'reset_at': _epoch(info.get('reset_at'))})
939
+ pause.update(cycle=scope_waits.get(pause['scope'], 0), until=None, exhausted=True, needs_you=True,
940
+ hint=hint, asked_at_budget=infra_budget())
941
+ print('forge: infrastructure failure (' + pause['class'] + ') on ' + scope_where(pause) + ' for ' + name
942
+ + '; nothing will be retried until a person acts' + (': ' + hint if hint else '')
943
+ + '; other tasks continue (no attempt spent)', file=sys.stderr, flush=True)
944
+
945
+ def join_pause(pause: dict, info: dict, cause: str, how: str, name: str) -> None:
946
+ """A stop on a scope already paused, running or exhausted. The pause takes the stronger
947
+ recovery and the later known reset, and keeps that reset in the info a raised infra-retries
948
+ restarts from. A stop that changes the recovery gives the pause its cause."""
949
+ reset, kept = _reset_of(info), _reset_of(pause['info'])
950
+ later = reset is not None and (kept is None or reset > kept)
951
+ merged = info if later else pause['info']
952
+ if how == 'ask' and not pause['needs_you']:
953
+ # A stop only a person clears, whether its task moved or not, ends a wait the pause was
954
+ # in: the other tasks on this pair or harness must not be dispatched into it again.
955
+ ask(pause, info, cause, name)
956
+ pause['info'] = merged
957
+ return
958
+ pause['info'] = merged
959
+ if later:
960
+ pause['reset_at'] = _epoch(info.get('reset_at'))
961
+ # An asking pause keeps waiting for a person, whatever this stop's own recovery is.
962
+ if pause['needs_you'] or _epoch(info.get('retry_after')) is None:
963
+ return
964
+ where, wait = scope_where(pause), infra_wait(info, 0)[0]
965
+ if pause['exhausted']:
966
+ if later:
967
+ pause['class'] = cause
968
+ print('forge: ' + cause + ' on ' + where + ' for ' + name + ' sets the reset a raised '
969
+ 'infra-retries waits for (' + ('%g' % wait) + 's)', file=sys.stderr, flush=True)
970
+ elif time.time() + wait > pause['until']:
971
+ # A shorter backoff must not release the pause before this stop's reset.
972
+ pause.update({'class': cause, 'until': time.time() + wait})
973
+ print('forge: ' + cause + ' on ' + where + ' for ' + name + ' extends the wait to '
974
+ + ('%g' % wait) + 's (provider retry-after)', file=sys.stderr, flush=True)
975
+
976
+ def without_peer(cause: str, info: dict, moved: bool) -> str:
977
+ """'wait' or 'ask': what the pause does while it holds back the cause's other tasks."""
978
+ how = forge_infra.entry(cause)['without_peer']
979
+ if how != 'wait_if_reset':
980
+ return how
981
+ after = _epoch(info.get('retry_after'))
982
+ return 'wait' if moved or (after is not None and after <= INFRA_WAIT_CAP) else 'ask'
983
+
789
984
  def infra_stopped(name: str) -> None:
790
- nonlocal paused, all_class
985
+ nonlocal paused, all_class, all_reset
791
986
  pairs_cache.pop(name, None)
792
987
  info = infra_info(plan / 'tasks' / name)
988
+ cause = forge_infra.cause_of(info.get('class'))
989
+ move = forge_infra.entry(cause)['move']
990
+ if move == 'retry':
991
+ # The first stop of this cause is tried again at once, on the same model, with no wait;
992
+ # a second one goes on as a lateral move.
993
+ if (name, cause) not in retried_stops and not interrupted and not graceful:
994
+ retried_stops.add((name, cause))
995
+ print('forge: infrastructure failure (' + cause + ') for ' + name
996
+ + '; dispatching it again at once (no attempt spent)', file=sys.stderr, flush=True)
997
+ if resume(name):
998
+ pending.insert(0, name)
999
+ return
1000
+ move = 'lateral'
793
1001
  scope, harness, model = infra_scope(info)
794
1002
  if scope == 'all':
795
1003
  paused = True
796
- all_class = all_class or info.get('class', '')
1004
+ all_class = all_class or cause
1005
+ reset = _epoch(info.get('reset_at'))
1006
+ all_reset = max(all_reset, reset) if all_reset is not None and reset is not None else all_reset or reset
797
1007
  if name not in infra_seen:
798
1008
  infra_seen.append(name)
799
- elif scope in pauses:
1009
+ write_paused()
1010
+ return
1011
+ created = scope not in pauses
1012
+ if created:
1013
+ pauses[scope] = {'scope': scope, 'class': cause, 'harness': harness,
1014
+ 'model': model if scope.startswith('model:') else None, 'tasks': [name],
1015
+ 'cycle': 0, 'until': None, 'exhausted': False, 'info': info,
1016
+ 'needs_you': False, 'hint': None, 'reset_at': _epoch(info.get('reset_at'))}
1017
+ elif name not in pauses[scope]['tasks']:
800
1018
  # A stop in a scope already paused joins its wait and is not counted again.
801
- if name not in pauses[scope]['tasks']:
802
- pauses[scope]['tasks'].append(name)
1019
+ pauses[scope]['tasks'].append(name)
1020
+ pause = pauses[scope]
1021
+ moved = move == 'lateral' and fall_back(name, info, scope, cause)
1022
+ how = without_peer(cause, info, moved)
1023
+ if created:
1024
+ if how == 'ask':
1025
+ ask(pause, info, cause, name)
1026
+ else:
1027
+ start_wait(pause, info, name)
803
1028
  else:
804
- pauses[scope] = {'scope': scope, 'class': info.get('class', ''), 'harness': harness,
805
- 'model': model if scope.startswith('model:') else None, 'tasks': [name],
806
- 'cycle': 0, 'until': None, 'exhausted': False, 'info': info}
807
- start_wait(pauses[scope], info, name)
808
- if scope != 'all':
809
- fall_back(name, info, scope)
1029
+ join_pause(pause, info, cause, how, name)
810
1030
  write_paused()
811
1031
 
812
1032
  def end_scoped_waits() -> None:
813
1033
  """Resume the tasks of every scope whose wait is over; an exhausted scope whose
814
- budget was raised meanwhile starts its next wait."""
1034
+ budget was raised meanwhile starts its next wait. A pause waiting for a person
1035
+ restarts only when the budget goes above what it was when it asked."""
815
1036
  for scope, pause in list(pauses.items()):
816
1037
  if interrupted:
817
1038
  return
818
1039
  if pause['exhausted']:
819
- if scope_waits.get(scope, 0) < infra_budget():
1040
+ if pause['needs_you']:
1041
+ restart = infra_budget() > pause['asked_at_budget']
1042
+ else:
1043
+ restart = scope_waits.get(scope, 0) < infra_budget()
1044
+ if restart:
820
1045
  start_wait(pause, pause['info'], ', '.join(pause['tasks']))
821
1046
  continue
822
1047
  if time.time() < pause['until']:
@@ -848,9 +1073,24 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
848
1073
  if state == 'NEEDS_INPUT':
849
1074
  return 'refused', (name + ' is waiting for an answer: forge-parallel.sh retry ' + str(plan)
850
1075
  + ' ' + name + ' --answer \u2026')
851
- if state not in RETRYABLE:
1076
+ decide, reason, approved = request.get('decide'), request.get('reason'), request.get('approved') is True
1077
+ if decide and state != 'NEEDS_DECISION':
1078
+ return 'refused', name + ' is ' + state + ', not waiting for a decision; --decide only decides a NEEDS_DECISION task'
1079
+ decision = []
1080
+ if state == 'NEEDS_DECISION':
1081
+ # Only a person's explicit decision resumes it: a choice, a reason, and --approved.
1082
+ if not decide and not dwarf:
1083
+ return 'refused', (name + ' is waiting for your decision, and only a decision resumes it: '
1084
+ + decision_head(plan, name) + ' (retry --decide retry=N | threshold=Pn, or --dwarf SPEC,'
1085
+ + ' with --reason and --approved)')
1086
+ if decide and dwarf:
1087
+ return 'refused', 'give --decide or --dwarf, not both: a decision is one choice'
1088
+ if not (reason or '').strip() or not approved:
1089
+ return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
1090
+ decision = (['--decide', decide] if decide else []) + ['--reason', reason, '--approved']
1091
+ elif state not in RETRYABLE:
852
1092
  return 'refused', 'a ' + state + ' task is not retried'
853
- command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (['--dwarf', dwarf] if dwarf else [])
1093
+ command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (['--dwarf', dwarf] if dwarf else []) + decision
854
1094
  rc = subprocess.run(command).returncode
855
1095
  if rc == 3:
856
1096
  try:
@@ -858,12 +1098,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
858
1098
  except OSError:
859
1099
  why = ''
860
1100
  return 'refused', why or 'the retry policy stopped this task: split it or name a --dwarf'
1101
+ if rc and status(name) == 'NEEDS_DECISION':
1102
+ # The attempt cap (#69) stopped it for a decision just now: say what it waits for.
1103
+ return 'refused', name + ' is waiting for your decision: ' + decision_head(plan, name)
861
1104
  if rc:
862
1105
  return 'refused', 'the retry could not be prepared (exit ' + str(rc) + '; see the run output)'
863
1106
  # A human's retry: no automatic budget is spent, and a stop marker the
864
1107
  # preparation cleared (an explicit --dwarf) no longer holds the task.
865
1108
  pairs_cache.pop(name, None)
866
1109
  refused.pop(name, None)
1110
+ # A decision sets how many attempts follow it: retry=N is N in all (this one and N-1
1111
+ # automatic ones), any other choice is this one. A plain retry leaves the budget in charge.
1112
+ # (retry_decided wrote decided.left for a decision.) A plain retry ends what a decision allowed.
1113
+ if state != 'NEEDS_DECISION':
1114
+ _remove(plan, 'tasks', name, 'decided.left')
867
1115
  retried.add(name)
868
1116
  human.add(name)
869
1117
  pending.insert(0, name)
@@ -1075,7 +1323,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1075
1323
  pending.insert(0, name)
1076
1324
  infra_seen.clear()
1077
1325
  paused = False
1078
- all_class = ''
1326
+ all_class, all_reset = '', None
1079
1327
  write_paused()
1080
1328
  end_scoped_waits()
1081
1329
  handle_requests()
@@ -1090,7 +1338,12 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1090
1338
  if any(overlap(tasks[name][3], tasks[other][3]) for other in active):
1091
1339
  continue
1092
1340
  if pauses and scope_held(name):
1093
- continue
1341
+ # Each move changes the models it is held on: the implementer, then the reviewer, in one pass,
1342
+ # before the loop below can end the run on a task only half moved.
1343
+ while move_held(name) and scope_held(name):
1344
+ pass
1345
+ if scope_held(name):
1346
+ continue
1094
1347
  root = plan / 'tasks' / name
1095
1348
  if not (root / 'base_ref').exists():
1096
1349
  worktree = Path((plan / 'wt_root').read_text().strip()) / '_integration'
@@ -1133,6 +1386,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1133
1386
  break
1134
1387
  time.sleep(0.05)
1135
1388
  finally:
1389
+ try:
1390
+ held_record()
1391
+ except Exception as error:
1392
+ _warn('could not record the pauses left: ' + str(error))
1136
1393
  # Not live from here on: a late `forge control` must not edit budgets nobody reads.
1137
1394
  live_stop(plan, tasks)
1138
1395
  # Poll before any signal. A process that has already exited keeps the result