@giamme/forge 0.15.0 → 0.16.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 (63) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/VERSION +1 -1
  3. package/docs/artifacts.md +1 -1
  4. package/docs/commands.md +14 -3
  5. package/docs/forge-ui.md +14 -0
  6. package/docs/memory.md +22 -0
  7. package/docs/reviews.md +7 -0
  8. package/forge +11 -0
  9. package/package.json +1 -1
  10. package/references/dataset.md +5 -2
  11. package/references/decompose.md +51 -5
  12. package/references/harnesses.md +4 -1
  13. package/references/solo.md +5 -1
  14. package/references/ui.md +10 -1
  15. package/scripts/forge-artifact.sh +53 -0
  16. package/scripts/forge-contract.py +55 -8
  17. package/scripts/forge-control.py +0 -2
  18. package/scripts/forge-dispatch.sh +28 -12
  19. package/scripts/forge-fail-first.py +3 -1
  20. package/scripts/forge-guard.py +247 -8
  21. package/scripts/forge-issues.py +12 -0
  22. package/scripts/forge-lib-adopt.sh +260 -0
  23. package/scripts/forge-lib-attribute.sh +10 -2
  24. package/scripts/forge-lib-plans.sh +16 -4
  25. package/scripts/forge-lib-review.sh +8 -2
  26. package/scripts/forge-lib-task.sh +19 -5
  27. package/scripts/forge-memory.sh +41 -4
  28. package/scripts/forge-metrics.sh +7 -0
  29. package/scripts/forge-parallel.sh +96 -13
  30. package/scripts/forge-route.py +16 -2
  31. package/scripts/forge-runs-rm.py +23 -7
  32. package/scripts/forge-runtime.py +25 -2
  33. package/scripts/forge-schedule.py +5 -2
  34. package/scripts/forge-shadow.py +2 -0
  35. package/scripts/forge-solo.sh +6 -0
  36. package/scripts/forge_dataset/cli.py +16 -0
  37. package/scripts/forge_dataset/export.py +1 -0
  38. package/scripts/forge_dataset/harvest.py +11 -0
  39. package/scripts/forge_dataset/history.py +126 -0
  40. package/scripts/forge_dataset/worktrees.py +95 -0
  41. package/scripts/forge_memory_list.py +153 -0
  42. package/scripts/forge_worktrees.py +88 -0
  43. package/ui/README.md +31 -0
  44. package/ui/docs/api.md +81 -4
  45. package/ui/forge_ui/__init__.py +14 -1
  46. package/ui/forge_ui/__main__.py +1 -1
  47. package/ui/forge_ui/control.py +77 -0
  48. package/ui/forge_ui/findings.py +7 -0
  49. package/ui/forge_ui/projects.py +571 -0
  50. package/ui/forge_ui/reader.py +27 -7
  51. package/ui/forge_ui/static/app.js +99 -21
  52. package/ui/forge_ui/static/cloudui.js +6 -2
  53. package/ui/forge_ui/static/convo.js +1 -1
  54. package/ui/forge_ui/static/diffview.js +2 -2
  55. package/ui/forge_ui/static/files.js +1 -1
  56. package/ui/forge_ui/static/index.html +5 -1
  57. package/ui/forge_ui/static/panel.js +28 -2
  58. package/ui/forge_ui/static/projectsview.js +372 -0
  59. package/ui/forge_ui/static/settings.js +136 -4
  60. package/ui/forge_ui/static/style.css +93 -3
  61. package/ui/forge_ui/static/uikit.js +94 -1
  62. package/ui/forge_ui/static/worktreesview.js +250 -0
  63. package/ui/forge_ui/worktrees.py +570 -0
@@ -19,14 +19,17 @@
19
19
  # [--sweep-ahead | --no-sweep-ahead] [--attribute | --no-attribute]
20
20
  # forge-parallel.sh retry <plan-dir> <task-id> [--dwarf <spec>] [--setup <command>]
21
21
  # [--answer <text> | --answer-file <file>] (a NEEDS_INPUT task)
22
- # [--decide retry=N|threshold=Pn | --dwarf <spec>] --reason "<why>" --approved
22
+ # [--decide retry=N|threshold=Pn] [--dwarf <spec>] --reason "<why>" --approved
23
23
  # (a NEEDS_DECISION task)
24
+ # [--no-dispatch] (prepare it and start nothing: the next `run` dispatches it)
24
25
  # [--timeout S] [--qa-threshold Pn|none|default] [--verify-retries N]
25
26
  # [--retry-failed N] [--infra-retries M]
26
27
  # forge-parallel.sh integrate <plan-dir> --approved [--verify-retries N] [--final-review <qa-spec>]
27
28
  # forge-parallel.sh review <plan-dir> [--qa <spec>] [--yolo-qa] [--qa-threshold Pn|none|default]
28
29
  # forge-parallel.sh attribute <plan-dir> [--force] (find a merge that breaks the failed verification)
29
30
  # forge-parallel.sh accept <plan-dir> <task-id> --reason "<why>" --approved
31
+ # forge-parallel.sh adopt <plan-dir> <commit|a..b> | --head --reason "<why>" [--qa <spec>] [--approved]
32
+ # (a commit made outside forge, reviewed alone, comes into the run)
30
33
  # forge-parallel.sh split <plan-dir> <new-plan> --tasks <id,id> [--dry-run]
31
34
  # forge-parallel.sh combine <new-plan> <plan-a> <plan-b> [<plan>...] [--verify <command>] [--dry-run]
32
35
  # forge-parallel.sh _task <plan-dir> <task-id> (internal; coordinator target)
@@ -144,7 +147,7 @@ JEV_OPTS=0
144
147
  # Flags shared by several subcommands, then the helper libraries. Functions only, resolved
145
148
  # at call time, so they may use die/note/field and friends defined below.
146
149
  source "$SKILL_DIR/scripts/forge-parallel-options.sh"
147
- for forge_lib in task gates verify attribute plans review; do
150
+ for forge_lib in task gates verify attribute plans review adopt; do
148
151
  [ -f "$SKILL_DIR/scripts/forge-lib-$forge_lib.sh" ] && source "$SKILL_DIR/scripts/forge-lib-$forge_lib.sh"
