@giamme/forge 0.17.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -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,49 @@
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
87
+ # --retro | --no-retro agents record what got in their way (retro, #132); plan file `retro_mode`
88
+ # (on or off; not `retro`, the notes directory). Without a flag the plan
89
+ # keeps its earlier choice, else (first plan only) takes the user
90
+ # `features` setting. The first plan with it on says what is recorded
91
+ # --brief LEVEL advisory, gated, strict or off (#135): one cheap read-only dispatch per
92
+ # task before it starts. Plan files `brief`, `brief_scope` (--brief-scope
93
+ # task|wave|plan, default task) and `brief_model` (--brief-model SPEC). On
94
+ # with no model is refused (exit 2); `off` writes `off` and drops the rest
95
+ # --summaries on|off a generated summary per task (#133); plan files `summaries` and
96
+ # `summaries_model` (--summaries-model SPEC); on with no model is refused.
97
+ # A flag beats the user setting (forge config show), which is read once, at
98
+ # the first plan; a re-plan without the flag keeps what the plan has, and an
99
+ # explicit off (--no-retro, --brief off, --summaries off) is kept as `off`
62
100
  # --fast ROLES which of dwarf, qa, planner, review ask for the fast service tier
63
101
  # (comma list, or all, or none). Kept in the plan; a re-plan without
64
102
  # the flag keeps it, and none removes it. codex and claude only
@@ -147,7 +185,7 @@ JEV_OPTS=0
147
185
  # Flags shared by several subcommands, then the helper libraries. Functions only, resolved
148
186
  # at call time, so they may use die/note/field and friends defined below.
149
187
  source "$SKILL_DIR/scripts/forge-parallel-options.sh"
150
- 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
151
189
  [ -f "$SKILL_DIR/scripts/forge-lib-$forge_lib.sh" ] && source "$SKILL_DIR/scripts/forge-lib-$forge_lib.sh"
152
190
  done
153
191
  OUTPUT=summary
@@ -207,6 +245,16 @@ pool_pick() { # pool_pick <comma-list> <index>
207
245
  echo "$last"
208
246
  }
209
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
+
210
258
  # --- profiles (#48) -------------------------------------------------------------
211
259
  # A named profile is chosen at `plan` (or by forge-solo.sh), frozen as <dir>/profile.json
212
260
  # and applied as the values its flags would have set. forge_decide.profiles does the
@@ -305,18 +353,438 @@ $(forge_profile_py value "$1/profile.json" policy.retry_failed policy.infra_retr
305
353
  EOF
306
354
  }
307
355
 
