@giamme/forge 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +16 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +81 -14
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +84 -15
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +20 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +621 -33
  17. package/references/harnesses.md +18 -3
  18. package/references/planning.md +43 -14
  19. package/references/ui.md +53 -6
  20. package/registry.tsv +8 -3
  21. package/scripts/forge-brief.py +88 -3
  22. package/scripts/forge-compare.py +4 -3
  23. package/scripts/forge-contract.py +202 -27
  24. package/scripts/forge-control.py +117 -5
  25. package/scripts/forge-dispatch.sh +34 -5
  26. package/scripts/forge-group.py +496 -0
  27. package/scripts/forge-groups.py +89 -0
  28. package/scripts/forge-handoff.py +1128 -0
  29. package/scripts/forge-lib-group.sh +641 -0
  30. package/scripts/forge-lib-plans.sh +339 -3
  31. package/scripts/forge-lib-task.sh +197 -4
  32. package/scripts/forge-memory.sh +245 -3
  33. package/scripts/forge-parallel.sh +715 -34
  34. package/scripts/forge-planner.py +104 -8
  35. package/scripts/forge-route.py +190 -12
  36. package/scripts/forge-runs.py +9 -5
  37. package/scripts/forge-schedule.py +354 -45
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-worktrees.py +243 -0
  40. package/scripts/forge_brief/__init__.py +294 -50
  41. package/scripts/forge_brief/answers.py +58 -11
  42. package/scripts/forge_brief/proposals.py +1630 -0
  43. package/scripts/forge_dataset/efforts.py +4 -3
  44. package/scripts/forge_dataset/export.py +24 -12
  45. package/scripts/forge_dataset/facts.py +5 -3
  46. package/scripts/forge_dataset/forecast.py +8 -18
  47. package/scripts/forge_dataset/harvest.py +204 -9
  48. package/scripts/forge_dataset/history.py +11 -6
  49. package/scripts/forge_dataset/importer.py +65 -1
  50. package/scripts/forge_dataset/names.py +66 -0
  51. package/scripts/forge_dataset/reviewers.py +5 -2
  52. package/scripts/forge_dataset/risk.py +6 -3
  53. package/scripts/forge_dataset/routing.py +6 -1
  54. package/scripts/forge_groups/__init__.py +308 -0
  55. package/scripts/forge_groups/attribute.py +289 -0
  56. package/scripts/forge_groups/review.py +286 -0
  57. package/scripts/forge_owner.py +152 -0
  58. package/scripts/forge_side/__init__.py +12 -7
  59. package/ui/docs/api.md +173 -17
  60. package/ui/forge_ui/control.py +361 -2
  61. package/ui/forge_ui/executions.py +8 -1
  62. package/ui/forge_ui/export.py +31 -4
  63. package/ui/forge_ui/groups.py +264 -0
  64. package/ui/forge_ui/models.py +70 -8
  65. package/ui/forge_ui/reader.py +262 -19
  66. package/ui/forge_ui/server.py +4 -0
  67. package/ui/forge_ui/static/app.js +93 -13
  68. package/ui/forge_ui/static/briefview.js +350 -47
  69. package/ui/forge_ui/static/diffview.js +86 -1
  70. package/ui/forge_ui/static/groupsview.js +332 -0
  71. package/ui/forge_ui/static/index.html +1 -0
  72. package/ui/forge_ui/static/panel.js +127 -7
  73. package/ui/forge_ui/static/projectsview.js +189 -10
  74. package/ui/forge_ui/static/runmodel.js +14 -3
  75. package/ui/forge_ui/static/storageview.js +91 -10
  76. package/ui/forge_ui/static/style.css +79 -5
  77. package/ui/forge_ui/static/worktreesview.js +233 -12
  78. package/ui/forge_ui/storage.py +14 -0
@@ -33,6 +33,11 @@
33
33
  # forge-parallel.sh split <plan-dir> <new-plan> --tasks <id,id> [--dry-run]
34
34
  # forge-parallel.sh combine <new-plan> <plan-a> <plan-b> [<plan>...] [--verify <command>] [--dry-run]
35
35
  # forge-parallel.sh _task <plan-dir> <task-id> (internal; coordinator target)
36
+ # forge-parallel.sh _group <plan-dir> <group-id> (internal; one QA review of a review=group group, #140)
37
+ # forge-parallel.sh _group_settle <plan-dir> <group-id> [--tasks a,b]
38
+ # (internal; send a FAIL group's implicated members back, #140)
39
+ # forge-parallel.sh _merge_group <plan-dir> <group-id>
40
+ # (internal; merge a PASS group's members with one merge, #140)
36
41
  # forge-parallel.sh _qa_only <plan-dir> <task-id> (internal; exit 0 when the next entry only re-runs QA)
37
42
  # forge-parallel.sh _waves <plan-dir> (internal; rewrite waves.tsv after a live `forge control add`)
38
43
  # forge-parallel.sh _sweep <plan-dir> --severity Pn [--plausible] [--max N]
@@ -49,16 +54,36 @@
49
54
  # by a listed reviewer of another model family, recorded and
50
55
  # never read (measures reviewer agreement). `none` turns it off
51
56
  # --shadow-rate R that share, 0..1 (default 0.1)
57
+ # --groups waves|FILE opt-in (#140): groups.tsv from the computed waves, or from FILE; a
58
+ # groups.tsv already in the plan dir is used as is. Validated, its
59
+ # group qa resolved and frozen (groups.frozen); `run` refuses when
60
+ # it or a member's deps/files changed since
61
+ # --group-review with --groups waves: the derived groups get review=group (one QA
62
+ # review for the whole group; high-difficulty tasks stay out)
63
+ # --group-max-tasks N most members of a review group (default 6)
64
+ # --group-max-diff-kb N most diff a group review reads, in KB (default 256; kept in the plan)
52
65
  # --reviewer-session opt-in experiment: a later review round continues the reviewer's
53
66
  # earlier session (claude, openclaude, codex) when the QA spec is
54
67
  # unchanged, and starts fresh whenever it cannot; each round is
55
68
  # logged in tasks/<id>/review_sessions.tsv and tagged in the
56
69
  # dataset. `--no-reviewer-session` turns it off (the default)
70
+ # --reviewer-session-rate R the same, on a sampled share R of the tasks only (implies
71
+ # --reviewer-session): round(R x n) tasks of each difficulty, picked by
72
+ # a hash of the run id and task id; the others review fresh and log
73
+ # `not-sampled`, so the two halves can be compared
57
74
  # --implementer-session opt-in: a retry continues the implementer's earlier session
58
75
  # (claude, openclaude) when its spec is unchanged and its work is
59
76
  # still what the review judged, and starts fresh whenever it cannot;
60
77
  # each attempt is logged in tasks/<id>/implementer_sessions.tsv.
61
78
  # `--no-implementer-session` turns it off (the default)
79
+ # --retry-per-model N a task may fail N times (1-99) on each model the retry policy
80
+ # gives it, then it moves a rung up. Replaces --escalate-after for
81
+ # this plan. Kept in retry_per_model. `--no-retry-per-model` removes
82
+ # it; a re-plan with neither keeps the file
83
+ # --after PREV start this plan from plan PREV's integration branch (#143): PREV must be
84
+ # fully merged, on its accepted tip, not running, and in the same repo.
85
+ # Kept in `after` (PREV's path) and `integration.base`; plan creates
86
+ # forge/<run>-integration there. A re-plan without the flag keeps it
62
87
  # --retro | --no-retro agents record what got in their way (retro, #132); plan file `retro_mode`
63
88
  # (on or off; not `retro`, the notes directory). Without a flag the plan
64
89
  # keeps its earlier choice, else (first plan only) takes the user
@@ -160,7 +185,7 @@ JEV_OPTS=0
160
185
  # Flags shared by several subcommands, then the helper libraries. Functions only, resolved
161
186
  # at call time, so they may use die/note/field and friends defined below.
162
187
  source "$SKILL_DIR/scripts/forge-parallel-options.sh"
163
- for forge_lib in task gates verify attribute plans review adopt; do
188
+ for forge_lib in task gates verify attribute plans review adopt group; do
164
189
  [ -f "$SKILL_DIR/scripts/forge-lib-$forge_lib.sh" ] && source "$SKILL_DIR/scripts/forge-lib-$forge_lib.sh"
165
190
  done
166
191
  OUTPUT=summary
@@ -220,6 +245,16 @@ pool_pick() { # pool_pick <comma-list> <index>
220
245
  echo "$last"
221
246
  }
222
247
 
248
+ # `script` is a task kind (tasks/<id>/run), not a model. A pool that can hand it out would
249
+ # make a blank row look scripted without a run file, or run a model under that name.
250
+ forge_refuse_script_pool() { # forge_refuse_script_pool <flag> <comma-list>
251
+ local spec
252
+ for spec in $(printf '%s' "${2:-}" | tr ',' ' '); do
253
+ [ "$spec" = script ] || continue
254
+ die "the $1 pool names 'script', which is reserved for a task that runs tasks/<id>/run"
255
+ done
256
+ }
257
+
223
258
  # --- profiles (#48) -------------------------------------------------------------
224
259
  # A named profile is chosen at `plan` (or by forge-solo.sh), frozen as <dir>/profile.json
225
260
  # and applied as the values its flags would have set. forge_decide.profiles does the
@@ -584,24 +619,172 @@ forge_features_table() { # forge_features_table <plan>
584
619
  return 0
585
620
  }
586
621
 