149
152
  done
150
153
  OUTPUT=summary
@@ -1101,6 +1104,7 @@ ensure_worktree() { # ensure_worktree <repo> <wt> <br> <base> <tdir> <plan> <id>
1101
1104
  else
1102
1105
  (cd "$REPO" && git worktree add -b "$br" "$wt" "$base") >"$tdir/worktree.out" 2>&1
1103
1106
  fi || return 1
1107
+ forge_worktree_event created "$PLAN" "$REPO" "$wt" "$br" task "$id"
1104
1108
  run_worktree_setup "$PLAN" "$REPO" "$wt" "$tdir" "$id"
1105
1109
  }
1106
1110
 
@@ -1364,6 +1368,7 @@ do_task_body() (
1364
1368
  fi
1365
1369
  review="$tdir/review-$attempt-$$"
1366
1370
  forge_review_snapshot "$wt" "$base" "$reviewed" "$review" || { echo ERROR > "$tdir/status"; return 1; }
1371
+ forge_review_deps "$wt" "$review" "$tdir/review.deps"
1367
1372
  source_fp="$(forge_fingerprint "$wt")" || return 1
1368
1373
  # The review copy is a commit: an untracked file the reviewer leaves there (a test run's
1369
1374
  # bytecode) changes nothing that merges, so only tracked content counts (#95).
@@ -1422,6 +1427,9 @@ do_task_body() (
1422
1427
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind "$qa_kind"
1423
1428
  echo
1424
1429
  [ ! -f "$PLAN/sweep_ahead" ] || python3 "$SKILL_DIR/scripts/forge-sweep.py" ahead "$PLAN" "$id" --role qa 2>/dev/null
1430
+ cat "$tdir/review.deps"
1431
+ [ -s "$tdir/failfirst.txt" ] || [ -s "$tdir/prereview.txt" ] || echo "Forge ran no tests of its own on this attempt, so nothing here stands in for yours."
1432
+ echo
1425
1433
  if [ -s "$tdir/failfirst.txt" ]; then cat "$tdir/failfirst.txt"; echo; fi
1426
1434
  if [ -s "$tdir/prereview.txt" ]; then cat "$tdir/prereview.txt"; echo; fi
1427
1435
  if [ -s "$tdir/guard.txt" ]; then
@@ -1575,6 +1583,7 @@ merge_task() { # merge_task <plan> <id> -> 0 merged, 1 conflicted
1575
1583
  if [ -s "$PLAN/accepted.integration" ] && [ "$(git -C "$int_wt" rev-parse HEAD)" != "$(cat "$PLAN/accepted.integration")" ]; then
1576
1584
  echo INVALIDATED > "$PLAN/tasks/$id/status"
1577
1585
  forge_dataset_event merge --dir "$PLAN" --task "$id" --set status=INVALIDATED --set reason=integration-moved
1586
+ note "$id: the integration branch moved outside this run. To bring those commits into the run: forge-parallel.sh adopt $PLAN --head --reason \"...\""
1578
1587
  return 1
1579
1588
  fi
1580
1589
  [ -z "$(git -C "$int_wt" status --porcelain -- . ':(exclude).forge')" ] || {
@@ -1622,7 +1631,7 @@ _retry_answer_scan() { # _retry_answer_scan <scratch-dir> <retry args...>
1622
1631
  local n=0 flag="" val="" novalue=0 rc=0 dwarf="" decide="" reason="" approved=0
1623
1632
  while [ $# -gt 0 ]; do
1624
1633
  case "$1" in
1625
- --no-ripwire|--yolo-dwarf|--yolo-qa) shift ;;
1634
+ --no-ripwire|--yolo-dwarf|--yolo-qa|--no-dispatch) shift ;;
1626
1635
  --output|--verify|--setup) [ $# -ge 2 ] || break; shift 2 ;;
1627
1636
  --dwarf) [ $# -ge 2 ] || break; dwarf="$2"; shift 2 ;;
1628
1637
  --decide) [ $# -ge 2 ] || break; decide="$2"; shift 2 ;;
@@ -1677,10 +1686,23 @@ PY
1677
1686
  sleep "$secs"
1678
1687
  }
1679
1688
 
1689
+ report_untested() { # report_untested <plan> <id>...: verdicts that rest on reading alone (#117)
1690
+ local plan="$1" id tests_note untested=0; shift
1691
+ for id in "$@"; do
1692
+ tests_note="$(forge_tests_note "$plan/tasks/$id/qa.last")"
1693
+ if [ -n "$tests_note" ]; then
1694
+ [ "$untested" = 0 ] && echo "reviews whose tests could not run:"
1695
+ untested=1
1696
+ printf ' %-14s %s\n' "$id" "$tests_note"
1697
+ fi
1698
+ done
1699
+ [ "$untested" = 0 ] || echo
1700
+ }
1701
+
1680
1702
  do_retry() {
1681
1703
  local PLAN="${1:?retry needs a plan dir}" id="${2:?retry needs a task id}"; shift 2
1682
1704
  FORGE_RUN_STARTED="$(forge_now)"
1683
- local NEWDWARF="" jev_rc=0 ANSWER="" ANSWER_FILE="" HAVE_ANSWER=0 DECIDE="" REASON="" APPROVED=0
1705
+ local NEWDWARF="" jev_rc=0 ANSWER="" ANSWER_FILE="" HAVE_ANSWER=0 DECIDE="" REASON="" APPROVED=0 NO_DISPATCH=0
1684
1706
  # An answer is validated before any option below writes into the plan: a rejected answer
1685
1707
  # changes nothing, --setup and --verify included. Only a NEEDS_INPUT task takes one. The
1686
1708
  # arguments are walked the way the loop below walks them (a value is never taken for a flag),
@@ -1728,6 +1750,7 @@ do_retry() {
1728
1750
  --decide) DECIDE="${2:?--decide needs retry=N or threshold=Pn}"; shift 2 ;;
1729
1751
  --reason) REASON="${2?--reason needs a text}"; shift 2 ;;
1730
1752
  --approved) APPROVED=1; shift ;;
1753
+ --no-dispatch) NO_DISPATCH=1; shift ;;
1731
1754
  # The check above refuses an empty answer first; these hold when its walk could not run.
1732
1755
  --answer) [ "$HAVE_ANSWER" = 0 ] || die "retry: give --answer or --answer-file once"
