@giamme/forge 0.13.1 → 0.14.1

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 (48) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +2 -0
  5. package/docs/commands.md +134 -8
  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 +201 -61
  13. package/references/harnesses.md +4 -1
  14. package/references/runtime.md +29 -0
  15. package/references/ui.md +10 -0
  16. package/scripts/forge-compare.py +491 -0
  17. package/scripts/forge-config.py +3 -3
  18. package/scripts/forge-contract.py +34 -8
  19. package/scripts/forge-control.py +105 -13
  20. package/scripts/forge-dispatch.sh +85 -25
  21. package/scripts/forge-jev-options.sh +17 -4
  22. package/scripts/forge-ledger.py +387 -0
  23. package/scripts/forge-lib-plans.sh +11 -2
  24. package/scripts/forge-lib-task.sh +390 -28
  25. package/scripts/forge-parallel-options.sh +20 -4
  26. package/scripts/forge-parallel.sh +123 -17
  27. package/scripts/forge-plan-check.py +68 -3
  28. package/scripts/forge-pr.py +276 -0
  29. package/scripts/forge-route.py +403 -38
  30. package/scripts/forge-runs.py +18 -1
  31. package/scripts/forge-runtime.py +94 -8
  32. package/scripts/forge-schedule.py +303 -46
  33. package/scripts/forge-verify-failed.py +111 -0
  34. package/scripts/forge-watch.py +372 -0
  35. package/scripts/forge_dataset/harvest.py +3 -1
  36. package/scripts/forge_fractal/cli.py +23 -6
  37. package/scripts/forge_infra.py +274 -0
  38. package/scripts/forge_jev/client.py +13 -9
  39. package/ui/docs/api.md +51 -8
  40. package/ui/forge_ui/export.py +6 -2
  41. package/ui/forge_ui/reader.py +172 -6
  42. package/ui/forge_ui/static/app.js +2 -2
  43. package/ui/forge_ui/static/checksview.js +20 -7
  44. package/ui/forge_ui/static/controls.js +6 -3
  45. package/ui/forge_ui/static/panel.js +69 -4
  46. package/ui/forge_ui/static/runmodel.js +30 -4
  47. package/ui/forge_ui/static/scene3d.js +3 -2
  48. package/ui/forge_ui/static/style.css +11 -4
@@ -4,11 +4,17 @@
4
4
  show <plan> [--json] every control, per-task overrides, pins and the change log
5
5
  set <plan> <key> <value> [--task ID] qa-threshold, timeout, escalate-after, escalate-effort,
6
6
  verify-retries, retry-budget, infra-retries, infra-backoff
7
- (none drops it), max-parallel (1-64), pre-review-tests
8
- (on/off), pre-review-parallel (1-64)
7
+ (none drops it), infra-fallback (on/off), max-parallel (1-64),
8
+ pre-review-tests
9
+ (on/off), pre-review-parallel (1-64), max-attempts (0 = no cap;
10
+ needs --confirm: raising the cap is a person's decision),
11
+ converge-window (reviews the non-converging signal looks at)
9
12
  pin <plan> <task> <spec> the model the task's next FULL implementer retry uses
10
13
  unpin <plan> <task>
11
14
  retry <plan> <task> [--dwarf SPEC] queue a retry of a stopped or failed task into the live run
15
+ a NEEDS_DECISION task (reviews that do not converge, or a stop with no
16
+ stronger model) is resumed only by a decision: --decide retry=N or
17
+ threshold=P0..P3, or --dwarf SPEC, each with --reason TEXT --approved
12
18
  add <plan> <task> queue a row added to tasks.tsv (with its prompt.md) into the live run
13
19
  drain <plan> start nothing new; running tasks finish and the scheduler waits
14
20
  while tasks remain (with none left to start, the run ends as usual)
@@ -19,8 +25,9 @@
19
25
  them like SIGTERM
20
26
 
21
27
  `show` reports escalate-after and verify-retries at their defaults (3 and 1) when unset,
22
- escalate-effort and pre-review-tests as on or off (off when the file is absent), pre-review-parallel
23
- at its default (2) when unset, and the two budgets only while a scheduler is live.
28
+ escalate-effort, infra-fallback and pre-review-tests as on or off (off when the file is absent),
29
+ pre-review-parallel at its default (2) when unset, each task's attempts used and cap (`9/8`, or `9/-`
30
+ with no cap), and the two budgets only while a scheduler is live.
24
31
 
25
32
  Every change is validated, written atomically under the plan's control lock (`control.lock`),
26
33
  appended to `control.log` and recorded as a dataset `control` event. This is the only writer of