622
+ # --- groups (#140) -----------------------------------------------------------------
623
+ # groups.tsv is the plan's frozen sets of tasks (scripts/forge_groups, forge-groups.py). Opt-in:
624
+ # with no groups.tsv, no --groups and no groups.frozen, nothing here runs or writes.
625
+ forge_groups_py() { python3 "$SKILL_DIR/scripts/forge-groups.py" "$@"; }
626
+
627
+ # forge_groups_id_of <plan> <task>: the id of the task's group, empty when it is in none.
628
+ forge_groups_id_of() { forge_groups_py of "$1" "$2" 2>/dev/null | awk -F'\t' 'NR == 1 { print $1 }'; }
629
+
630
+ # forge_groups_die <message from forge-groups.py>: its one-line message, without the prefix, exit 2.
631
+ forge_groups_die() { local msg="$1"; die "${msg#forge-groups: }" 2; }
632
+
633
+ # forge_groups_have_review <plan>: 0 when some group has review=group.
634
+ forge_groups_have_review() {
635
+ [ -f "$1/groups.tsv" ] || return 1
636
+ forge_groups_py show "$1" 2>/dev/null | awk -F'\t' '$2 == "group" { found = 1 } END { exit !found }'
637
+ }
638
+
639
+ # forge_groups_max_tasks <plan> [flag]: the flag, else the plan's group_max_tasks, else 6.
640
+ forge_groups_max_tasks() {
641
+ local value="${2:-}"
642
+ [ -n "$value" ] || value="$(head -1 "$1/group_max_tasks" 2>/dev/null)"
643
+ printf '%s' "${value:-6}"
644
+ }
645
+
646
+ # Put back the groups a refused derive replaced, or remove the ones it just wrote.
647
+ # A Fractal refusal must not leave a review=group groups.tsv that makes every later plan exit 2.
648
+ forge_groups_snap_restore() { # forge_groups_snap_restore <plan> <snap dir or empty>
649
+ local plan="$1" snap="${2:-}"
650
+ if [ -n "$snap" ] && [ -f "$snap/groups.tsv" ]; then cp "$snap/groups.tsv" "$plan/groups.tsv"
651
+ else rm -f "$plan/groups.tsv"; fi
652
+ if [ -n "$snap" ] && [ -f "$snap/groups.frozen" ]; then cp "$snap/groups.frozen" "$plan/groups.frozen"
653
+ else rm -f "$plan/groups.frozen"; fi
654
+ [ -z "$snap" ] || rm -rf "$snap"
655
+ }
656
+
657
+ forge_groups_snap_drop() { [ -z "${1:-}" ] || rm -rf "$1"; }
658
+
659
+ # forge_groups_plan <plan> <--groups value> <--group-review 0|1> <--group-max-tasks value>
660
+ forge_groups_plan() {
661
+ local plan="$1" src="$2" review="$3" max="$4" out="" snap=""
662
+ # derive and a --groups file replace groups.tsv before the Fractal check can refuse them.
663
+ if [ -f "$plan/groups.tsv" ] || [ -f "$plan/groups.frozen" ]; then
664
+ snap="$(mktemp -d)" || die "could not snapshot the plan's groups" 3
665
+ [ ! -f "$plan/groups.tsv" ] || cp "$plan/groups.tsv" "$snap/groups.tsv" \
666
+ || { forge_groups_snap_drop "$snap"; die "could not snapshot $plan/groups.tsv" 3; }
667
+ [ ! -f "$plan/groups.frozen" ] || cp "$plan/groups.frozen" "$snap/groups.frozen" \
668
+ || { forge_groups_snap_drop "$snap"; die "could not snapshot $plan/groups.frozen" 3; }
669
+ fi
670
+ if [ "$src" = waves ]; then
671
+ out="$(forge_groups_py derive "$plan" --review "$([ "$review" = 1 ] && echo group || echo task)" \
672
+ --max-tasks "$(forge_groups_max_tasks "$plan" "$max")" 2>&1)" || { forge_groups_snap_drop "$snap"; forge_groups_die "$out"; }
673
+ elif [ -n "$src" ]; then
674
+ cp "$src" "$plan/groups.tsv" || { forge_groups_snap_drop "$snap"; die "could not copy '$src' to $plan/groups.tsv" 3; }
675
+ fi
676
+ if [ ! -f "$plan/groups.tsv" ] && [ ! -f "$plan/groups.frozen" ]; then
677
+ forge_groups_snap_drop "$snap"
678
+ return 0
679
+ fi
680
+ # validate, then resolve (writes the group qa back), then freeze
681
+ out="$(forge_groups_py validate "$plan" --max-tasks "$(forge_groups_max_tasks "$plan" "$max")" 2>&1)" \
682
+ || { forge_groups_snap_drop "$snap"; forge_groups_die "$out"; }
683
+ if forge_groups_have_review "$plan" && forge_plan_is_fractal "$plan"; then
684
+ forge_groups_snap_restore "$plan" "$snap"
685
+ die "group review does not support Fractal yet" 2
686
+ fi
687
+ forge_groups_snap_drop "$snap"
688
+ out="$(forge_groups_py resolve "$plan" 2>&1)" || forge_groups_die "$out"
689
+ out="$(forge_groups_py freeze "$plan" 2>&1)" || forge_groups_die "$out"
690
+ return 0
691
+ }
692
+
693
+ # Group flags are refused before do_plan's loop writes a shared flag's file.
694
+ # A bad value, or --group-review without --groups waves, must not leave --qa-threshold
695
+ # (or any earlier shared flag) written into the plan dir.
696
+ forge_groups_flags_early() {
697
+ local review=0 src=""
698
+ while [ $# -gt 0 ]; do
699
+ case "$1" in
700
+ --groups)
701
+ [ -n "${2:-}" ] || die "--groups needs waves or a groups.tsv file"
702
+ if [ "$2" != waves ]; then
703
+ [ -f "$2" ] && [ -r "$2" ] || die "--groups '$2' is not a readable file (use waves, or a groups.tsv)"
704
+ fi
705
+ src="$2"; shift 2 ;;
706
+ --group-review) review=1; shift ;;
707
+ --group-max-tasks)
708
+ printf '%s' "${2:-}" | grep -Eq '^[0-9]{1,6}$' && [ "$((10#$2))" -ge 1 ] \
709
+ || die "--group-max-tasks needs a positive integer"
710
+ shift 2 ;;
711
+ --group-max-diff-kb)
712
+ printf '%s' "${2:-}" | grep -Eq '^[0-9]{1,9}$' && [ "$((10#$2))" -ge 1 ] \
713
+ || die "--group-max-diff-kb needs a positive integer"
714
+ shift 2 ;;
715
+ --repo|--after|--planner|--decompose-level|--profile|--shadow-qa|--shadow-rate|--explore|--dwarf|--dwarf-high|--dwarf-medium|--dwarf-low|--qa|--qa-high|--qa-medium|--qa-low|--pre-review-parallel|--reviewer-session-rate|--fast|--brief|--brief-scope|--brief-model|--summaries|--summaries-model|--qa-threshold|--max-attempts|--converge-window|--gate|--decide-budget)
716
+ if [ $# -ge 2 ]; then shift 2; else shift; fi ;;
717
+ *) shift ;;
718
+ esac
719
+ done
720
+ [ "$review" = 0 ] || [ "$src" = waves ] || die "--group-review goes with --groups waves (it sets the review of the groups waves derives)"
721
+ }
722
+
723
+ # render_groups <plan>: the table's groups block and, when a group reviews its members together,
724
+ # the reviews line. Nothing without a groups.tsv.
725
+ render_groups() {
726
+ [ -f "$1/groups.tsv" ] || return 0
727
+ python3 - "$SKILL_DIR/scripts" "$1" "$(printf '%q' "$1")" <<'PY'
728
+ import sys
729
+ sys.path.insert(0, sys.argv[1])
730
+ import forge_groups
731
+ try:
732
+ groups = forge_groups.load(sys.argv[2])
733
+ except forge_groups.GroupError:
734
+ groups = []
735
+ if groups:
736
+ qas = ['qa=' + g.qa if g.qa != '-' else '-' for g in groups]
737
+ ids = max(len(g.id) for g in groups)
738
+ qa_w = max(len(q) for q in qas)
739
+ members = [', '.join(g.members) for g in groups]
740
+ mem_w = max(len(m) for m in members)
741
+ print('groups:')
742
+ for g, q, m in zip(groups, qas, members):
743
+ goal = g.goal if g.goal != '-' else '(no goal)'
744
+ print(' %-*s %-12s %-*s %-*s — %s' % (ids, g.id, 'review=' + g.review, qa_w, q, mem_w, m,
745
+ goal if g.title == '-' else '%s: %s' % (g.title, goal)))
746
+ missing = [g.id for g in groups if g.goal == '-']
747
+ if missing:
748
+ # A goal is what a group review and a brief prompt say the group is for (#136).
749
+ print('%d group(s) have no goal (%s): set one with forge group set %s GID --goal "..."'
750
+ % (len(missing), ', '.join(missing), sys.argv[3]))
751
+ print()
752
+ PY
753
+ }
754
+
755
+ # forge_groups_review_counts <plan>: "<groups> <members>" of the review=group groups, or nothing.
756
+ forge_groups_review_counts() {
757
+ [ -f "$1/groups.tsv" ] || return 0
758
+ forge_groups_py show "$1" 2>/dev/null | awk -F'\t' '$2 == "group" { g++; m += split($4, a, ",") } END { if (g) print g, m }'
759
+ }
760
+
587
761
  do_plan() {
588
762
  local PLAN="${1:?plan needs a plan dir}"; shift
589
763
  local PF_NAME="" PF_NONE=0 PF_QT=0
590
764
  forge_profile_precheck "$PLAN" "$@"
591
765
  local REPO="" D_ANY="" D_HI="" D_MD="" D_LO="" Q_ANY="" Q_HI="" Q_MD="" Q_LO=""
592
766
  PP_INFRA_FALLBACK=""
593
- local PLANNER="" NOMEM=0 jev_rc=0 DLEVEL="" SHADOW_QA="" SHADOW_RATE="" EXPLORE="" FAIL_FIRST="" REVIEWER_SESSION="" IMPLEMENTER_SESSION="" PRE_REVIEW="" PRE_REVIEW_PARALLEL=""
767
+ local PLANNER="" NOMEM=0 jev_rc=0 DLEVEL="" SHADOW_QA="" SHADOW_RATE="" EXPLORE="" FAIL_FIRST="" REVIEWER_SESSION="" RS_RATE="" IMPLEMENTER_SESSION="" PRE_REVIEW="" PRE_REVIEW_PARALLEL=""
594
768
  local FAST_GIVEN=0 FAST_PARSED=""
595
769
  local RETRO_FLAG="" BRIEF_FLAG="" BRIEF_SCOPE_FLAG="" BRIEF_MODEL_FLAG="" SUMM_FLAG="" SUMM_MODEL_FLAG=""
596
- local COLLAPSE=0 COLLAPSED_NOW=0 FEAT_ERR=""
770
+ local RETRY_PER_MODEL=""
771
+ local COLLAPSE=0 COLLAPSED_NOW=0 FEAT_ERR="" GRP_SRC="" GRP_REVIEW=0 GRP_MAX="" GRP_DIFF=""
772
+ local CHAIN_PREV="" CHAIN_BASE="" CHAIN_MOVE=0
597
773
  # The retro, brief and summaries choices, settled before anything is written: a refusal
598
774
  # (a bad value, no model, a spec that does not resolve) leaves the plan dir as it was.
599
775
  forge_features_scan "$@"
600
776
  [ -d "$PLAN" ] || die "plan dir '$PLAN' does not exist"
601
777
  forge_features_resolve "$PLAN" || die "$FEAT_ERR" 2
778
+ # --after (#143), settled before anything is written: every refusal leaves the plan dir and the
779
+ # branches as they were. Its files and the integration branch are written below, once the repo is known.
780
+ plans_chain_early "$PLAN" "$@"
781
+ # Before the loop: --qa-threshold and --max-attempts write their files while parsing,
782
+ # so a group flag refused later on the same command would leave those files behind.
783
+ forge_groups_flags_early "$@"
602
784
  while [ $# -gt 0 ]; do
603
785
  case "$1" in
604
786
  --repo) REPO="${2:?}"; shift 2 ;;
787
+ --after) [ -n "${2:-}" ] || die "--after needs a plan directory" 2; shift 2 ;;
605
788
  --planner) PLANNER="${2:?}"; shift 2 ;;
606
789
  --decompose-level)
607
790
  case "${2:-}" in low|medium|high) DLEVEL="$2"; shift 2 ;;
@@ -617,6 +800,19 @@ do_plan() {
617
800
  printf '%s' "${2:-}" | grep -Eq '^(0?\.[0-9]+|0|1|1\.0+)$' || die "--shadow-rate needs a share between 0 and 1"
618
801
  SHADOW_RATE="$2"; shift 2 ;;
619
802
  --explore) EXPLORE="${2:?--explore needs a share between 0 and 0.5}"; shift 2 ;;