356
+ # --- retro, brief and summaries (#132, #135, #133): options frozen into the plan -------
357
+ # `plan` writes six plan files (retro_mode, brief, brief_scope, brief_model, summaries,
358
+ # summaries_model) that forge_side.settings(plan) reads at run time. The retro file is not
359
+ # called `retro`: <plan>/retro/ is where the notes are kept. For each, a flag of this call
360
+ # wins, then what the plan already has (a re-plan without the flag keeps it, as
361
+ # --reviewer-session is kept), then the user `features` setting, read here once. The user
362
+ # setting turns a feature on or off only before the plan is first planned (no waves.tsv):
363
+ # after that the plan is frozen, here as in forge_side.settings, and a feature a re-plan does
364
+ # not name stays as it was. (A flag that turns a feature on may still take its scope and
365
+ # model from the user setting.) A feature that is on writes its files. One that is off
366
+ # because a flag said so, or because the plan already said `off`, writes `off` into its
367
+ # switch file (retro_mode, brief, summaries), so a later re-plan or a plan made from this
368
+ # one cannot take it from the user setting again; its scope and model files go. One that is
369
+ # merely off by default (no flag, no file, the user setting off) writes nothing, which is
370
+ # what keeps a plan with every feature off exactly what it was before these options.
371
+ #
372
+ # forge_features_resolve sets FEAT_* and writes nothing; it returns 2 (FEAT_ERR says why) when
373
+ # a feature is on with no model, or a model spec does not resolve. forge_features_store writes
374
+ # the files and says what retro records the first time. An empty value means "no file".
375
+ forge_features_user() { # prints key=value lines: the stored user settings, defaults when unreadable
376
+ PYTHONPATH="$SKILL_DIR/scripts${PYTHONPATH:+:$PYTHONPATH}" python3 - <<'PY' 2>/dev/null || true
377
+ import forge_side
378
+ f = forge_side.stored_features()
379
+ for k in ('retro', 'brief', 'brief.scope', 'brief.model', 'summaries', 'summaries.model'):
380
+ print('%s=%s' % (k, f.get(k) or ''))
381
+ PY
382
+ }
383
+
384
+ forge_feature_file() { # forge_feature_file <plan> <name> -> first line, trimmed; empty when absent
385
+ local line=""
386
+ if [ -f "$1/$2" ] && [ -r "$1/$2" ]; then IFS= read -r line < "$1/$2" || true; fi
387
+ line="${line#"${line%%[![:space:]]*}"}"
388
+ printf '%s' "${line%"${line##*[![:space:]]}"}"
389
+ }
390
+
391
+ forge_feature_spec_ok() { # forge_feature_spec_ok <flag name> <spec>: dispatch's own dry run, as a --qa spec resolves
392
+ local tmp err rc=0
393
+ tmp="$(mktemp -d)" || { FEAT_ERR="could not make a temporary directory"; return 2; }
394
+ mkdir -p "$tmp/repo" "$tmp/run"; echo spec-check > "$tmp/prompt"
395
+ bash "$SKILL_DIR/scripts/forge-dispatch.sh" side "$2" --repo "$tmp/repo" --run-dir "$tmp/run" \
396
+ --prompt-file "$tmp/prompt" --dry-run >/dev/null 2>"$tmp/err" || rc=$?
397
+ err="$(awk 'NF { line = $0 } END { print line }' "$tmp/err" 2>/dev/null)"
398
+ rm -rf "${tmp:?}"
399
+ [ "$rc" -eq 0 ] || { FEAT_ERR="$1: '$2' does not resolve to a model${err:+ ($err)}"; return 2; }
400
+ }
401
+
402
+ forge_features_resolve() { # forge_features_resolve <plan>
403
+ local plan="$1" key val
404
+ local u_retro=off u_brief=off u_scope=task u_bmodel="" u_summ=off u_smodel=""
405
+ while IFS== read -r key val; do
406
+ case "$key" in
407
+ retro) [ "$val" = on ] && u_retro=on ;;
408
+ brief) [ -n "$val" ] && u_brief="$val" ;;
409
+ brief.scope) [ -n "$val" ] && u_scope="$val" ;;
410
+ brief.model) u_bmodel="$val" ;;
411
+ summaries) [ -n "$val" ] && u_summ="$val" ;;
412
+ summaries.model) u_smodel="$val" ;;
413
+ esac
414
+ done <<FEATURES_EOF
415
+ $(forge_features_user)
416
+ FEATURES_EOF
417
+ # Planned before: the user setting no longer turns anything on or off (see above).
418
+ if [ -e "$plan/waves.tsv" ]; then u_retro=off; u_brief=off; u_summ=off; fi
419
+ local f_retro f_brief f_scope f_bmodel f_summ f_smodel
420
+ f_retro="$(forge_feature_file "$plan" retro_mode)"; f_brief="$(forge_feature_file "$plan" brief)"
421
+ f_scope="$(forge_feature_file "$plan" brief_scope)"; f_bmodel="$(forge_feature_file "$plan" brief_model)"
422
+ f_summ="$(forge_feature_file "$plan" summaries)"; f_smodel="$(forge_feature_file "$plan" summaries_model)"
423
+
424
+ # retro: `on`; `off` when a flag or the plan says so; else no file
425
+ local retro="${RETRO_FLAG:-${f_retro:-$u_retro}}"
426
+ FEAT_RETRO=""
427
+ if [ "$retro" = on ]; then FEAT_RETRO=on
428
+ elif [ -n "$RETRO_FLAG" ] || [ -n "$f_retro" ]; then FEAT_RETRO=off; fi
429
+
430
+ # brief: the level, its scope and its model
431
+ local level="${BRIEF_FLAG:-${f_brief:-$u_brief}}"
432
+ case "$level" in advisory|gated|strict|off) ;; *) level=off ;; esac
433
+ FEAT_BRIEF=""; FEAT_BRIEF_SCOPE=""; FEAT_BRIEF_MODEL=""
434
+ if [ "$level" = off ] && { [ -n "$BRIEF_FLAG" ] || [ -n "$f_brief" ]; }; then FEAT_BRIEF=off; fi
435
+ if [ "$level" != off ]; then
436
+ local scope="${BRIEF_SCOPE_FLAG:-${f_scope:-$u_scope}}" bmodel="${BRIEF_MODEL_FLAG:-${f_bmodel:-$u_bmodel}}"
437
+ case "$scope" in task|wave|plan) ;; *) scope=task ;; esac
438
+ if [ -z "$bmodel" ]; then
439
+ FEAT_ERR="brief is $level but has no model: pass --brief-model SPEC or run 'forge config set brief.model SPEC'"
440
+ return 2
441
+ fi
442
+ FEAT_BRIEF="$level"; FEAT_BRIEF_SCOPE="$scope"; FEAT_BRIEF_MODEL="$bmodel"
443
+ fi
444
+
445
+ # summaries: the mode and its model
446
+ local mode="${SUMM_FLAG:-${f_summ:-$u_summ}}"
447
+ case "$mode" in on|off) ;; *) mode=off ;; esac
448
+ FEAT_SUMM=""; FEAT_SUMM_MODEL=""
449
+ if [ "$mode" = off ] && { [ -n "$SUMM_FLAG" ] || [ -n "$f_summ" ]; }; then FEAT_SUMM=off; fi
450
+ if [ "$mode" = on ]; then
451
+ local smodel="${SUMM_MODEL_FLAG:-${f_smodel:-$u_smodel}}"
452
+ if [ -z "$smodel" ]; then
453
+ FEAT_ERR="summaries is on but has no model: pass --summaries-model SPEC or run 'forge config set summaries.model SPEC'"
454
+ return 2
455
+ fi
456
+ FEAT_SUMM=on; FEAT_SUMM_MODEL="$smodel"
457
+ fi
458
+
459
+ # Every model that will be dispatched resolves now, not at its first dispatch.
460
+ if [ -n "$FEAT_BRIEF_MODEL" ]; then forge_feature_spec_ok --brief-model "$FEAT_BRIEF_MODEL" || return 2; fi
461
+ if [ -n "$FEAT_SUMM_MODEL" ] && [ "$FEAT_SUMM_MODEL" != "$FEAT_BRIEF_MODEL" ]; then
462
+ forge_feature_spec_ok --summaries-model "$FEAT_SUMM_MODEL" || return 2
463
+ fi
464
+ return 0
465
+ }
466
+
467
+ # The six flags are read in a pass of their own, before the main loop: the shared flags
468
+ # (--qa-threshold, ...) write into the plan dir as they are parsed, so a refusal that came
469
+ # after them would leave their files behind. Here nothing has been written yet, and every bad
470
+ # value or missing model ends the call with the plan dir untouched.
471
+ forge_features_scan() { # forge_features_scan "$@": sets the *_FLAG variables of do_plan
472
+ while [ $# -gt 0 ]; do
473
+ case "$1" in
474
+ --retro) RETRO_FLAG=on ;;
475
+ --no-retro) RETRO_FLAG=off ;;
476
+ --brief)
477
+ case "${2:-}" in advisory|gated|strict|off) BRIEF_FLAG="$2"; shift ;;
478
+ *) die "--brief must be advisory, gated, strict or off" ;; esac ;;
479
+ --brief-scope)
480
+ case "${2:-}" in task|wave|plan) BRIEF_SCOPE_FLAG="$2"; shift ;;
481
+ *) die "--brief-scope must be task, wave or plan" ;; esac ;;
482
+ --brief-model)
483
+ [ -n "${2:-}" ] || die "--brief-model needs a model spec"
484
+ BRIEF_MODEL_FLAG="$2"; shift ;;
485
+ --summaries)
486
+ case "${2:-}" in on|off) SUMM_FLAG="$2"; shift ;;
487
+ *) die "--summaries must be on or off" ;; esac ;;
488
+ --summaries-model)
489
+ [ -n "${2:-}" ] || die "--summaries-model needs a model spec"
490
+ SUMM_MODEL_FLAG="$2"; shift ;;
491
+ esac
492
+ shift
493
+ done
494
+ }
495
+
496
+ forge_features_store() { # forge_features_store <plan>
497
+ local plan="$1" pair name var val
498
+ for pair in retro_mode:FEAT_RETRO brief:FEAT_BRIEF brief_scope:FEAT_BRIEF_SCOPE brief_model:FEAT_BRIEF_MODEL \
499
+ summaries:FEAT_SUMM summaries_model:FEAT_SUMM_MODEL; do
500
+ name="${pair%%:*}"; var="${pair#*:}"; val="${!var}"
501
+ if [ -z "$val" ]; then
502
+ rm -f "${plan:?}/${name:?}"
503
+ else
504
+ printf '%s\n' "$val" > "$plan/$name" || die "could not write $plan/$name" 3
505
+ fi
506
+ done
507
+ if [ "$FEAT_RETRO" = on ]; then forge_retro_notice "$plan"; fi
508
+ return 0
509
+ }
510
+
511
+ # Said once per user, to stderr, the first time a plan has retro on. The marker is in the state dir.
512
+ forge_retro_notice() { # forge_retro_notice <plan>
513
+ local marker="${XDG_STATE_HOME:-$HOME/.local/state}/forge/retro.noticed"
514
+ [ ! -e "$marker" ] || return 0
515
+ note "retro is on. Each agent records what got in its way: a note with the command it ran and an excerpt of the error."
516
+ note " Kept in $1/retro/, in tasks/<id>/retro.json and in the local dataset. Nothing leaves this machine"
517
+ note " unless you approve it with 'forge retro issues'. This notice is shown once per user."
518
+ { mkdir -p "${marker%/*}" && : > "$marker"; } 2>/dev/null || true
519
+ }
520
+
521
+ # 0 when this plan records retro notes. settings() is the switch: the plan file, the user
522
+ # setting before waves.tsv, and FORGE_RETRO=off. Auto's planner is dispatched before `plan`
523
+ # writes retro_mode, so AUTO_RETRO_FLAG (on, off, or empty) carries the flag that call will
524
+ # hand to plan. Off from the environment still wins. Prints nothing and writes nothing.
525
+ forge_retro_on() { # forge_retro_on <plan>
526
+ local flag="${AUTO_RETRO_FLAG:-}"
527
+ PYTHONPATH="$SKILL_DIR/scripts${PYTHONPATH:+:$PYTHONPATH}" \
528
+ python3 - "$1" "$flag" >/dev/null <<'PY'
529
+ import os, sys
530
+ import forge_side
531
+ plan, flag = sys.argv[1], sys.argv[2]
532
+ if os.environ.get('FORGE_RETRO', '').strip().lower() == 'off':
533
+ sys.exit(1)
534
+ if flag == 'on':
535
+ sys.exit(0)
536
+ if flag == 'off':
537
+ sys.exit(1)
538
+ sys.exit(0 if forge_side.settings(plan).get('retro') else 1)
539
+ PY
540
+ }
541
+
542
+ # The retro instruction, printed so it can be the last block of a prompt. Nothing when retro
543
+ # is off, which is what keeps that prompt byte-identical.
544
+ forge_retro_prompt() { # forge_retro_prompt <plan> <role>
545
+ forge_retro_on "$1" || return 0
546
+ echo
547
+ python3 "$SKILL_DIR/scripts/forge-contract.py" retro --role "$2" \
548
+ || note "retro: could not write the $2 instruction"
549
+ return 0
550
+ }
551
+
552
+ # One dispatch's notes. A failure is one warning and never the caller's result: the status
553
+ # and the exit code stay whatever the dispatch already decided. No task for a whole-run
554
+ # dispatch (the planner, the final review). The inbox is the dwarf worktree's.
555
+ forge_retro_record() { # forge_retro_record <plan> <role> <dir> [task] [attempt] [inbox]
556
+ forge_retro_on "$1" || return 0
557
+ local plan="$1" role="$2" dir="$3" task="${4:-}" attempt="${5:-}" inbox="${6:-}"
558
+ local cmd=(python3 "$SKILL_DIR/scripts/forge-retro.py" record "$plan" --role "$role" --dir "$dir")
559
+ [ -n "$task" ] && cmd+=(--task "$task")
560
+ [ -n "$attempt" ] && cmd+=(--attempt "$attempt")
561
+ [ -n "$inbox" ] && cmd+=(--inbox "$inbox")
562
+ if ! "${cmd[@]}" >/dev/null 2>&1; then
563
+ note "retro: could not record the $role notes${task:+ for $task}"
564
+ fi
565
+ return 0
566
+ }
567
+
568
+ # Rewrite retro.md. Quiet: integrate and review regenerate after their dispatches, and the
569
+ # run's own summary line is forge_retro_summary_line. A failure is one warning.
570
+ forge_retro_report() { # forge_retro_report <plan>
571
+ forge_retro_on "$1" || return 0
572
+ python3 "$SKILL_DIR/scripts/forge-retro.py" report "$1" >/dev/null 2>&1 \
573
+ || note "retro: could not write the report"
574
+ return 0
575
+ }
576
+
577
+ # Write retro.md and print the one summary line when the report has any pattern. Nothing
578
+ # when it does not, or when retro is off (no call, no file).
579
+ forge_retro_summary_line() { # forge_retro_summary_line <plan>
580
+ forge_retro_on "$1" || return 0
581
+ local json
582
+ json="$(python3 "$SKILL_DIR/scripts/forge-retro.py" report "$1" --json 2>/dev/null)" || {
583
+ note "retro: could not write the report"
584
+ return 0
585
+ }
586
+ printf '%s' "$json" | python3 -c '
587
+ import json, sys
588
+ doc = json.load(sys.stdin)
589
+ plan = sys.argv[1]
590
+ n = u = f = 0
591
+ for group in doc.get("groups") or []:
592
+ k = len(group.get("patterns") or [])
593
+ n += k
594
+ if group.get("id") == "user":
595
+ u += k
596
+ elif group.get("id") == "forge":
597
+ f += k
598
+ if n:
599
+ sys.stdout.write("retro: %d patterns (%d you can fix, %d for forge): %s/retro.md\n" % (n, u, f, plan))
600
+ ' "$1"
601
+ return 0
602
+ }
603
+
604
+ # One line per feature that is on, from the plan files (what the run will do).
605
+ forge_features_table() { # forge_features_table <plan>
606
+ local plan="$1" level scope model
607
+ if [ "$(forge_feature_file "$plan" retro_mode)" = on ]; then
608
+ echo "retro: agents record what got in their way; report at retro.md (local only)"
609
+ fi
610
+ level="$(forge_feature_file "$plan" brief)"
611
+ case "$level" in
612
+ advisory|gated|strict)
613
+ scope="$(forge_feature_file "$plan" brief_scope)"; model="$(forge_feature_file "$plan" brief_model)"
614
+ echo "brief: $level, ${scope:-task} scope, ${model:-no model}; one cheap read-only dispatch per task before it starts" ;;
615
+ esac
616
+ if [ "$(forge_feature_file "$plan" summaries)" = on ]; then
617
+ echo "summaries: on, $(forge_feature_file "$plan" summaries_model); one cheap dispatch per task when its attempts or status change"
618
+ fi
619
+ return 0
620
+ }
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
+
308
761
  do_plan() {
309
762
  local PLAN="${1:?plan needs a plan dir}"; shift
310
763
  local PF_NAME="" PF_NONE=0 PF_QT=0
311
764
  forge_profile_precheck "$PLAN" "$@"
312
765
  local REPO="" D_ANY="" D_HI="" D_MD="" D_LO="" Q_ANY="" Q_HI="" Q_MD="" Q_LO=""
313
766
  PP_INFRA_FALLBACK=""
314
- 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=""
315
768
  local FAST_GIVEN=0 FAST_PARSED=""
316
- local COLLAPSE=0 COLLAPSED_NOW=0
769
+ local RETRO_FLAG="" BRIEF_FLAG="" BRIEF_SCOPE_FLAG="" BRIEF_MODEL_FLAG="" SUMM_FLAG="" SUMM_MODEL_FLAG=""
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
773
+ # The retro, brief and summaries choices, settled before anything is written: a refusal
774
+ # (a bad value, no model, a spec that does not resolve) leaves the plan dir as it was.
775
+ forge_features_scan "$@"
776
+ [ -d "$PLAN" ] || die "plan dir '$PLAN' does not exist"
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 "$@"
317
784
  while [ $# -gt 0 ]; do
318
785
  case "$1" in
319
786
  --repo) REPO="${2:?}"; shift 2 ;;
787
+ --after) [ -n "${2:-}" ] || die "--after needs a plan directory" 2; shift 2 ;;
320
788
  --planner) PLANNER="${2:?}"; shift 2 ;;