@@ -56,6 +63,14 @@ import stat
56
63
  import subprocess
57
64
  import sys
58
65
  import time
66
+ from pathlib import Path
67
+
68
+ # forge_infra.py sits beside this file: the causes table and the wording the run summary shares. As in
69
+ # forge-schedule.py, the directory is put on sys.path here, since -I or PYTHONSAFEPATH would leave it off.
70
+ SCRIPTS = os.path.dirname(os.path.realpath(__file__))
71
+ if SCRIPTS not in sys.path:
72
+ sys.path.insert(0, SCRIPTS)
73
+ import forge_infra # noqa: E402
59
74
 
60
75
  SKILL = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
61
76
  LOCK_WAIT = 5.0
@@ -74,6 +89,7 @@ NEXT_DECISION = 'at the next retry decision'
74
89
  NEXT_RETRY = 'at the next full retry (not QA-only resumes)'
75
90
  NEXT_VERIFY = 'at the next verification'
76
91
  NEXT_INFRA_WAIT = 'at the next infrastructure wait'
92
+ NEXT_INFRA_STOP = 'at the next infrastructure stop'
77
93
  NEXT_DISPATCH = "at the scheduler's next dispatch decision"
78
94
 
79
95
 
@@ -397,7 +413,8 @@ def nullable(value):
397
413
  return None if value in (None, '', '-', 'UNASSIGNED') else value
398
414
 
399
415
 
400
- PAUSE_KEYS = ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')
416
+ PAUSE_KEYS = ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted', 'needs_you', 'hint',
417
+ 'reset_at')
401
418
 
402
419
 
403
420
  def paused_scopes(text):
@@ -427,12 +444,14 @@ def show(plan, rows):
427
444
  verify_retries=number(get('verify_retries')),
428
445
  retry_budget=budget('retry_budget'), infra_budget=budget('infra_budget'))
429
446
  run['infra_backoff'] = get('infra_backoff') or default_backoff()
447
+ run['infra_fallback'] = 'on' if get('infra_fallback') == 'on' else 'off'
430
448
  parallel = number(get('max_parallel'))
431
449
  run['max_parallel'] = parallel if parallel and parallel <= 64 else None
432
450
  stopping = get('stop') if live else None
433
451
  run['drained'] = live and has(plan, 'drain')
434
452
  run['stopping'] = stopping if stopping in ('graceful', 'now') else None
435
453
  run['infra_paused'] = paused_scopes(get('infra.paused')) if live else None
454
+ pauses, now = run['infra_paused'] or [], time.time()
436
455
  if run['escalate_after'] is None:
437
456
  run['escalate_after'] = DEFAULT_ESCALATE_AFTER
438
457
  if run['verify_retries'] is None:
@@ -454,6 +473,10 @@ def show(plan, rows):
454
473
  retries_used=number(get(base + 'retries.used')) or 0,
455
474
  pin=get(base + 'escalation.pin'), escalation_stop=has(plan, base + 'escalation.stop'),
456
475
  escalation_next=get(base + 'escalation.next'))
476
+ if tasks[task]['status'] == 'INFRA':
477
+ # Present on an INFRA task only (#81): its cause, where it stopped, when the limit resets, who must act.
478
+ info = forge_infra.parse_stop(get(base + 'infra.txt'))
479
+ tasks[task]['infra'] = forge_infra.stop_of(task, info, pauses, now)
457
480
  log = []
458
481
  for line in reversed((read_file(plan, 'control.log', tail=LOG_TAIL) or '').splitlines()):
459
482
  try:
@@ -497,6 +520,20 @@ def schedule_module():
497
520
  return _SCHEDULE
498
521
 
499
522
 
523
+ _ROUTE = None
524
+
525
+
526
+ def route_module():
527
+ """forge-route.py, loaded by path: the one owner of a task's attempts used and its cap (#69)."""
528
+ global _ROUTE
529
+ if _ROUTE is None:
530
+ import importlib.util
531
+ spec = importlib.util.spec_from_file_location('forge_route', os.path.join(SKILL, 'scripts', 'forge-route.py'))
532
+ _ROUTE = importlib.util.module_from_spec(spec)
533
+ spec.loader.exec_module(_ROUTE)
534
+ return _ROUTE
535
+
536
+
500
537
  def _backoff(value, task):
501
538
  if value == 'none':
502
539
  return value
