@giamme/forge 0.12.0 → 0.12.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.
@@ -10,6 +10,8 @@
10
10
  # [--verify <command>] [--setup <command>] [--dry-run]
11
11
  # [--timeout S] [--retry-failed N] [--infra-retries M]
12
12
  # [--qa-threshold P0|P1|P2|P3] [--verify-retries N] [--no-forecast]
13
+ # [--sweep P0|P1|P2|P3 [--sweep-plausible] [--sweep-max N]]
14
+ # [--sweep-ahead | --no-sweep-ahead]
13
15
  # forge-parallel.sh retry <plan-dir> <task-id> [--dwarf <spec>] [--setup <command>]
14
16
  # [--timeout S] [--qa-threshold Pn] [--verify-retries N]
15
17
  # forge-parallel.sh integrate <plan-dir> --approved [--verify-retries N] [--final-review <qa-spec>]
@@ -20,6 +22,8 @@
20
22
  # forge-parallel.sh _task <plan-dir> <task-id> (internal; coordinator target)
21
23
  # forge-parallel.sh _qa_only <plan-dir> <task-id> (internal; exit 0 when the next entry only re-runs QA)
22
24
  # forge-parallel.sh _waves <plan-dir> (internal; rewrite waves.tsv after a live `forge control add`)
25
+ # forge-parallel.sh _sweep <plan-dir> --severity Pn [--plausible] [--max N]
26
+ # (internal; plan the finding sweep, print its task ids)
23
27
  #
24
28
  # Routing flags (plan):
25
29
  # --dwarf <spec> fallback for any difficulty tier not named below
@@ -49,6 +53,13 @@
49
53
  # --infra-retries M wait out quota/auth/network stops up to M times instead of pausing
50
54
  # --qa-threshold Pn a reviewer FAIL made only of findings less severe than Pn is
51
55
  # accepted as PASS-with-known-issues (P0 worst ... P3 mildest)
56
+ # --sweep Pn once every task has merged, before verification: the open findings
57
+ # at Pn or worse (tolerated, and PLAUSIBLE with --sweep-plausible) become
58
+ # at most --sweep-max N fix tasks (default 5), one per file, each with a
59
+ # narrow review; the sweep plan is printed and kept in sweep/. Once per
60
+ # plan; what it does not fix stays for `forge issues`
61
+ # --sweep-ahead a task is also told the open findings in files it owns, to fix only
62
+ # on its way (kept for the plan; --no-sweep-ahead turns it off)
52
63
  #
53
64
  # Exit codes: 0 ok | 2 usage/validation | 3 precondition (not a git repo, etc.)
54
65
  # 5 some task failed QA or verification failed | 6 integration conflict
@@ -584,6 +595,28 @@ preflight_plan() {
584
595
  fi
585
596
  }
586
597
 