803
+ --groups)
804
+ [ -n "${2:-}" ] || die "--groups needs waves or a groups.tsv file"
805
+ if [ "$2" != waves ]; then
806
+ [ -f "$2" ] && [ -r "$2" ] || die "--groups '$2' is not a readable file (use waves, or a groups.tsv)"
807
+ fi
808
+ GRP_SRC="$2"; shift 2 ;;
809
+ --group-review) GRP_REVIEW=1; shift ;;
810
+ --group-max-tasks)
811
+ printf '%s' "${2:-}" | grep -Eq '^[0-9]{1,6}$' && [ "$((10#$2))" -ge 1 ] || die "--group-max-tasks needs a positive integer"
812
+ GRP_MAX="$((10#$2))"; shift 2 ;;
813
+ --group-max-diff-kb)
814
+ printf '%s' "${2:-}" | grep -Eq '^[0-9]{1,9}$' && [ "$((10#$2))" -ge 1 ] || die "--group-max-diff-kb needs a positive integer"
815
+ GRP_DIFF="$((10#$2))"; shift 2 ;;
620
816
  --collapse-chains) COLLAPSE=1; shift ;;
621
817
  --dwarf) D_ANY="${2:?}"; shift 2 ;;
622
818
  --dwarf-high) D_HI="${2:?}"; shift 2 ;;
@@ -636,7 +832,15 @@ do_plan() {
636
832
  || die "--pre-review-parallel needs an integer from 1 to 64" 2
637
833
  PRE_REVIEW_PARALLEL="$((10#$2))"; shift 2 ;;
638
834
  --reviewer-session) REVIEWER_SESSION=on; shift ;;
639
- --no-reviewer-session) REVIEWER_SESSION=off; shift ;;
835
+ --no-reviewer-session) REVIEWER_SESSION=off; RS_RATE=""; shift ;;
836
+ --reviewer-session-rate)
837
+ printf '%s' "${2:-}" | grep -Eq '^(0?\.[0-9]+|0|1|1\.0+)$' || die "--reviewer-session-rate needs a share between 0 and 1"
838
+ REVIEWER_SESSION=on; RS_RATE="$2"; shift 2 ;;
839
+ --retry-per-model)
840
+ printf '%s' "${2:-}" | grep -Eq '^[1-9][0-9]?$' \
841
+ || die "--retry-per-model needs an integer from 1 to 99" 2
842
+ RETRY_PER_MODEL="$((10#$2))"; shift 2 ;;
843
+ --no-retry-per-model) RETRY_PER_MODEL=off; shift ;;
640
844
  --implementer-session) IMPLEMENTER_SESSION=on; shift ;;
641
845
  --no-implementer-session) IMPLEMENTER_SESSION=off; shift ;;
642
846
  --fast)
@@ -666,9 +870,15 @@ do_plan() {
666
870
  esac
667
871
  done
668
872
  [ -d "$PLAN" ] || die "plan dir '$PLAN' does not exist"
873
+ [ "$GRP_REVIEW" = 0 ] || [ "$GRP_SRC" = waves ] || die "--group-review goes with --groups waves (it sets the review of the groups waves derives)"
669
874
  # The profile (#48) first: its gates and budget count for every decision-model step below,
670
875
  # and its values stand in for the flags this call did not give.
671
876
  forge_profile_plan
877
+ # Pools are flags or the profile just applied. `script` in either is a reserved word.
878
+ forge_refuse_script_pool --dwarf "$D_ANY"
879
+ forge_refuse_script_pool --dwarf-high "$D_HI"
880
+ forge_refuse_script_pool --dwarf-medium "$D_MD"
881
+ forge_refuse_script_pool --dwarf-low "$D_LO"
672
882
  [ "$JEV_OPTS" = 1 ] && forge_jev_export
673
883
  # Freeze the selection next to the task table, so run and retry restore it rather
674
884
  # than re-deciding. Written on every plan: a re-plan is a new decision.
@@ -693,6 +903,10 @@ do_plan() {
693
903
  esac
694
904
  [ -z "$SHADOW_RATE" ] || [ "$SHADOW_QA" = none ] || [ "$SHADOW_QA" = off ] \
695
905
  || printf '%s\n' "$SHADOW_RATE" > "$PLAN/shadow_rate"
906
+ # Group options (#140): kept as plan files, only when given, so a re-plan, retry, rerun or split
907
+ # keeps what the plan was made with.
908
+ [ -z "$GRP_MAX" ] || printf '%s\n' "$GRP_MAX" > "$PLAN/group_max_tasks"
909
+ [ -z "$GRP_DIFF" ] || printf '%s\n' "$GRP_DIFF" > "$PLAN/group_max_diff_kb"
696
910
  # Fail-first evidence (opt-in, advisory) is part of the plan too: every task's review gets it.
697
911
  case "$FAIL_FIRST" in on) : > "$PLAN/fail_first" ;; off) rm -f "$PLAN/fail_first" ;; esac
698
912
  # Pre-review tests (opt-in, #85): each attempt's affected tests run before its review, and a
@@ -703,8 +917,24 @@ do_plan() {
703
917
  # Reviewer-session continuation (opt-in experiment): the file holds `on`. Readers only
704
918
  # test that it exists; the dataset records its content.
705
919
  case "$REVIEWER_SESSION" in on) printf '%s\n' on > "$PLAN/reviewer_session" ;; off) rm -f "$PLAN/reviewer_session" ;; esac
920
+ # A sampled share (--reviewer-session-rate): which tasks continue, fixed now so a re-plan or a
921
+ # retry never moves a task between the two halves. `--reviewer-session` alone means every task.
922
+ if [ -n "$RS_RATE" ]; then
923
+ printf '%s\n' "$RS_RATE" > "$PLAN/reviewer_session_rate"
924
+ reviewer_session_pick "$PLAN" "$RS_RATE" > "$PLAN/reviewer_session_tasks.tmp" \
925
+ && mv "$PLAN/reviewer_session_tasks.tmp" "$PLAN/reviewer_session_tasks" \
926
+ || die "could not pick the reviewer-session tasks" 3
927
+ elif [ "$REVIEWER_SESSION" = on ] || [ "$REVIEWER_SESSION" = off ]; then
928
+ rm -f "$PLAN/reviewer_session_rate" "$PLAN/reviewer_session_tasks"
929
+ fi
706
930
  # Implementer-session continuation (opt-in, #90): the same `on` file, read the same way.
707
931
  case "$IMPLEMENTER_SESSION" in on) printf '%s\n' on > "$PLAN/implementer_session" ;; off) rm -f "$PLAN/implementer_session" ;; esac
932
+ # N failures on each rung (#141). Omitted on a re-plan, so an earlier choice stays.
933
+ case "$RETRY_PER_MODEL" in
934
+ '') ;;
935
+ off) rm -f "$PLAN/retry_per_model" ;;
936
+ *) printf '%s\n' "$RETRY_PER_MODEL" > "$PLAN/retry_per_model" || die "could not write $PLAN/retry_per_model" ;;
937
+ esac
708
938
  # Which roles ask for the fast tier. Omitted on a re-plan, so an earlier choice stays.
709
939
  forge_fast_store "$PLAN"
710
940
  # Retro, brief and summaries (#132, #133, #135), as forge_features_resolve settled them.
@@ -766,7 +996,7 @@ PY
766
996
  # Uncommitted work is invisible to every dwarf, because worktrees branch from a
767
997
  # commit. That is the likeliest way to get a confusingly wrong result, so it is
768
998
  # stated loudly rather than left for the user to deduce from an odd diff.
769
- if [ -n "$(cd "$REPO" && git status --porcelain 2>/dev/null)" ]; then
999
+ if [ ! -s "$PLAN/after" ] && [ -z "${CHAIN_PREV:-}" ] && [ -n "$(cd "$REPO" && git status --porcelain 2>/dev/null)" ]; then
770
1000
  note "WARNING: '$REPO' has uncommitted changes. Task worktrees branch from HEAD,"
771
1001
  note " so those edits will NOT be visible to any dwarf. Commit or stash first"
772
1002
  note " if the tasks depend on them."
@@ -898,8 +1128,12 @@ EOF
898
1128
  fi
899
1129
  # resolve dwarf. UNASSIGNED is a marker from a previous plan, not a user
900
1130
  # choice, so it must be re-resolved rather than preserved like a real override.
1131
+ # `script` is an override too: no pool, no exploration, and the cell stays `script`.
901
1132
  [ "$dw" = "UNASSIGNED" ] && dw="-"
902
- if [ "$dw" = "-" ] || [ -z "$dw" ]; then
1133
+ if [ "$dw" = "script" ]; then
1134
+ [ -x "$PLAN/tasks/$id/run" ] \
1135
+ || die "task '$id' is a script task but tasks/$id/run is missing or not executable"
1136
+ elif [ "$dw" = "-" ] || [ -z "$dw" ]; then
903
1137
  case "$diff" in
904
1138
  high) if [ -n "$D_HI" ]; then dw="$(pool_pick "$D_HI" "$hi_i")"; hi_i=$((hi_i+1)); fi ;;
905
1139
  medium) if [ -n "$D_MD" ]; then dw="$(pool_pick "$D_MD" "$md_i")"; md_i=$((md_i+1)); fi ;;
@@ -947,6 +1181,8 @@ EOF
947
1181
  fi
948
1182
 
949
1183
  compute_waves "$PLAN"
1184
+ # Only once tasks.tsv has passed its checks: a refused plan leaves no after, integration.base or branch.
1185
+ plans_chain_store "$PLAN" "$REPO" "$(cat "$PLAN/run_id")"
950
1186
 
951
1187
  # --- jev: forward dependency ----------------------------------------------------
952
1188
  # Wave order is structural, but it cannot see an earlier-wave task written against
@@ -996,6 +1232,10 @@ EOF
996
1232
  note "plan shape could not be recorded (advisory)${shape_err:+: $shape_err}"
997
1233
  fi
998
1234
 
1235
+ # Groups (#140): after the last wave computation and the last change to a task's deps, so the
1236
+ # frozen fingerprint is of the table the run will use.
1237
+ forge_groups_plan "$PLAN" "$GRP_SRC" "$GRP_REVIEW" "$GRP_MAX"
1238
+
999
1239
  render_table "$PLAN"
1000
1240
  # What the gates did, from plan-gates.json: files and deps they added, prompts and
1001
1241
  # requirements still flagged. Prints nothing when no gate recorded anything.
@@ -1064,18 +1304,75 @@ compute_waves() {
1064
1304
  mv -f "$D" "$PLAN/deferrals.txt" && mv -f "$W" "$PLAN/waves.tsv"
1065
1305
  }
1066
1306
 