@@ -537,9 +574,12 @@ KEYS = {
537
574
  'retry-budget': ('both', _budget, 'retry_budget', True, NEXT_DECISION),
538
575
  'infra-retries': ('plan', _int, 'infra_budget', True, NEXT_DECISION),
539
576
  'infra-backoff': ('plan', _backoff, 'infra_backoff', False, NEXT_INFRA_WAIT),
577
+ 'infra-fallback': ('plan', _onoff, 'infra_fallback', False, NEXT_INFRA_STOP),
540
578
  'max-parallel': ('plan', _parallel, 'max_parallel', True, NEXT_DISPATCH),
541
579
  'pre-review-tests': ('plan', _onoff, 'pre_review_tests', False, NEXT_ATTEMPT),
542
580
  'pre-review-parallel': ('plan', _parallel, 'pre_review_parallel', False, NEXT_ATTEMPT),
581
+ 'max-attempts': ('plan', _int, 'max_attempts', False, NEXT_DECISION),
582
+ 'converge-window': ('plan', _int, 'converge_window', False, NEXT_DECISION),
543
583
  }
544
584
 
545
585
 
@@ -592,6 +632,12 @@ def change(args, plan, rows, action, task, key, work, applies, summary, live_onl
592
632
  def cmd_set(args):
593
633
  plan, rows = load(args.plan)
594
634
  scope, check, name, live_only, applies = KEYS[args.key]
635
+ # The cap on a task's attempts is a person's decision: any change to it is given with --confirm.
636
+ if args.key == 'max-attempts' and not args.confirm:
637
+ raise Refused('max-attempts is a person\'s decision: a task at its cap waits for one, and raising the cap '
638
+ 'lets it run more attempts; give --confirm to change it')
639
+ if args.confirm and args.key != 'max-attempts':
640
+ raise Invalid('--confirm applies only to max-attempts')
595
641
  task = args.task
596
642
  if task is not None:
597
643
  require_task(rows, task)
@@ -758,8 +804,9 @@ def check_row(plan, rows, task):
758
804
  return dwarf, qa
759
805
 
760
806
 
761
- def queue(args, plan, verb, task, dwarf):
762
- """Write the request under the control lock, live only; log it with its id."""
807
+ def queue(args, plan, verb, task, dwarf, decision=None):
808
+ """Write the request under the control lock, live only; log it with its id.
809
+ decision: a retry's (--decide choice or None, reason, approved) for a NEEDS_DECISION task."""
763
810
  with control_lock(plan):
764
811
  probe(plan, 'control.log')
765
812
  if not is_live(plan):
@@ -768,8 +815,10 @@ def queue(args, plan, verb, task, dwarf):
768
815
  refuse_task(plan, task, pin=True)
769
816
  name = f'{time.time_ns()}-{os.getpid()}.json'
770
817
  request = dict(verb=verb, task=task, dwarf=dwarf, at=time.time(), actor=args.actor)
818
+ if decision:
819
+ request.update(decide=decision[0], reason=decision[1], approved=True)
771
820
  write_atomic(plan, f'{REQUESTS}/{name}', json.dumps(request) + '\n')
772
- audit(plan, args.actor, verb, task, None, dwarf, None, request=name)
821
+ audit(plan, args.actor, verb, task, None, dwarf or (decision[0] if decision else None), None, request=name)
773
822
  if args.json:
774
823
  json.dump(dict(queued=True, request=name), sys.stdout)
775
824
  sys.stdout.write('\n')
@@ -779,6 +828,35 @@ def queue(args, plan, verb, task, dwarf):
779
828
  return 0
780
829
 
781
830
 
831
+ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
832
+
833
+
834
+ def decision_of(plan, args, dwarf):
835
+ """The decision a retry carries, (choice or None, reason, True), or None for a plain retry.
836
+ A NEEDS_DECISION task is resumed only by a decision: --decide or --dwarf, with --reason and
837
+ --approved. --decide is for no other task."""
838
+ status = task_status(plan, args.task, strict=True)
839
+ if status != 'NEEDS_DECISION':
840
+ if args.decide is not None:
841
+ raise Refused(f'task {args.task} is {status}, not waiting for a decision: --decide only decides a NEEDS_DECISION task')
842
+ return None
843
+ if args.decide is None and dwarf is None:
844
+ head = ' '.join(line.strip() for line in (read_file(plan, f'tasks/{args.task}/decision.md') or '').splitlines()[:3]
845
+ if line.strip())
846
+ raise Refused(f'task {args.task} is waiting for your decision, and only a decision resumes it: {head or "see decision.md"} '
847
+ '(retry --decide retry=N | threshold=Pn, or --dwarf SPEC, each with --reason TEXT --approved)')
848
+ if args.decide is not None and dwarf is not None:
849
+ raise Invalid('give --decide or --dwarf, not both: a decision is one choice')
850
+ if args.decide is not None and not DECISION.fullmatch(args.decide):
851
+ raise Invalid('--decide takes retry=N (1 to 20) or threshold=P0|P1|P2|P3')
852
+ reason = re.sub(r'\s+', ' ', args.reason or '').strip()
853
+ if not reason:
854
+ raise Invalid('a decision needs --reason TEXT: it is recorded with the task')
855
+ if not args.approved:
856
+ raise Invalid('a decision needs --approved: it resumes a task forge stopped, and is only given on the user\'s instruction')
857
+ return args.decide, reason, True
858
+
859
+
782
860
  def cmd_retry(args):
783
861
  plan, rows = load(args.plan)
784
862
  require_task(rows, args.task)
@@ -786,9 +864,10 @@ def cmd_retry(args):
786
864
  if args.dwarf is not None:
787
865
  dwarf = clean_spec(args.dwarf, '--dwarf')
788
866
  refuse_task(plan, args.task, pin=True) # before the doctor: MERGED and Fractal need no model check
867
+ decision = decision_of(plan, args, dwarf)
789
868
  if dwarf:
790
869
  doctor(dwarf)
791
- return queue(args, plan, 'retry', args.task, dwarf)
870
+ return queue(args, plan, 'retry', args.task, dwarf, decision)
792
871
 
793
872
 
794
873
  def cmd_add(args):
@@ -821,6 +900,7 @@ def cmd_show(args):
821
900
  f" fractal {'yes' if controls['fractal'] else 'no'}")