598
+ # The implementer a sweep task gets when the plan has a low tier (or a plain --dwarf pool): checked
599
+ # with the rest, before any model is paid for, since no task may have used it yet.
600
+ sweep_preflight() { # sweep_preflight <plan>
601
+ local spec flags=""
602
+ spec="$(python3 -c 'import json, sys
603
+ try:
604
+ data = json.load(open(sys.argv[1]))
605
+ except Exception:
606
+ sys.exit()
607
+ for tier in ("low", "any"):
608
+ specs = data.get(tier) if isinstance(data, dict) else None
609
+ if isinstance(specs, list) and specs and isinstance(specs[0], str) and specs[0]:
610
+ print(specs[0]); break' "$1/fractal-routing.json" 2>/dev/null)"
611
+ [ -n "$spec" ] || return 0
612
+ [ -f "$1/yolo_dwarf" ] && flags=--yolo
613
+ /bin/bash "$DISPATCH" doctor --spec "$spec" --role dwarf $flags
614
+ }
615
+
616
+ sweep_plan() { # sweep_plan <plan> --severity Pn [--plausible] [--max N]: the scheduler's _sweep
617
+ python3 "$SKILL_DIR/scripts/forge-sweep.py" plan "$@"
618
+ }
619
+
587
620
  write_capsule() { # write_capsule <plan> <id> <role>
588
621
  local PLAN="$1" me="$2" role="$3" T="$1/tasks.tsv"
589
622
  local run_id; run_id="$(cat "$PLAN/run_id")"
@@ -798,6 +831,7 @@ do_task_body() (
798
831
  --run-dir "$tdir" > "$tdir/dwarf.memory"
799
832
  {
800
833
  python3 "$SKILL_DIR/scripts/forge-prompt.py" --requirements "$tdir/prompt.md" --capsule "$tdir/baseline.capsule" --approach "$tdir/approach.md" --retry "$tdir/retry_findings.md" --memory "$tdir/dwarf.memory"
834
+ [ ! -f "$PLAN/sweep_ahead" ] || python3 "$SKILL_DIR/scripts/forge-sweep.py" ahead "$PLAN" "$id" --role dwarf 2>/dev/null
801
835
  echo "Implement this task in the repository. Follow the intended approach unless it is wrong; explain deviations. Run the task's requested verification and report results."
802
836
  echo "On retry, fix the findings in the existing work; preserve parts not criticised. Explain any finding you reject."
803
837
  echo; python3 "$SKILL_DIR/scripts/forge-contract.py" dwarf
@@ -933,13 +967,17 @@ do_task_body() (
933
967
  else
934
968
  rm -f "$tdir/changes.since.diff" "$tdir/changes.since.range" "$tdir/changes.since.stat"
935
969
  fi
970
+ # A finding sweep's fix task gets the narrow review: one FIXED / NOT FIXED line per finding.
971
+ local qa_kind=task
972
+ [ ! -f "$tdir/sweep.json" ] || qa_kind=sweep
936
973
  # QA uses the dispatch-time ownership and baseline, never later merge state.
937
974
  /bin/bash "$MEMORY" inject "$REPO" qa --task "$tdir/prompt.md" \
938
975
  --run-dir "$tdir" > "$tdir/qa.memory"
939
976
  {
940
977
  python3 "$SKILL_DIR/scripts/forge-prompt.py" --requirements "$tdir/prompt.md" --capsule "$tdir/baseline.capsule" --approach "$tdir/approach.md" --retry "$tdir/retry_findings.md" ${prompt_extra[@]+"${prompt_extra[@]}"} --memory "$tdir/dwarf.memory" --memory "$tdir/qa.memory"
941
- python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind task
978
+ python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind "$qa_kind"
942
979
  echo
980
+ [ ! -f "$PLAN/sweep_ahead" ] || python3 "$SKILL_DIR/scripts/forge-sweep.py" ahead "$PLAN" "$id" --role qa 2>/dev/null
943
981
  if [ -s "$tdir/failfirst.txt" ]; then cat "$tdir/failfirst.txt"; echo; fi
944
982
  # A subset failure is the one thing a reviewer most wants to know and cannot see
945
983
  # from the diff. It runs in a throwaway export of the reviewed commit, so the task
@@ -971,9 +1009,11 @@ do_task_body() (
971
1009
  echo "matters because another task may own those files."
972
1010
  echo
973
1011
  fi
974
- python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind task ${qa_thr:+--threshold "$qa_thr"}
1012
+ python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind "$qa_kind" ${qa_thr:+--threshold "$qa_thr"}
975
1013
  echo
976
- echo '```diff'; cat "$tdir/changes.diff"; echo '```'
1014
+ # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
1015
+ # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
1016
+ echo '```diff'; git -C "$wt" diff --binary --irreversible-delete "$base" "$reviewed" -- . ':(exclude).forge'; echo '```'
977
1017
  echo; /bin/bash "$MEMORY" note qa
978
1018
  echo "Place any learning notes before the final FORGE_VERDICT: PASS or FORGE_VERDICT: FAIL line."
979
1019
  } > "$tdir/qa.input"
@@ -1147,6 +1187,8 @@ merge_task() { # merge_task <plan> <id> -> 0 merged, 1 conflicted
1147
1187
  git -C "$int_wt" rev-parse HEAD > "$PLAN/accepted.integration"
1148
1188
  touch "$PLAN/tasks/$id/merged"
1149
1189
  rm -f "$tdir/conflict.files"
1190
+ # Which of a sweep task's findings its reviewer marked fixed: what `forge issues` leaves out.
1191
+ [ ! -f "$tdir/sweep.json" ] || python3 "$SKILL_DIR/scripts/forge-sweep.py" settle "$PLAN" "$id" >/dev/null 2>&1 || true
1150
1192
  forge_dataset_event merge --dir "$PLAN" --task "$id" --set status=MERGED --set commit="$reviewed" \
1151
1193
  --set integration="$(cat "$PLAN/accepted.integration")"
1152
1194
  return 0
@@ -1678,6 +1720,7 @@ do_run() {
1678
1720
  esac
1679
1721
  done
1680
1722
  [ "$JEV_OPTS" = 1 ] && forge_jev_settle "$PLAN"
1723
+ [ -n "$PP_SWEEP" ] || [ "$PP_SWEEP_PLAUSIBLE$PP_SWEEP_MAX_SET" = 00 ] || die "--sweep-plausible and --sweep-max go with --sweep"
1681
1724
  case "$OUTPUT" in summary|full) ;; *) die "--output must be summary or full" ;; esac
1682
1725
  export FORGE_OUTPUT="$OUTPUT"
1683
1726
  case "$MAXP" in ''|*[!0-9]*) die "--max-parallel must be positive" ;; esac
@@ -1723,6 +1766,7 @@ do_run() {
1723
1766
  [ "${FORGE_RIPWIRE:-}" != off ] || touch "$PLAN/no_ripwire"
1724
1767
  [ ! -f "$PLAN/no_ripwire" ] || export FORGE_RIPWIRE=off
1725
1768
  preflight_plan "$PLAN" || return $?
1769
+ [ -z "$PP_SWEEP" ] || sweep_preflight "$PLAN" || return $?
1726
1770
  /bin/bash "$SKILL_DIR/scripts/forge-install-ripwire.sh" || true
1727
1771
  forge_metric_phase preparation
1728
1772
  mkdir -p "$wt_root"
@@ -1763,6 +1807,8 @@ do_run() {
1763
1807
  local sched_rc=0 paused=0 sched_args=()
1764
1808
  [ "$PP_RETRY_FAILED" -gt 0 ] && sched_args+=(--retry-failed "$PP_RETRY_FAILED")
1765
1809
  [ "$PP_INFRA_RETRIES" -gt 0 ] && sched_args+=(--infra-retries "$PP_INFRA_RETRIES")
1810
+ [ -n "$PP_SWEEP" ] && sched_args+=(--sweep "$PP_SWEEP" --sweep-max "$PP_SWEEP_MAX")
1811
+ [ "$PP_SWEEP_PLAUSIBLE" = 1 ] && sched_args+=(--sweep-plausible)
1766
1812
  forge_metric_phase dispatch
1767
1813
  # In the background so a signal to this shell ends the wait; the scheduler gets it as TERM,
1768
1814
  # stops its tasks and returns 130.
@@ -1983,5 +2029,6 @@ case "$CMD" in
1983
2029
  _prepare_retry) retry_for_scheduler "$@" ;;
1984
2030
  _qa_only) qa_only_next "$@" ;;
1985
2031
  _waves) compute_waves "$@" ;;
2032
+ _sweep) sweep_plan "$@" ;;
1986
2033
  *) die "unknown subcommand '$CMD'" ;;
1987
2034
  esac
@@ -9,6 +9,7 @@ import os
9
9
  from pathlib import Path
10
10
  import re
11
11
  import shutil
12
+ import signal
12
13
  import subprocess
13
14
  import sys
14
15
  import time
@@ -97,6 +98,51 @@ def phase(attempt: str, name: str, rc: str | None = None) -> None:
97
98
  write_json(path, data)
98
99
 
99
100
 
101
+ CLOCK_EVERY_S = 1.0
102
+
103
+
104
+ class _ClockStop(Exception):
105
+ pass
106
+
107
+
108
+ def clock(log: str, out: str, every: str | None = None) -> None:
109
+ """When the harness log grew: one `<epoch seconds> <bytes>` line in `out` for each sample that saw a new
110
+ size, the first at the start. codex's and grok's events carry no time of their own, so forge-ui times them
111
+ from this. Runs beside the harness until a TERM (dispatch sends it once the harness exited) or until the
112
+ dispatch that started it is gone, and ends with one last sample. Advisory: nothing reads its exit."""
113
+ def stop(signum: int, frame: object) -> None:
114
+ raise _ClockStop()
115
+
116
+ signal.signal(signal.SIGTERM, stop)
117
+ signal.signal(signal.SIGINT, stop)
118
+ parent, period, last = os.getppid(), float(every) if every else CLOCK_EVERY_S, -1
119
+
120
+ def sample() -> None:
121
+ nonlocal last
122
+ # A TERM waits until the line is whole: it is delivered when the mask is lifted.
123
+ signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
124
+ try:
125
+ size = os.stat(log).st_size
126
+ if size != last:
127
+ with open(out, 'a') as stream:
128
+ stream.write('%.3f %d\n' % (time.time(), size))
129
+ last = size
130
+ except OSError:
131
+ pass
132
+ finally:
133
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGTERM})
134
+
135
+ try:
136
+ while os.getppid() == parent:
137
+ sample()
138
+ time.sleep(period)
139
+ except _ClockStop:
140
+ pass
141
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
142
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
143
+ sample()
144
+
145
+
100
146
  def token_count(value: object) -> int | None:
101
147
  return value if type(value) is int and value >= 0 else None
102
148
 
@@ -254,7 +300,7 @@ def _finish(attempt: Path, root: Path, role: str, harness: str, rc: str) -> None
254
300
  session_path.unlink(missing_ok=True)
255
301
  if found is not None:
256
302
  session_path.write_text(found + '\n')
257
- for suffix in ('prompt', 'last', 'log', 'resolved', 'cmd', 'timedout', 'infra', 'orphans',
303
+ for suffix in ('prompt', 'last', 'log', 'clock', 'resolved', 'cmd', 'timedout', 'infra', 'orphans',
258
304
  'session', 'continue'):
259
305
  if suffix == 'prompt' and not prompt_ready:
260
306
  continue
@@ -621,6 +667,8 @@ def main() -> None:
621
667
  report(*args)
622
668
  elif command == 'classify':
623
669
  classify_command(*args)
670
+ elif command == 'clock':
671
+ clock(*args)
624
672
  else:
625
673
  raise ValueError('unknown runtime command: ' + command)
626
674
  except (OSError, ValueError, RuntimeError) as error:
@@ -11,6 +11,11 @@ Two opt-in behaviours live here, both off by default so a plain `run` is unchang
11
11
  stops dispatching, lets running tasks drain and exits 8: nothing was the task's fault
12
12
  and no attempt was spent, so the next `run` simply resumes.
13
13
 
14
+ A third, ``--sweep Pn``, also per invocation: once every task has merged, the open review
15
+ findings at Pn or worse become fix tasks (``forge-parallel.sh _sweep``, forge-sweep.py) that
16
+ this run then dispatches like any other, once per plan. A fix task that fails leaves its
17
+ findings for ``forge issues`` and does not fail the run.
18
+
14
19
  Both numbers are per invocation, but while the scheduler runs they are mirrored into the
15
20
  plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
16
21
  decision, so `forge control` can change them mid-run. See "live control files" below.
@@ -527,7 +532,8 @@ def live_stop(plan: object, names: object) -> None:
527
532
 
528
533
 
529
534
  def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
530
- infra_retries: int = 0) -> int:
535
+ infra_retries: int = 0, sweep: str | None = None, sweep_max: int = 5,
536
+ sweep_plausible: bool = False) -> int:
531
537
  if capacity <= 0:
532
538
  raise ValueError('capacity must be positive')
533
539
  if retry_failed < 0 or infra_retries < 0:
@@ -569,6 +575,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
569
575
  human = set() # tasks whose next dispatch is a `forge control retry` (dataset trigger human)
570
576
  fractal = _fractal_plan(plan)
571
577
  drain_told = False # the drained message was printed for this drain
578
+ sweep_asked = False # this invocation already asked for the finding sweep
572
579
 
573
580
  def status(name: str) -> str:
574
581
  root = plan / 'tasks' / name
@@ -880,6 +887,38 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
880
887
  _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
881
888
  return 'applied', None
882
889
 
890
+ def is_fix(name: str) -> bool:
891
+ """A finding sweep's fix task."""
892
+ return (plan / 'tasks' / name / 'sweep.json').is_file()
893
+
894
+ def sweep_due() -> bool:
895
+ """--sweep was given, every task merged, nothing stops or holds the run, and this plan was
896
+ never swept (sweep/plan.json is the planner's record, and its marker)."""
897
+ return (bool(sweep) and not sweep_asked and not interrupted and not graceful and not paused
898
+ and not drained(plan) and not (plan / 'sweep' / 'plan.json').exists()
899
+ and all(status(name) == 'MERGED' for name in tasks))
900
+
901
+ def start_sweep() -> int:
902
+ """Plan the finding sweep and queue its fix tasks; how many were queued. Whatever goes
903
+ wrong here ends the run without a sweep, never with a failure."""
904
+ nonlocal sweep_asked
905
+ sweep_asked = True
906
+ command = ['/bin/bash', script, '_sweep', str(plan), '--severity', sweep, '--max', str(sweep_max)]
907
+ result = subprocess.run(command + (['--plausible'] if sweep_plausible else []),
908
+ stdout=subprocess.PIPE, text=True)
909
+ if result.returncode:
910
+ _warn('the finding sweep could not be planned (exit ' + str(result.returncode)
911
+ + '); its findings stay for forge issues')
912
+ return 0
913
+ queued = 0
914
+ for name in result.stdout.split():
915
+ outcome, reason = apply_add({'task': name})
916
+ if outcome == 'applied':
917
+ queued += 1
918
+ else:
919
+ _warn('sweep task ' + name + ' was not queued: ' + str(reason))
920
+ return queued
921
+
883
922
  def handle_requests() -> None:
884
923
  """Apply or refuse each queued request; the outcome is logged under the control lock."""
885
924
  for name in list_requests(plan):
@@ -960,7 +999,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
960
999
  if status(name) not in ('PENDING', 'BLOCKED', 'INFRA'):
961
1000
  pending.remove(name)
962
1001
  swept = time.monotonic()
963
- while pending or active or waiting_scopes():
1002
+ while pending or active or waiting_scopes() or sweep_due():
964
1003
  # Reap before honouring the stop. A signal during the sleep, and a task
965
1004
  # that exits while another merge is still running, have already written
966
1005
  # a result; breaking first used to skip them and mark them INTERRUPTED.
@@ -1071,6 +1110,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1071
1110
  # BLOCKED would turn "the provider was down" into a recorded failure.
1072
1111
  # A task held back by its pin is still an infrastructure stop.
1073
1112
  break
1113
+ if not pending and sweep_due() and start_sweep():
1114
+ continue
1074
1115
  for name in pending:
1075
1116
  mark(name, 'BLOCKED')
1076
1117
  break
@@ -1125,7 +1166,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1125
1166
  if paused or any(live_pause(pause) for pause in pauses.values()) \
1126
1167
  or any(status(name) == 'INFRA' for name in tasks):
1127
1168
  return INFRA_EXIT
1128
- return 0 if all(status(name) == 'MERGED' for name in tasks) else 5
1169
+ # A fix task that did not merge leaves its findings for `forge issues`; the run's own work is done.
1170
+ return 0 if all(status(name) == 'MERGED' for name in tasks if not is_fix(name)) else 5
1129
1171
 
1130
1172
 
1131
1173
  def main() -> None:
@@ -1153,9 +1195,12 @@ def main() -> None:
1153
1195
  parser.add_argument('capacity', type=int)
1154
1196
  parser.add_argument('--retry-failed', type=int, default=0, metavar='N')
1155
1197
  parser.add_argument('--infra-retries', type=int, default=0, metavar='M')
1198
+ parser.add_argument('--sweep', choices=('P0', 'P1', 'P2', 'P3'))
1199
+ parser.add_argument('--sweep-max', type=int, default=5, metavar='N')
1200
+ parser.add_argument('--sweep-plausible', action='store_true')
1156
1201
  args = parser.parse_args(sys.argv[1:])
1157
1202
  sys.exit(schedule(args.script, args.plan, args.capacity, args.retry_failed,
1158
- args.infra_retries))
1203
+ args.infra_retries, args.sweep, args.sweep_max, args.sweep_plausible))
1159
1204
  except (OSError, ValueError, KeyError) as error:
1160
1205
  print('forge scheduler: ' + str(error), file=sys.stderr)
1161
1206
  sys.exit(3)
@@ -300,7 +300,9 @@ fi
300
300
  if [ -s "$RUN/failfirst.txt" ]; then cat "$RUN/failfirst.txt"; echo; fi
301
301
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo
302
302
  echo
303
- echo '```diff'; cat "$RUN/changes.diff"; echo '```'
303
+ # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
304
+ # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
305
+ echo '```diff'; git -C "$REPO" diff --binary --irreversible-delete "$START" "$END" -- . ':(exclude).forge'; echo '```'
304
306
  echo; /bin/bash "$MEMORY" note qa
305
307
  echo "Place any learning notes before the final FORGE_VERDICT: PASS or FORGE_VERDICT: FAIL line."
306
308
  } > "$RUN/qa.input"