@giamme/forge 0.14.1 → 0.15.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 (42) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/commands.md +288 -6
  5. package/docs/models.md +53 -0
  6. package/package.json +1 -1
  7. package/references/dataset.md +12 -3
  8. package/references/decompose.md +103 -4
  9. package/references/harnesses.md +17 -0
  10. package/references/planning.md +59 -0
  11. package/references/ui.md +39 -1
  12. package/scripts/forge-compare.py +6 -3
  13. package/scripts/forge-config.py +531 -4
  14. package/scripts/forge-dispatch.sh +56 -2
  15. package/scripts/forge-lib-plans.sh +19 -2
  16. package/scripts/forge-lib-review.sh +5 -3
  17. package/scripts/forge-lib-task.sh +119 -0
  18. package/scripts/forge-parallel-options.sh +12 -6
  19. package/scripts/forge-parallel.sh +565 -21
  20. package/scripts/forge-plan-check.py +591 -8
  21. package/scripts/forge-planner.py +480 -0
  22. package/scripts/forge-runtime.py +86 -0
  23. package/scripts/forge-shadow.py +51 -7
  24. package/scripts/forge-solo.sh +81 -7
  25. package/scripts/forge_dataset/cli.py +10 -0
  26. package/scripts/forge_dataset/efforts.py +215 -0
  27. package/scripts/forge_dataset/harvest.py +44 -0
  28. package/scripts/forge_decide/__init__.py +19 -1
  29. package/scripts/forge_decide/builtin_profiles.json +25 -0
  30. package/scripts/forge_decide/cli.py +12 -0
  31. package/scripts/forge_decide/profiles.py +866 -0
  32. package/scripts/forge_decide/resolve.py +38 -6
  33. package/ui/docs/api.md +87 -8
  34. package/ui/forge_ui/control.py +173 -12
  35. package/ui/forge_ui/executions.py +28 -8
  36. package/ui/forge_ui/models.py +60 -1
  37. package/ui/forge_ui/reader.py +21 -1
  38. package/ui/forge_ui/static/leaderboard.js +5 -1
  39. package/ui/forge_ui/static/modelstats.js +25 -1
  40. package/ui/forge_ui/static/panel.js +19 -2
  41. package/ui/forge_ui/static/settings.js +788 -25
  42. package/ui/forge_ui/static/style.css +23 -0
@@ -20,6 +20,13 @@
20
20
  # [--approach <file>] [--yolo-dwarf] [--yolo-qa]
21
21
  # [--native-review] [--no-memory] [--timeout <s>] [--dry-run] [--ui]
22
22
  # [--fail-first] [--qa-threshold P0|P1|P2|P3|none]
23
+ # [--fast ROLES] dwarf, qa or none (planner, review and all are refused);
24
+ # kept in <run-dir>/fast. none removes it; omitting it keeps it
25
+ # [--profile NAME | --no-profile] a named profile (forge config profile list) picks
26
+ # the dwarf and qa (its medium pool, else its any pool), the QA
27
+ # threshold, the timeout and the fast roles that no flag gives;
28
+ # frozen in <run-dir>/profile.json, which later runs of the dir keep.
29
+ # With neither flag, that copy, else the default profile, applies
23
30
  #
24
31
  # Reads <run-dir>/prompt.md the implementation instruction (required)
25
32
  # <run-dir>/goal.txt one line, what the user asked for (optional)
@@ -29,6 +36,7 @@
29
36
  # <run-dir>/verdict PASS | FAIL | UNKNOWN, when qa emitted one (after the severity gate)
30
37
  # <run-dir>/qa.gate, known_issues.md the gate's decision and the tolerated findings
31
38
  # <run-dir>/qa_threshold with --qa-threshold: the blocking level (default P2)
39
+ # <run-dir>/profile.json with a profile: the frozen copy of it
32
40
  # <run-dir>/failfirst.json with --fail-first: do the change's tests fail without it?
33
41
  # <run-dir>/status RUNNING, then this invocation's outcome
34
42
  # <run-dir>/dwarf.spec, qa.spec and attempts.tsv
@@ -95,7 +103,7 @@ forge_metric_on_exit() {
95
103
  }
96
104
 
97
105
  if [ "${1:-}" = --help ] || [ "${1:-}" = -h ]; then
98
- sed -n '18,39s/^# *//p' "$0"
106
+ sed -n '18,47s/^# *//p' "$0"
99
107
  forge_fractal_help
100
108
  echo 'Explicit Fractal retry: repeat the original command with --retry.'
101
109
  exit 0
@@ -104,8 +112,12 @@ RUN="${1:-}"; [ -n "$RUN" ] || die "usage: forge-solo.sh <run-dir> --repo <dir>
104
112
  case "$RUN" in -*) die "first argument must be the run directory, got '$RUN'" ;; esac