822
901
  print(' ' + ' '.join(f"{k.replace('_', '-')} {cell(v)}" + (' (default)' if k == 'qa_threshold' and run['qa_threshold_source'] == 'default' else '')
823
902
  for k, v in run.items() if k not in ('infra_paused', 'qa_threshold_source')))
903
+ now = time.time()
824
904
  for p in run['infra_paused'] or []:
825
905
  tasks = ','.join(t for t in (p['tasks'] or []) if isinstance(t, str)) or '-'
826
906
  if p['exhausted']:
@@ -829,12 +909,20 @@ def cmd_show(args):
829
909
  when = f"wait {cell(p['cycle'])} until {stamp(p['until'])}"
830
910
  else:
831
911
  when = 'waiting for running tasks to finish'
832
- print(f" paused {p['scope']} ({cell(p['class'])}) tasks {tasks} {when}")
833
- columns = ('task', 'status', 'dwarf', 'qa', 'threshold', 'budget', 'used', 'pin', 'stop', 'next')
912
+ # The reset, and a pause that waits on a person says so with the hint (#81).
913
+ parts = [when] + [text for text in [forge_infra.reset_text(p['reset_at'], now)] if text]
914
+ if p['needs_you']:
915
+ parts.append('needs you' + (f": {p['hint']}" if isinstance(p['hint'], str) and p['hint'] else ''))
916
+ print(f" paused {p['scope']} ({forge_infra.label(p['class'])}) tasks {tasks} " + ' '.join(parts))
917
+ columns = ('task', 'status', 'dwarf', 'qa', 'threshold', 'budget', 'used', 'attempts', 'pin', 'stop', 'next')
834
918
  table = [columns]
835
919
  for task, t in controls['tasks'].items():