1733
1756
  ANSWER="${2?--answer needs the answer text}"; HAVE_ANSWER=1; shift 2
@@ -1774,6 +1797,14 @@ do_retry() {
1774
1797
  PP_RETRY_FAILED=0
1775
1798
  fi
1776
1799
  [ "$HAVE_ANSWER" = 0 ] || [ "$st" = NEEDS_INPUT ] || die "retry: '$id' is $st, not waiting for an answer; --answer and --answer-file only answer a NEEDS_INPUT task"
1800
+ # The budgets are this call's own, and --no-dispatch ends the call before any attempt spends them.
1801
+ if [ "$NO_DISPATCH" = 1 ] && { [ "$PP_RETRY_FAILED_SET" = 1 ] || [ "$PP_INFRA_RETRIES_SET" = 1 ]; }; then
1802
+ die "retry: --retry-failed and --infra-retries apply to the attempts this call runs, and --no-dispatch runs none; give them to the run: forge-parallel.sh run $PLAN --retry-failed N" 2
1803
+ fi
1804
+ # A recorded decision is already what the next run does: a second one would stack onto its count.
1805
+ if [ -n "$DECIDE" ] && [ -f "$tdir/retry.prepared" ]; then
1806
+ die "retry: '$id' already has a decision recorded and waits for the next run; forge-parallel.sh run $PLAN starts it" 2
1807
+ fi
1777
1808
  retry_decision_gate "$PLAN" "$id" "$st" "$DECIDE" "$NEWDWARF" "$REASON" "$APPROVED"
1778
1809
  # A task at its attempt cap (#69) is refused with the decision commands unless --decide retry=N reaches past it.
1779
1810
  if ! attempt_cap_gate "$PLAN" "$id" "$st" "$DECIDE"; then write_results "$PLAN"; return 2; fi
@@ -1800,7 +1831,8 @@ do_retry() {
1800
1831
  prepare_retry "$PLAN" "$id" "$NEWDWARF" || prc=$?
1801
1832
  # A person's plain retry ends what an earlier decision allowed; resuming after an
1802
1833
  # infrastructure stop is not a new choice, so the allowance carries over.
1803
- [ "$prc" != 0 ] || [ "$st" = INFRA ] || rm -f "${tdir:?}/decided.left"
1834
+ # Nor is changing a prepared task's model: the count its decision granted still stands.
1835
+ [ "$prc" != 0 ] || [ "$st" = INFRA ] || [ -f "$tdir/retry.prepared" ] || rm -f "${tdir:?}/decided.left"
1804
1836
  fi
1805
1837
  if [ "$prc" != 0 ]; then
1806
1838
  write_results "$PLAN"
@@ -1808,7 +1840,8 @@ do_retry() {
1808
1840
  return "$prc"
1809
1841
  fi
1810
1842
  [ "${FORGE_RIPWIRE:-}" != off ] || touch "$PLAN/no_ripwire"
1811
- dependencies_ready "$PLAN" "$id" || { write_results "$PLAN"; return 5; }
1843
+ # --no-dispatch leaves the dependencies to the `run` that dispatches it: one can merge in that same run.
1844
+ [ "$NO_DISPATCH" = 1 ] || dependencies_ready "$PLAN" "$id" || { write_results "$PLAN"; return 5; }
1812
1845
  local vrepo vcheckout; vrepo="$(cat "$PLAN/repo" 2>/dev/null)"; vcheckout="$(cat "$PLAN/wt_root")/_integration"
1813
1846
  [ -d "$vcheckout" ] || vcheckout="$vrepo"
1814
1847
  verify_lanes_check "$PLAN" "$vrepo" "$vcheckout"
@@ -1818,6 +1851,16 @@ do_retry() {
1818
1851
  rm -f "$tdir/status"
1819
1852
  # The pauses an earlier run ended with describe that run: this retry's summary must not report them.
1820
1853
  rm -f "$PLAN/infra.last"
1854
+ # #118: `retry` holds the plan lock until its attempts end, so several tasks cannot resume side by
1855
+ # side. This stops once the retry is prepared, and the marker tells the next `run` that dispatch is
1856
+ # a person's retry. The decision's count is already in decided.left, which that run honours.
1857
+ if [ "$NO_DISPATCH" = 1 ]; then
1858
+ : > "$tdir/retry.prepared" || die "retry: could not record the prepared retry" 1
1859
+ write_results "$PLAN"
1860
+ note "$id is ready and nothing was dispatched; forge-parallel.sh run $PLAN starts it"
1861
+ return 0
1862
+ fi
1863
+ rm -f "$tdir/retry.prepared"
1821
1864
 
1822
1865
  note "retrying $id with dwarf $(field "$T" "$id" dwarf)"
1823
1866
  forge_fast_fractal_note "$PLAN"
@@ -1875,6 +1918,7 @@ do_retry() {
1875
1918
  note "$id PASS but conflicted on merge — branch preserved"
1876
1919
  fi
1877
1920
  fi
1921
+ report_untested "$PLAN" "$id"
1878
1922
  # Tasks still to run (#112): the run that dispatches them verifies the integration branch at its
1879
1923
  # end, and integrate verifies its candidate, so verifying now would only be repeated.
1880
1924
  local left="" lid
@@ -2206,6 +2250,24 @@ run_wait() { # run_wait <pid>
2206
2250
  while kill -0 "$1" 2>/dev/null; do run_rc=0; wait "$1" || run_rc=$?; done
2207
2251
  }
2208
2252
 
2253
+ # A standalone retry runs its dispatches in the foreground, and bash runs a trap only between
2254
+ # commands, so a TERM to the retry's pid alone ended it and left the dispatch, its harness and
2255
+ # the tools they started running in the task's worktree (#129). retry_stop sends TERM to
2256
+ # everything below the retry job (forge-guard.py stop-tree, which reads ps itself), and waits,
2257
+ # bounded, while each dispatch's EXIT trap stops its harness and reaps what it started. What
2258
+ # still runs then is killed, and the guard's backstop runs on any harness record a dispatch
2259
+ # left behind, as the scheduler's does.
2260
+ RETRY_STOP_WAIT=20 # seconds; a dispatch's EXIT trap needs about 1 s plus its ~6 s reap
2261
+ retry_stop() { # retry_stop <job pid> <plan> <task>
2262
+ local record
2263
+ python3 "$SKILL_DIR/scripts/forge-guard.py" stop-tree "$1" --wait "$RETRY_STOP_WAIT" >/dev/null 2>&1 \
2264
+ || kill -TERM "$1" 2>/dev/null
2265
+ [ -n "$2" ] && [ -n "$3" ] || return 0
2266
+ for record in "$2/tasks/$3/dwarf.harness" "$2/tasks/$3/qa.harness"; do
2267
+ [ ! -e "$record" ] || python3 "$SKILL_DIR/scripts/forge-guard.py" stop "$record" >/dev/null 2>&1
2268
+ done
2269
+ }
2270
+
2209
2271
  # The handler of do_run's subshell: a signal reaches the job in progress (the scheduler,
2210
2272
  # then the verification) as TERM. Before any job exists there is nothing to clean up.
2211
2273
  run_signal() {
@@ -2324,6 +2386,7 @@ do_run() {
2324
2386
  if [ ! -d "$int_wt" ]; then
2325
2387
  (cd "$REPO" && git worktree add "$int_wt" "$int_br" >/dev/null 2>&1) \
2326
2388
  || die "could not create integration worktree" 3
2389
+ forge_worktree_event created "$PLAN" "$REPO" "$int_wt" "$int_br" integration
2327
2390
  # The integration worktree is where a merged result gets validated, so it needs
2328
2391
  # the same setup the task worktrees get. Without it, the one checkout holding
2329
2392
  # every task's merged work is the one checkout that cannot build or test it.
@@ -2332,7 +2395,7 @@ do_run() {
2332
2395
  fi
2333
2396
 
2334
2397
  if [ -s "$PLAN/accepted.integration" ] && [ "$(git -C "$int_wt" rev-parse HEAD)" != "$(cat "$PLAN/accepted.integration")" ]; then
2335
- die "integration branch changed outside this run" 3
2398
+ die "integration branch changed outside this run. To bring those commits into the run: forge-parallel.sh adopt $PLAN --head --reason \"...\"" 3
2336
2399
  fi
2337
2400
  git -C "$int_wt" rev-parse HEAD > "$PLAN/accepted.integration"
2338
2401
  local id failed=0
@@ -2387,7 +2450,9 @@ do_run() {
2387
2450
  # branch so there is something to inspect and retry from.
2388
2451
  if [ -s "$PLAN/results.tsv" ]; then
2389
2452
  for id in $(awk -F'\t' '$2=="MERGED" {print $1}' "$PLAN/results.tsv"); do
2390
- (cd "$REPO" && git worktree remove --force "$wt_root/$id" >/dev/null 2>&1)
2453
+ [ -e "$wt_root/$id" ] || continue
2454
+ (cd "$REPO" && git worktree remove --force "$wt_root/$id" >/dev/null 2>&1) \
2455
+ && forge_worktree_event removed "$PLAN" "$REPO" "$wt_root/$id" "forge/$run_id/$id" task "$id"
2391
2456
  done
2392
2457
  fi
2393
2458
 
@@ -2416,6 +2481,9 @@ do_run() {
2416
2481
  done
2417
2482
  [ "$drift" = 1 ] && echo
2418
2483
 
2484
+ # shellcheck disable=SC2046 # ids are single words
2485
+ report_untested "$PLAN" $(all_ids "$T")
2486
+
2419
2487
  # From this run's own flags, never from a verification.status an earlier run left.
2420
2488
  if [ "$interrupted" = 1 ]; then
2421
2489
  if [ "$vstopped" = 1 ]; then echo "interrupted during verification, which was stopped and not rerun."
@@ -2512,6 +2580,7 @@ do_integrate() {
2512
2580
  out="$PLAN/integrate-$(date +%s)-$$"; mkdir -p "$out"
2513
2581
  candidate="$(cat "$PLAN/wt_root")/_candidate-$$"
2514
2582
  git -C "$REPO" worktree add --detach "$candidate" "$parent" > "$out/setup.log" 2>&1 || return 3
2583
+ forge_worktree_event created "$PLAN" "$REPO" "$candidate" - candidate
2515
2584
  if ! git -C "$candidate" merge --no-ff -m "forge: integrate run $run_id" "$target" > "$out/merge.log" 2>&1; then
2516
2585
  forge_dataset_event integrate_conflict --dir "$PLAN" --set branch="$cur" --set parent="$parent" \
2517
2586
  --set target="$target" --set conflicts="$(git -C "$candidate" diff --name-only --diff-filter=U 2>/dev/null | tr '\n' ' ')" \
@@ -2550,6 +2619,7 @@ do_integrate() {
2550
2619
  forge_dataset_event integrate_advanced --dir "$PLAN" --set branch="$cur" --set parent="$parent" \
2551
2620
  --set candidate="$candidate_sha" --set target="$target" --set verification="$(cat "$out/verification.status" 2>/dev/null)"
2552
2621
  git -C "$REPO" worktree remove "$candidate" || return 3
2622
+ forge_worktree_event removed "$PLAN" "$REPO" "$candidate" - candidate
2553
2623
  echo "merged candidate of $int_br into $cur (verification: $(cat "$out/verification.status"))"
2554
2624
  }
2555
2625
 
@@ -2777,7 +2847,7 @@ if [ "${1:-}" = --help ] || [ "${1:-}" = -h ]; then
2777
2847
  forge_fractal_help
2778
2848
  exit 0
2779
2849
  fi
2780
- [ $# -ge 1 ] || die "usage: forge-parallel.sh <plan|auto|run|retry|accept|review|integrate|split|attribute|combine> <plan-dir> [...]"
2850
+ [ $# -ge 1 ] || die "usage: forge-parallel.sh <plan|auto|run|retry|accept|adopt|review|integrate|split|attribute|combine> <plan-dir> [...]"
2781
2851
  CMD="$1"; shift
2782
2852
  [ ! -f "${1:-}/no_ripwire" ] || export FORGE_RIPWIRE=off
2783
2853
  if [ -d "${1:-}" ]; then
@@ -2785,7 +2855,7 @@ if [ -d "${1:-}" ]; then
2785
2855
  fi
2786
2856
  case "$CMD" in
2787
2857
  # `combine` takes a plan dir that does not exist yet and locks its sources itself.
2788
- run|retry|integrate|accept|review|split|attribute)
2858
+ run|retry|integrate|accept|adopt|review|split|attribute)
2789
2859
  if [ "${FORGE_PLAN_LOCK:-}" != "${1:-}" ]; then
2790
2860
  exec python3 "$SKILL_DIR/scripts/forge-schedule.py" lock "$SELF" "$CMD" "$@"
2791
2861
  fi ;;
@@ -2794,7 +2864,7 @@ esac
2794
2864
  # path (die included). Installed after the lock re-exec, so it fires once, in the process
2795
2865
  # that did the work; `_task` and `_merge` are parts of a `run` and are not recorded alone.
2796
2866
  case "$CMD" in
2797
- plan|run|retry|integrate|accept|review|split|attribute|combine)
2867
+ plan|run|retry|integrate|accept|adopt|review|split|attribute|combine)
2798
2868
  FORGE_DATASET_INVOCATION="inv-$(date +%s)-$$-$RANDOM"; export FORGE_DATASET_INVOCATION
2799
2869
  FORGE_DATASET_STARTED="$(date +%s)"
2800
2870
  FORGE_DATASET_ARGV=("$@")
@@ -2804,7 +2874,7 @@ esac
2804
2874
  need_fn() { declare -F "$1" >/dev/null || die "'$CMD' is not available: $1 is missing" 3; }
2805
2875
  # A plan with a frozen profile asks its decision-model gates from that copy (`plan` does it itself,
2806
2876
  # after it freezes). The internal subcommands inherit it from the `run` that started them.
2807
- case "$CMD" in run|retry|integrate|accept|review|split|attribute) forge_profile_export "${1:-}" ;; esac
2877
+ case "$CMD" in run|retry|integrate|accept|adopt|review|split|attribute) forge_profile_export "${1:-}" ;; esac
2808
2878
  case "$CMD" in
2809
2879
  plan) do_plan "$@"; rc=$?; forge_update_notice; exit "$rc" ;;
2810
2880
  auto) do_auto "$@" ;;
@@ -2821,9 +2891,22 @@ case "$CMD" in
2821
2891
  trap - TERM INT
2822
2892
  [ "$run_signalled" = 1 ] && [ "$rc" -gt 128 ] && rc=130
2823
2893
  forge_update_notice; exit "$rc" ;;
2824
- retry) do_retry "$@" ;;
2894
+ retry)
2895
+ # As run: the handler lives at the pid the user started, and do_retry runs in a background
2896
+ # job it waits for. A signal stops that job's whole tree (retry_stop, #129), and the retry
2897
+ # returns only once what it dispatched has stopped.
2898
+ retry_signalled=0 retry_job=""
2899
+ trap 'retry_signalled=1; [ -n "$retry_job" ] && retry_stop "$retry_job" "${1:-}" "${2:-}"' TERM INT
2900
+ ( do_retry "$@" ) <&0 &
2901
+ retry_job=$!
2902
+ [ "$retry_signalled" = 1 ] && retry_stop "$retry_job" "${1:-}" "${2:-}"
2903
+ run_wait "$retry_job"; rc=$run_rc
2904
+ trap - TERM INT
2905
+ [ "$retry_signalled" = 1 ] && [ "$rc" -le 128 ] && rc=143
2906
+ exit "$rc" ;;
2825
2907
  integrate) do_integrate "$@" ;;
2826
2908
  accept) need_fn do_accept; do_accept "$@" ;;
2909
+ adopt) need_fn do_adopt; do_adopt "$@" ;;
2827
2910
  review) need_fn do_review; do_review "$@" ;;