105
113
  shift
106
114
 
115
+ # --- profiles (#48): the same reading, freezing and exporting as forge-parallel.sh's plan ---
116
+ forge_profile_py() { PYTHONPATH="$SKILL_DIR/scripts${PYTHONPATH:+:$PYTHONPATH}" python3 -m forge_decide.profiles "$@"; }
117
+
107
118
  OUTPUT=summary
108
119
  REPO="$PWD"; DWARF=""; QA="opus"; APPROACH=""; YD=""; YQ=""; NATIVE=""; TIMEOUT=""; DRY=0; FAIL_FIRST=0; QA_THR=
120
+ FAST_GIVEN=0; FAST_PARSED=""; QA_GIVEN=0; PF_NAME=""; PF_NONE=0
109
121
  while [ $# -gt 0 ]; do
110
122
  case "$1" in
111
123
  --fractal) forge_fractal_flag on || exit $?; shift ;;
@@ -116,7 +128,9 @@ while [ $# -gt 0 ]; do
116
128
  --output) OUTPUT="${2:?}"; shift 2 ;;
117
129
  --repo) REPO="${2:?--repo needs a value}"; shift 2 ;;
118
130
  --dwarf) DWARF="${2:?--dwarf needs a spec}"; shift 2 ;;
119
- --qa) QA="${2:?--qa needs a spec}"; shift 2 ;;
131
+ --qa) QA="${2:?--qa needs a spec}"; QA_GIVEN=1; shift 2 ;;
132
+ --profile) PF_NAME="${2:?--profile needs a profile name}"; shift 2 ;;
133
+ --no-profile) PF_NONE=1; shift ;;
120
134
  --approach) APPROACH="${2:?--approach needs a file}"; shift 2 ;;
121
135
  --yolo-dwarf) YD="--yolo"; shift ;;
122
136
  --yolo-qa) YQ="--yolo"; shift ;;
@@ -126,6 +140,11 @@ while [ $# -gt 0 ]; do
126
140
  --timeout) TIMEOUT="${2:?--timeout needs seconds}"; shift 2 ;;
127
141
  --dry-run) DRY=1; shift ;;
128
142
  --fail-first) FAIL_FIRST=1; shift ;;
143
+ --fast)
144
+ [ -n "${2:-}" ] || die "--fast needs a comma list of roles (dwarf, qa, planner, review), all or none"
145
+ forge_fast_parse "$2" solo
146
+ FAST_GIVEN=1
147
+ shift 2 ;;
129
148
  --qa-threshold)
130
149
  QA_THR="$(printf '%s' "${2:?--qa-threshold needs P0, P1, P2, P3 or none}" | tr 'a-z' 'A-Z')"
131
150
  case "$QA_THR" in P0|P1|P2|P3) ;; NONE) QA_THR=none ;; *) die "--qa-threshold must be P0, P1, P2, P3 or none, got '$2'" 2 ;; esac
@@ -149,6 +168,48 @@ done
149
168
 
150
169
  case "$OUTPUT" in summary|full) ;; *) die "--output must be summary or full" ;; esac
151
170
 