836
- table.append((task, t['status'], cell(t['dwarf']), cell(t['qa']), cell(t['qa_threshold']), cell(t['retry_budget']),
837
- cell(t['retries_used']), cell(t['pin']), 'yes' if t['escalation_stop'] else '-',
920
+ status = f"{t['status']} ({t['infra']['cause']})" if t.get('infra') else t['status']
921
+ # attempts used/cap (#69): 9/8, or 9/- for a plan with no cap. Text only: the JSON keeps its keys.
922
+ used, cap = route_module().attempt_cap(Path(plan), task)
923
+ attempts = f"{used}/{cell(cap)}"
924
+ table.append((task, status, cell(t['dwarf']), cell(t['qa']), cell(t['qa_threshold']), cell(t['retry_budget']),
925
+ cell(t['retries_used']), attempts, cell(t['pin']), 'yes' if t['escalation_stop'] else '-',
838
926
  cell(t['escalation_next'])))
839
927
  widths = [max(len(r[i]) for r in table) for i in range(len(columns))]
840
928
  for r in table:
@@ -872,6 +960,7 @@ def parser():
872
960
  p.add_argument('key', choices=list(KEYS))
873
961
  p.add_argument('value')
874
962
  p.add_argument('--task', metavar='ID', help='change this task only (qa-threshold, retry-budget)')
963
+ p.add_argument('--confirm', action='store_true', help="max-attempts only: the change is a person's decision")
875
964
  p.set_defaults(func=cmd_set)
876
965
  p = sub.add_parser('pin', help="set the model a task's next full retry uses")
877
966
  common(p)
@@ -886,6 +975,9 @@ def parser():
886
975
  common(p)
887
976
  p.add_argument('task')
888
977
  p.add_argument('--dwarf', metavar='SPEC', help='the implementer for this retry (an explicit escalation)')
978
+ p.add_argument('--decide', metavar='CHOICE', help='decide a NEEDS_DECISION task: retry=N (1 to 20) or threshold=P0..P3')
979
+ p.add_argument('--reason', metavar='TEXT', help='why (a decision needs it)')
980
+ p.add_argument('--approved', action='store_true', help='the decision is the user\'s (a decision needs it)')
889
981
  p.set_defaults(func=cmd_retry)
890
982
  p = sub.add_parser('add', help='queue a row added to tasks.tsv into the live run')
891
983
  common(p)
@@ -33,11 +33,18 @@
33
33
  # Environment: FORGE_REGISTRY alternate registry file (default: <skill>/registry.tsv)
34
34
  # FORGE_ORPHAN_GUARD off = do not run the harness in its own process group
35
35
  # (default on; also skipped under FORGE_FRACTAL_RUN)
36
+ # FORGE_RESULT_GRACE claude/openclaude: seconds a log that ends in the model's final
37
+ # result may stay silent before forge ends the harness (an open
38
+ # background task keeps it up); default 1800, 0 = off. Either way
39
+ # a dispatch killed after that result is not a timeout.
36
40
  #
37
41
  # Exit codes: 0 ok | 2 usage/resolution error | 3 harness missing or unusable
38
42
  # 4 backend ran but failed | 7 backend exceeded --timeout and was killed
39
- # 8 infrastructure failure (auth, quota, rate limit, network, or an empty
40
- # answer): the model never got to do its work. $ROLE.infra says which.
43
+ # (not when its log ended in a final result and only background tasks kept it up:
44
+ # that result stands, as after FORGE_RESULT_GRACE; $ROLE.settled says which)
45
+ # 8 infrastructure failure (auth, usage_limit, budget, capacity, rate_limit,
46
+ # provider_down, network, or an empty answer; forge_infra.py says what each
47
+ # means): the model never got to do its work. $ROLE.infra says which.
41
48
  # A DWARF that exits 0 with an empty final message also writes $ROLE.infra
42
49
  # (class=empty) but still exits 0; consult the file only if the diff is empty.
43
50
  # 9 the session was not continued (--continue-session only): the harness cannot
@@ -370,6 +377,15 @@ if [ "$LIMIT_SOURCE" = registry ] || [ "$LIMIT_SOURCE" = default ]; then
370
377
  fi
371
378
  fi
372
379
 
380
+ # --- the grace after a final result (#110) --------------------------------------
381
+ # claude and openclaude stay up while a background task of the session is open, even after the
382
+ # model's final result. Once the log ends in that result and stays silent this long, forge ends
383
+ # the harness and the result stands. Long on purpose: a background test run can wake the session
384
+ # for another turn many minutes later.
385
+ RESULT_GRACE="${FORGE_RESULT_GRACE:-1800}"
386
+ case "$RESULT_GRACE" in ''|*[!0-9]*) die "FORGE_RESULT_GRACE must be a nonnegative integer" ;; esac
387
+ [ "${#RESULT_GRACE}" -gt 9 ] || RESULT_GRACE=$((10#$RESULT_GRACE))
388
+
373
389
  # --- run dir & prompt ---------------------------------------------------------
374
390
  [ -d "$REPO" ] || die "--repo '$REPO' is not a directory"
375
391
  REPO="$(cd "$REPO" && pwd)"
@@ -387,7 +403,7 @@ write_continue() { :; } # redefined below once there is an attempt to archive
387
403
  ATTEMPT=""
388
404
  if [ "$PREFLIGHT" != 1 ] && [ "$DRY" != 1 ]; then
389
405
  ATTEMPT="$(python3 "$RUNTIME" begin "$RUN_DIR" "$ROLE")" || exit 3
390
- rm -f "$RUN_DIR/$ROLE.last" "$RUN_DIR/$ROLE.log" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.resolved" "$RUN_DIR/$ROLE.cmd" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.session" "$RUN_DIR/$ROLE.continue" "$RUN_DIR/$ROLE.harness"
406
+ rm -f "$RUN_DIR/$ROLE.last" "$RUN_DIR/$ROLE.log" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.resolved" "$RUN_DIR/$ROLE.cmd" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.settled" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.session" "$RUN_DIR/$ROLE.continue" "$RUN_DIR/$ROLE.harness"
391
407
  trap 'exit 143' TERM
392
408
  trap 'exit 130' INT
393
409
  # GUARD_ON is 1 only when the harness was started in its own process group (see the
@@ -403,7 +419,7 @@ if [ "$PREFLIGHT" != 1 ] && [ "$DRY" != 1 ]; then
403
419
  # Interrupted after the harness exited but before the normal reap.
404
420
  python3 "$GUARD" reap "$hpid" "$RUN_DIR/$ROLE.orphans" >/dev/null 2>&1
405
421
  fi
406
- if [ -n "${wpid:-}" ]; then pkill -P "$wpid" 2>/dev/null; kill "$wpid" 2>/dev/null; fi
422
+ for watcher in ${wpid:-} ${spid:-}; do pkill -P "$watcher" 2>/dev/null; kill "$watcher" 2>/dev/null; done
407
423
  [ -z "${cpid:-}" ] || kill "$cpid" 2>/dev/null
408
424
  rm -f "$RUN_DIR/$ROLE.harness"
409
425
  }
@@ -704,6 +720,7 @@ if [ "$DRY" != 1 ] || [ "$PREFLIGHT" = 1 ]; then preflight_command; fi
704
720
  [ -n "$CLAMPED" ] && echo "clamped=$CLAMPED"
705
721
  echo "timeout=$LIMIT"
706
722
  echo "timeout_source=$LIMIT_SOURCE"
723
+ case "$HARNESS" in claude|openclaude) echo "result_grace=$RESULT_GRACE" ;; esac
707
724
  # Native review ignores the assembled prompt, so whether it reached the model is a fact
708
725
  # worth recording rather than inferring from the role and harness later.
709
726
  echo "delivery=$([ "$NATIVE_REVIEW" = 1 ] && echo native_review || echo custom)"
@@ -743,7 +760,7 @@ fi
743
760
  # when a stale $LAST is already there. That is harmless when each run gets a fresh
744
761
  # run-dir, and silently wrong for `forge-parallel.sh retry`, which reuses the task
745
762
  # directory — it would read the first attempt's result and never notice.
746
- rm -f "$LAST" "$LOG" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.clock.stop" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.harness"
763
+ rm -f "$LAST" "$LOG" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.clock.stop" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.settled" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.harness"
747
764
  python3 "$RUNTIME" phase "$ATTEMPT" model
748
765
  t0="$(date +%s)"
749
766
  # Process-group guard. A dwarf that starts `npm test &` and ends its turn leaves that
@@ -784,6 +801,19 @@ if [ "$GUARD_ON" = 1 ]; then
784
801
  fi
785
802
  fi
786
803
 
804
+ # Ends the harness: the whole process group first when the harness has its own (GUARD_ON),
805
+ # then children, then the process itself, then SIGKILL for a CLI that traps TERM and takes
806
+ # its time. Without the guard there is no group to signal as a unit.
807
+ stop_harness() {
808
+ [ "$GUARD_ON" != 1 ] || kill -s TERM -- "-$hpid" 2>/dev/null
809
+ pkill -TERM -P "$hpid" 2>/dev/null
810
+ kill -TERM "$hpid" 2>/dev/null
811
+ sleep 5
812
+ [ "$GUARD_ON" != 1 ] || kill -s KILL -- "-$hpid" 2>/dev/null
813
+ pkill -KILL -P "$hpid" 2>/dev/null
814
+ kill -KILL "$hpid" 2>/dev/null
815
+ }
816
+
787
817
  # Watchdog. Only antigravity has a time bound of its own, and `timeout` is not
788
818
  # present on stock macOS, so without this a hung backend blocks forever — and under
789
819
  # forge-parallel's `xargs -P` one hung task silently stalls its whole wave. The
@@ -795,19 +825,24 @@ if [ "${LIMIT:-0}" != "0" ]; then
795
825
  sleep "$LIMIT"
796
826
  kill -0 "$hpid" 2>/dev/null || exit 0
797
827
  : > "$RUN_DIR/$ROLE.timedout"
798
- # The whole process group first when the harness has its own (GUARD_ON), then
799
- # children, then the process itself, then SIGKILL for a CLI that traps TERM and
800
- # takes its time. Without the guard there is no group to signal as a unit.
801
- [ "$GUARD_ON" != 1 ] || kill -s TERM -- "-$hpid" 2>/dev/null
802
- pkill -TERM -P "$hpid" 2>/dev/null
803
- kill -TERM "$hpid" 2>/dev/null
804
- sleep 5
805
- [ "$GUARD_ON" != 1 ] || kill -s KILL -- "-$hpid" 2>/dev/null
806
- pkill -KILL -P "$hpid" 2>/dev/null
807
- kill -KILL "$hpid" 2>/dev/null
828
+ stop_harness
808
829
  ) >/dev/null 2>&1 &