2828
2911
  split) need_fn do_split; do_split "$@" ;;
2829
2912
  attribute) need_fn do_attribute; do_attribute "$@" ;;
@@ -647,6 +647,19 @@ def attempt_rows(tdir: Path) -> list:
647
647
  return rows
648
648
 
649
649
 
650
+ def held_attempts(tdir: Path, current: str) -> int:
651
+ """N when the latest decision is `retry=N dwarf=<current>`: a person put the task on this model for N attempts.
652
+
653
+ Only on that model: once the policy, or a later --dwarf, moves the task, the usual patience applies again."""
654
+ try:
655
+ lines = (tdir / 'decisions.tsv').read_text().splitlines()
656
+ except OSError:
657
+ return 0
658
+ cells = lines[-1].split('\t') if lines else []
659
+ match = re.fullmatch(r'retry=([0-9]{1,3}) dwarf=(\S+)', cells[2]) if len(cells) > 2 else None
660
+ return int(match.group(1)) if match and match.group(2) == current else 0
661
+
662
+
650
663
  def decided_attempt(tdir: Path) -> int:
651
664
  """The attempt number of the latest row of tasks/<id>/decisions.tsv (epoch, attempt, choice, reason);
652
665
  0 when the task has no decision. The attempts counted against a model start after it."""