171
+ # A profile (#48) stands in for the flags that were not given. Read and checked here, before the
172
+ # model is asked for and before anything is written: an unknown or invalid profile stops the run.
173
+ [ -z "$PF_NAME" ] || [ "$PF_NONE" = 0 ] || die "--profile and --no-profile are mutually exclusive"
174
+ pf_args=()
175
+ [ -z "$PF_NAME" ] || pf_args+=(--profile "$PF_NAME")
176
+ [ "$PF_NONE" = 0 ] || pf_args+=(--no-profile)
177
+ [ -z "$DWARF" ] || pf_args+=(--given dwarf)
178
+ [ "$QA_GIVEN" != 1 ] || pf_args+=(--given qa)
179
+ [ -z "$QA_THR" ] || pf_args+=(--given qa_threshold)
180
+ [ -z "$TIMEOUT" ] || pf_args+=(--given timeout)
181
+ [ "$FAST_GIVEN" != 1 ] || pf_args+=(--given fast)
182
+ pf_auto=0; pf_planner=0
183
+ for pf_arg in ${FRACTAL_ARGS[@]+"${FRACTAL_ARGS[@]}"}; do
184
+ case "$pf_arg" in
185
+ --dwarf-low|--dwarf-medium|--dwarf-high) pf_args+=(--given "${pf_arg#--}") ;;
186
+ --fractal-auto-decompose) pf_auto=1 ;;
187
+ --fractal-planner) pf_planner=1; pf_args+=(--given fractal-planner) ;;
188
+ esac
189
+ done
190
+ PF_LINE=""
191
+ pf_out="$(forge_profile_py solo "$RUN" --repo "$REPO" ${pf_args[@]+"${pf_args[@]}"})" || exit $?
192
+ while IFS="$(printf '\t')" read -r pf_key pf_val; do
193
+ case "$pf_key" in
194
+ dwarf) DWARF="$pf_val" ;;
195
+ qa) QA="$pf_val" ;;
196
+ qa_threshold) QA_THR="$pf_val" ;;
197
+ timeout) TIMEOUT="$pf_val" ;;
198
+ fast) forge_fast_parse "$pf_val" solo; FAST_GIVEN=1 ;;
199
+ # Fractal's tier pools and planner count only where Fractal is selected (and the planner
200
+ # only with automatic decomposition, which --fractal-planner needs).
201
+ pool.low) [ "$FRACTAL_CHOICE" != on ] || FRACTAL_ARGS+=(--dwarf-low "$pf_val") ;;
202
+ pool.medium) [ "$FRACTAL_CHOICE" != on ] || FRACTAL_ARGS+=(--dwarf-medium "$pf_val") ;;
203
+ pool.high) [ "$FRACTAL_CHOICE" != on ] || FRACTAL_ARGS+=(--dwarf-high "$pf_val") ;;
204
+ fractal_planner) [ "$FRACTAL_CHOICE$pf_auto$pf_planner" != on10 ] || FRACTAL_ARGS+=(--fractal-planner "$pf_val") ;;
205
+ line) PF_LINE="$pf_val" ;;
206
+ # The gates and budget of the copy this run uses, for it and everything it starts.
207
+ decide) [ -z "$pf_val" ] || export FORGE_DECIDE_PROFILE_JSON="$pf_val" ;;
208
+ esac
209
+ done <<EOF
210
+ $pf_out
211
+ EOF
212
+
152
213
  # Forge never picks the model: every dispatch spends the user's quota, and choosing
153
214
  # for them is not the tool's call.
154
215
  [ -n "$DWARF" ] || die "--dwarf is required"
@@ -165,6 +226,13 @@ case "$(cd "$RUN" && pwd)/" in
165
226
  esac
166
227
 
167
228
  RUN="$(cd "$RUN" && pwd)"
229
+ # The frozen copy, atomically. Only the process that holds the run's lock writes it (a refused
230
+ # second start, or a dry run, must not change what an active run froze): the first pass above
231
+ # only read and checked, and the re-exec under the lock chooses again from the same arguments.
232
+ if [ "$DRY" != 1 ] && [ "${FORGE_SOLO_LOCK:-}" = "$RUN" ]; then
233
+ forge_profile_py solo "$RUN" --repo "$REPO" --no-validate --write ${pf_args[@]+"${pf_args[@]}"} >/dev/null || exit $?
234
+ fi
235
+ [ -z "$PF_LINE" ] || [ -n "${FORGE_SOLO_LOCK:-}" ] || echo "$PF_LINE"
168
236
  # Freeze the selection now that the run dir is real and absolute. A retry of this
169
237
  # same run dir restores it rather than re-reading whatever flags are passed then.
170
238
  [ "$JEV_OPTS" = 1 ] && { forge_jev_restore "$RUN" || true; forge_jev_record "$RUN"; }
@@ -174,6 +242,8 @@ REPO="$(cd "$REPO" && pwd)"
174
242
  if [ "$DRY" != 1 ] && [ "${FORGE_SOLO_LOCK:-}" != "$RUN" ]; then
175
243
  exec python3 "$SKILL_DIR/scripts/forge-fractal.py" _lock "$RUN" "$0" "${ORIGINAL_ARGS[@]}"
176
244
  fi
245
+ # After the lock re-exec, so the process that dispatches is the one that writes it.
246
+ forge_fast_store "$RUN"
177
247
  RUN_ID="$(basename "$RUN")"
178
248
  export FORGE_CAPABILITY_CACHE="$RUN/capabilities"
179
249
  TFLAG=""; [ -n "$TIMEOUT" ] && TFLAG="--timeout $TIMEOUT"
@@ -183,6 +253,10 @@ FFLAGS=()
183
253
  [ -z "$YD" ] || FFLAGS+=(--yolo-dwarf)
184
254
  [ -z "$YQ" ] || FFLAGS+=(--yolo-qa)
185
255
  forge_fractal_select "$RUN" "$REPO" solo "$DRY" --dwarf "$DWARF" --qa "$QA" ${FFLAGS[@]+"${FFLAGS[@]}"} || exit $?
256
+ forge_fast_fractal_note "$RUN"
257
+ # Computed after Fractal selects, so a Fractal dispatch is not asked for the tier.
258
+ ft_dwarf="$(forge_fast_tier "$RUN" dwarf)"
259
+ ft_qa="$(forge_fast_tier "$RUN" qa)"
186
260
  if [ -n "${FORGE_FRACTAL_RUN:-}" ]; then
187
261
  # The UI choice is per invocation: a tmux resume replays these args and must not open it again.