809
830
  wpid=$!
810
831
  fi
832
+ # A final result the CLI stays open after (#110): once the log ends in it and has been silent for
833
+ # the grace, the harness is ended like a timeout, but the result stands (see below).
834
+ spid=""
835
+ case "$HARNESS" in claude|openclaude)
836
+ if [ "$RESULT_GRACE" != 0 ]; then
837
+ (
838
+ python3 "$RUNTIME" settle "$LOG" "$RESULT_GRACE" "$hpid" </dev/null || exit 0
839
+ kill -0 "$hpid" 2>/dev/null || exit 0
840
+ : > "$RUN_DIR/$ROLE.settled"
841
+ stop_harness
842
+ ) >/dev/null 2>&1 &
843
+ spid=$!
844
+ fi ;;
845
+ esac
811
846
 
812
847
  wait "$hpid"; rc=$?
813
848
  # Its last sample is in before `finish` copies the clock into the attempt. A stop file, not a TERM:
@@ -818,13 +853,13 @@ if [ -n "$cpid" ]; then
818
853
  { : > "$RUN_DIR/$ROLE.clock.stop"; } 2>/dev/null || kill -TERM "$cpid" 2>/dev/null
819
854
  wait "$cpid" 2>/dev/null; cpid=""; rm -f "$RUN_DIR/$ROLE.clock.stop"