@@ -720,7 +733,7 @@ def granted_attempts(tdir: Path) -> int:
720
733
  for line in lines:
721
734
  cells = line.split('\t')
722
735
  if len(cells) > 2:
723
- match = re.fullmatch(r'retry=([0-9]{1,3})', cells[2])
736
+ match = re.match(r'retry=([0-9]{1,3})(?: |$)', cells[2]) # `retry=2 dwarf=<spec>` grants 2 as well
724
737
  if match:
725
738
  total += int(match.group(1))
726
739
  return total
@@ -895,7 +908,8 @@ def _decide(plan: Path, tdir: Path, args, after: int):
895
908
  decided = decided_attempt(tdir)
896
909
  rows = [row for row in attempt_rows(tdir) if row[0] > decided]
897
910
  streak = failed_streak(rows, current, registry, by_effort=step, laterals=lateral_rows(tdir))
898
- if streak < after:
911
+ # `--decide retry=N --dwarf <spec>` (#118) is N attempts on that model, whatever the usual patience is.
912
+ if streak < max(after, held_attempts(tdir, current)):
899
913
  return MARKERS, (), '', 0
900
914
  target, why = stronger(current, load_pools(plan / 'fractal-routing.json'), registry)
901
915
  # Only once no higher tier has a model. A tier-up is still the stronger move.
