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