820
855
  fi
821
- if [ -n "$wpid" ]; then
822
- # The watchdog is asleep in a child of its own; kill that too or it outlives the
823
- # run as an orphan holding the timer.
824
- pkill -P "$wpid" 2>/dev/null
825
- kill "$wpid" 2>/dev/null
826
- wait "$wpid" 2>/dev/null
827
- fi
856
+ for watcher in $wpid $spid; do
857
+ # The watchdog is asleep in a child of its own, and so is the grace watcher; kill that
858
+ # too or it outlives the run as an orphan holding the timer.
859
+ pkill -P "$watcher" 2>/dev/null
860
+ kill "$watcher" 2>/dev/null
861
+ wait "$watcher" 2>/dev/null
862
+ done
828
863
  # Anything the harness left running in its group is an abandoned background job. Kill it
829
864
  # before reading the tree, and leave the list for the caller. Bounded (~3s) and advisory:
830
865
  # a reaper failure changes nothing about the exit code.
@@ -839,14 +874,37 @@ DURATION=$(( $(date +%s) - t0 ))
839
874
  echo "duration_s=$DURATION" >> "$RUN_DIR/$ROLE.resolved"
840
875
  [ "$OUTPUT" != full ] || cat "$LOG"
841
876
  [ "$OUTPUT" != summary ] || echo "forge: role=$ROLE backend_exit=$rc final=$LAST log=$LOG metrics=$ATTEMPT/metrics.json"
877
+ # Ended by forge after the model's final result, with only background tasks open: the answer was
878
+ # in, so the role finished and its result stands, whether the grace or the watchdog ended it. The
879
+ # exit is the one the CLI gives for that result. A turn that began while forge was ending it is cut
880
+ # off, as by a timeout.
881
+ if [ -f "$RUN_DIR/$ROLE.settled" ] || [ -f "$RUN_DIR/$ROLE.timedout" ]; then
882
+ case "$HARNESS" in claude|openclaude)
883
+ if verdict="$(python3 "$RUNTIME" settled "$LOG" 2>/dev/null)"; then
884
+ # The marker is written before the harness is stopped, so it says the grace came first.
885
+ if [ -f "$RUN_DIR/$ROLE.settled" ]; then after="${RESULT_GRACE}s of silence"; ended_by=grace
886
+ else after="the ${LIMIT}s timeout"; ended_by=timeout; fi
887
+ printf 'ended_by=%s\nbackend_exit=%s\n' "$ended_by" "$rc" > "$RUN_DIR/$ROLE.settled"
888
+ rm -f "$RUN_DIR/$ROLE.timedout"
889
+ if [ "$verdict" = error ]; then rc=1; else rc=0; fi
890
+ note "$HARNESS gave its final result, then stayed open on a background task; forge ended it after $after — the result stands"
891
+ elif [ -f "$RUN_DIR/$ROLE.settled" ]; then
892
+ rm -f "$RUN_DIR/$ROLE.settled"; : > "$RUN_DIR/$ROLE.timedout"
893
+ note "$HARNESS began another turn while forge was ending it after its final result — see $LOG"
894
+ write_continue failed timeout
895
+ exit 7
896
+ fi ;;
897
+ esac
898
+ fi
842
899
  if [ -f "$RUN_DIR/$ROLE.timedout" ]; then