@@ -20,10 +20,13 @@ reported per step; the run dir is kept when worktrees or branches could not be d
20
20
  after a failed removal the files that identify the run are the last to go, so the same command
21
21
  finishes the job. `forge runs rm` on a path that no longer exists only unregisters it.
22
22
 
23
- What the run owns on the repo's side is decided here, not read from the run dir: a worktree is the
24
- run's only under <repo>/../.forge-worktrees/<run id>/ (as forge-parallel.sh derives it, not from
25
- the `wt_root` file) on a branch forge/<run id>/<task> for a task in tasks.tsv or
26
- forge/<run id>-integration. Any other worktree in that place is `foreign`, and never touched. A
23
+ What the run owns on the repo's side is decided here, not read from the run dir, by the rule in
24
+ forge_worktrees.py that forge-ui's Worktrees screen shares: a worktree is the run's only under
25
+ <repo>/../.forge-worktrees/<run id>/ (as forge-parallel.sh derives it, not from the `wt_root` file)
26
+ on a branch forge/<run id>/<task> for a task in tasks.tsv or forge/<run id>-integration, or detached
27
+ and named like a scratch worktree forge left there (`_candidate-<n>`, `_attribute[-<n>]`). Any other
28
+ worktree in that place is `foreign`, and never touched. Each worktree removed is recorded in the
29
+ dataset as `worktree_removed`. A
27
30
  worktree with uncommitted or untracked changes is `dirty`: never removed, and --worktrees then
28
31
  keeps the run dir too.
29
32
 
@@ -60,7 +63,8 @@ SKILL = Path(__file__).resolve().parent.parent
60
63
  sys.path.insert(0, str(SKILL / 'scripts'))
61
64
 
62
65
  import forge_registry # noqa: E402
63
- from forge_dataset import DatasetError, data_home, dataset_dir, enabled, harvest, importer, record_strict # noqa: E402
66
+ import forge_worktrees # noqa: E402
67
+ from forge_dataset import DatasetError, data_home, dataset_dir, enabled, harvest, importer, record, record_strict # noqa: E402
64
68
 
65
69
  OK, REFUSED, BUSY, FAILED = 0, 2, 3, 4
66
70
  # fullmatch: with `$` alone, a trailing newline would pass
@@ -249,6 +253,7 @@ class Run:
249
253
  self.branches = []
250
254
  self.removable = set() # paths of the worktrees --worktrees removes (or prunes, when missing on disk)
251
255
  self.wt_root = None
256
+ self.owners = {} # worktree path -> forge_worktrees kind (None: foreign), for the dataset events
252
257
 
253
258
 
254
259
  def identify(target):
@@ -285,7 +290,7 @@ def identify(target):
285
290
  seen.add(task)
286
291
  run.tasks.append(task)
287
292
  # forge-parallel.sh: wt_root="$(cd "$REPO/.." && pwd)/.forge-worktrees/$run_id", a logical cd
288
- run.wt_root = os.path.realpath(os.path.join(os.path.normpath(os.path.join(run.repo, '..')), '.forge-worktrees', run.run_id))
293
+ run.wt_root = forge_worktrees.wt_root(run.repo, run.run_id)
289
294
  if contains(path, run.wt_root) or contains(run.wt_root, path):
290
295
  raise Refused('refusing to delete %s: it overlaps the run\'s worktree root %s' % (path, run.wt_root))
291
296
  return run
@@ -446,8 +451,12 @@ def inspect_git(run):
446
451
  ours = wt['branch'] in branch_refs
447
452
  if not in_root and not ours:
448
453
  continue # the main worktree, or another run's: not this command's business
454
+ # forge_worktrees.owner is the rule forge-ui's Worktrees screen uses too: a task or integration branch in
455
+ # the run's folder, or a scratch worktree integrate or the culprit search left there.
456
+ kind = forge_worktrees.owner(wt['path'], wt['branch'], run.run_id, run.tasks, run.wt_root)
457
+ run.owners[wt['path']] = kind
449
458
  entry = dict(path=wt['path'], branch=(wt['branch'] or '').replace('refs/heads/', '', 1) or None,
450
- kind='run' if in_root and ours else 'foreign', dirty=None, removed=False, note='')
459
+ kind='run' if kind else 'foreign', dirty=None, removed=False, note='')
451
460
  if entry['kind'] == 'run':
452
461
  if not os.path.isdir(wt['path']):
453
462
  entry.update(dirty=False, note='missing on disk; `git worktree prune` forgets it')
@@ -583,6 +592,13 @@ def remove_worktrees(run):
583
592
  code, _, err = git(run.repo, 'worktree', 'remove', entry['path'])
584
593
  if code == 0:
585
594
  entry['removed'] = True
595
+ # Fail-open, like every capture: the removal happened whether or not the store took it.
596
+ kind = run.owners.get(entry['path']) or 'task'
597
+ removed = event(run, 'worktree_removed', path=entry['path'], branch=entry['branch'] or '-',
598
+ kind=kind, repo_path=run.repo, by='forge runs rm')
599
+ if kind == 'task' and entry['branch']:
600
+ removed['task'] = entry['branch'].split('/', 2)[-1]
601
+ record([removed], repo=run.repo, where='event:worktree_removed')
586
602
  else:
587
603
  entry['note'] = (err or 'git worktree remove exit %d' % code).splitlines()[0]
588
604
  problems.append('%s: %s' % (entry['path'], entry['note']))
@@ -632,11 +632,30 @@ def _codex_terminal_errors(events: list) -> list[str]:
632
632
  error = event.get('error')
633
633
  message = error.get('message') if isinstance(error, dict) else error
634
634
  pending.append(message if isinstance(message, str) else json.dumps(event))
635
+ elif kind == 'item.completed' and isinstance(event.get('item'), dict) and event['item'].get('type') == 'error':
636
+ pass # a notice ("Falling back from WebSockets to HTTPS"), not the run going on
635
637
  else:
636
638
  pending = [] # any later activity means the run went on past the error
637
639
  return pending
638
640
 
639
641
 
642
+ # codex's own words for a connection that never came up (#114). Only the message it stopped on
643
+ # answers to these, or stderr when it emitted no event at all: beside a turn, the same words on
644
+ # stderr are routine (an MCP server's transport, a model-list refresh) while the turn fails for its
645
+ # own reason, an early reconnect notice says nothing about a later failure, and "request timed out"
646
+ # in another harness's raw log may be a test's output.
647
+ _CODEX_NETWORK = _P(r"\bworkspace routing discovery (?:failed|timed out)\b|\berror sending request\b|\brequest timed out\b", re.I)
648
+ _CODEX_RECONNECTS_SPENT = _P(r"\bReconnecting\.\.\. (\d+)/\1\b")
649
+
650
+
651
+ def _codex_network(pending: list, now: float | None = None):
652
+ """A network stop when codex stopped on its own network wording, or after using up its
653
+ reconnect loop whatever it said next. None otherwise."""
654
+ if pending and (_CODEX_NETWORK.search(pending[-1]) or any(_CODEX_RECONNECTS_SPENT.search(m) for m in pending)):
655
+ return 'network', retry_after('\n'.join(pending), now), _one_line(pending[-1])
656
+ return None
657
+
658
+
640
659
  def _codex_final(events: list, last: str) -> str:
641
660
  try:
642
661
  path = Path(last) if last else None
@@ -681,11 +700,15 @@ def classify(log: str, harness: str, rc: object, last: str = '', role: str = '',
681
700
  if final.strip():
682
701
  return None
683
702
  if pending:
684
- hit = classify_text('\n'.join(pending), now=now)
703
+ hit = classify_text('\n'.join(pending), now=now) or _codex_network(pending, now)
685
704
  if hit:
686
705
  return hit
687
706
  return 'empty', None, 'codex finished with exit 0 but produced no final message'
688
- return classify_text('\n'.join(pending + [_tail(stray)]), now=now)
707
+ hit = classify_text('\n'.join(pending + [_tail(stray)]), now=now) or _codex_network(pending, now)
708
+ if hit or events:
709
+ return hit
710
+ # It died before its first event, so stderr is all it said and no turn gave another reason.
711
+ return _codex_network([line for line in stray if _CODEX_NETWORK.search(line)], now)
689
712
 
690
713
  if harness == 'opencode' and events:
691
714
  # Like codex: an error event counts when the run produced no answer after it.
@@ -631,6 +631,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
631
631
  backoff_warned = [] # an invalid infra_backoff file is reported once
632
632
  graceful = False # `forge control stop`: start nothing more, end once running tasks are done
633
633
  human = set() # tasks whose next dispatch is a `forge control retry` (dataset trigger human)
634
+ for name in tasks: # `retry --no-dispatch` (#118) prepared it for this run: still a person's retry
635
+ if (plan / 'tasks' / name / 'retry.prepared').exists():
636
+ retried.add(name)
637
+ human.add(name)
634
638
  fractal = _fractal_plan(plan)
635
639
  drain_told = False # the drained message was printed for this drain
636
640
  sweep_asked = False # this invocation already asked for the finding sweep
@@ -1083,8 +1087,6 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1083
1087
  return 'refused', (name + ' is waiting for your decision, and only a decision resumes it: '
1084
1088
  + decision_head(plan, name) + ' (retry --decide retry=N | threshold=Pn, or --dwarf SPEC,'
1085
1089
  + ' with --reason and --approved)')
1086
- if decide and dwarf:
1087
- return 'refused', 'give --decide or --dwarf, not both: a decision is one choice'
1088
1090
  if not (reason or '').strip() or not approved:
1089
1091
  return 'refused', name + ' is waiting for your decision: a decision needs --reason and --approved'
1090
1092
  decision = (['--decide', decide] if decide else []) + ['--reason', reason, '--approved']
@@ -1356,6 +1358,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1356
1358
  FORGE_DATASET_TRIGGER='human' if name in human else 'auto')
1357
1359
  if name in retried else None)
1358
1360
  human.discard(name)