188
262
  REMEMBER_ARGS=()
@@ -235,7 +309,7 @@ if [ "$DRY" = 1 ]; then
235
309
  echo "--- dry run ---"
236
310
  [ "$FORGE_UI_WANTED" != 1 ] || note "--ui ignored: a dry run starts no UI"
237
311
  /bin/bash "$DISPATCH" dwarf "$DWARF" --repo "$REPO" --run-dir "$RUN" \
238
- --ripwire-query-file "$RUN/prompt.md" --prompt-file "$RUN/dwarf.input" $YD $TFLAG --dry-run
312
+ --ripwire-query-file "$RUN/prompt.md" --prompt-file "$RUN/dwarf.input" $YD $TFLAG $ft_dwarf --dry-run
239
313
  echo
240
314
  echo "qa would be: $QA $NATIVE $YQ"
241
315
  echo "dwarf prompt: $RUN/dwarf.input ($(wc -l < "$RUN/dwarf.input" | tr -d ' ') lines)"
@@ -243,8 +317,8 @@ if [ "$DRY" = 1 ]; then
243
317
  fi
244
318
 
245
319
  forge_metric_phase preflight
246
- /bin/bash "$DISPATCH" doctor --spec "$DWARF" --role dwarf $YD $TFLAG || exit $?
247
- /bin/bash "$DISPATCH" doctor --spec "$QA" --role qa $YQ $NATIVE $TFLAG || exit $?
320
+ /bin/bash "$DISPATCH" doctor --spec "$DWARF" --role dwarf $YD $TFLAG $ft_dwarf || exit $?
321
+ /bin/bash "$DISPATCH" doctor --spec "$QA" --role qa $YQ $NATIVE $TFLAG $ft_qa || exit $?
248
322
  /bin/bash "$SKILL_DIR/scripts/forge-install-ripwire.sh" || true
249
323
  # After the _lock re-exec and the Fractal checkpoint exit, so it runs once per run.
250
324
  forge_ui_launch "$RUN"
@@ -260,7 +334,7 @@ forge_metric_phase dispatch
260
334
  note "dwarf $DWARF in $REPO"
261
335
  guard_before_dwarf "$REPO" "$RUN"
262
336
  /bin/bash "$DISPATCH" dwarf "$DWARF" --repo "$REPO" --run-dir "$RUN" \
263
- --ripwire-query-file "$RUN/prompt.md" --prompt-file "$RUN/dwarf.input" $YD $TFLAG --output "$OUTPUT"
337
+ --ripwire-query-file "$RUN/prompt.md" --prompt-file "$RUN/dwarf.input" $YD $TFLAG $ft_dwarf --output "$OUTPUT"
264
338
  rc=$?
265
339
  dur_dwarf="$(sed -n 's/^duration_s=//p' "$RUN/dwarf.resolved" 2>/dev/null | tail -1)"
266
340
  /bin/bash "$MEMORY" record "$REPO" --last "$RUN/dwarf.last" --role dwarf \
@@ -326,7 +400,7 @@ fi
326
400
  forge_metric_phase dispatch
327
401
  note "qa $QA on $(wc -l < "$RUN/changes.diff" | tr -d ' ') diff lines"
328
402
  /bin/bash "$DISPATCH" qa "$QA" --repo "$REVIEW" --review-base "$(cat "$RUN/review.base")" --run-dir "$RUN" \
329
- --ripwire-query-file "$RUN/prompt.md" --prompt-file "$RUN/qa.input" $YQ $NATIVE $TFLAG --output "$OUTPUT"
403
+ --ripwire-query-file "$RUN/prompt.md" --prompt-file "$RUN/qa.input" $YQ $NATIVE $TFLAG $ft_qa --output "$OUTPUT"
330
404
  rc=$?
331
405
  forge_metric_phase verification
332
406
  verdict="$(forge_verdict "$RUN/qa.last")"
@@ -201,6 +201,13 @@ def run_forecast(args) -> int:
201
201
  return forecast.main(args)
202
202
 
203
203
 
204
+ def slow_notes(args) -> int:
205
+ from . import efforts
206
+ for line in efforts.plan_notes(args.plan):
207
+ print(line)
208
+ return 0
209
+
210
+
204
211
  def parser() -> argparse.ArgumentParser:
205
212
  top = argparse.ArgumentParser(prog='forge dataset', description='The run dataset: every run\'s inputs and outcomes.')
206
213
  sub = top.add_subparsers(dest='command', required=True)
@@ -253,6 +260,9 @@ def parser() -> argparse.ArgumentParser:
253
260
  p.add_argument('--json', action='store_true')
254
261
  p.add_argument('--run', action='store_true', help=argparse.SUPPRESS) # forge-parallel.sh run: budgeted, silent, records