843
900
  note "$HARNESS exceeded the ${LIMIT}s timeout and was killed after ${DURATION}s — see $LOG"
844
901
  write_continue failed timeout
845
902
  exit 7
846
903
  fi
847
- # Infrastructure, not the model's work: auth, quota, rate limit, network, or an answer that
848
- # never arrived. Classified from the LOG because $LAST is only created later, by the EXIT
849
- # trap's `finish`. Any trouble running the classifier counts as "not infrastructure".
904
+ # Infrastructure, not the model's work: auth, a usage limit, budget, capacity, rate limit, a
905
+ # provider or the network, or an answer that never arrived. Classified from the LOG because $LAST
906
+ # is only created later, by the EXIT trap's `finish`. Any trouble running the classifier counts as
907
+ # "not infrastructure".
850
908
  INFRA="$(python3 "$RUNTIME" classify "$LOG" "$HARNESS" "$rc" "$LAST" "$ROLE" 2>/dev/null)" || INFRA=""
851
909
  if [ -n "$INFRA" ]; then
852
910
  TAB=$'\t'
@@ -855,6 +913,8 @@ if [ -n "$INFRA" ]; then
855
913
  {
856
914
  echo "class=$infra_class"
857
915
  echo "retry_after=$infra_after"
916
+ # The moment the wait ends, when the message said how long it is.
917
+ case "$infra_after" in ''|*[!0-9]*) ;; *) echo "reset_at=$(( $(date +%s) + infra_after ))" ;; esac
858
918
  echo "detail=$infra_detail"
859
919
  echo "rc=$rc"
860
920
  echo "role=$ROLE"
@@ -78,6 +78,17 @@ _forge_decide_word() {
78
78
  return 1
79
79
  }
80
80
 
81
+ # _forge_decide_split <array-name> <text> — split <text> on IFS into the named array
82
+ # without pathname expansion, so a `*` or `?` in a flag value stays as typed (GitHub #82).
83
+ # The caller's noglob setting is left as it was.
84
+ _forge_decide_split() {
85
+ local had_noglob=0
86
+ case $- in *f*) had_noglob=1 ;; esac
87
+ set -f
88
+ eval "$1=(\$2)"
89
+ [ "$had_noglob" = 1 ] || set +f
90
+ }
91
+
81
92
  # _forge_decide_gate_list <list> — validate and append `name=mode[,name=mode...]` to
82
93
  # DECIDE_GATES. Nothing is appended unless every entry is valid.
83
94
  _forge_decide_gate_list() {
@@ -86,8 +97,9 @@ _forge_decide_gate_list() {
86
97
  echo "--gate needs name=mode[,name=mode...]; gates: $FORGE_DECIDE_GATE_NAMES; modes: $FORGE_DECIDE_MODE_NAMES" >&2
87
98
  return 2
88
99
  fi
89
- local IFS=,
90
- for entry in $list; do
100
+ local IFS=, entries
101
+ _forge_decide_split entries "$list"
102
+ for entry in ${entries[@]+"${entries[@]}"}; do
91
103
  name="${entry%%=*}"; mode="${entry#*=}"
92
104
  if [ "$name" = "$entry" ] || [ -z "$name" ]; then
93
105
  echo "--gate: '$entry' is not name=mode; gates: $FORGE_DECIDE_GATE_NAMES; modes: $FORGE_DECIDE_MODE_NAMES" >&2
@@ -117,8 +129,9 @@ _forge_decide_budget_spec() {
117
129
  local spec="$1" part field value tokens="$DECIDE_BUDGET_TOKENS" usd="$DECIDE_BUDGET_USD"
118
130
  local usage="--decide-budget expects tokens=N[,usd=X] (N a whole number, X a number, both >= 0)"
119
131
  [ -n "$spec" ] || { echo "$usage" >&2; return 2; }
120
- local IFS=,
121
- for part in $spec; do
132
+ local IFS=, parts
133
+ _forge_decide_split parts "$spec"
134
+ for part in ${parts[@]+"${parts[@]}"}; do
122
135
  field="${part%%=*}"; value="${part#*=}"
123
136
  [ "$field" != "$part" ] || { echo "$usage; got '$part'" >&2; return 2; }
124
137
  case "$field" in