1361
+ _remove(plan, 'tasks', name, 'retry.prepared')
1359
1362
  process = subprocess.Popen(
1360
1363
  ['/bin/bash', script, '_task', str(plan), name],
1361
1364
  stdout=log, stderr=subprocess.STDOUT, start_new_session=True, env=env,
@@ -229,6 +229,8 @@ def run(args) -> int:
229
229
  if bash('forge_review_snapshot', args.worktree, args.base, args.reviewed, str(review)).returncode:
230
230
  status = 'error'
231
231
  return 0
232
+ # The prompt is the primary's, so this checkout has to hold what it says.
233
+ bash('forge_review_deps', args.worktree, str(review), os.devnull)
232
234
  before = bash('forge_fingerprint', str(review), '--tracked').stdout.strip()
233
235
  shutil.copyfile(Path(args.tdir) / 'qa.input', out / 'qa.input')
234
236
  env = dict(os.environ, FORGE_SHADOW='1', FORGE_SHADOW_ATTEMPT=args.attempt,
@@ -362,6 +362,7 @@ fi
362
362
 
363
363
  REVIEW="$RUN/review-$(date +%s)-$$"
364
364
  forge_review_snapshot "$REPO" "$START" "$END" "$REVIEW" || die "cannot create review snapshot" 3
365
+ forge_review_deps "$REPO" "$REVIEW" "$RUN/review.deps"
365
366
  SOURCE_FP="$(forge_fingerprint "$REPO")" || exit 3
366
367
  [ "$(forge_tree "$REPO")" = "$END" ] || { echo INVALIDATED > "$RUN/verdict"; die "source changed while preparing QA" 5; }
367
368
  # The review snapshot is a commit; the reviewer's untracked leftovers there do not count (#95).
@@ -387,6 +388,9 @@ fi
387
388
  python3 "$SKILL_DIR/scripts/forge-prompt.py" --requirements "$RUN/prompt.md" --approach "$APPROACH" --goal "$RUN/goal.txt" --memory "$RUN/dwarf.memory" --memory "$RUN/qa.memory"
388
389
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind solo
389
390
  echo
391
+ cat "$RUN/review.deps"
392
+ [ -s "$RUN/failfirst.txt" ] || echo "Forge ran no tests of its own on this attempt, so nothing here stands in for yours."
393
+ echo
390
394
  if [ -s "$RUN/failfirst.txt" ]; then cat "$RUN/failfirst.txt"; echo; fi
391
395
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo --threshold "$THR"
392
396
  echo
@@ -422,6 +426,8 @@ dur_qa="$(sed -n 's/^duration_s=//p' "$RUN/qa.resolved" 2>/dev/null | tail -1)"
422
426
  # Otherwise forge enforces the severity rule itself, as a decomposed task's gate does; a gate
423
427
  # that cannot run (no output) keeps the reviewer's verdict.
424
428
  gate_note=""
429
+ tests_note="$(forge_tests_note "$RUN/qa.last")"
430
+ [ -z "$tests_note" ] || note "the reviewer's tests could not run: $tests_note"
425
431
  if [ -z "$NATIVE" ]; then
426
432
  gate_line="$(python3 "$SKILL_DIR/scripts/forge-contract.py" gate --verdict "${verdict:-UNKNOWN}" \
427
433
  --qa-last "$RUN/qa.last" --threshold "$THR" --known-issues "$RUN/known_issues.md" 2>/dev/null)" || gate_line=""
@@ -196,6 +196,16 @@ def run_reviewers(args) -> int:
196
196
  return reviewers.main(args)
197
197
 
198
198
 
199
+ def run_history(args) -> int:
200
+ from . import history
201
+ return history.main(args)
202
+
203
+
204
+ def run_worktrees(args) -> int:
205
+ from . import worktrees
206
+ return worktrees.main(args)
207
+
208
+
199
209
  def run_forecast(args) -> int:
200
210
  from . import forecast
201
211
  return forecast.main(args)
@@ -254,6 +264,12 @@ def parser() -> argparse.ArgumentParser:
254
264
  p.add_argument('--repo', help='only this repo')
255
265
  p.add_argument('--json', action='store_true')
256
266
  p.set_defaults(func=run_reviewers)
267
+ p = sub.add_parser('history', help="every review's findings and every learning, for forge-ui's Projects screen")
268
+ p.add_argument('--json', action='store_true')
269
+ p.set_defaults(func=run_history)
270
+ p = sub.add_parser('worktrees', help="the worktrees forge created and removed, for forge-ui's Worktrees screen")
271
+ p.add_argument('--json', action='store_true')
272
+ p.set_defaults(func=run_worktrees)
257
273
  p = sub.add_parser('forecast', help="a plan's likely tokens, time and first-try pass rate, from past tasks (advisory)")
258
274
  p.add_argument('plan', help='the plan dir')
259
275
  p.add_argument('--repo', help='only history from this repo')
@@ -635,6 +635,7 @@ def _qa_rows(runs: Runs):
635
635
  # Receipts from before findings_parse existed: an empty list then cannot
636
636
  # tell a clean review from a parser failure, which was rare; read it as clean.
637
637
  completeness=d.get('findings_parse') or review_completeness(d['verdict'], found),
638
+ tests=d.get('tests'),
638
639
  worst=_worst(found),
639
640
  # The dispatch this row was built from. A shadow pair names that event,
640
641
  # so an earlier execution of the same attempt cannot claim it.
@@ -170,6 +170,14 @@ def findings(message: str | None) -> list:
170
170
  return parse_review(message)[0]
171
171
 
172
172
 
173
+ def review_tests(message: str | None) -> dict | None:
174
+ """What a QA reply says about its tests; None when it does not, or the contract cannot load."""
175
+ try:
176
+ return contract().tests_report(message) if message else None
177
+ except Exception:
178
+ return None
179
+
180
+
173
181
  def parse_review(message: str | None) -> tuple[list, bool]:
174
182
  """(findings, parsed): parsed is False when the contract's parser raised."""
175
183
  if not message:
@@ -305,6 +313,8 @@ def locate(root: str | Path, role: str | None = None) -> dict:
305
313
  plan, ctx['scope'] = p.parent.parent, 'final_review'
306
314
  elif p.name.startswith('integrate-') and (p.parent / 'tasks.tsv').exists():
307
315
  plan, ctx['scope'] = p.parent, 'integrate'
316
+ elif p.name.startswith('adopt-') and (p.parent / 'tasks.tsv').exists():
317
+ plan, ctx['scope'] = p.parent, 'adopt'
308
318
  elif (p / 'tasks.tsv').exists() or (p / 'run_id').exists():
309
319
  plan, ctx['scope'] = p, 'plan'
310
320
  if plan is not None:
@@ -438,6 +448,7 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
438
448
  prompt_bytes=metrics.get('prompt_bytes'), final_source=final_source,
439
449
  verdict=verdict, findings=found, learnings=learnings(message),
440
450
  findings_parse=review_completeness(verdict, found, parsed) if role == 'qa' else None,
451
+ tests=review_tests(message) if role == 'qa' else None,
441
452
  session_id=session_id, session_continue=session_continue,
442
453
  root=str(root), scope=prov.get('scope'), trigger=prov.get('trigger'),
443
454
  **({'shadow': shadow} if shadow else {}),