1307
+ # Under the dispatch estimate when the plan set --retry-per-model (#141). Nothing without the file.
1308
+ # The worst case and the tasks the attempt cap cuts short come from forge-route.py worst-case.
1309
+ render_retry_per_model() { # render_retry_per_model <plan>
1310
+ [ -f "$1/retry_per_model" ] || return 0
1311
+ python3 - "$SKILL_DIR/scripts/forge-route.py" "$1" <<'PY'
1312
+ import json, re, subprocess, sys
1313
+ route, plan = sys.argv[1], sys.argv[2]
1314
+ try:
1315
+ n = open(plan + '/retry_per_model', encoding='utf-8').read().strip()
1316
+ except OSError:
1317
+ sys.exit(0)
1318
+ print('retry per model: %s (a task may fail %s times on each model the retry policy gives it, then it moves a rung up)' % (n, n))
1319
+ try:
1320
+ raw = subprocess.check_output([sys.executable, route, 'worst-case', '--plan', plan], text=True)
1321
+ data = json.loads(raw)
1322
+ except (OSError, subprocess.CalledProcessError, ValueError):
1323
+ sys.exit(0)
1324
+ print('worst case with retry-per-model %s: %s dispatches' % (n, data.get('total', 0)))
1325
+ capped = data.get('capped') or []
1326
+ if not capped:
1327
+ sys.exit(0)
1328
+ cap = 8
1329
+ try:
1330
+ text = open(plan + '/max_attempts', encoding='utf-8').read().strip()
1331
+ except OSError:
1332
+ text = ''
1333
+ if re.fullmatch(r'[0-9]{1,9}', text):
1334
+ cap = int(text)
1335
+ print('max-attempts %s stops these tasks before the top of their ladder: %s (plan --max-attempts N raises it)'
1336
+ % (cap, ', '.join(str(task) for task in capped)))
1337
+ PY
1338
+ }
1339
+
1067
1340
  render_table() {
1068
1341
  local PLAN="$1" T="$1/tasks.tsv" W="$1/waves.tsv"
1069
1342
  local run_id; run_id="$(cat "$PLAN/run_id")"
1070
1343
  local n; n="$(all_ids "$T" | wc -l | tr -d ' ')"
1071
1344
  local waves; waves="$(awk -F'\t' '{print $1}' "$W" | sort -u | wc -l | tr -d ' ')"
1072
1345
  echo "run forge/$run_id repo $(cat "$PLAN/repo")"
1346
+ plans_chain_line "$PLAN"
1073
1347
  [ -s "$PLAN/goal.txt" ] && echo "goal: $(head -1 "$PLAN/goal.txt")"
1074
- local est=$((n*2)) extra=""
1348
+ # A scripted task runs tasks/<id>/run: no implementer dispatch. Its review still counts.
1349
+ local dwarfs scripted=0 script_ids="" sid
1350
+ dwarfs="$(awk -F'\t' '!/^#/ && NF && $5 != "script" { c++ } END { print c + 0 }' "$T")"
1351
+ while IFS= read -r sid; do
1352
+ [ -n "$sid" ] || continue
1353
+ scripted=$((scripted + 1))
1354
+ script_ids="${script_ids:+$script_ids, }$sid"
1355
+ done <<EOF
1356
+ $(awk -F'\t' '!/^#/ && NF && $5 == "script" { print $1 }' "$T")
1357
+ EOF
1358
+ local est=$((dwarfs + n)) extra=""
1075
1359
  if [ -s "$PLAN/planner" ]; then
1076
1360
  est=$((est+1)); extra=" + 1 planner ($(cat "$PLAN/planner"))"
1077
1361
  fi
1078
- echo "tasks: $n waves: $waves estimated dispatches: $est ($n dwarf + $n qa$extra)"
1362
+ # A review=group group is reviewed once for all its members (#140): the estimate counts that.
1363
+ local grp_counts grp_n=0 grp_m=0 reviews="$n"
1364
+ grp_counts="$(forge_groups_review_counts "$PLAN")"
1365
+ if [ -n "$grp_counts" ]; then
1366
+ read -r grp_n grp_m <<<"$grp_counts"
1367
+ reviews=$((n - grp_m + grp_n))
1368
+ est=$((dwarfs + reviews + (est - dwarfs - n)))
1369
+ fi
1370
+ echo "tasks: $n waves: $waves estimated dispatches: $est ($dwarfs dwarf + $reviews qa$extra)"
1371
+ [ -z "$grp_counts" ] || echo "reviews: $reviews ($grp_n groups replace $grp_m task reviews)"
1372
+ if [ "$scripted" -gt 0 ]; then
1373
+ echo "scripted tasks: $scripted ($script_ids) run tasks/<id>/run; no implementer model"
1374
+ fi
1375
+ render_retry_per_model "$PLAN"
1079
1376
  if [ -s "$PLAN/shadow_qa" ]; then
1080
1377
  local rate; rate="$(cat "$PLAN/shadow_rate" 2>/dev/null || echo 0.1)"
1081
1378
  echo "shadow review: $(cat "$PLAN/shadow_qa") on a sampled $rate of reviewed attempts" \
@@ -1095,7 +1392,9 @@ render_table() {
1095
1392
  echo "pre-review tests: on, but $(cat "$PLAN/repo")/.forge/verify-subset (a test command with {files} or {changed}) is missing, so nothing will run"
1096
1393
  fi
1097
1394
  fi
1098
- if [ -f "$PLAN/reviewer_session" ]; then
1395
+ if [ -f "$PLAN/reviewer_session" ] && [ -f "$PLAN/reviewer_session_rate" ]; then
1396
+ echo "reviewer-session: on for $(grep -c . "$PLAN/reviewer_session_tasks" 2>/dev/null || echo 0) of $(all_ids "$PLAN/tasks.tsv" | grep -c .) tasks (a sampled $(cat "$PLAN/reviewer_session_rate")); the others review fresh and log not-sampled, to compare"
1397
+ elif [ -f "$PLAN/reviewer_session" ]; then
1099
1398
  echo "reviewer-session: a later review round continues the reviewer's earlier session when its QA spec is unchanged (experiment; falls back to a fresh session)"
1100
1399
  fi
1101
1400
  if [ -f "$PLAN/implementer_session" ]; then
@@ -1148,6 +1447,7 @@ EOF
1148
1447
  done
1149
1448
  echo
1150
1449
  done
1450
+ render_groups "$PLAN"
1151
1451
  # A chain collapsed on this call, or a chain left as a chain. one and branches say nothing.
1152
1452
  # COLLAPSED_NOW is do_plan's: collapsed.json from an earlier plan is not announced again.
1153
1453
  local shape_note=""
@@ -1219,6 +1519,10 @@ preflight_plan() {
1219
1519
  flags=""; [ -f "$plan/yolo_$role" ] && flags=--yolo
1220
1520
  ft="$(forge_fast_tier "$plan" "$role")"
1221
1521
  spec="$(field "$plan/tasks.tsv" "$id" "$role")"
1522
+ # A scripted task has no implementer model. Its reviewer is still checked.
1523
+ if [ "$role" = dwarf ] && [ "$spec" = script ]; then
1524
+ continue
1525
+ fi
1222
1526
  # Once per spec, role and options: the same arguments get the same answer, and a note doctor
1223
1527
  # adds (a slow effort) is said once, not once per task.
1224
1528
  key="$role|$spec|$flags|$ft"
@@ -1442,7 +1746,7 @@ record_retry_source() { # record_retry_source <tdir> <attempt>
1442
1746
  trail="$tdir/retry_sources.tsv"; tmp="$tdir/.retry_sources.tsv.tmp"
1443
1747
  [ -s "$tdir/retry_findings.md" ] || return 0
1444
1748
  src="$(cat "$tdir/retry_findings.source" 2>/dev/null)"
1445
- case "$src" in review|prereview|bounce|message|answer) ;; *) src=review ;; esac
1749
+ case "$src" in review|prereview|bounce|message|answer|prompt) ;; *) src=review ;; esac
1446
1750
  if [ -e "$trail" ]; then
1447
1751
  [ -f "$trail" ] && [ -r "$trail" ] || return 1
1448
1752
  awk -F'\t' -v n="$n" '$1 != n' "$trail" > "$tmp" 2>/dev/null || { rm -f "$tmp"; return 1; }
@@ -1452,6 +1756,155 @@ record_retry_source() { # record_retry_source <tdir> <attempt>
1452
1756
  printf '%s\t%s\t%s\n' "$n" "$src" "$(date +%s)" >> "$tmp" && mv "$tmp" "$trail" || { rm -f "$tmp"; return 1; }
1453
1757
  }
1454
1758
 