321
789
  --decompose-level)
322
790
  case "${2:-}" in low|medium|high) DLEVEL="$2"; shift 2 ;;
@@ -332,6 +800,19 @@ do_plan() {
332
800
  printf '%s' "${2:-}" | grep -Eq '^(0?\.[0-9]+|0|1|1\.0+)$' || die "--shadow-rate needs a share between 0 and 1"
333
801
  SHADOW_RATE="$2"; shift 2 ;;
334
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 ;;
335
816
  --collapse-chains) COLLAPSE=1; shift ;;
336
817
  --dwarf) D_ANY="${2:?}"; shift 2 ;;
337
818
  --dwarf-high) D_HI="${2:?}"; shift 2 ;;
@@ -351,7 +832,15 @@ do_plan() {
351
832
  || die "--pre-review-parallel needs an integer from 1 to 64" 2
352
833
  PRE_REVIEW_PARALLEL="$((10#$2))"; shift 2 ;;
353
834
  --reviewer-session) REVIEWER_SESSION=on; shift ;;
354
- --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 ;;
355
844
  --implementer-session) IMPLEMENTER_SESSION=on; shift ;;
356
845
  --no-implementer-session) IMPLEMENTER_SESSION=off; shift ;;
357
846
  --fast)
@@ -359,6 +848,8 @@ do_plan() {
359
848
  forge_fast_parse "$2" plan
360
849
  FAST_GIVEN=1
361
850
  shift 2 ;;
851
+ --retro|--no-retro) shift ;; # read by forge_features_scan
852
+ --brief|--brief-scope|--brief-model|--summaries|--summaries-model) shift 2 ;;
362
853
  *)
363
854
  # `case` is not a loop, so `continue` here belongs to the enclosing while.
364
855
  # The shared flags write into the plan dir (--qa-threshold), so it must exist first.
@@ -379,9 +870,15 @@ do_plan() {
379
870
  esac
380
871
  done
381
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)"
382
874
  # The profile (#48) first: its gates and budget count for every decision-model step below,
383
875
  # and its values stand in for the flags this call did not give.
384
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"
385
882
  [ "$JEV_OPTS" = 1 ] && forge_jev_export
386
883
  # Freeze the selection next to the task table, so run and retry restore it rather
387
884
  # than re-deciding. Written on every plan: a re-plan is a new decision.
@@ -406,6 +903,10 @@ do_plan() {
406
903
  esac
407
904
  [ -z "$SHADOW_RATE" ] || [ "$SHADOW_QA" = none ] || [ "$SHADOW_QA" = off ] \
408
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"
409
910
  # Fail-first evidence (opt-in, advisory) is part of the plan too: every task's review gets it.
410
911
  case "$FAIL_FIRST" in on) : > "$PLAN/fail_first" ;; off) rm -f "$PLAN/fail_first" ;; esac
411
912
  # Pre-review tests (opt-in, #85): each attempt's affected tests run before its review, and a