255
262
  p.set_defaults(func=run_forecast)
263
+ p = sub.add_parser('slow-notes', help=argparse.SUPPRESS) # forge-parallel.sh plan: under the table
264
+ p.add_argument('plan')
265
+ p.set_defaults(func=slow_notes)
256
266
  p = sub.add_parser('event', help=argparse.SUPPRESS)
257
267
  p.add_argument('name')
258
268
  p.add_argument('--dir')
@@ -0,0 +1,215 @@
1
+ """A note when a spec is measurably slower than a lower effort of the same model.
2
+
3
+ `slow_note` is advisory. It never changes the spec it was given, and the callers that
4
+ print it (doctor --spec, and the plan table) do not change an exit code because of it.
5
+
6
+ The dataset decides when it is on and both this effort and a lower one of the same model
7
+ have at least five first attempts. Each lower effort is checked, nearest first. The note
8
+ names the nearest one this effort is at least twice as slow as, with a first-try pass
9
+ rate no better. A nearer pair that has enough data but fails that rule does not hide a
10
+ farther pair that meets it. When at least one pair has enough data and none meet the
11
+ rule, there is no note: measured data overrides the built-in table. Otherwise one
12
+ built-in row applies, `haiku:max` against `haiku:xhigh` on the claude harness's model
13
+ (#86, 2026-10-28).
14
+
15
+ python3 -m forge_dataset.efforts SPEC
16
+
17
+ prints the note, or nothing. Run it from `scripts/`. `plan_notes` gives the plan table's
18
+ lines (`forge-dataset.py slow-notes PLAN`, printed by `forge-parallel.sh plan`), kept out
19
+ of forge-plan-check.py: that file builds the planner's send-back prompt, and nothing that
20
+ builds a prompt reads the dataset.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import math
25
+ import statistics
26
+ import subprocess
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ from . import SKILL, connect, dataset_dir, enabled
31
+ from .export import Runs, Store
32
+ from .forecast import registry_models, resolve
33
+ from .routing import tasks as routing_tasks
34
+
35
+ MIN_TASKS = 5
36
+ # No measured pair had five first attempts on both sides, so the built-in table may speak.
37
+ _SKIP = object()
38
+
39
+ # alias, effort, the lower effort, and the harness whose model id the row belongs to.
40
+ # openclaude's haiku is that same model; opencode's is not, and does not match.
41
+ _TABLE = (
42
+ dict(alias='haiku', effort='max', lower='xhigh', harness='claude',
43
+ passes=(7, 7), lower_passes=(4, 4), minutes=7.8, lower_minutes=1.9,
44
+ source='#86, 2026-10-28'),
45
+ )
46
+
47
+
48
+ def _parts(spec):
49
+ """(alias, effort or None, harness or None) of alias[:effort[:harness]]."""
50
+ parts = str(spec or '').split(':')
51
+ alias = parts[0]
52
+ effort = parts[1] if len(parts) > 1 and parts[1] else None
53
+ harness = parts[2] if len(parts) > 2 and parts[2] else None
54
+ return alias, effort, harness
55
+
56
+
57
+ def _efforts(spec) -> list:
58
+ """Efforts the pairing accepts, weakest first. Empty when dispatch cannot say."""
59
+ try:
60
+ done = subprocess.run(
61
+ ['bash', str(SKILL / 'scripts' / 'forge-dispatch.sh'), 'efforts', '--spec', spec],
62
+ capture_output=True, text=True, timeout=30)
63
+ except (OSError, subprocess.SubprocessError):
64
+ return []
65
+ if done.returncode != 0:
66
+ return []
67
+ return [line.strip() for line in done.stdout.splitlines() if line.strip()]
68
+
69
+
70
+ def _runs(store):
71
+ """A Runs over `store` (a Runs, a Store, or a connection), or over the dataset.
72
+
73
+ Reading the default store does not create one: a machine with no dataset yet is
74
+ simply a machine with no measured rows.
75
+ """
76
+ if isinstance(store, Runs):
77
+ return store
78
+ if isinstance(store, Store):
79
+ return Runs(store)
80
+ if store is not None:
81
+ return Runs(Store(store))
82
+ if not (dataset_dir() / 'dataset.sqlite').is_file():
83
+ return None
84
+ db = connect()
85
+ try:
86
+ return Runs(Store(db))
87
+ finally:
88
+ db.close()
89
+
90
+
91
+ def _arm(records, model_id, effort) -> dict:
92
+ """n (first attempts with an outcome), passes, and the median of runtime_s/attempts."""
93
+ group = [r for r in records if r.get('model_id') == model_id and r.get('effort') == effort
94
+ and r.get('first_pass') is not None]
95
+ samples = []
96
+ for record in group:
97
+ attempts = record.get('attempts') or 0
98
+ runtime = record.get('runtime_s')
99
+ if isinstance(runtime, bool) or isinstance(attempts, bool):
100
+ continue
101
+ if isinstance(runtime, (int, float)) and isinstance(attempts, (int, float)) and attempts > 0:
102
+ if math.isfinite(runtime) and math.isfinite(attempts):
103
+ samples.append(runtime / attempts)
104
+ return dict(n=len(group), k=sum(1 for r in group if r['first_pass']),
105
+ median=statistics.median(samples) if samples else None)
106
+
107
+
108
+ def _line(alias, effort, lower, passes, lower_passes, minutes, lower_minutes, source) -> str:
109
+ k, n = passes
110
+ k2, n2 = lower_passes
111
+ ratio = int(math.floor(minutes / lower_minutes + 0.5))
112
+ return ('%s:%s: no measured gain over %s:%s (first try %d/%d vs %d/%d) at about %dx the time '
113
+ '(%.1f vs %.1f min; %s). The spec is unchanged.'
114
+ % (alias, effort, alias, lower, k, n, k2, n2, ratio, minutes, lower_minutes, source))
115
+
116
+
117
+ def _from_dataset(records, alias, effort, model_id, lowers):
118
+ """The dataset's note, None when measured pairs do not qualify, or _SKIP.
119
+
120
+ `lowers` is weakest first, so the walk starts at the nearest. The first lower
121
+ effort that meets the rule is the one named. A pair with enough data that fails
122
+ the rule does not stop the walk: a farther effort may still qualify. If any pair
123
+ had enough data and none met the rule, return None so the built-in table stays quiet.
124
+ """
125
+ hi = _arm(records, model_id, effort)
126
+ measured = False
127
+ for lower in reversed(lowers):
128
+ lo = _arm(records, model_id, lower)
129
+ if hi['n'] < MIN_TASKS or lo['n'] < MIN_TASKS:
130
+ continue
131
+ measured = True
132
+ slower = (hi['median'] is not None and lo['median'] is not None and lo['median'] > 0
133
+ and hi['median'] >= 2 * lo['median'])
134
+ no_better = hi['k'] * lo['n'] <= lo['k'] * hi['n']
135
+ if slower and no_better:
136
+ return _line(alias, effort, lower, (hi['k'], hi['n']), (lo['k'], lo['n']),
137
+ hi['median'] / 60.0, lo['median'] / 60.0,
138
+ 'forge dataset, %d runs' % (hi['n'] + lo['n']))
139
+ return None if measured else _SKIP
140
+
141
+
142
+ def _from_table(alias, effort, model_id, lowers, registry):
143
+ for row in _TABLE:
144
+ if (alias, effort) != (row['alias'], row['effort']) or row['lower'] not in lowers:
145
+ continue
146
+ same = (registry.get(alias) or {}).get(row['harness'])
147
+ if not same or model_id != same:
148
+ continue
149
+ return _line(alias, effort, row['lower'], row['passes'], row['lower_passes'],
150
+ row['minutes'], row['lower_minutes'], row['source'])
151
+ return None
152
+
153
+
154
+ def slow_note(spec, *, store=None):
155
+ """One note when `spec` is a measured slowdown, else None. Never raises."""
156
+ try:
157
+ alias, effort, _harness = _parts(spec)
158
+ if not alias or not effort:
159
+ return None
160
+ registry = registry_models()
161
+ model_id, effort = resolve(spec, registry)
162
+ if not model_id or not effort:
163
+ return None
164
+ ladder = _efforts(spec)
165
+ if effort not in ladder:
166
+ return None
167
+ lowers = ladder[:ladder.index(effort)]
168
+ if not lowers:
169
+ return None
170
+ # The flag gates the dataset, an injected store included. No file yet is not an error:
171
+ # there is nothing measured, so the built-in table still applies.
172
+ if enabled():
173
+ runs = _runs(store)
174
+ if runs is not None:
175
+ found = _from_dataset(routing_tasks(runs), alias, effort, model_id, lowers)
176
+ if found is not _SKIP:
177
+ return found
178
+ return _from_table(alias, effort, model_id, lowers, registry)
179
+ except Exception:
180
+ return None
181
+
182
+
183
+ def plan_notes(plan) -> list:
184
+ """`note:` lines for the distinct slow specs in a plan's dwarf and qa columns.
185
+
186
+ After routing, tasks.tsv holds concrete specs. The same spec twice is one line. A
187
+ missing table prints nothing.
188
+ """
189
+ from .harvest import tasks_rows
190
+ seen, out = set(), []
191
+ for row in tasks_rows(Path(plan) / 'tasks.tsv').values():
192
+ for spec in (row.get('dwarf'), row.get('qa')):
193
+ spec = (spec or '').strip()
194
+ if not spec or spec == '-' or spec in seen:
195
+ continue
196
+ seen.add(spec)
197
+ text = slow_note(spec)
198
+ if text:
199
+ out.append('note: ' + text)
200
+ return out
201
+
202
+
203
+ def main(argv=None) -> int:
204
+ args = list(sys.argv[1:] if argv is None else argv)
205
+ if len(args) != 1:
206
+ print('usage: python3 -m forge_dataset.efforts SPEC', file=sys.stderr)
207
+ return 2
208
+ text = slow_note(args[0])
209
+ if text:
210
+ print(text)
211
+ return 0
212
+
213
+
214
+ if __name__ == '__main__':
215
+ sys.exit(main())
@@ -120,6 +120,14 @@ def as_int(value) -> int | None:
120
120
  return None
121
121
 
122
122
 
123
+ def as_text(value) -> str | None:
124
+ """A non-empty string, or None. A missing tier field and a JSON null both land here."""
125
+ if isinstance(value, str):
126
+ value = value.strip()
127
+ return value or None
128
+ return None
129
+
130
+
123
131
  def signature(path: Path) -> list | None:
124
132
  try:
125
133
  st = path.stat()
@@ -414,6 +422,10 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
414
422
  # gets its own role: nothing that reads qa dispatches mistakes it for the one that decided.
415
423
  role='qa_shadow' if shadow and role == 'qa' else role, alias=resolved.get('alias'), harness=harness, model=resolved.get('model'),
416
424
  effort=None if not effort or effort.startswith('<') else effort,
425
+ # metrics.json is the record finish() wrote. A run from before that record falls
426
+ # back to the resolved line, which exists only when a tier was asked.
427
+ service_tier=as_text(metrics.get('service_tier')) or as_text(resolved.get('service_tier')),
428
+ speed=as_text(metrics.get('speed')), speed_reason=as_text(metrics.get('speed_reason')),
417
429
  yolo=resolved.get('yolo') == 'ON', passthrough=resolved.get('passthrough') == 'yes',
418
430
  clamped=resolved.get('clamped'), timeout=as_int(resolved.get('timeout')),
419
431
  timeout_source=resolved.get('timeout_source'), delivery=delivery,
@@ -710,6 +722,18 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
710
722
  plan_gates = read_json(plan / 'plan-gates.json')
711
723
  if plan_gates is not None:
712
724
  later['plan_gates'] = plan_gates
725
+ # Same rule as plan_gates: hashed only when the file is there, so a plan from before
726
+ # these records keeps its id. plan-gate.json is the planner's one-task-or-plan record
727
+ # (plan-gates.json, plural, is the decision-model gates).
728
+ plan_shape = read_json(plan / 'plan-shape.json')
729
+ collapsed_record = read_json(plan / 'collapsed.json')
730
+ plan_gate = read_json(plan / 'plan-gate.json')
731
+ if plan_shape is not None:
732
+ later['plan_shape'] = plan_shape
733
+ if collapsed_record is not None:
734
+ later['collapsed'] = collapsed_record
735
+ if plan_gate is not None:
736
+ later['plan_gate'] = plan_gate
713
737
  inputs = json.dumps([text(plan / 'goal.txt'), text(plan / 'tasks.tsv'), text(declared_path),
714
738
  {t: [r['prompt'], r['approach']] for t, r in per_task.items()}] + ([later] if later else []),
715
739
  sort_keys=True, default=str)
@@ -739,6 +763,26 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
739
763
  )
740
764
  if plan_gates is not None:
741
765
  data['plan_gates'] = plan_gates
766
+ if plan_shape is not None:
767
+ # shape, widest and the count of waves come from plan-shape.json. The count is
768
+ # `wave_count`: `waves` stays the task→wave map on every plan, one type across the store.
769
+ if 'shape' in plan_shape:
770
+ data['shape'] = plan_shape['shape']
771
+ if 'widest' in plan_shape:
772
+ data['widest'] = plan_shape['widest']
773
+ if 'waves' in plan_shape:
774
+ data['wave_count'] = plan_shape['waves']
775
+ if collapsed_record is not None:
776
+ data['collapsed'] = True
777
+ origin = collapsed_record.get('from')
778
+ if isinstance(origin, list):
779
+ data['collapsed_from'] = origin
780
+ if plan_gate is not None:
781
+ data['plan_gate'] = plan_gate
782
+ # Who started the plan: `auto` for forge-parallel.sh auto. Absent for a plan built by hand.
783
+ orchestrator = first_line(plan / 'orchestrator')
784
+ if orchestrator:
785
+ data['orchestrator'] = orchestrator
742
786
  return dict(rid='plan:%s:%s' % (prov.get('run'), sha256(inputs.encode())[:16]), kind='plan',
743
787
  ts=time.time(), src=src, run=prov.get('run'), run_id=prov.get('run_id'), mode='parallel',
744
788
  inv=prov.get('inv'), data=data)
@@ -14,9 +14,27 @@ File schema, the same at both levels (unknown keys are kept and ignored):
14
14
  "budget": {"run_tokens", "run_usd", "daily_tokens", "daily_usd"},
15
15
  "providers": {"<name>": {"type", "url", "model", "key_env", "key_file", "context",
16
16
  "price_usd_per_mtok", "local"}},
17
- "profiles": {"<name>": {"gates", "budget"}},
17
+ "default_profile": "<name>",
18
+ "profiles": {"<name>": {
19
+ "routing": {"dwarf": {"any"|"low"|"medium"|"high": [spec, ...]},
20
+ "qa": {"any"|"low"|"medium"|"high": [spec, ...]},
21
+ "planner": spec, "fractal_planner": spec, "final_reviewer": spec,
22
+ "escalate_after": int >= 0, "escalate_effort": bool},
23
+ "policy": {"qa_threshold": "P0"|"P1"|"P2"|"P3"|"none", "retry_failed": int >= 0,
24
+ "infra_retries": int >= 0, "verify_retries": int >= 0, "timeout": int >= 0,
25
+ "explore": number in [0, 0.5], "shadow_qa": [spec, ...],
26
+ "shadow_rate": number in [0, 1],
27
+ "fast": ["dwarf"|"qa"|"planner"|"review", ...]},
28
+ "gates": {...as above...}, "budget": {...as above...}}},
18
29
  "privacy": "never-send"}
19
30
 
31
+ A spec is alias[:effort[:harness]]. Every key of a profile is optional. Unknown keys inside
32
+ `routing` or `policy` (and unknown tiers under `dwarf`/`qa`) are refused by
33
+ profiles.validate(), to catch typos; unknown top-level keys of a profile are kept and
34
+ ignored. `default_profile` names the profile a run uses when none is asked for (the user
35
+ file's beats the repo file's). Two built-in profiles, `balanced` and `lite`
36
+ (builtin_profiles.json, read-only), are found after both files; see profiles.py.
37
+
20
38
  A provider's key comes from `key_env` when that variable is set, else from `key_file`; it
21
39
  may name both, or neither (a local server may need no key).
22
40
  A gate may also be written as a bare mode string ("drift": "on"). USER_ONLY keys count only
@@ -0,0 +1,25 @@
1
+ {
2
+ "version": 1,
3
+ "profiles": {
4
+ "balanced": {
5
+ "source": "#86 SWE-bench Pro decomposed runs, 2026-10-28; docs/models.md",
6
+ "routing": {
7
+ "dwarf": {"low": ["haiku:xhigh"], "medium": ["sonnet:medium"], "high": ["opus:high"]},
8
+ "qa": {"low": ["sonnet:medium"], "medium": ["sonnet:high"], "high": ["opus:high"]},
9
+ "planner": "sonnet:high",
10
+ "escalate_after": 2
11
+ },
12
+ "policy": {"retry_failed": 2}
13
+ },
14
+ "lite": {
15
+ "source": "#86 SWE-bench Pro decomposed runs, 2026-10-28; docs/models.md",
16
+ "routing": {
17
+ "dwarf": {"low": ["haiku:xhigh"], "medium": ["sonnet:medium"], "high": ["sonnet:high"]},
18
+ "qa": {"low": ["sonnet:medium"], "medium": ["sonnet:high"], "high": ["sonnet:high"]},
19
+ "planner": "sonnet:high",
20
+ "escalate_after": 2
21
+ },
22
+ "policy": {"retry_failed": 2}
23
+ }
24
+ }
25
+ }
@@ -402,6 +402,18 @@ def cmd_gate(args) -> int:
402
402
  else:
403
403
  data = _user_preview()
404
404
  configured = data.get('providers') if isinstance(data.get('providers'), dict) else {}
405
+ if args.profile is not None and repo is None:
406
+ # Gates go into the user file's profile of that name. Where only another level has it (a
407
+ # built-in, a repo profile), that would create a user profile holding just the gates, which
408
+ # hides the other copy's routing and policy.
409
+ from . import profiles as profiles_module
410
+ own = data.get('profiles') if isinstance(data.get('profiles'), dict) else {}
411
+ other = profiles_module.available(_repo(None)).get(args.profile)
412
+ if args.profile not in own and other is not None:
413
+ kind = 'built-in' if other['level'] == 'builtin' else '%s-level' % other['level']
414
+ raise Usage('%s profile %r is not stored in your user file, and gates for it would hide it; '
415
+ 'copy it first: forge config profile create NAME --from %s, then pass --profile NAME'
416
+ % (kind, args.profile, args.profile))
405
417
  if args.provider is not None and args.provider not in configured:
406
418
  # A legacy provider exists only once migrated; a --repo write never touches the user
407
419
  # file, so there it has to be migrated already.