1759
+ # The reviewer's harness refused the prompt for its size (#145): codex's input_too_large, claude's
1760
+ # "Prompt is too long". A retry would send the same prompt; the task's note says what to do instead.
1761
+ qa_input_too_large() { # qa_input_too_large <task dir>
1762
+ grep -qE 'input_too_large|Input exceeds the maximum length|[Pp]rompt is too long|context_length_exceeded' \
1763
+ "$1/qa.log" "$1/qa.out" 2>/dev/null
1764
+ }
1765
+
1766
+ # What the implementer was given (#150): prompt.md and approach.md as they were when dwarf.input was
1767
+ # built, kept next to them as prompt.dispatched / approach.dispatched. A missing approach.md is an empty
1768
+ # copy. Each goes through a temp file and mv; prompt.dispatched is written last, because its presence is
1769
+ # what says the pair is complete.
1770
+ record_dispatched_inputs() { # record_dispatched_inputs <tdir>
1771
+ local tdir="$1" f tmp
1772
+ for f in approach prompt; do
1773
+ tmp="$tdir/.$f.dispatched.tmp"
1774
+ if [ -f "$tdir/$f.md" ]; then cp "$tdir/$f.md" "$tmp" || { rm -f "$tmp"; return 1; }
1775
+ else : > "$tmp" || return 1; fi
1776
+ mv "$tmp" "$tdir/$f.dispatched" || { rm -f "$tmp"; return 1; }
1777
+ done
1778
+ }
1779
+
1780
+ # Whether the planner edited prompt.md or approach.md while the attempt ran (#150). Returns 0 when it did:
1781
+ # the attempt is then STALE, written to stale.diff and control.log, and the caller stops before any review.
1782
+ # Returns 1 when nothing changed, or when the attempt predates the .dispatched copies (no check possible).
1783
+ prompt_drifted() { # prompt_drifted <plan> <id> <tdir> <attempt>
1784
+ local PLAN="$1" id="$2" tdir="$3" attempt="$4" f cur old changed=() tmp="$3/.stale.diff.tmp" what
1785
+ [ -f "$tdir/prompt.dispatched" ] || return 1
1786
+ : > "$tmp" || return 1
1787
+ for f in prompt approach; do
1788
+ cur="$tdir/$f.md"; [ -f "$cur" ] || cur=/dev/null
1789
+ old="$tdir/$f.dispatched"; [ -f "$old" ] || continue
1790
+ cmp -s "$old" "$cur" && continue
1791
+ changed+=("$f.md")
1792
+ diff -u --label "$f.md (attempt $attempt)" --label "$f.md (now)" "$old" "$cur" >> "$tmp" || true
1793
+ done
1794
+ if [ "${#changed[@]}" -eq 0 ]; then rm -f "$tmp" "$tdir/stale.diff"; return 1; fi
1795
+ mv "$tmp" "$tdir/stale.diff" || rm -f "$tmp"
1796
+ python3 - "$SKILL_DIR/scripts/forge-control.py" "$PLAN" "$id" "$attempt" "${changed[@]}" <<'PY' 2>/dev/null \
1797
+ || note "$id: control.log not updated with the prompt change"
1798
+ import importlib.util, sys
1799
+ from pathlib import Path
1800
+ spec = importlib.util.spec_from_file_location('forge_control', sys.argv[1])
1801
+ module = importlib.util.module_from_spec(spec)
1802
+ sys.modules['forge_control'] = module
1803
+ spec.loader.exec_module(module)
1804
+ module.audit(Path(sys.argv[2]), 'scheduler', 'prompt-changed', sys.argv[3], 'prompt', int(sys.argv[4]), None,
1805
+ files=sys.argv[5:])
1806
+ PY
1807
+ what="${changed[0]}"; [ "${#changed[@]}" -eq 1 ] || what="${changed[0]} and ${changed[1]}"
1808
+ note "$id: $what changed during attempt $attempt — not reviewed; the implementer gets the new text (no attempt spent)"
1809
+ echo STALE > "$tdir/status"
1810
+ # The implementer has to run again, so a saved QA-only resume of this attempt no longer applies.
1811
+ rm -f "$tdir/resume"
1812
+ return 0
1813
+ }
1814
+
1815
+ # A scripted task (#142) has the literal `script` in its dwarf column: its command is the executable
1816
+ # tasks/<id>/run, and its qa column reviews the result.
1817
+ task_is_script() { # task_is_script <plan> <id>
1818
+ [ "$(field "$1/tasks.tsv" "$2" dwarf)" = script ]
1819
+ }
1820
+
1821
+ # A fenced block of a file (its last <chars> characters when given), the fence longer than any run of
1822
+ # backticks inside it so the content cannot close it early.
1823
+ script_fenced() { # script_fenced <file> [chars]
1824
+ python3 - "$1" "${2:-}" <<'PY'
1825
+ import re, sys
1826
+ text = open(sys.argv[1], encoding='utf-8', errors='replace').read()
1827
+ if sys.argv[2]:
1828
+ text = text[-int(sys.argv[2]):]
1829
+ fence = '`' * max([3] + [len(m) + 1 for m in re.findall(r'`+', text)])
1830
+ print(fence)
1831
+ print(text, end='' if text.endswith('\n') or not text else '\n')
1832
+ print(fence)
1833
+ PY
1834
+ }
1835
+
1836
+ # Runs a scripted task's command from the task's base and records the run. Returns 0 when the command
1837
+ # exited 0 (the caller goes on to the snapshot and the review); otherwise the status and qa.last are
1838
+ # written and it returns 1: no review, no noretry (a person may edit run, and the next attempt resets
1839
+ # the worktree).
1840
+ run_script_task() { # run_script_task <plan> <id> <tdir> <wt> <base>
1841
+ local PLAN="$1" id="$2" tdir="$3" wt="$4" base="$5" run="$3/run"
1842
+ local limit="${FORGE_TIMEOUT:-2700}" pid rc=0 timed_out=0 started deadline waited=0 hex rec exit_json note_txt
1843
+ # As for a dispatch: 0 is no limit, and a leading zero is decimal (bash would read 08 as octal).
1844
+ case "$limit" in ''|*[!0-9]*) limit=2700 ;; esac
1845
+ limit=$(( 10#$limit ))
1846
+ local cmd=("$run")
1847
+ if [ ! -f "$run" ] || [ ! -x "$run" ]; then
1848
+ echo FAIL > "$tdir/status"
1849
+ echo "tasks/$id/run is missing or not executable." > "$tdir/qa.last"
1850
+ note "$id: tasks/$id/run is missing or not executable"; return 1
1851
+ fi
1852
+ head -c 2 "$run" | grep -q '^#!' || cmd=(/bin/bash "$run")
1853
+ # Every attempt starts from the base, so the cumulative diff is what the command produced. The branch
1854
+ # history stays; .forge is forge's own.
1855
+ if ! { git -C "$wt" read-tree -u --reset "$base" && git -C "$wt" clean -fdq -e .forge; } >"$tdir/script.reset.out" 2>&1; then
1856
+ echo ERROR > "$tdir/status"
1857
+ note "$id: could not reset the worktree to its base — see $tdir/script.reset.out"; return 1
1858
+ fi
1859
+ : > "$tdir/script.log"
1860
+ started="$(python3 -c 'import time; print(time.time())')"
1861
+ # exec keeps the pid: forge-guard.py session makes it a process group leader, so pid is the group id.
1862
+ ( cd "$wt" && export FORGE_TASK_ID="$id" FORGE_PLAN="$PLAN" FORGE_WORKTREE="$wt" FORGE_BASE_REF="$base" \
1863
+ && exec python3 "$SKILL_DIR/scripts/forge-guard.py" session -- "${cmd[@]}" ) </dev/null >"$tdir/script.log" 2>&1 &
1864
+ pid=$!
1865
+ deadline=$(( SECONDS + limit ))
1866
+ while kill -0 "$pid" 2>/dev/null; do
1867
+ if [ "$limit" -gt 0 ] && [ "$SECONDS" -ge "$deadline" ]; then timed_out=1; break; fi
1868
+ sleep 0.2
1869
+ done
1870
+ if [ "$timed_out" = 1 ]; then
1871
+ # TERM the group, KILL after 10 s whatever is left of it (timeout(1) is not on macOS).
1872
+ kill -TERM -- "-$pid" 2>/dev/null || kill -TERM "$pid" 2>/dev/null
1873
+ while kill -0 -- "-$pid" 2>/dev/null && [ "$waited" -lt 50 ]; do sleep 0.2; waited=$(( waited + 1 )); done
1874
+ kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null
1875
+ wait "$pid" 2>/dev/null
1876
+ else
1877
+ wait "$pid"; rc=$?
1878
+ # What the command left running in its group is stopped with it.
1879
+ python3 "$SKILL_DIR/scripts/forge-guard.py" reap "$pid" "$tdir/script.orphans" >/dev/null 2>&1 || true
1880
+ fi
1881
+ exit_json="$rc"; [ "$timed_out" = 0 ] || exit_json=""
1882
+ hex="$(python3 -c 'import uuid; print(uuid.uuid4().hex[:16])')"
1883
+ rec="$tdir/attempts/script-$hex"
1884
+ rm -f "$tdir/script.ran"
1885
+ if mkdir -p "$rec" && cp "$tdir/script.log" "$rec/script.log" && cp "$run" "$rec/run"; then
1886
+ # The review shows this copy: run may be edited before a QA-only resume reviews this attempt.
1887
+ printf '%s\n' "$rec" > "$tdir/script.ran"
1888
+ python3 - "$rec/metrics.json" "$started" "$exit_json" <<'PY' || note "$id: the script run was not recorded in attempts/"
1889
+ import json, os, sys, time
1890
+ path, started, code = sys.argv[1:4]
1891
+ data = {'role': 'script', 'harness': 'script', 'exit_code': int(code) if code else None,
1892
+ 'wall_started': float(started), 'elapsed_s': {'total': time.time() - float(started)}}
1893
+ with open(path + '.tmp', 'w') as handle:
1894
+ json.dump(data, handle, indent=2)
1895
+ os.replace(path + '.tmp', path)
1896
+ PY
1897
+ else
1898
+ note "$id: the script run was not recorded in attempts/"
1899
+ fi
1900
+ [ "$timed_out" = 1 ] || [ "$rc" != 0 ] || return 0
1901
+ if [ "$timed_out" = 1 ]; then note_txt="The script timed out after ${limit}s."; else note_txt="The script exited $rc."; fi
1902
+ { echo "$note_txt"; echo; echo "Its output (last 3000 characters of script.log):"; script_fenced "$tdir/script.log" 3000; } > "$tdir/qa.last"
1903
+ echo FAIL > "$tdir/status"
1904
+ note "$id: ${note_txt%.} — not reviewed (see $tdir/script.log)"
1905
+ return 1
1906
+ }
1907
+
1455
1908
  do_task_body() (
1456
1909
  local PLAN="${1:?}" id="${2:?}"
1457
1910
  local T="$PLAN/tasks.tsv" REPO run_id base wt br tdir attempt resume=""
@@ -1471,6 +1924,16 @@ do_task_body() (
1471
1924
  [ -s "$PLAN/timeout" ] && export FORGE_TIMEOUT="$(cat "$PLAN/timeout")"
1472
1925
  wt="$(cat "$PLAN/wt_root")/$id"
1473
1926
  br="forge/$run_id/$id"
1927
+ # A member of a review=group group (#140) stops at IMPLEMENTED: its group is reviewed once, later.
1928
+ # Looked up once. A task in no group, or in a review=task group, takes the path below unchanged,
1929
+ # and a plan with no groups.tsv starts no process for it.
1930
+ local grp_id="" grp_review="" grp_qa=""
1931
+ if [ -f "$PLAN/groups.tsv" ]; then
1932
+ IFS=$'\t' read -r grp_id grp_review grp_qa < <(forge_groups_py of "$PLAN" "$id" 2>/dev/null) || true
1933
+ [ "$grp_review" = group ] || grp_id=""
1934
+ fi
1935
+ # No task review happened for a member, so a QA-only resume cannot apply to it.
1936
+ [ -z "$grp_id" ] || rm -f "$tdir/resume"
1474
1937
  # Every attempt gets a distinct number and commit message. A QA-only resume (the
1475
1938
  # reviewer hit an infrastructure failure, or never reached a verdict) re-reviews work
1476
1939
  # that is already committed, so it neither runs the dwarf nor spends an attempt.
@@ -1518,10 +1981,23 @@ do_task_body() (
1518
1981
  return 1
1519
1982
  fi
1520
1983
 
1984
+ local is_script=0
1985
+ task_is_script "$PLAN" "$id" && is_script=1
1521
1986
  if [ -z "$resume" ]; then
1522
1987
  # Persist each source separately; QA receives complete context once.
1523
1988
  write_capsule "$PLAN" "$id" dwarf >/dev/null
1524
1989
  cp "$tdir/capsule.md" "$tdir/baseline.capsule"
1990
+ # What this attempt's implementer is given, to tell later whether the planner edited it (#150).
1991
+ record_dispatched_inputs "$tdir" || { rm -f "$tdir/prompt.dispatched"; note "$id: could not record the dispatched prompt; a later edit will not be detected"; }
1992
+ if [ "$is_script" = 1 ]; then
1993
+ # A scripted task (#142) runs its command here instead of the implementer below (memory,
1994
+ # dispatch, gates). The snapshot and everything after it are the same.
1995
+ forge_metric_phase dispatch
1996
+ run_script_task "$PLAN" "$id" "$tdir" "$wt" "$base" || return 1
1997
+ fi
1998
+ # The implementer's part, from here to the snapshot, belongs to model tasks only (no reindent, to
1999
+ # keep the diff of this section readable).
2000
+ if [ "$is_script" != 1 ]; then
1525
2001
  # --task lets Jev narrow the injected slice to facts that bear on THIS task. Without
1526
2002
  # it, or with Jev off, the full role slice is injected exactly as before.
1527
2003
  /bin/bash "$MEMORY" inject "$REPO" dwarf --task "$tdir/prompt.md" \
@@ -1624,6 +2100,7 @@ do_task_body() (
1624
2100
  guard_after_dwarf "$wt" "$tdir" "$id"
1625
2101
  # Before the snapshot, so a dwarf that only asked a question (and changed nothing) still reaches it.
1626
2102
  forge_post_dwarf_gates "$PLAN" "$id" "$tdir" "$wt" "$attempt" || return 0
2103
+ fi
1627
2104
  forge_metric_phase snapshot
1628
2105
  # Capture the real diff, including new files, then commit on the task branch.
1629
2106
  # Diffed against the task's pinned base rather than the branch head, so a retry
@@ -1639,12 +2116,18 @@ do_task_body() (
1639
2116
  && git diff --cached --binary "$base" -- . ":(exclude).forge") > "$tdir/changes.diff" 2>/dev/null || { echo ERROR > "$tdir/status"; return 1; }
1640
2117
  if [ ! -s "$tdir/changes.diff" ]; then
1641
2118
  # A harness that exited 0 with an empty final message and changed nothing did not
1642
- # decline the task; it never really ran (login, quota, a dropped connection).
1643
- if grep -qx 'class=empty' "$tdir/dwarf.infra" 2>/dev/null; then
2119
+ # decline the task; it never really ran (login, quota, a dropped connection). Nor did one
2120
+ # its CLI cancelled first (grok, at a tool call a headless run cannot approve): a pause,
2121
+ # not a failed attempt marked never to retry.
2122
+ if grep -qxE 'class=(empty|cancelled)' "$tdir/dwarf.infra" 2>/dev/null; then
1644
2123
  infra_stop "$tdir" "$id" dwarf "$attempt"; return 8
1645
2124
  fi
1646
2125
  echo FAIL > "$tdir/status"
1647
2126
  : > "$tdir/noretry"
2127
+ if [ "$is_script" = 1 ]; then
2128
+ echo "The script produced no changes." > "$tdir/qa.last"
2129
+ note "$id: the script produced an empty diff"; return 1
2130
+ fi
1648
2131
  echo "The dwarf produced no changes at all." > "$tdir/qa.last"
1649
2132
  note "$id: dwarf produced an empty diff"; return 1
1650
2133
  fi
@@ -1653,6 +2136,10 @@ do_task_body() (
1653
2136
  # already judged.
1654
2137
  if [ -s "$tdir/changes.prev.diff" ] && cmp -s "$tdir/changes.diff" "$tdir/changes.prev.diff" \
1655
2138
  && [ "$(cat "$tdir/retry_findings.source" 2>/dev/null)" != bounce ]; then
2139
+ # A retry its CLI cancelled before it changed anything did not keep the code on purpose.
2140
+ if grep -qx 'class=cancelled' "$tdir/dwarf.infra" 2>/dev/null; then
2141
+ infra_stop "$tdir" "$id" dwarf "$attempt"; return 8
2142
+ fi
1656
2143
  echo FAIL > "$tdir/status"
1657
2144
  : > "$tdir/noretry"
1658
2145
  echo "The retry changed nothing: the diff is byte-identical to the previous attempt." \
@@ -1669,7 +2156,7 @@ do_task_body() (
1669
2156
  fi
1670
2157
 
1671
2158
  (cd "$wt" && git -c user.name=forge -c user.email=forge@local \
1672
- commit --allow-empty -q -m "forge($id) attempt $attempt: $(field "$T" "$id" title)") >/dev/null 2>&1 || {
2159
+ commit --allow-empty -q -m "forge($id) attempt $attempt: $(field "$T" "$id" title)$([ "$is_script" != 1 ] || echo ' (script)')") >/dev/null 2>&1 || {
1673
2160
  echo ERROR > "$tdir/status"; return 1;
1674
2161
  }
1675
2162
  reviewed="$(git -C "$wt" rev-parse HEAD)" || return 1
@@ -1688,6 +2175,37 @@ do_task_body() (
1688
2175
  else
1689
2176
  reviewed="$(cat "$tdir/reviewed.commit")"
1690
2177
  fi
2178
+ # A prompt or approach edited since the implementer was given it: judged against text it never saw.
2179
+ # STALE, not reviewed, nothing spent; the committed work stays on the branch (#150).
2180
+ if prompt_drifted "$PLAN" "$id" "$tdir" "$attempt"; then return 0; fi
2181
+ if [ -n "$grp_id" ]; then
2182
+ # The member's own pipeline ends here: no review snapshot, QA, shadow or fail-first. The tests of
2183
+ # --pre-review-tests still run, on a snapshot that lives only for them: a red attempt is FAIL and
2184
+ # goes back unreviewed, as for any task.
2185
+ if [ -f "$PLAN/pre_review_tests" ]; then
2186
+ review="$tdir/review-$attempt-$$"
2187
+ local stale
2188
+ for stale in "$tdir"/review-*; do forge_drop_snapshot "$stale"; done
2189
+ FORGE_REVIEW_SNAPSHOT="$review"
2190
+ forge_review_snapshot "$wt" "$base" "$reviewed" "$review" || { echo ERROR > "$tdir/status"; return 1; }
2191
+ if ! forge_pre_review "$review" "$tdir" "$REPO" "$PLAN"; then
2192
+ : > "$tdir/prereview.failed"
2193
+ rm -f "$tdir/qa.last"
2194
+ echo FAIL > "$tdir/status"
2195
+ note "$id: the tests this attempt affects fail — sent back to the implementer without a review (see $tdir/prereview.md)"
2196
+ return 0
2197
+ fi
2198
+ forge_drop_snapshot "$review"; FORGE_REVIEW_SNAPSHOT=""
2199
+ else
2200
+ rm -f "$tdir/prereview.json" "$tdir/prereview.txt" "$tdir/prereview.md"
2201
+ fi
2202
+ # The fingerprint a review would have recorded, then the status: a reader that sees IMPLEMENTED
2203
+ # can trust reviewed.commit and source.fingerprint.
2204
+ forge_fingerprint "$wt" > "$tdir/source.fingerprint.tmp" && mv "$tdir/source.fingerprint.tmp" "$tdir/source.fingerprint" || return 1
2205
+ echo IMPLEMENTED > "$tdir/status"
2206
+ note "$id: implemented — waits for group $grp_id's review"
2207
+ return 0
2208
+ fi
1691
2209
  review="$tdir/review-$attempt-$$"
1692
2210
  # One review of a task at a time, so any snapshot already here is an interrupted review's: a signal
1693
2211
  # ends this subshell without its EXIT trap (#139).
@@ -1746,13 +2264,30 @@ do_task_body() (
1746
2264
  # A finding sweep's fix task gets the narrow review: one FIXED / NOT FIXED line per finding.
1747
2265
  local qa_kind=task
1748
2266
  [ ! -f "$tdir/sweep.json" ] || qa_kind=sweep
2267
+ [ "$is_script" != 1 ] || qa_kind=script
1749
2268
  # QA uses the dispatch-time ownership and baseline, never later merge state.
1750
2269
  /bin/bash "$MEMORY" inject "$REPO" qa --task "$tdir/prompt.md" \
1751
2270
  --run-dir "$tdir" > "$tdir/qa.memory"
2271
+ # The diff goes inline up to the whole-run review's limit (#145). Over it, the prompt holds the
2272
+ # stat and the reviewer reads the diff in its snapshot, which holds this attempt as one commit over
2273
+ # its base, as the whole-run review and adopt already do. At most the limit plus one byte is read.
2274
+ # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
2275
+ # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
2276
+ local qa_inline=1
2277
+ git -C "$wt" diff --binary --irreversible-delete "$base" "$reviewed" -- . ':(exclude).forge' 2>/dev/null |
2278
+ head -c $((REVIEW_DIFF_LIMIT + 1)) > "$tdir/.qa.diff"
2279
+ [ "$(wc -c < "$tdir/.qa.diff" | tr -d ' ')" -le "$REVIEW_DIFF_LIMIT" ] || qa_inline=0
1752
2280
  {
1753
2281
  python3 "$SKILL_DIR/scripts/forge-prompt.py" --requirements "$tdir/prompt.md" --capsule "$tdir/baseline.capsule" --approach "$tdir/approach.md" --retry "$tdir/retry_findings.md" --retry-source "$(cat "$tdir/retry_findings.source" 2>/dev/null || echo review)" ${prompt_extra[@]+"${prompt_extra[@]}"} --memory "$tdir/dwarf.memory" --memory "$tdir/qa.memory"
1754
2282
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind "$qa_kind"
1755
2283
  echo
2284
+ if [ "$is_script" = 1 ]; then
2285
+ local ran_dir="$tdir"
2286
+ [ ! -s "$tdir/script.ran" ] || [ ! -f "$(cat "$tdir/script.ran")/run" ] || ran_dir="$(cat "$tdir/script.ran")"
2287
+ echo "The command (tasks/$id/run, as it ran):"; script_fenced "$ran_dir/run"
2288
+ echo; echo "Its output (last 3000 characters of script.log):"; script_fenced "$ran_dir/script.log" 3000
2289
+ echo
2290
+ fi
1756
2291
  [ ! -f "$PLAN/sweep_ahead" ] || python3 "$SKILL_DIR/scripts/forge-sweep.py" ahead "$PLAN" "$id" --role qa 2>/dev/null
1757
2292
  cat "$tdir/review.deps"
1758
2293
  [ -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."
@@ -1769,6 +2304,18 @@ do_task_body() (
1769
2304
  echo "A promise of later work means a check may never have run; judge the diff on its own merits."
1770
2305
  echo
1771
2306
  fi
2307
+ local blocked_claims=""
2308
+ [ ! -f "$tdir/dwarf.last" ] || blocked_claims="$(python3 "$SKILL_DIR/scripts/forge-contract.py" blocked --message "$tdir/dwarf.last" 2>/dev/null \
2309
+ | python3 -c 'import json, sys
2310
+ for r in json.load(sys.stdin):
2311
+ print(" - %s: %s" % (r["path"], r["why"]))' 2>/dev/null)" || blocked_claims=""
2312
+ if [ -n "$blocked_claims" ]; then
2313
+ # A claim, not a fact: only the reviewer's {outside=...} on a finding can stop the task (#149).
2314
+ echo "The implementer says these fixes need files outside the task:"
2315
+ printf '%s\n' "$blocked_claims"
2316
+ echo "Confirm a real one with {outside=<path>} on the finding it blocks, or refute it."
2317
+ echo
2318
+ fi
1772
2319
  if [ -s "$tdir/drift.txt" ]; then
1773
2320
  # The reviewer is already asked about scope and had no way to know the answer.
1774
2321
  echo "Scope note: this task declared it would touch $(field "$T" "$id" files), and the"
@@ -1780,15 +2327,24 @@ do_task_body() (
1780
2327
  fi
1781
2328
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind "$qa_kind" --threshold "$qa_thr"
1782
2329
  echo
1783
- # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
1784
- # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
1785
- echo '```diff'; git -C "$wt" diff --binary --irreversible-delete "$base" "$reviewed" -- . ':(exclude).forge'; echo '```'
2330
+ if [ "$qa_inline" = 1 ]; then
2331
+ echo '```diff'; cat "$tdir/.qa.diff"; echo '```'
2332
+ else
2333
+ echo "The diff is larger than $((REVIEW_DIFF_LIMIT / 1024)) KB, so it is not inlined. Read it in your"
2334
+ echo "working directory, which holds this attempt as the last commit over its base:"
2335
+ echo " git diff HEAD~1 HEAD -- . ':(exclude).forge'"
2336
+ echo "Its stat ($(git -C "$wt" diff --shortstat "$base" "$reviewed" -- . ':(exclude).forge' 2>/dev/null | sed 's/^ *//')):"
2337
+ echo '```text'
2338
+ git -C "$wt" diff --stat=200 "$base" "$reviewed" -- . ':(exclude).forge' 2>/dev/null | head -c 65536
2339
+ echo '```'
2340
+ fi
1786
2341
  echo; /bin/bash "$MEMORY" note qa
1787
2342
  echo "Place any learning notes before the final FORGE_VERDICT: PASS or FORGE_VERDICT: FAIL line."
1788
2343
  # Last, so a shadow review, which copies this file byte for byte, carries the same
1789
2344
  # instruction. Its notes are not recorded: only this task's own dispatch is.
1790
2345
  forge_retro_prompt "$PLAN" qa
1791
2346
  } > "$tdir/qa.input"
2347
+ rm -f "$tdir/.qa.diff"
1792
2348
  # Opt-in (plan --shadow-qa): a second, independent review of this same diff, to measure
1793
2349
  # how often two reviewers agree. It reviews its own snapshot from its own dir under
1794
2350
  # $PLAN/shadow/, and nothing in this script ever reads its result.
@@ -1806,6 +2362,8 @@ do_task_body() (
1806
2362
  if [ "$rs_on" = 1 ]; then
1807
2363
  if [ -n "${FORGE_FRACTAL_RUN:-}" ] || forge_plan_is_fractal "$PLAN"; then
1808
2364
  rs_reason=fractal
2365
+ elif [ -f "$PLAN/reviewer_session_rate" ] && ! grep -qxF "$id" "$PLAN/reviewer_session_tasks" 2>/dev/null; then
2366
+ rs_reason=not-sampled # the comparison half of --reviewer-session-rate: every round is fresh
1809
2367
  elif [ ! -s "$tdir/retry_findings.md" ]; then
1810
2368
  rs_reason=first-round
1811
2369
  else
@@ -1855,7 +2413,13 @@ do_task_body() (
1855
2413
  case "$rc" in
1856
2414
  7) echo TIMEOUT > "$tdir/status"; note "$id: qa hit the dispatch timeout — see $tdir/qa.out" ;;
1857
2415
  8) infra_stop "$tdir" "$id" qa "$attempt"; return 8 ;;
1858
- *) echo ERROR > "$tdir/status"; note "$id: qa dispatch failed — see $tdir/qa.out" ;;
2416
+ *) echo ERROR > "$tdir/status"
2417
+ if qa_input_too_large "$tdir"; then
2418
+ # The same prompt fails the same way: say so, and what does work (#145).
2419
+ note "$id: the reviewer's harness refused the prompt as too large ($(wc -c < "$tdir/qa.input" | tr -d ' ') bytes; see $tdir/qa.log). A retry sends the same prompt. Review the commit from a snapshot instead: forge-parallel.sh adopt $PLAN $(cut -c1-12 "$tdir/reviewed.commit" 2>/dev/null) --qa <spec> --reason \"...\", or split the task"
2420
+ else
2421
+ note "$id: qa dispatch failed — see $tdir/qa.out"
2422
+ fi ;;
1859
2423
  esac
1860
2424
  return 1
1861
2425
  fi
@@ -1896,17 +2460,10 @@ do_task_body() (
1896
2460
  # Entry point for both the scheduler's `_task` and `retry`: runs the pipeline, then logs
1897
2461
  # the attempt (including infrastructure stops, which spend nothing) for later audit.
1898
2462
  do_task() {
1899
- local rc crc=0 stop_before
2463
+ local rc
1900
2464
  do_task_body "$@"; rc=$?
1901
2465
  record_attempt "$1" "$2"
1902
- # The retry policy's state (escalation.next or escalation.stop), decided now rather than
1903
- # at the next retry so a spent retry budget still reports it and the scheduler sees it.
1904
- stop_before="$(cat "$1/tasks/$2/escalation.stop" 2>/dev/null)"
1905
- python3 "$SKILL_DIR/scripts/forge-route.py" escalation --plan "$1" --task "$2" --check \
1906
- --qa-only-next "$(qa_only_next_flag "$1" "$2")" >/dev/null 2>&1 || crc=$?
1907
- # A FAIL that does not converge, or that the policy could not move to a stronger model, waits
1908
- # for a person (NEEDS_DECISION). attempts.tsv was written above and keeps FAIL.
1909
- decision_after_attempt "$1" "$2" "$stop_before" "$crc"
2466
+ post_attempt "$1" "$2"
1910
2467
  return $rc
1911
2468
  }
1912
2469
 
@@ -2077,6 +2634,8 @@ do_retry() {
2077
2634
  # A decision is judged the same way, before any option writes: a NEEDS_DECISION task is resumed
2078
2635
  # only by --decide or --dwarf with --reason and --approved, and --decide is for no other task.
2079
2636
  if [ "$pre_ok" = 1 ] && [ -s "$PLAN/tasks.tsv" ] && all_ids "$PLAN/tasks.tsv" | grep -qx "$id"; then
2637
+ # Before any option writes: an implemented group member has nothing to retry.
2638
+ [ "$(task_status "$PLAN" "$id")" != IMPLEMENTED ] || plans_implemented_refuse "$PLAN" "$id"
2080
2639
  retry_decision_gate "$PLAN" "$id" "$(task_status "$PLAN" "$id")" "$pre_decide" "$pre_dwarf" "$pre_reason" "$pre_approved"
2081
2640
  fi
2082
2641
  while [ $# -gt 0 ]; do
@@ -2125,6 +2684,7 @@ do_retry() {
2125
2684
  [ -s "$PLAN/wt_root" ] || die "this plan has never been run — use 'run', not 'retry'"
2126
2685
  local st; st="$(task_status "$PLAN" "$id")"
2127
2686
  [ "$st" = "MERGED" ] && die "task '$id' already merged — nothing to retry"
2687
+ [ "$st" != IMPLEMENTED ] || plans_implemented_refuse "$PLAN" "$id"
2128
2688
  # A decision's grant is exactly what it says, and the profile's default budget of further attempts
2129
2689
  # does not stretch it: a task waiting for a decision (resumed by --decide or --dwarf), or an
2130
2690
  # infrastructure stop resumed while a decision's count is kept. Only a --retry-failed typed on this
@@ -2270,8 +2830,9 @@ do_retry() {
2270
2830
  fi
2271
2831
  write_results "$PLAN"
2272
2832
  echo
2273
- printf ' %-14s %-9s %s\n' id status branch
2274
- awk -F'\t' '{printf " %-14s %-9s %s\n", $1, $2, $3}' "$PLAN/results.tsv"
2833
+ # 14 covers NEEDS_DECISION; 9 pushes the branch column out for IMPLEMENTED (11) too.
2834
+ printf ' %-14s %-14s %s\n' id status branch
2835
+ awk -F'\t' '{printf " %-14s %-14s %s\n", $1, $2, $3}' "$PLAN/results.tsv"
2275
2836
  run_report_extras "$PLAN"
2276
2837
  report_decisions "$PLAN"
2277
2838
  [ "$(task_status "$PLAN" "$id")" = "MERGED" ] || return 5
@@ -2636,6 +3197,9 @@ PY
2636
3197
  forge_brief_start() { # forge_brief_start <plan>
2637
3198
  local plan="$1"
2638
3199
  rm -f "$plan/brief.pid"
3200
+ # The writer's own output goes to brief.out: say the missing-groups note here, on the console, first.
3201
+ PYTHONPATH="$SKILL_DIR/scripts${PYTHONPATH:+:$PYTHONPATH}" python3 -c \
3202
+ 'import sys, forge_brief; forge_brief.note_missing_groups(sys.argv[1])' "$plan" || true
2639
3203
  python3 - "$plan" "$SKILL_DIR/scripts/forge-brief.py" <<'PY' || { note "brief: could not start the question writer"; return 0; }
2640
3204
  import os, subprocess, sys
2641
3205
  plan, script = sys.argv[1], sys.argv[2]
@@ -2710,6 +3274,71 @@ forge_brief_stale() { # forge_brief_stale <plan> <merged-task>
2710
3274
  return 0
2711
3275
  }
2712
3276
 
3277
+ # The values this run is using, after profile defaults. verify_cmd and timeout are paths:
3278
+ # python reads the files, so a quote or a trailing newline is not stripped on the way in.
3279
+ # A failure here is one note; the run goes on. run.flags.json describes this run of the plan,
3280
+ # not a choice a split or rerun copies, so it is not in the plan option lists.
3281
+ forge_run_flags_write() { # forge_run_flags_write <plan> <max-parallel> [argv...]
3282
+ local plan="$1" maxp="$2" timeout_file="" verify_file="" fractal=0 ahead=0 sweep_max=""
3283
+ shift 2
3284
+ [ ! -s "$plan/timeout" ] || timeout_file="$plan/timeout"
3285
+ [ ! -f "$plan/verify_cmd" ] || verify_file="$plan/verify_cmd"
3286
+ forge_plan_is_fractal "$plan" && fractal=1
3287
+ [ ! -f "$plan/sweep_ahead" ] || ahead=1
3288
+ [ "$PP_SWEEP_MAX_SET" = 1 ] && sweep_max="$PP_SWEEP_MAX"
3289
+ python3 - "$plan/run.flags.json" \
3290
+ "$PP_RETRY_FAILED" "$PP_INFRA_RETRIES" "$PP_SWEEP" "$sweep_max" \
3291
+ "$PP_SWEEP_PLAUSIBLE" "$ahead" "$maxp" "$timeout_file" "$verify_file" "$fractal" \
3292
+ -- "$@" <<'PY' >/dev/null 2>&1 || note "could not write $plan/run.flags.json"
3293
+ import json, os, sys, tempfile, time
3294
+
3295
+ def text(path):
3296
+ if not path:
3297
+ return None
3298
+ with open(path, 'r', encoding='utf-8', newline='') as handle:
3299
+ raw = handle.read()
3300
+ return raw if raw != '' else None
3301
+
3302
+ def whole(value):
3303
+ return int(value) if value != '' else None
3304
+
3305
+ args = sys.argv[1:]
3306
+ if len(args) < 12 or args[11] != '--':
3307
+ sys.exit(1)
3308
+ dest = args[0]
3309
+ retry, infra, sweep, sweep_max, plausible, ahead, maxp, timeout_file, verify_file, fractal = args[1:11]
3310
+ timeout = text(timeout_file)
3311
+ data = {
3312
+ 'retry_failed': int(retry),
3313
+ 'infra_retries': int(infra),
3314
+ 'sweep': sweep or None,
3315
+ 'sweep_max': whole(sweep_max),
3316
+ 'sweep_plausible': plausible == '1',
3317
+ 'sweep_ahead': ahead == '1',
3318
+ 'max_parallel': int(maxp),
3319
+ 'timeout': int(timeout.strip()) if timeout is not None else None,
3320
+ 'verify': text(verify_file),
3321
+ 'fractal': fractal == '1',
3322
+ 'argv': args[12:],
3323
+ 'at': time.time(),
3324
+ }
3325
+ parent = os.path.dirname(dest) or '.'
3326
+ fd, tmp = tempfile.mkstemp(prefix='.run.flags.json.', dir=parent)
3327
+ try:
3328
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
3329
+ json.dump(data, handle, ensure_ascii=False, indent=2)
3330
+ handle.write('\n')
3331
+ os.replace(tmp, dest)
3332
+ except Exception:
3333
+ try:
3334
+ os.unlink(tmp)
3335
+ except OSError:
3336
+ pass
3337
+ sys.exit(1)
3338
+ PY
3339
+ return 0
3340
+ }
3341
+
2713
3342
  do_run() {
2714
3343
  local run_child="" run_stop=0 run_phase=pre run_rc=0 interrupted=0 vstopped=0
2715
3344
  FORGE_RUN_STOPPABLE=1
@@ -2717,7 +3346,7 @@ do_run() {
2717
3346
  local PLAN="${1:?run needs a plan dir}"; shift
2718
3347
  FORGE_RUN_STARTED="$(forge_now)" # the summary's overridden verdicts are this run's
2719
3348
  local fractal_pipeline_args=("$@")
2720
- local MAXP=3 DRY=0 jev_rc=0 FORECAST=1
3349
+ local MAXP=3 DRY=0 jev_rc=0 FORECAST=1 fractal_answer=""
2721
3350
  while [ $# -gt 0 ]; do
2722
3351
  case "$1" in
2723
3352
  --no-forecast) FORECAST=0; shift ;;
@@ -2754,13 +3383,28 @@ do_run() {
2754
3383
  export FORGE_OUTPUT="$OUTPUT"
2755
3384
  case "$MAXP" in ''|*[!0-9]*) die "--max-parallel must be positive" ;; esac
2756
3385
  [ "$MAXP" -gt 0 ] || die "--max-parallel must be positive"
3386
+ # Said once, before any dispatch. The run itself still follows retry_per_model.
3387
+ if [ -f "$PLAN/retry_per_model" ] && [ -f "$PLAN/escalate_after" ]; then
3388
+ note "retry-per-model $(tr -d '[:space:]' < "$PLAN/retry_per_model") replaces --escalate-after for this plan"
3389
+ fi
2757
3390
  local T="$PLAN/tasks.tsv" W="$PLAN/waves.tsv"
2758
3391
  [ -s "$W" ] || die "no waves.tsv — run the plan subcommand first"
2759
3392
  grep -q 'UNASSIGNED' "$T" && die "some tasks are UNASSIGNED — assign a dwarf before running"
3393
+ # groups.tsv and its members' deps and files are as the plan froze them (#140). Nothing to
3394
+ # check without groups; checked before anything is dispatched, a dry run included.
3395
+ if [ -f "$PLAN/groups.tsv" ] || [ -f "$PLAN/groups.frozen" ]; then
3396
+ local groups_out
3397
+ groups_out="$(forge_groups_py check "$PLAN" 2>&1)" || forge_groups_die "$groups_out"
3398
+ if forge_groups_have_review "$PLAN" && { [ "${FRACTAL_CHOICE:-}" = on ] || forge_plan_is_fractal "$PLAN"; }; then
3399
+ die "group review does not support Fractal yet" 2
3400
+ fi
3401
+ fi
2760
3402
 
2761
3403
  compute_waves "$PLAN"
2762
3404
  local REPO run_id wt_root int_wt int_br
2763
3405
  REPO="$(cat "$PLAN/repo")"; run_id="$(cat "$PLAN/run_id")"
3406
+ # A plan made with --after: the plan it follows must still end where this one starts (#143).
3407
+ plans_chain_run_check "$PLAN" "$REPO"
2764
3408
  # Before any decision-model step: the privacy floor and the run budget read these.
2765
3409
  [ "$JEV_OPTS" = 1 ] && forge_decide_env "$REPO" "$PLAN"
2766
3410
  if [ "$DRY" != 1 ]; then
@@ -2770,6 +3414,22 @@ do_run() {
2770
3414
  forge_ui_register "$PLAN"
2771
3415
  forge_storage_check "$PLAN" "$REPO"
2772
3416
  fi
3417
+ # --fractal and an existing selection are refused above. The other way on is this
3418
+ # prompt, which forge_fractal_parallel_run asks only once stdin is a terminal and
3419
+ # fractal-selection.json does not exist yet (enabled: false has already chosen).
3420
+ # Answering y must refuse before that call writes fractal-selection.json; answering
3421
+ # n is the same as --no-fractal, so it is not asked twice.
3422
+ if [ "$DRY" != 1 ] && [ -t 0 ] && [ -z "${FRACTAL_CHOICE:-}" ] \
3423
+ && [ ! -e "$PLAN/fractal-selection.json" ] && ! forge_plan_is_fractal "$PLAN" \
3424
+ && forge_groups_have_review "$PLAN"; then
3425
+ printf 'Use Fractal for this run? [y/N] ' >&2
3426
+ IFS= read -r fractal_answer || fractal_answer=""
3427
+ fractal_answer="$(printf '%s' "$fractal_answer" | tr -d '\r' | tr '[:upper:]' '[:lower:]')"
3428
+ case "$fractal_answer" in
3429
+ y) die "group review does not support Fractal yet" 2 ;;
3430
+ esac
3431
+ forge_fractal_flag off || exit $?
3432
+ fi
2773
3433
  forge_fractal_parallel_run "$PLAN" "$REPO" "$DRY" ${fractal_pipeline_args[@]+"${fractal_pipeline_args[@]}"} || return $?
2774
3434
  forge_fast_fractal_note "$PLAN"
2775
3435
  # Durable, beside the repo — never TMPDIR. A temp worktree root has destroyed
@@ -2794,6 +3454,9 @@ do_run() {
2794
3454
  return 0
2795
3455
  fi
2796
3456
 
3457
+ # run.flags.json describes this run of the plan, not a choice a split or rerun copies.
3458
+ forge_run_flags_write "$PLAN" "$MAXP" ${fractal_pipeline_args[@]+"${fractal_pipeline_args[@]}"}
3459
+
2797
3460
  forge_metric_begin "$PLAN" parallel
2798
3461
  forge_metric_phase preflight
2799
3462
  [ "${FORGE_RIPWIRE:-}" != off ] || touch "$PLAN/no_ripwire"
@@ -2810,10 +3473,13 @@ do_run() {
2810
3473
  die "branch 'forge/$run_id' blocks task branches 'forge/$run_id/<task>' (git refs are files, so a ref cannot also be a directory). Delete or rename it: git branch -D forge/$run_id" 3
2811
3474
  fi
2812
3475
  if ! (cd "$REPO" && git rev-parse --verify "$int_br" >/dev/null 2>&1); then
2813
- (cd "$REPO" && git branch "$int_br" HEAD) || die "could not create $int_br" 3
3476
+ # A chained plan starts where the plan it follows ended, not at HEAD, even when its branch is gone.
3477
+ local int_start=HEAD
3478
+ [ ! -s "$PLAN/after" ] || [ ! -s "$PLAN/integration.base" ] || int_start="$(head -1 "$PLAN/integration.base")"
3479
+ (cd "$REPO" && git branch "$int_br" "$int_start") || die "could not create $int_br" 3
2814
3480
  # Where the integration branch started, so a whole-run review can diff exactly what
2815
3481
  # this run added. Plans created before this file existed fall back to a merge-base.
2816
- git -C "$REPO" rev-parse HEAD > "$PLAN/integration.base"
3482
+ git -C "$REPO" rev-parse "$int_start" > "$PLAN/integration.base"
2817
3483
  fi
2818
3484
  if [ ! -d "$int_wt" ]; then
2819
3485
  (cd "$REPO" && git worktree add "$int_wt" "$int_br" >/dev/null 2>&1) \
@@ -2904,8 +3570,9 @@ do_run() {
2904
3570
  echo
2905
3571
  echo "results (integration branch: $int_br)"
2906
3572
  echo "artifacts: $PLAN/tasks/<id>/{dwarf,qa}.{last,log}; results: $PLAN/results.tsv"
2907
- printf ' %-14s %-9s %s\n' id status branch
2908
- awk -F'\t' '{printf " %-14s %-9s %s\n", $1, $2, $3}' "$PLAN/results.tsv"
3573
+ # 14 covers NEEDS_DECISION; 9 pushes the branch column out for IMPLEMENTED (11) too.
3574
+ printf ' %-14s %-14s %s\n' id status branch
3575
+ awk -F'\t' '{printf " %-14s %-14s %s\n", $1, $2, $3}' "$PLAN/results.tsv"
2909
3576
  echo
2910
3577
  if [ -n "$retro_line" ]; then printf '%s\n\n' "$retro_line"; fi
2911
3578
  run_report_extras "$PLAN"
@@ -2954,10 +3621,19 @@ do_run() {
2954
3621
  fi
2955
3622
  # Tasks stopped for a decision (#69): why, and the choices. Not failures to retry either.
2956
3623
  report_decisions "$PLAN"
3624
+ # Members implemented and waiting for their group's review (#140): not failures either.
3625
+ local implemented; implemented="$(awk -F'\t' '$2=="IMPLEMENTED" {print $1}' "$PLAN/results.tsv")"
3626
+ if [ -n "$implemented" ]; then
3627
+ echo "implemented, waiting for their group's review:"
3628
+ for id in $implemented; do
3629
+ printf ' %s: group %s\n' "$id" "$(forge_groups_id_of "$PLAN" "$id")"
3630
+ done
3631
+ echo
3632
+ fi
2957
3633
  # The retry hint is for tasks that actually failed; a run that only failed verification,
2958
3634
  # or only paused on infrastructure, has nothing to retry task by task. An interrupted task
2959
3635
  # has its own hint above, a task waiting for an answer or a decision its own block.
2960
- if [ "$(awk -F'\t' '$2!="MERGED" && $2!="INFRA" && $2!="PENDING" && $2!="BLOCKED" && $2!="INTERRUPTED" && $2!="NEEDS_INPUT" && $2!="NEEDS_DECISION" {n++} END {print n+0}' "$PLAN/results.tsv")" -gt 0 ]; then
3636
+ if [ "$(awk -F'\t' '$2!="MERGED" && $2!="INFRA" && $2!="PENDING" && $2!="BLOCKED" && $2!="INTERRUPTED" && $2!="NEEDS_INPUT" && $2!="NEEDS_DECISION" && $2!="IMPLEMENTED" {n++} END {print n+0}' "$PLAN/results.tsv")" -gt 0 ]; then
2961
3637
  echo "retry a failed task with its reviewer's findings:"
2962
3638
  echo " forge-parallel.sh retry $PLAN <task-id> [--dwarf <spec>]"
2963
3639
  echo "or let a run retry them itself: forge-parallel.sh run $PLAN --retry-failed 1"
@@ -3023,6 +3699,8 @@ do_integrate() {
3023
3699
  parent="$(git -C "$REPO" rev-parse HEAD)" || return 3
3024
3700
  target="$(git -C "$REPO" rev-parse "$int_br")" || return 3
3025
3701
  [ -s "$PLAN/accepted.integration" ] && [ "$target" = "$(cat "$PLAN/accepted.integration")" ] || die "integration revision does not match the accepted run" 3
3702
+ # The branch holds the work of every plan it follows: one merge brings them all.
3703
+ [ ! -s "$PLAN/after" ] || echo "this brings plans $(plans_chain_names "$PLAN")"
3026
3704
  out="$PLAN/integrate-$(date +%s)-$$"; mkdir -p "$out"
3027
3705
  candidate="$(cat "$PLAN/wt_root")/_candidate-$$"
3028
3706
  git -C "$REPO" worktree add --detach "$candidate" "$parent" > "$out/setup.log" 2>&1 || return 3
@@ -3407,6 +4085,9 @@ case "$CMD" in
3407
4085
  combine) need_fn do_combine; do_combine "$@" ;;
3408
4086
  _task) do_task "$@" ;;
3409
4087
  _merge) merge_task "$@" ;;
4088
+ _group) need_fn do_group; do_group "$@" ;;
4089
+ _group_settle) need_fn do_group_settle; do_group_settle "$@" ;;
4090
+ _merge_group) need_fn merge_group; merge_group "$@" ;;
3410
4091
  # The live scheduler's accept (forge control accept, #138): it holds the plan lock already.
3411
4092
  _accept) need_fn do_accept; FORGE_ACCEPT_LIVE=1 do_accept "$@" ;;
3412
4093
  _prepare_retry) retry_for_scheduler "$@" ;;