@@ -416,10 +917,28 @@ do_plan() {
416
917
  # Reviewer-session continuation (opt-in experiment): the file holds `on`. Readers only
417
918
  # test that it exists; the dataset records its content.
418
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
419
930
  # Implementer-session continuation (opt-in, #90): the same `on` file, read the same way.
420
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
421
938
  # Which roles ask for the fast tier. Omitted on a re-plan, so an earlier choice stays.
422
939
  forge_fast_store "$PLAN"
940
+ # Retro, brief and summaries (#132, #133, #135), as forge_features_resolve settled them.
941
+ forge_features_store "$PLAN"
423
942
  # Exploration is decided here and only here, so the table and preflight see what will run.
424
943
  # On by default: choosing models from measured pass rates needs some randomized picks, and
425
944
  # history had almost none (9 tasks ever ran on more than one spec). The flag wins, then
@@ -477,7 +996,7 @@ PY
477
996
  # Uncommitted work is invisible to every dwarf, because worktrees branch from a
478
997
  # commit. That is the likeliest way to get a confusingly wrong result, so it is
479
998
  # stated loudly rather than left for the user to deduce from an odd diff.
480
- 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
481
1000
  note "WARNING: '$REPO' has uncommitted changes. Task worktrees branch from HEAD,"
482
1001
  note " so those edits will NOT be visible to any dwarf. Commit or stash first"
483
1002
  note " if the tasks depend on them."
@@ -609,8 +1128,12 @@ EOF
609
1128
  fi
610
1129
  # resolve dwarf. UNASSIGNED is a marker from a previous plan, not a user
611
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`.
612
1132
  [ "$dw" = "UNASSIGNED" ] && dw="-"
613
- 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
614
1137
  case "$diff" in
615
1138
  high) if [ -n "$D_HI" ]; then dw="$(pool_pick "$D_HI" "$hi_i")"; hi_i=$((hi_i+1)); fi ;;
616
1139
  medium) if [ -n "$D_MD" ]; then dw="$(pool_pick "$D_MD" "$md_i")"; md_i=$((md_i+1)); fi ;;
@@ -658,6 +1181,8 @@ EOF
658
1181
  fi
659
1182
 
660
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")"
661
1186
 
662
1187
  # --- jev: forward dependency ----------------------------------------------------
663
1188
  # Wave order is structural, but it cannot see an earlier-wave task written against
@@ -707,6 +1232,10 @@ EOF
707
1232
  note "plan shape could not be recorded (advisory)${shape_err:+: $shape_err}"
708
1233
  fi
709
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
+
710
1239
  render_table "$PLAN"
711
1240
  # What the gates did, from plan-gates.json: files and deps they added, prompts and
712
1241
  # requirements still flagged. Prints nothing when no gate recorded anything.
@@ -775,18 +1304,75 @@ compute_waves() {
775
1304
  mv -f "$D" "$PLAN/deferrals.txt" && mv -f "$W" "$PLAN/waves.tsv"
776
1305
  }
777
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
+
778
1340
  render_table() {
779
1341
  local PLAN="$1" T="$1/tasks.tsv" W="$1/waves.tsv"
780
1342
  local run_id; run_id="$(cat "$PLAN/run_id")"
781
1343
  local n; n="$(all_ids "$T" | wc -l | tr -d ' ')"
782
1344
  local waves; waves="$(awk -F'\t' '{print $1}' "$W" | sort -u | wc -l | tr -d ' ')"
783
1345
  echo "run forge/$run_id repo $(cat "$PLAN/repo")"
1346
+ plans_chain_line "$PLAN"
784
1347
  [ -s "$PLAN/goal.txt" ] && echo "goal: $(head -1 "$PLAN/goal.txt")"
785
- 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=""
786
1359
  if [ -s "$PLAN/planner" ]; then
787
1360
  est=$((est+1)); extra=" + 1 planner ($(cat "$PLAN/planner"))"
788
1361
  fi
789
- 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"
790
1376
  if [ -s "$PLAN/shadow_qa" ]; then
791
1377
  local rate; rate="$(cat "$PLAN/shadow_rate" 2>/dev/null || echo 0.1)"
792
1378
  echo "shadow review: $(cat "$PLAN/shadow_qa") on a sampled $rate of reviewed attempts" \
@@ -806,7 +1392,9 @@ render_table() {
806
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"
807
1393
  fi
808
1394
  fi
809
- 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
810
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)"
811
1399
  fi
812
1400
  if [ -f "$PLAN/implementer_session" ]; then
@@ -817,6 +1405,7 @@ render_table() {
817
1405
  fast_roles="$(awk 'NF { printf "%s%s", (n++ ? ", " : ""), $0 }' "$PLAN/fast")"
818
1406
  echo "fast tier: $fast_roles — billed at a higher rate (codex service_tier=fast; claude fast mode needs extra usage enabled)"
819
1407
  fi
1408
+ forge_features_table "$PLAN"
820
1409
  if [ -f "$PLAN/profile.json" ]; then
821
1410
  local profile_line; profile_line="$(forge_profile_py line "$PLAN/profile.json" 2>/dev/null)"
822
1411
  [ -z "$profile_line" ] || echo "$profile_line"
@@ -858,6 +1447,7 @@ EOF
858
1447
  done
859
1448
  echo
860
1449
  done
1450
+ render_groups "$PLAN"
861
1451
  # A chain collapsed on this call, or a chain left as a chain. one and branches say nothing.
862
1452
  # COLLAPSED_NOW is do_plan's: collapsed.json from an earlier plan is not announced again.
863
1453
  local shape_note=""
@@ -929,6 +1519,10 @@ preflight_plan() {
929
1519
  flags=""; [ -f "$plan/yolo_$role" ] && flags=--yolo
930
1520
  ft="$(forge_fast_tier "$plan" "$role")"
931
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
932
1526
  # Once per spec, role and options: the same arguments get the same answer, and a note doctor
933
1527
  # adds (a slow effort) is said once, not once per task.
934
1528
  key="$role|$spec|$flags|$ft"
@@ -1141,6 +1735,176 @@ check_drift() { # check_drift <declared-comma-list> <tdir> <wt> <base>
1141
1735
  return 0
1142
1736
  }
1143
1737
 
1738
+ # The attempt trail (#133): one line per attempt that starts with carried findings, saying why it
1739
+ # happened, as `<attempt>\t<source>\t<epoch>`. The source is read the way forge-prompt.py reads it
1740
+ # (a missing or unknown one is a review). A line for the same attempt number is replaced rather than
1741
+ # repeated: an infrastructure stop refunds the attempt, so its restart runs the same number again.
1742
+ # An existing trail that cannot be read is left as it is (non-zero return): rewriting it from this
1743
+ # one line would drop the history.
1744
+ record_retry_source() { # record_retry_source <tdir> <attempt>
1745
+ local tdir="$1" n="$2" src trail tmp
1746
+ trail="$tdir/retry_sources.tsv"; tmp="$tdir/.retry_sources.tsv.tmp"
1747
+ [ -s "$tdir/retry_findings.md" ] || return 0
1748
+ src="$(cat "$tdir/retry_findings.source" 2>/dev/null)"
1749
+ case "$src" in review|prereview|bounce|message|answer|prompt) ;; *) src=review ;; esac
1750
+ if [ -e "$trail" ]; then
1751
+ [ -f "$trail" ] && [ -r "$trail" ] || return 1
1752
+ awk -F'\t' -v n="$n" '$1 != n' "$trail" > "$tmp" 2>/dev/null || { rm -f "$tmp"; return 1; }
1753
+ else
1754
+ : > "$tmp" || return 1
1755
+ fi
1756
+ printf '%s\t%s\t%s\n' "$n" "$src" "$(date +%s)" >> "$tmp" && mv "$tmp" "$trail" || { rm -f "$tmp"; return 1; }
1757
+ }
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
+
1144
1908
  do_task_body() (
1145
1909
  local PLAN="${1:?}" id="${2:?}"
1146
1910
  local T="$PLAN/tasks.tsv" REPO run_id base wt br tdir attempt resume=""
@@ -1160,6 +1924,16 @@ do_task_body() (
1160
1924
  [ -s "$PLAN/timeout" ] && export FORGE_TIMEOUT="$(cat "$PLAN/timeout")"
1161
1925
  wt="$(cat "$PLAN/wt_root")/$id"
1162
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"
1163
1937
  # Every attempt gets a distinct number and commit message. A QA-only resume (the
1164
1938
  # reviewer hit an infrastructure failure, or never reached a verdict) re-reviews work
1165
1939
  # that is already committed, so it neither runs the dwarf nor spends an attempt.
@@ -1207,10 +1981,23 @@ do_task_body() (
1207
1981
  return 1
1208
1982
  fi
1209
1983
 
1984
+ local is_script=0
1985
+ task_is_script "$PLAN" "$id" && is_script=1
1210
1986
  if [ -z "$resume" ]; then
1211
1987
  # Persist each source separately; QA receives complete context once.
1212
1988
  write_capsule "$PLAN" "$id" dwarf >/dev/null
1213
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
1214
2001
  # --task lets Jev narrow the injected slice to facts that bear on THIS task. Without
1215
2002
  # it, or with Jev off, the full role slice is injected exactly as before.
1216
2003
  /bin/bash "$MEMORY" inject "$REPO" dwarf --task "$tdir/prompt.md" \
@@ -1224,7 +2011,11 @@ do_task_body() (
1224
2011
  echo; python3 "$SKILL_DIR/scripts/forge-contract.py" dwarf $([ ! -f "$PLAN/pre_review_tests" ] || echo --pre-review) \
1225
2012
  $([ -z "$(verify_source_for "$PLAN" "$REPO")" ] || echo --verify-after-merge)
1226
2013
  echo; /bin/bash "$MEMORY" note dwarf
2014
+ # Last, after the memory note. Nothing is printed when retro is off.
2015
+ forge_retro_prompt "$PLAN" dwarf
1227
2016
  } > "$tdir/dwarf.input"
2017
+ # This attempt starts with the findings just written to dwarf.input (#133).
2018
+ record_retry_source "$tdir" "$attempt" || note "$id: retry_sources.tsv not updated; the attempt trail stays as it was"
1228
2019
  guard_before_dwarf "$wt" "$tdir"
1229
2020
  # Whether this attempt continues the implementer's earlier session (plan
1230
2021
  # --implementer-session, #90): only a retry of judged work that is still exactly what was
@@ -1268,6 +2059,9 @@ do_task_body() (
1268
2059
  if [ -n "$is_fp" ] && [ "$(forge_fingerprint "$wt")" = "$is_fp" ]; then
1269
2060
  # It changed nothing, so the same input goes to a fresh session, which decides the attempt.
1270
2061
  is_mode=fresh
2062
+ # The fresh dispatch deletes dwarf.last and dwarf.log as it starts. Record the
2063
+ # continuation first; a failure to record does not change the attempt.
2064
+ forge_retro_record "$PLAN" dwarf "$tdir" "$id" "$attempt" "$wt/.forge/retro-inbox.jsonl"
1271
2065
  "${dwarf_cmd[@]}" >"$tdir/dwarf.out" 2>&1
1272
2066
  rc=$?
1273
2067
  else
@@ -1287,6 +2081,9 @@ do_task_body() (
1287
2081
  fi
1288
2082
  if [ "${FORGE_OUTPUT:-summary}" = full ]; then cat "$tdir/dwarf.out"; fi
1289
2083
  if [ "$rc" -ne 0 ]; then
2084
+ # The dispatch ended without a result memory would record. Keep its notes anyway;
2085
+ # a failure to record them does not change the status this case is about to write.
2086
+ forge_retro_record "$PLAN" dwarf "$tdir" "$id" "$attempt" "$wt/.forge/retro-inbox.jsonl"
1290
2087
  case "$rc" in
1291
2088
  7) echo TIMEOUT > "$tdir/status"; note "$id: dwarf hit the dispatch timeout — see $tdir/dwarf.out" ;;
1292
2089
  8) infra_stop "$tdir" "$id" dwarf "$attempt"; return 8 ;;
@@ -1298,10 +2095,12 @@ do_task_body() (
1298
2095
  /bin/bash "$MEMORY" record "$REPO" --last "$tdir/dwarf.last" --role dwarf \
1299
2096
  --run-id "$run_id" --task "$id" --model "$dw" --run-dir "$tdir" \
1300
2097
  --duration "$(dispatch_duration "$tdir" dwarf)" >/dev/null 2>&1
2098
+ forge_retro_record "$PLAN" dwarf "$tdir" "$id" "$attempt" "$wt/.forge/retro-inbox.jsonl"
1301
2099
 
1302
2100
  guard_after_dwarf "$wt" "$tdir" "$id"
1303
2101
  # Before the snapshot, so a dwarf that only asked a question (and changed nothing) still reaches it.
1304
2102
  forge_post_dwarf_gates "$PLAN" "$id" "$tdir" "$wt" "$attempt" || return 0
2103
+ fi
1305
2104
  forge_metric_phase snapshot
1306
2105
  # Capture the real diff, including new files, then commit on the task branch.
1307
2106
  # Diffed against the task's pinned base rather than the branch head, so a retry
@@ -1317,12 +2116,18 @@ do_task_body() (
1317
2116
  && git diff --cached --binary "$base" -- . ":(exclude).forge") > "$tdir/changes.diff" 2>/dev/null || { echo ERROR > "$tdir/status"; return 1; }
1318
2117
  if [ ! -s "$tdir/changes.diff" ]; then
1319
2118
  # A harness that exited 0 with an empty final message and changed nothing did not
1320
- # decline the task; it never really ran (login, quota, a dropped connection).
1321
- 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
1322
2123
  infra_stop "$tdir" "$id" dwarf "$attempt"; return 8
1323
2124
  fi
1324
2125
  echo FAIL > "$tdir/status"
1325
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
1326
2131
  echo "The dwarf produced no changes at all." > "$tdir/qa.last"
1327
2132
  note "$id: dwarf produced an empty diff"; return 1
1328
2133
  fi
@@ -1331,6 +2136,10 @@ do_task_body() (
1331
2136
  # already judged.
1332
2137
  if [ -s "$tdir/changes.prev.diff" ] && cmp -s "$tdir/changes.diff" "$tdir/changes.prev.diff" \
1333
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
1334
2143
  echo FAIL > "$tdir/status"
1335
2144
  : > "$tdir/noretry"
1336
2145
  echo "The retry changed nothing: the diff is byte-identical to the previous attempt." \
@@ -1347,7 +2156,7 @@ do_task_body() (
1347
2156
  fi
1348
2157
 
1349
2158
  (cd "$wt" && git -c user.name=forge -c user.email=forge@local \
1350
- 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 || {
1351
2160
  echo ERROR > "$tdir/status"; return 1;
1352
2161
  }
1353
2162
  reviewed="$(git -C "$wt" rev-parse HEAD)" || return 1
@@ -1366,7 +2175,43 @@ do_task_body() (
1366
2175
  else
1367
2176
  reviewed="$(cat "$tdir/reviewed.commit")"
1368
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
1369
2209
  review="$tdir/review-$attempt-$$"
2210
+ # One review of a task at a time, so any snapshot already here is an interrupted review's: a signal
2211
+ # ends this subshell without its EXIT trap (#139).
2212
+ local stale
2213
+ for stale in "$tdir"/review-*; do forge_drop_snapshot "$stale"; done
2214
+ FORGE_REVIEW_SNAPSHOT="$review" # forge_metric_begin's EXIT trap removes it, whatever the outcome
1370
2215
  forge_review_snapshot "$wt" "$base" "$reviewed" "$review" || { echo ERROR > "$tdir/status"; return 1; }
1371
2216
  forge_review_deps "$wt" "$review" "$tdir/review.deps"
1372
2217
  source_fp="$(forge_fingerprint "$wt")" || return 1
@@ -1419,13 +2264,30 @@ do_task_body() (
1419
2264
  # A finding sweep's fix task gets the narrow review: one FIXED / NOT FIXED line per finding.
1420
2265
  local qa_kind=task
1421
2266
  [ ! -f "$tdir/sweep.json" ] || qa_kind=sweep
2267
+ [ "$is_script" != 1 ] || qa_kind=script
1422
2268
  # QA uses the dispatch-time ownership and baseline, never later merge state.
1423
2269
  /bin/bash "$MEMORY" inject "$REPO" qa --task "$tdir/prompt.md" \
1424
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
1425
2280
  {
1426
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"
1427
2282
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind "$qa_kind"
1428
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
1429
2291
  [ ! -f "$PLAN/sweep_ahead" ] || python3 "$SKILL_DIR/scripts/forge-sweep.py" ahead "$PLAN" "$id" --role qa 2>/dev/null
1430
2292
  cat "$tdir/review.deps"
1431
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."
@@ -1442,6 +2304,18 @@ do_task_body() (
1442
2304
  echo "A promise of later work means a check may never have run; judge the diff on its own merits."
1443
2305
  echo
1444
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
1445
2319
  if [ -s "$tdir/drift.txt" ]; then
1446
2320
  # The reviewer is already asked about scope and had no way to know the answer.
1447
2321
  echo "Scope note: this task declared it would touch $(field "$T" "$id" files), and the"
@@ -1453,12 +2327,24 @@ do_task_body() (
1453
2327
  fi
1454
2328
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind "$qa_kind" --threshold "$qa_thr"
1455
2329
  echo
1456
- # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
1457
- # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
1458
- 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
1459
2341
  echo; /bin/bash "$MEMORY" note qa
1460
2342
  echo "Place any learning notes before the final FORGE_VERDICT: PASS or FORGE_VERDICT: FAIL line."
2343
+ # Last, so a shadow review, which copies this file byte for byte, carries the same
2344
+ # instruction. Its notes are not recorded: only this task's own dispatch is.
2345
+ forge_retro_prompt "$PLAN" qa
1461
2346
  } > "$tdir/qa.input"
2347
+ rm -f "$tdir/.qa.diff"
1462
2348
  # Opt-in (plan --shadow-qa): a second, independent review of this same diff, to measure
1463
2349
  # how often two reviewers agree. It reviews its own snapshot from its own dir under
1464
2350
  # $PLAN/shadow/, and nothing in this script ever reads its result.
@@ -1476,6 +2362,8 @@ do_task_body() (
1476
2362
  if [ "$rs_on" = 1 ]; then
1477
2363
  if [ -n "${FORGE_FRACTAL_RUN:-}" ] || forge_plan_is_fractal "$PLAN"; then
1478
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
1479
2367
  elif [ ! -s "$tdir/retry_findings.md" ]; then
1480
2368
  rs_reason=first-round
1481
2369
  else
@@ -1501,6 +2389,9 @@ do_task_body() (
1501
2389
  fi
1502
2390
  rs_mode=fresh
1503
2391
  mv "$tdir/qa.out" "$tdir/qa.continue.out" 2>/dev/null || true
2392
+ # The fresh dispatch deletes qa.last and qa.log as it starts. Record the continuation
2393
+ # first; a failure to record does not change the round.
2394
+ forge_retro_record "$PLAN" qa "$tdir" "$id" "$attempt"
1504
2395
  "${qa_cmd[@]}" >"$tdir/qa.out" 2>&1
1505
2396
  rc=$?
1506
2397
  fi
@@ -1518,16 +2409,26 @@ do_task_body() (
1518
2409
  fi
1519
2410
  if [ "${FORGE_OUTPUT:-summary}" = full ]; then cat "$tdir/qa.out"; fi
1520
2411
  if [ "$rc" -ne 0 ]; then
2412
+ forge_retro_record "$PLAN" qa "$tdir" "$id" "$attempt"
1521
2413
  case "$rc" in
1522
2414
  7) echo TIMEOUT > "$tdir/status"; note "$id: qa hit the dispatch timeout — see $tdir/qa.out" ;;
1523
2415
  8) infra_stop "$tdir" "$id" qa "$attempt"; return 8 ;;
1524
- *) 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 ;;
1525
2423
  esac
1526
2424
  return 1
1527
2425
  fi
1528
2426
  rm -f "$tdir/resume"
1529
2427
 
1530
2428
  forge_metric_phase verification
2429
+ # Before the invalidation return: a review that changed a tracked file still finished,
2430
+ # and its notes are the point of that dispatch. Recording never changes the status.
2431
+ forge_retro_record "$PLAN" qa "$tdir" "$id" "$attempt"
1531
2432
  if [ "$(forge_fingerprint "$wt")" != "$source_fp" ] || [ "$(forge_fingerprint "$review" --tracked)" != "$review_fp" ]; then
1532
2433
  # The committed work is untouched, so --retry-failed may review it again (reason `review`);
1533
2434
  # the merge-time invalidations below leave no reason and wait for a human.
@@ -1559,17 +2460,10 @@ do_task_body() (
1559
2460
  # Entry point for both the scheduler's `_task` and `retry`: runs the pipeline, then logs
1560
2461
  # the attempt (including infrastructure stops, which spend nothing) for later audit.
1561
2462
  do_task() {
1562
- local rc crc=0 stop_before
2463
+ local rc
1563
2464
  do_task_body "$@"; rc=$?
1564
2465
  record_attempt "$1" "$2"
1565
- # The retry policy's state (escalation.next or escalation.stop), decided now rather than
1566
- # at the next retry so a spent retry budget still reports it and the scheduler sees it.
1567
- stop_before="$(cat "$1/tasks/$2/escalation.stop" 2>/dev/null)"
1568
- python3 "$SKILL_DIR/scripts/forge-route.py" escalation --plan "$1" --task "$2" --check \
1569
- --qa-only-next "$(qa_only_next_flag "$1" "$2")" >/dev/null 2>&1 || crc=$?
1570
- # A FAIL that does not converge, or that the policy could not move to a stronger model, waits
1571
- # for a person (NEEDS_DECISION). attempts.tsv was written above and keeps FAIL.
1572
- decision_after_attempt "$1" "$2" "$stop_before" "$crc"
2466
+ post_attempt "$1" "$2"
1573
2467
  return $rc
1574
2468
  }
1575
2469
 
@@ -1740,6 +2634,8 @@ do_retry() {
1740
2634
  # A decision is judged the same way, before any option writes: a NEEDS_DECISION task is resumed
1741
2635
  # only by --decide or --dwarf with --reason and --approved, and --decide is for no other task.
1742
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"
1743
2639
  retry_decision_gate "$PLAN" "$id" "$(task_status "$PLAN" "$id")" "$pre_decide" "$pre_dwarf" "$pre_reason" "$pre_approved"
1744
2640
  fi
1745
2641
  while [ $# -gt 0 ]; do
@@ -1788,6 +2684,7 @@ do_retry() {
1788
2684
  [ -s "$PLAN/wt_root" ] || die "this plan has never been run — use 'run', not 'retry'"
1789
2685
  local st; st="$(task_status "$PLAN" "$id")"
1790
2686
  [ "$st" = "MERGED" ] && die "task '$id' already merged — nothing to retry"
2687
+ [ "$st" != IMPLEMENTED ] || plans_implemented_refuse "$PLAN" "$id"
1791
2688
  # A decision's grant is exactly what it says, and the profile's default budget of further attempts
1792
2689
  # does not stretch it: a task waiting for a decision (resumed by --decide or --dwarf), or an
1793
2690
  # infrastructure stop resumed while a decision's count is kept. Only a --retry-failed typed on this
@@ -1914,6 +2811,7 @@ do_retry() {
1914
2811
  if [ "$st" = "PASS" ]; then
1915
2812
  if merge_task "$PLAN" "$id"; then
1916
2813
  note "$id PASS -> merged"
2814
+ forge_brief_stale "$PLAN" "$id"
1917
2815
  else
1918
2816
  note "$id PASS but conflicted on merge — branch preserved"
1919
2817
  fi
@@ -1932,8 +2830,9 @@ do_retry() {
1932
2830
  fi
1933
2831
  write_results "$PLAN"
1934
2832
  echo
1935
- printf ' %-14s %-9s %s\n' id status branch
1936
- 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"
1937
2836
  run_report_extras "$PLAN"
1938
2837
  report_decisions "$PLAN"
1939
2838
  [ "$(task_status "$PLAN" "$id")" = "MERGED" ] || return 5
@@ -2279,6 +3178,167 @@ run_signal() {
2279
3178
  # Not a ( ) function: main runs it as `( do_run ... ) &`, one subshell that is both the
2280
3179
  # background job and the home of its signal handler. A function called with `&` would be a
2281
3180
  # second subshell level, and an async function does not run its EXIT trap.
3181
+ # --- brief mode in a run (#135) ------------------------------------------------------
3182
+ # The effective level: advisory, gated, strict or off. Settings are the switch (the plan file and
3183
+ # FORGE_BRIEF=off); anything that cannot be read is off, so a broken brief never holds a run.
3184
+ forge_brief_level() { # forge_brief_level <plan>
3185
+ local level
3186
+ level="$(PYTHONPATH="$SKILL_DIR/scripts${PYTHONPATH:+:$PYTHONPATH}" python3 - "$1" 2>/dev/null <<'PY'
3187
+ import sys
3188
+ import forge_side
3189
+ print(forge_side.settings(sys.argv[1])['brief']['level'])
3190
+ PY
3191
+ )" || level=off
3192
+ case "$level" in advisory|gated|strict) echo "$level" ;; *) echo off ;; esac
3193
+ }
3194
+
3195
+ # `forge-brief.py write` in a session of its own, output to brief.out, without waiting. brief.pid holds
3196
+ # the writer's supervisor, which removes it when the writer ends: the scheduler's gated wait reads it.
3197
+ forge_brief_start() { # forge_brief_start <plan>
3198
+ local plan="$1"
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
3203
+ python3 - "$plan" "$SKILL_DIR/scripts/forge-brief.py" <<'PY' || { note "brief: could not start the question writer"; return 0; }
3204
+ import os, subprocess, sys
3205
+ plan, script = sys.argv[1], sys.argv[2]
3206
+ pidfile = os.path.join(plan, 'brief.pid')
3207
+ ready, signal_ready = os.pipe()
3208
+ child = os.fork()
3209
+ if child:
3210
+ os.close(signal_ready)
3211
+ os.read(ready, 1) # the child wrote brief.pid (or gave up): the file is there before this returns
3212
+ sys.exit(0)
3213
+ code = 1
3214
+ try:
3215
+ os.close(ready)
3216
+ os.setsid()
3217
+ out = os.open(os.path.join(plan, 'brief.out'), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
3218
+ null = os.open(os.devnull, os.O_RDONLY)
3219
+ os.dup2(null, 0); os.dup2(out, 1); os.dup2(out, 2)
3220
+ with open(pidfile, 'w') as handle:
3221
+ handle.write('%d\n' % os.getpid())
3222
+ os.write(signal_ready, b'1'); os.close(signal_ready)
3223
+ code = subprocess.run([sys.executable, script, 'write', plan], stdin=subprocess.DEVNULL).returncode
3224
+ except BaseException:
3225
+ pass
3226
+ finally:
3227
+ try:
3228
+ os.write(signal_ready, b'1')
3229
+ except OSError:
3230
+ pass
3231
+ try:
3232
+ os.unlink(pidfile)
3233
+ except OSError:
3234
+ pass
3235
+ os._exit(code)
3236
+ PY
3237
+ }
3238
+
3239
+ # Strict: the questions of the tasks that have not started and nobody answered, each with the command that
3240
+ # answers it. Exit 3 when there are any, so the caller refuses before the scheduler starts.
3241
+ forge_brief_strict() { # forge_brief_strict <plan>
3242
+ local plan="$1" rc=0
3243
+ python3 "$SKILL_DIR/scripts/forge-brief.py" write "$plan" >&2 || note "brief: the question writer did not finish; tasks without questions are not held"
3244
+ PYTHONPATH="$SKILL_DIR/scripts${PYTHONPATH:+:$PYTHONPATH}" python3 - "$plan" <<'PY' || rc=$?
3245
+ import shlex, sys
3246
+ import forge_brief
3247
+ import forge_brief.answers as answers
3248
+ plan = sys.argv[1]
3249
+ try:
3250
+ found = forge_brief.collect(plan)['questions']
3251
+ except Exception:
3252
+ sys.exit(0)
3253
+ open_ = [q for q in found if q['state'] in ('open', 'possibly_stale') and not answers.past_start(plan, q['task'])]
3254
+ if not open_:
3255
+ sys.exit(0)
3256
+ err = sys.stderr
3257
+ err.write('forge: strict brief: %d question(s) wait for your answer before any task starts:\n' % len(open_))
3258
+ for q in open_:
3259
+ err.write(' %s %s: %s\n' % (q['task'], q['id'], q['text']))
3260
+ err.write(' default: %s\n' % (q['default'] or '(none)'))
3261
+ err.write(' forge brief answer %s %s %s "…"\n' % (shlex.quote(plan), q['task'], q['id']))
3262
+ err.write('forge: nothing was started. Answer them, then run again.\n')
3263
+ sys.exit(3)
3264
+ PY
3265
+ return "$rc"
3266
+ }
3267
+
3268
+ # After a merge, with brief on: flag the dependents' open questions when the merge touched files outside
3269
+ # the task's own. A failure is one line and changes nothing else.
3270
+ forge_brief_stale() { # forge_brief_stale <plan> <merged-task>
3271
+ [ "$(forge_brief_level "$1")" = off ] && return 0
3272
+ python3 "$SKILL_DIR/scripts/forge-brief.py" stale "$1" "$2" >/dev/null 2>&1 \
3273
+ || note "brief: could not flag the dependents of $2 as possibly stale"
3274
+ return 0
3275
+ }
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
+
2282
3342
  do_run() {
2283
3343
  local run_child="" run_stop=0 run_phase=pre run_rc=0 interrupted=0 vstopped=0
2284
3344
  FORGE_RUN_STOPPABLE=1
@@ -2286,7 +3346,7 @@ do_run() {
2286
3346
  local PLAN="${1:?run needs a plan dir}"; shift
2287
3347
  FORGE_RUN_STARTED="$(forge_now)" # the summary's overridden verdicts are this run's
2288
3348
  local fractal_pipeline_args=("$@")
2289
- local MAXP=3 DRY=0 jev_rc=0 FORECAST=1
3349
+ local MAXP=3 DRY=0 jev_rc=0 FORECAST=1 fractal_answer=""
2290
3350
  while [ $# -gt 0 ]; do
2291
3351
  case "$1" in
2292
3352
  --no-forecast) FORECAST=0; shift ;;
@@ -2323,13 +3383,28 @@ do_run() {
2323
3383
  export FORGE_OUTPUT="$OUTPUT"
2324
3384
  case "$MAXP" in ''|*[!0-9]*) die "--max-parallel must be positive" ;; esac
2325
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
2326
3390
  local T="$PLAN/tasks.tsv" W="$PLAN/waves.tsv"
2327
3391
  [ -s "$W" ] || die "no waves.tsv — run the plan subcommand first"
2328
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
2329
3402
 
2330
3403
  compute_waves "$PLAN"
2331
3404
  local REPO run_id wt_root int_wt int_br
2332
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"
2333
3408
  # Before any decision-model step: the privacy floor and the run budget read these.
2334
3409
  [ "$JEV_OPTS" = 1 ] && forge_decide_env "$REPO" "$PLAN"
2335
3410
  if [ "$DRY" != 1 ]; then
@@ -2337,6 +3412,23 @@ do_run() {
2337
3412
  printf '%s\n' "$MAXP" > "$PLAN/max_parallel"
2338
3413
  # Plan registers too; this also picks up plans made before it did.
2339
3414
  forge_ui_register "$PLAN"
3415
+ forge_storage_check "$PLAN" "$REPO"
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 $?
2340
3432
  fi
2341
3433
  forge_fractal_parallel_run "$PLAN" "$REPO" "$DRY" ${fractal_pipeline_args[@]+"${fractal_pipeline_args[@]}"} || return $?
2342
3434
  forge_fast_fractal_note "$PLAN"
@@ -2362,6 +3454,9 @@ do_run() {
2362
3454
  return 0
2363
3455
  fi
2364
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
+
2365
3460
  forge_metric_begin "$PLAN" parallel
2366
3461
  forge_metric_phase preflight
2367
3462
  [ "${FORGE_RIPWIRE:-}" != off ] || touch "$PLAN/no_ripwire"
@@ -2378,10 +3473,13 @@ do_run() {
2378
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
2379
3474
  fi
2380
3475
  if ! (cd "$REPO" && git rev-parse --verify "$int_br" >/dev/null 2>&1); then
2381
- (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
2382
3480
  # Where the integration branch started, so a whole-run review can diff exactly what
2383
3481
  # this run added. Plans created before this file existed fall back to a merge-base.
2384
- git -C "$REPO" rev-parse HEAD > "$PLAN/integration.base"
3482
+ git -C "$REPO" rev-parse "$int_start" > "$PLAN/integration.base"
2385
3483
  fi
2386
3484
  if [ ! -d "$int_wt" ]; then
2387
3485
  (cd "$REPO" && git worktree add "$int_wt" "$int_br" >/dev/null 2>&1) \
@@ -2402,8 +3500,16 @@ do_run() {
2402
3500
  # Also before any model is paid for: what this plan is likely to cost, and which tasks
2403
3501
  # history says may bounce. Advisory, budgeted and silent without history; it never stops a run.
2404
3502
  [ "$FORECAST" = 1 ] && forecast_report "$PLAN"
2405
- # Invalid verification lanes stop the run here, before any model is paid for.
3503
+ # Invalid verification lanes stop the run here, before any model is paid for, so before the question writer below.
2406
3504
  verify_lanes_check "$PLAN" "$REPO" "$int_wt"
3505
+ # Brief mode (#135), when the plan has it on. Strict asks first and refuses to start while a question of a
3506
+ # task that has not started is unanswered; advisory and gated write the questions beside the scheduler.
3507
+ local brief_level
3508
+ brief_level="$(forge_brief_level "$PLAN")"
3509
+ case "$brief_level" in
3510
+ strict) forge_brief_strict "$PLAN" || exit $? ;;
3511
+ advisory|gated) forge_brief_start "$PLAN" ;;
3512
+ esac
2407
3513
  # Say now, before any model is paid for, which suites the verify command will not run.
2408
3514
  verify_coverage_report "$REPO" "$(verify_command_for "$PLAN" "$REPO")" "$PLAN/verification.coverage.txt"
2409
3515
  local sched_rc=0 paused=0 sched_args=()
@@ -2456,12 +3562,19 @@ do_run() {
2456
3562
  done
2457
3563
  fi
2458
3564
 
3565
+ # After the scheduler (and verification) and before the summary. Retro off: no call,
3566
+ # no retro.md. A failure here does not change the exit code decided below.
3567
+ local retro_line=""
3568
+ retro_line="$(forge_retro_summary_line "$PLAN")"
3569
+
2459
3570
  echo
2460
3571
  echo "results (integration branch: $int_br)"
2461
3572
  echo "artifacts: $PLAN/tasks/<id>/{dwarf,qa}.{last,log}; results: $PLAN/results.tsv"
2462
- printf ' %-14s %-9s %s\n' id status branch
2463
- 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"
2464
3576
  echo
3577
+ if [ -n "$retro_line" ]; then printf '%s\n\n' "$retro_line"; fi
2465
3578
  run_report_extras "$PLAN"
2466
3579
  # Pre-review tests (#85): every check of the plan, and the reviews the red ones saved.
2467
3580
  local pre_review
@@ -2508,10 +3621,19 @@ do_run() {
2508
3621
  fi
2509
3622
  # Tasks stopped for a decision (#69): why, and the choices. Not failures to retry either.
2510
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
2511
3633
  # The retry hint is for tasks that actually failed; a run that only failed verification,
2512
3634
  # or only paused on infrastructure, has nothing to retry task by task. An interrupted task
2513
3635
  # has its own hint above, a task waiting for an answer or a decision its own block.
2514
- 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
2515
3637
  echo "retry a failed task with its reviewer's findings:"
2516
3638
  echo " forge-parallel.sh retry $PLAN <task-id> [--dwarf <spec>]"
2517
3639
  echo "or let a run retry them itself: forge-parallel.sh run $PLAN --retry-failed 1"
@@ -2577,6 +3699,8 @@ do_integrate() {
2577
3699
  parent="$(git -C "$REPO" rev-parse HEAD)" || return 3
2578
3700
  target="$(git -C "$REPO" rev-parse "$int_br")" || return 3
2579
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")"
2580
3704
  out="$PLAN/integrate-$(date +%s)-$$"; mkdir -p "$out"
2581
3705
  candidate="$(cat "$PLAN/wt_root")/_candidate-$$"
2582
3706
  git -C "$REPO" worktree add --detach "$candidate" "$parent" > "$out/setup.log" 2>&1 || return 3
@@ -2665,14 +3789,35 @@ forge_auto_unparse() { # forge_auto_unparse <plan-dir>
2665
3789
  rm -f "$1/tasks.tsv" "$1/tasks.declared.tsv"
2666
3790
  }
2667
3791
 
3792
+ # The planner's notes, once. A dispatch that ran before `plan` wrote run_id leaves
3793
+ # AUTO_PLANNER_RECORDED=0; recording then would store run_id null for good. The caller
3794
+ # records after `plan`, or on an exit that will never reach it. A later dispatch (the
3795
+ # send-back) already has the file and records itself.
3796
+ forge_auto_record_planner() { # forge_auto_record_planner <plan>
3797
+ [ "${AUTO_PLANNER_RECORDED:-1}" = 0 ] || return 0
3798
+ forge_retro_record "$1" planner "$1"
3799
+ AUTO_PLANNER_RECORDED=1
3800
+ }
3801
+
2668
3802
  # One planner dispatch: prompt in $PLAN/planner.prompt, reply in $PLAN/planner.last. Sets
2669
3803
  # AUTO_RC (0, 4 or 8) for the caller instead of exiting, so a send-back can reuse it.
2670
3804
  forge_auto_dispatch() { # forge_auto_dispatch <plan-dir> <repo> <spec> <fast-option-or-empty>
2671
3805
  local plan="$1" repo="$2" spec="$3" tier="$4" rc=0
2672
3806
  AUTO_RC=0
3807
+ AUTO_PLANNER_RECORDED=0
2673
3808
  note "auto: dispatching the planner ($spec) for the whole plan"
3809
+ # Last. The planner runs before `plan` stores retro_mode; AUTO_RETRO_FLAG says whether
3810
+ # this call's flags will turn it on. Off appends nothing, so the file stays as written.
3811
+ forge_retro_prompt "$plan" planner >> "$plan/planner.prompt"
2674
3812
  bash "$DISPATCH" planner "$spec" --repo "$repo" --run-dir "$plan" --prompt-file "$plan/planner.prompt" \
2675
3813
  --output summary ${tier:+$tier} >&2 || rc=$?
3814
+ # No task: the planner is the whole plan. Its result is AUTO_RC, set below, not this.
3815
+ # run_id is written by `plan`, which has not run yet on a new directory. Record now only
3816
+ # when that file is already there (a send-back); otherwise the caller records after `plan`.
3817
+ if [ -s "$plan/run_id" ]; then
3818
+ forge_retro_record "$plan" planner "$plan"
3819
+ AUTO_PLANNER_RECORDED=1
3820
+ fi
2676
3821
  if [ "$rc" -eq 8 ]; then
2677
3822
  note "auto: the planner stopped on an infrastructure failure (see $plan/planner.infra). Nothing was dispatched after the planner; fix the cause and run auto again"
2678
3823
  AUTO_RC=8
@@ -2785,23 +3930,41 @@ AUTO_PROFILE
2785
3930
  forge_fast_store "$PLAN"
2786
3931
  fast_tier="$(forge_fast_tier "$PLAN" planner)"
2787
3932
 
3933
+ # The flag `plan` is about to store. The planner is dispatched before that write, and
3934
+ # FORGE_RETRO=off still wins inside forge_retro_on. Last flag wins, as plan's own scan.
3935
+ AUTO_RETRO_FLAG=""
3936
+ local retro_scan=""
3937
+ for retro_scan in ${PLAN_ARGS[@]+"${PLAN_ARGS[@]}"}; do
3938
+ case "$retro_scan" in
3939
+ --retro) AUTO_RETRO_FLAG=on ;;
3940
+ --no-retro) AUTO_RETRO_FLAG=off ;;
3941
+ esac
3942
+ done
2788
3943
  note "auto: checking the planner ($PLANNER) before any model call"
2789
3944
  bash "$DISPATCH" doctor --spec "$PLANNER" --role planner ${fast_tier:+$fast_tier} >&2 || exit $?
2790
3945
  python3 "$PLANNER_PY" prompt --plan "$PLAN" --goal-file "$REQUEST" ${DLEVEL:+--level "$DLEVEL"} >/dev/null || exit $?
2791
3946
  forge_auto_dispatch "$PLAN" "$REPO" "$PLANNER" "$fast_tier"
2792
- [ "$AUTO_RC" -eq 0 ] || exit "$AUTO_RC"
3947
+ if [ "$AUTO_RC" -ne 0 ]; then
3948
+ forge_auto_record_planner "$PLAN"
3949
+ exit "$AUTO_RC"
3950
+ fi
2793
3951
  python3 "$PLANNER_PY" parse --plan "$PLAN" --reply "$PLAN/planner.last" || rc=$?
2794
3952
  case "$rc" in
2795
3953
  0) ;;
2796
- 4) note "auto: the planner's reply was refused (see $PLAN/planner.refused). Nothing was dispatched after the planner"
3954
+ 4) forge_auto_record_planner "$PLAN"
3955
+ note "auto: the planner's reply was refused (see $PLAN/planner.refused). Nothing was dispatched after the planner"
2797
3956
  exit 4 ;;
2798
- *) exit "$rc" ;;
3957
+ *) forge_auto_record_planner "$PLAN"
3958
+ exit "$rc" ;;
2799
3959
  esac
2800
3960
  from_planner=1
2801
3961
  fi
2802
3962
 
2803
3963
  # 4. plan, and one send-back when the plan gates ask for it.
2804
3964
  bash "$SELF" plan "$PLAN" ${PLAN_ARGS[@]+"${PLAN_ARGS[@]}"}; rc=$?
3965
+ # planner.last is still the first reply. plan has written run_id when it got that far,
3966
+ # and the send-back below overwrites the reply, so this is the moment to record it.
3967
+ forge_auto_record_planner "$PLAN"
2805
3968
  if [ "$rc" -eq 4 ] && [ "$from_planner" = 1 ] && [ -s "$PLAN/plan.sendback.md" ]; then
2806
3969
  note "auto: the plan gates sent items back; asking the planner once more"
2807
3970
  cp "$PLAN/planner.last" "$PLAN/planner.first.last" 2>/dev/null || true
@@ -2814,16 +3977,22 @@ AUTO_PROFILE
2814
3977
  cat "$PLAN/plan.sendback.md"
2815
3978
  } >> "$PLAN/planner.prompt"
2816
3979
  forge_auto_dispatch "$PLAN" "$REPO" "$PLANNER" "$fast_tier"
2817
- [ "$AUTO_RC" -eq 0 ] || exit "$AUTO_RC"
3980
+ if [ "$AUTO_RC" -ne 0 ]; then
3981
+ forge_auto_record_planner "$PLAN"
3982
+ exit "$AUTO_RC"
3983
+ fi
2818
3984
  rc=0
2819
3985
  python3 "$PLANNER_PY" parse --plan "$PLAN" --reply "$PLAN/planner.last" || rc=$?
2820
3986
  case "$rc" in
2821
3987
  0) ;;
2822
- 4) note "auto: the planner's second reply was refused (see $PLAN/planner.refused). Nothing was dispatched after the planner"
3988
+ 4) forge_auto_record_planner "$PLAN"
3989
+ note "auto: the planner's second reply was refused (see $PLAN/planner.refused). Nothing was dispatched after the planner"
2823
3990
  exit 4 ;;
2824
- *) exit "$rc" ;;
3991
+ *) forge_auto_record_planner "$PLAN"
3992
+ exit "$rc" ;;
2825
3993
  esac
2826
3994
  bash "$SELF" plan "$PLAN" ${PLAN_ARGS[@]+"${PLAN_ARGS[@]}"}; rc=$?
3995
+ forge_auto_record_planner "$PLAN"
2827
3996
  if [ "$rc" -eq 4 ]; then
2828
3997
  note "auto: the plan gates sent items back a second time; stopping. See $PLAN/plan.sendback.md"
2829
3998
  fi
@@ -2868,7 +4037,8 @@ case "$CMD" in
2868
4037
  FORGE_DATASET_INVOCATION="inv-$(date +%s)-$$-$RANDOM"; export FORGE_DATASET_INVOCATION
2869
4038
  FORGE_DATASET_STARTED="$(date +%s)"
2870
4039
  FORGE_DATASET_ARGV=("$@")
2871
- trap 'forge_dataset_rc=$?; trap - EXIT; forge_dataset_invocation "$CMD" "$forge_dataset_rc" "$FORGE_DATASET_STARTED" ${FORGE_DATASET_ARGV[@]+"${FORGE_DATASET_ARGV[@]}"}; exit "$forge_dataset_rc"' EXIT ;;
4040
+ # An adopt's or final review's snapshot goes too, whatever the exit path (#139).
4041
+ trap 'forge_dataset_rc=$?; trap - EXIT; forge_drop_snapshot "${FORGE_REVIEW_SNAPSHOT:-}"; forge_drop_snapshot "${FINAL_REVIEW_SNAPSHOT:-}"; forge_dataset_invocation "$CMD" "$forge_dataset_rc" "$FORGE_DATASET_STARTED" ${FORGE_DATASET_ARGV[@]+"${FORGE_DATASET_ARGV[@]}"}; exit "$forge_dataset_rc"' EXIT ;;
2872
4042
  esac
2873
4043
  # Subcommands implemented in the optional libraries fail clearly if the library is absent.
2874
4044
  need_fn() { declare -F "$1" >/dev/null || die "'$CMD' is not available: $1 is missing" 3; }
@@ -2915,6 +4085,11 @@ case "$CMD" in
2915
4085
  combine) need_fn do_combine; do_combine "$@" ;;
2916
4086
  _task) do_task "$@" ;;
2917
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 "$@" ;;
4091
+ # The live scheduler's accept (forge control accept, #138): it holds the plan lock already.
4092
+ _accept) need_fn do_accept; FORGE_ACCEPT_LIVE=1 do_accept "$@" ;;
2918
4093
  _prepare_retry) retry_for_scheduler "$@" ;;
2919
4094
  _qa_only) qa_only_next "$@" ;;
2920
4095
  _waves) compute_waves "$@" ;;