@giamme/forge 0.13.1 → 0.14.1
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.
- package/CHANGELOG.md +38 -0
- package/SKILL.md +17 -11
- package/VERSION +1 -1
- package/docs/artifacts.md +2 -0
- package/docs/commands.md +134 -8
- package/docs/development.md +3 -0
- package/docs/reviews.md +2 -0
- package/docs/troubleshooting.md +5 -1
- package/forge +28 -1
- package/package.json +1 -1
- package/references/dataset.md +3 -1
- package/references/decompose.md +201 -61
- package/references/harnesses.md +4 -1
- package/references/runtime.md +29 -0
- package/references/ui.md +10 -0
- package/scripts/forge-compare.py +491 -0
- package/scripts/forge-config.py +3 -3
- package/scripts/forge-contract.py +34 -8
- package/scripts/forge-control.py +105 -13
- package/scripts/forge-dispatch.sh +85 -25
- package/scripts/forge-jev-options.sh +17 -4
- package/scripts/forge-ledger.py +387 -0
- package/scripts/forge-lib-plans.sh +11 -2
- package/scripts/forge-lib-task.sh +390 -28
- package/scripts/forge-parallel-options.sh +20 -4
- package/scripts/forge-parallel.sh +123 -17
- package/scripts/forge-plan-check.py +68 -3
- package/scripts/forge-pr.py +276 -0
- package/scripts/forge-route.py +403 -38
- package/scripts/forge-runs.py +18 -1
- package/scripts/forge-runtime.py +94 -8
- package/scripts/forge-schedule.py +303 -46
- package/scripts/forge-verify-failed.py +111 -0
- package/scripts/forge-watch.py +372 -0
- package/scripts/forge_dataset/harvest.py +3 -1
- package/scripts/forge_fractal/cli.py +23 -6
- package/scripts/forge_infra.py +274 -0
- package/scripts/forge_jev/client.py +13 -9
- package/ui/docs/api.md +51 -8
- package/ui/forge_ui/export.py +6 -2
- package/ui/forge_ui/reader.py +172 -6
- package/ui/forge_ui/static/app.js +2 -2
- package/ui/forge_ui/static/checksview.js +20 -7
- package/ui/forge_ui/static/controls.js +6 -3
- package/ui/forge_ui/static/panel.js +69 -4
- package/ui/forge_ui/static/runmodel.js +30 -4
- package/ui/forge_ui/static/scene3d.js +3 -2
- package/ui/forge_ui/static/style.css +11 -4
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""forge runs rerun / forge runs compare: the same plan under another implementer, side by side.
|
|
3
|
+
|
|
4
|
+
`forge runs rerun <run-dir> --dwarf SPEC` copies a plan's tasks and prompts into a NEW plan
|
|
5
|
+
directory, with SPEC as every task's implementer, and sets it up the way `forge-parallel.sh plan`
|
|
6
|
+
leaves a plan: new task worktrees and branches (forge/<new id>/<task>) and a new integration branch
|
|
7
|
+
(forge/<new id>-integration) that starts at the commit the original run started from, so both
|
|
8
|
+
runs begin from the same code. It dispatches nothing: it prints what a second run would cost (the
|
|
9
|
+
forecast when the dataset has history for it) and the command that starts it. `--run --yes`
|
|
10
|
+
starts it. Nothing is ever merged: a rerun only writes its own forge/<new id>... branches and never
|
|
11
|
+
touches the branch you work on, the original run or its branches.
|
|
12
|
+
|
|
13
|
+
`forge runs compare <run-dir-A> <run-dir-B>` sets two runs of one repo side by side, per task:
|
|
14
|
+
status, attempts, tokens, time and diff size. It reads the plan directories (and the dataset for
|
|
15
|
+
tokens and time, when the runs are in it) and, unless `--no-record` is given, records the pair
|
|
16
|
+
as one `comparison` dataset event. Nothing routes on it.
|
|
17
|
+
|
|
18
|
+
One pair of runs is one sample: a task that passed on one model and failed on the other may just
|
|
19
|
+
have been the model's day. The numbers say what happened, not which model is better.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import hashlib
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
import re
|
|
29
|
+
import shutil
|
|
30
|
+
import subprocess
|
|
31
|
+
import sys
|
|
32
|
+
import time
|
|
33
|
+
|
|
34
|
+
SKILL = Path(__file__).resolve().parent.parent
|
|
35
|
+
sys.path.insert(0, str(SKILL / 'scripts'))
|
|
36
|
+
sys.path.insert(0, str(SKILL / 'ui'))
|
|
37
|
+
|
|
38
|
+
# Plan options that travel with a rerun, so it is judged the way the original was. Not the ones
|
|
39
|
+
# `plan` writes itself (routing, Jev's frozen selection) or that a fresh plan decides (exploration).
|
|
40
|
+
OPTION_FILES = ('no_ripwire', 'no_memory', 'yolo_dwarf', 'yolo_qa', 'reviewer_session', 'implementer_session',
|
|
41
|
+
'pre_review_tests', 'pre_review_parallel', 'qa_threshold', 'timeout', 'verify_retries', 'verify_cmd',
|
|
42
|
+
'verify_parallel', 'setup_cmd', 'final_qa', 'shadow_qa', 'shadow_rate', 'escalate_after', 'fail_first')
|
|
43
|
+
PLAN_FILES = ('repo.identity', 'goal.txt', 'request.md')
|
|
44
|
+
TASK_FILES = ('prompt.md', 'approach.md')
|
|
45
|
+
NAME = re.compile(r'[^A-Za-z0-9._-]+')
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Refusal(Exception):
|
|
49
|
+
def __init__(self, message, code=3):
|
|
50
|
+
super().__init__(message)
|
|
51
|
+
self.code = code
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def git(repo, *args):
|
|
55
|
+
out = subprocess.run(['git', '-C', str(repo), *args], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
|
56
|
+
return out.returncode, out.stdout.strip()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def text(path: Path) -> str:
|
|
60
|
+
try:
|
|
61
|
+
return path.read_text(errors='replace').strip()
|
|
62
|
+
except OSError:
|
|
63
|
+
return ''
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def table(path: Path) -> list:
|
|
67
|
+
"""tasks.tsv as dicts: id, deps, difficulty, files, dwarf, qa, title (blank and # lines skipped)."""
|
|
68
|
+
keys = ('id', 'deps', 'difficulty', 'files', 'dwarf', 'qa', 'title')
|
|
69
|
+
rows = []
|
|
70
|
+
for line in text(path).splitlines():
|
|
71
|
+
if not line.strip() or line.startswith('#'):
|
|
72
|
+
continue
|
|
73
|
+
cells = line.split('\t')
|
|
74
|
+
row = dict(zip(keys, cells + [''] * (len(keys) - len(cells))))
|
|
75
|
+
if row['id']:
|
|
76
|
+
rows.append(row)
|
|
77
|
+
return rows
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def fractal_enabled(plan: Path) -> bool:
|
|
81
|
+
raw = text(plan / 'fractal-selection.json')
|
|
82
|
+
if not raw:
|
|
83
|
+
return False
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(raw).get('enabled') is not False
|
|
86
|
+
except (ValueError, AttributeError):
|
|
87
|
+
return True
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def source(run_dir: str) -> dict:
|
|
91
|
+
"""The plan a rerun starts from, or a Refusal saying what is missing."""
|
|
92
|
+
plan = Path(run_dir).resolve()
|
|
93
|
+
if not (plan / 'tasks.tsv').is_file():
|
|
94
|
+
raise Refusal('%s is not a decomposed run: it has no tasks.tsv (a solo run has no task table to rerun)' % plan)
|
|
95
|
+
rows = table(plan / 'tasks.tsv')
|
|
96
|
+
if not rows:
|
|
97
|
+
raise Refusal('%s has an empty tasks.tsv' % plan)
|
|
98
|
+
repo = text(plan / 'repo')
|
|
99
|
+
if not repo or not Path(repo).is_dir():
|
|
100
|
+
raise Refusal("the plan's repository '%s' does not exist" % repo)
|
|
101
|
+
base = text(plan / 'integration.base')
|
|
102
|
+
if not base:
|
|
103
|
+
raise Refusal('%s has no integration.base: that plan never started a run, so there is no starting commit '
|
|
104
|
+
'to rerun from (use it as it is: forge-parallel.sh run)' % plan)
|
|
105
|
+
if git(repo, 'rev-parse', '--verify', '--quiet', base + '^{commit}')[0] != 0:
|
|
106
|
+
raise Refusal('the commit %s that the run started from is not in %s any more' % (base[:7], repo))
|
|
107
|
+
if fractal_enabled(plan):
|
|
108
|
+
raise Refusal('this plan runs under Fractal, which binds each task to output paths under the plan directory; '
|
|
109
|
+
'a Fractal-backed plan cannot be rerun')
|
|
110
|
+
running = [r['id'] for r in rows if text(plan / 'tasks' / r['id'] / 'status') == 'RUNNING']
|
|
111
|
+
if running:
|
|
112
|
+
raise Refusal('task %s is RUNNING (or a run was killed); let it finish, or settle it with '
|
|
113
|
+
'"forge-parallel.sh run %s", before rerunning' % (', '.join(running), plan))
|
|
114
|
+
return dict(plan=plan, rows=rows, repo=repo, base=base, run_id=text(plan / 'run_id') or plan.name)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# --- the dataset, read-only -------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
def history():
|
|
120
|
+
"""The dataset's Runs, or None when there is no store (reading must not create one)."""
|
|
121
|
+
try:
|
|
122
|
+
from forge_dataset import connect, dataset_dir
|
|
123
|
+
from forge_dataset.export import Runs, Store
|
|
124
|
+
if not (dataset_dir() / 'dataset.sqlite').exists():
|
|
125
|
+
return None
|
|
126
|
+
db = connect()
|
|
127
|
+
try:
|
|
128
|
+
return Runs(Store(db))
|
|
129
|
+
finally:
|
|
130
|
+
db.close()
|
|
131
|
+
except Exception:
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def cost(runs, uid, task) -> tuple:
|
|
136
|
+
"""(tokens, seconds) of a task's dwarf and QA calls over every attempt; None when unrecorded."""
|
|
137
|
+
if runs is None or not uid:
|
|
138
|
+
return None, None
|
|
139
|
+
try:
|
|
140
|
+
from forge_dataset.forecast import _cost
|
|
141
|
+
return _cost(runs, uid, task)
|
|
142
|
+
except Exception:
|
|
143
|
+
return None, None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def human_tokens(n):
|
|
147
|
+
if n is None:
|
|
148
|
+
return '-'
|
|
149
|
+
return '%.1fk' % (n / 1000) if n >= 1000 else '%d' % n
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def human_time(s):
|
|
153
|
+
if s is None:
|
|
154
|
+
return '-'
|
|
155
|
+
s = int(round(s))
|
|
156
|
+
return '%dm%02ds' % divmod(s, 60) if s >= 60 else '%ds' % s
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# --- rerun ------------------------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
def slug(spec: str) -> str:
|
|
162
|
+
return NAME.sub('-', spec).strip('-.') or 'rerun'
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def target(src: dict, to, spec: str) -> dict:
|
|
166
|
+
new = Path(to).resolve() if to else src['plan'].with_name('%s-%s' % (src['plan'].name, slug(spec)))
|
|
167
|
+
rid = re.sub(r'^forge-', '', new.name)
|
|
168
|
+
repo = src['repo']
|
|
169
|
+
if new.exists():
|
|
170
|
+
raise Refusal('%s already exists; pick another directory with --to' % new)
|
|
171
|
+
if git(repo, 'check-ref-format', '--branch', 'forge/%s-integration' % rid)[0] != 0 \
|
|
172
|
+
or git(repo, 'check-ref-format', '--branch', 'forge/%s/x' % rid)[0] != 0:
|
|
173
|
+
raise Refusal("'%s' cannot be part of a branch name; pick another directory with --to" % rid, 2)
|
|
174
|
+
clash = git(repo, 'for-each-ref', '--format=%(refname:short)', 'refs/heads/forge/%s' % rid,
|
|
175
|
+
'refs/heads/forge/%s-integration' % rid, 'refs/heads/forge/%s/' % rid)[1]
|
|
176
|
+
if clash:
|
|
177
|
+
raise Refusal('branches already exist for run id %s (%s); pick another directory with --to' % (rid, clash.splitlines()[0]))
|
|
178
|
+
wt_root = Path(os.path.dirname(os.path.abspath(repo))) / '.forge-worktrees' / rid
|
|
179
|
+
if wt_root.exists() and any(wt_root.iterdir()):
|
|
180
|
+
raise Refusal("worktree root '%s' already exists; pick another directory with --to" % wt_root)
|
|
181
|
+
return dict(plan=new, run_id=rid, branch='forge/%s-integration' % rid, wt_root=wt_root)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def write_table(path: Path, rows: list) -> None:
|
|
185
|
+
keys = ('id', 'deps', 'difficulty', 'files', 'dwarf', 'qa', 'title')
|
|
186
|
+
body = '# id\tdeps\tdifficulty\tfiles\tdwarf\tqa\ttitle\n'
|
|
187
|
+
body += ''.join('\t'.join(r[k] for k in keys) + '\n' for r in rows)
|
|
188
|
+
path.write_text(body)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def copy_plan(src: dict, new: dict, rows: list) -> None:
|
|
192
|
+
plan, out = src['plan'], new['plan']
|
|
193
|
+
out.mkdir(parents=True)
|
|
194
|
+
write_table(out / 'tasks.tsv', rows)
|
|
195
|
+
(out / 'repo').write_text(src['repo'] + '\n')
|
|
196
|
+
(out / 'integration.base').write_text(src['base'] + '\n')
|
|
197
|
+
for name in PLAN_FILES + OPTION_FILES:
|
|
198
|
+
if (plan / name).is_file():
|
|
199
|
+
shutil.copy2(plan / name, out / name)
|
|
200
|
+
if (plan / 'verify.d').is_dir():
|
|
201
|
+
shutil.copytree(plan / 'verify.d', out / 'verify.d')
|
|
202
|
+
for row in rows:
|
|
203
|
+
for name in TASK_FILES:
|
|
204
|
+
if (plan / 'tasks' / row['id'] / name).is_file():
|
|
205
|
+
(out / 'tasks' / row['id']).mkdir(parents=True, exist_ok=True)
|
|
206
|
+
shutil.copy2(plan / 'tasks' / row['id'] / name, out / 'tasks' / row['id'] / name)
|
|
207
|
+
(out / 'rerun-of.txt').write_text('rerun of %s\nrun_id %s\nstarted from %s\n' % (plan, src['run_id'], src['base']))
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def forecast_lines(new: Path) -> list:
|
|
211
|
+
try:
|
|
212
|
+
from forge_dataset import forecast
|
|
213
|
+
fc = forecast.build(new)
|
|
214
|
+
if fc and fc['tasks']:
|
|
215
|
+
return forecast.lines(fc, brief=True)
|
|
216
|
+
except Exception:
|
|
217
|
+
pass
|
|
218
|
+
return []
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def warning(rows: list, spec: str, src: dict, runs) -> list:
|
|
222
|
+
qas = sorted({r['qa'] for r in rows if r['qa']})
|
|
223
|
+
out = ['This spends a second run\'s tokens: %d task%s on %s, each reviewed by %s (more when one is sent back), '
|
|
224
|
+
'then verification.' % (len(rows), '' if len(rows) == 1 else 's', spec, ', '.join(qas) or 'its reviewer')]
|
|
225
|
+
uid = text(src['plan'] / 'dataset.uid')
|
|
226
|
+
spent = [cost(runs, uid, r['id'])[0] for r in rows]
|
|
227
|
+
if any(v is not None for v in spent):
|
|
228
|
+
out.append('The original run recorded about %s tokens for these tasks (dwarf and QA); another model may use '
|
|
229
|
+
'more or less.' % human_tokens(sum(v for v in spent if v)))
|
|
230
|
+
return out
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def rerun(argv) -> int:
|
|
234
|
+
parser = argparse.ArgumentParser(
|
|
235
|
+
prog='forge runs rerun', description="Copy a finished plan into a new one with another implementer, from the same "
|
|
236
|
+
"starting commit. Dispatches nothing unless --run --yes is given; never merges.")
|
|
237
|
+
parser.add_argument('run_dir', metavar='RUN_DIR', help="the plan's run directory")
|
|
238
|
+
parser.add_argument('--dwarf', required=True, metavar='SPEC', help='the implementer for every task (a registry alias, '
|
|
239
|
+
'optionally :effort or :effort:harness)')
|
|
240
|
+
parser.add_argument('--qa', metavar='SPEC', help='another reviewer too (default: each task keeps its own, so the comparison '
|
|
241
|
+
'changes one thing)')
|
|
242
|
+
parser.add_argument('--to', metavar='DIR', help='the new plan directory (default: <run-dir>-<spec>)')
|
|
243
|
+
parser.add_argument('--max-parallel', type=int, metavar='N', help='passed to run (with --run)')
|
|
244
|
+
parser.add_argument('--run', action='store_true', help='start the new plan now; needs --yes')
|
|
245
|
+
parser.add_argument('--yes', action='store_true', help='say that spending a second run\'s tokens is wanted (with --run)')
|
|
246
|
+
parser.add_argument('--dry-run', action='store_true', help='say what would be created and change nothing')
|
|
247
|
+
args = parser.parse_args(argv)
|
|
248
|
+
if args.run and not args.yes:
|
|
249
|
+
parser.error('--run spends a second run\'s tokens: read the forecast first (leave --run off to see it), then add --yes')
|
|
250
|
+
if args.yes and not args.run:
|
|
251
|
+
parser.error('--yes goes with --run')
|
|
252
|
+
if args.max_parallel is not None and args.max_parallel < 1:
|
|
253
|
+
parser.error('--max-parallel must be positive')
|
|
254
|
+
try:
|
|
255
|
+
return rerun_plan(args)
|
|
256
|
+
except Refusal as refusal:
|
|
257
|
+
print('forge runs rerun: %s' % refusal, file=sys.stderr)
|
|
258
|
+
return refusal.code
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def rerun_plan(args) -> int:
|
|
262
|
+
from forge_dataset.forecast import registry_models
|
|
263
|
+
src = source(args.run_dir)
|
|
264
|
+
registry = registry_models()
|
|
265
|
+
for label, spec in (('--dwarf', args.dwarf), ('--qa', args.qa)):
|
|
266
|
+
if spec and registry and spec.split(':')[0] not in registry:
|
|
267
|
+
raise Refusal("%s: '%s' is not an alias in the registry (%s)" % (label, spec, ', '.join(sorted(registry))), 2)
|
|
268
|
+
rows = [dict(r, dwarf=args.dwarf, qa=args.qa or r['qa']) for r in src['rows']]
|
|
269
|
+
if all(a['dwarf'] == b['dwarf'] and a['qa'] == b['qa'] for a, b in zip(src['rows'], rows)):
|
|
270
|
+
raise Refusal('every task already ran on %s with that reviewer: a rerun would compare a run with itself' % args.dwarf)
|
|
271
|
+
new = target(src, args.to, args.dwarf)
|
|
272
|
+
runs = history()
|
|
273
|
+
print('rerun of %s (run %s, started from %s)' % (src['plan'], src['run_id'], src['base'][:7]))
|
|
274
|
+
print(' new plan: %s' % new['plan'])
|
|
275
|
+
print(' branches: %s and forge/%s/<task>; worktrees in %s' % (new['branch'], new['run_id'], new['wt_root']))
|
|
276
|
+
print(' implementer %s for %d task%s; %s' % (args.dwarf, len(rows), '' if len(rows) == 1 else 's',
|
|
277
|
+
'reviewer %s' % args.qa if args.qa else 'reviewers as in the original'))
|
|
278
|
+
if args.dry_run:
|
|
279
|
+
for line in warning(rows, args.dwarf, src, runs):
|
|
280
|
+
print(line)
|
|
281
|
+
print('(dry run: nothing created, nothing dispatched)')
|
|
282
|
+
return 0
|
|
283
|
+
created = []
|
|
284
|
+
try:
|
|
285
|
+
copy_plan(src, new, rows)
|
|
286
|
+
created.append('plan')
|
|
287
|
+
if git(src['repo'], 'branch', new['branch'], src['base'])[0] != 0:
|
|
288
|
+
raise Refusal('could not create %s' % new['branch'])
|
|
289
|
+
created.append('branch')
|
|
290
|
+
planned = subprocess.run(['bash', str(SKILL / 'scripts' / 'forge-parallel.sh'), 'plan', str(new['plan']),
|
|
291
|
+
'--explore', '0'], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
|
292
|
+
if planned.returncode != 0:
|
|
293
|
+
raise Refusal('forge-parallel.sh plan failed (%d):\n%s' % (planned.returncode, (planned.stdout + planned.stderr).strip()))
|
|
294
|
+
changed = [r['id'] for r in table(new['plan'] / 'tasks.tsv') if r['dwarf'] != args.dwarf]
|
|
295
|
+
if changed:
|
|
296
|
+
raise Refusal('plan chose another implementer for %s; a head-to-head needs %s on every task' % (', '.join(changed), args.dwarf))
|
|
297
|
+
except BaseException:
|
|
298
|
+
if 'branch' in created:
|
|
299
|
+
git(src['repo'], 'branch', '-D', new['branch'])
|
|
300
|
+
if 'plan' in created:
|
|
301
|
+
shutil.rmtree(new['plan'], ignore_errors=True)
|
|
302
|
+
raise
|
|
303
|
+
print('created. Nothing is dispatched yet.')
|
|
304
|
+
for line in warning(rows, args.dwarf, src, runs):
|
|
305
|
+
print(line)
|
|
306
|
+
shown = forecast_lines(new['plan'])
|
|
307
|
+
for line in shown:
|
|
308
|
+
print(line)
|
|
309
|
+
if not shown:
|
|
310
|
+
print('(no forecast: the dataset has no matching history for %s yet)' % args.dwarf)
|
|
311
|
+
command = 'bash %s run %s --no-forecast%s' % (SKILL / 'scripts' / 'forge-parallel.sh', new['plan'],
|
|
312
|
+
' --max-parallel %d' % args.max_parallel if args.max_parallel else '')
|
|
313
|
+
if not args.run:
|
|
314
|
+
print('start it: %s (or: forge runs rerun ... --run --yes)' % command)
|
|
315
|
+
print('then compare: forge runs compare %s %s' % (src['plan'], new['plan']))
|
|
316
|
+
return 0
|
|
317
|
+
print('starting: %s' % command)
|
|
318
|
+
sys.stdout.flush()
|
|
319
|
+
rc = subprocess.run(command.split(), stdin=subprocess.DEVNULL).returncode
|
|
320
|
+
print('compare: forge runs compare %s %s' % (src['plan'], new['plan']))
|
|
321
|
+
return rc
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# --- compare ----------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def attempts_of(plan: Path, task: str) -> tuple:
|
|
327
|
+
"""(attempts, first attempt's status) from attempts.tsv: ts, number, status, ..."""
|
|
328
|
+
lines = [l.split('\t') for l in text(plan / 'tasks' / task / 'attempts.tsv').splitlines() if l.strip()]
|
|
329
|
+
return len(lines), (lines[0][2] if lines and len(lines[0]) > 2 else None)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def diff_size(side: dict, task: str):
|
|
333
|
+
"""(added, deleted) lines on the task's branch since the commit it started from, or None."""
|
|
334
|
+
base = text(side['plan'] / 'tasks' / task / 'base_ref')
|
|
335
|
+
branch = 'forge/%s/%s' % (side['run_id'], task)
|
|
336
|
+
if not base or git(side['repo'], 'rev-parse', '--verify', '--quiet', branch)[0] != 0:
|
|
337
|
+
return None
|
|
338
|
+
code, out = git(side['repo'], 'diff', '--numstat', base, branch)
|
|
339
|
+
if code != 0:
|
|
340
|
+
return None
|
|
341
|
+
added = deleted = 0
|
|
342
|
+
for line in out.splitlines():
|
|
343
|
+
a, d = line.split('\t')[:2]
|
|
344
|
+
added += int(a) if a.isdigit() else 0
|
|
345
|
+
deleted += int(d) if d.isdigit() else 0
|
|
346
|
+
return added, deleted
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def load_side(run_dir: str, runs) -> dict:
|
|
350
|
+
from forge_ui import reader
|
|
351
|
+
plan = Path(run_dir).resolve()
|
|
352
|
+
if not (plan / 'tasks.tsv').is_file():
|
|
353
|
+
raise Refusal('%s is not a decomposed run: it has no tasks.tsv' % plan)
|
|
354
|
+
rows = table(plan / 'tasks.tsv')
|
|
355
|
+
statuses = {t['id']: t['status'] for t in reader.summarize(plan).get('task_statuses') or []}
|
|
356
|
+
side = dict(plan=plan, run_id=text(plan / 'run_id') or plan.name, repo=text(plan / 'repo'), uid=text(plan / 'dataset.uid') or None,
|
|
357
|
+
base=text(plan / 'integration.base') or None, tasks={})
|
|
358
|
+
for row in rows:
|
|
359
|
+
tid = row['id']
|
|
360
|
+
n, first = attempts_of(plan, tid)
|
|
361
|
+
tokens, seconds = cost(runs, side['uid'], tid)
|
|
362
|
+
side['tasks'][tid] = dict(task=tid, tier=row['difficulty'], dwarf=row['dwarf'], qa=row['qa'],
|
|
363
|
+
status=statuses.get(tid) or text(plan / 'tasks' / tid / 'status') or 'NOT RUN',
|
|
364
|
+
attempts=n, first=first, tokens=tokens, seconds=seconds,
|
|
365
|
+
diff=diff_size(side, tid))
|
|
366
|
+
return side
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def summary(a: dict, b: dict) -> dict:
|
|
370
|
+
ids = [t for t in a['tasks'] if t in b['tasks']]
|
|
371
|
+
out = dict(tasks=len(ids), only_a=[t for t in a['tasks'] if t not in b['tasks']],
|
|
372
|
+
only_b=[t for t in b['tasks'] if t not in a['tasks']], both_merged=[], merged_only_a=[], merged_only_b=[], neither=[])
|
|
373
|
+
for t in ids:
|
|
374
|
+
ma, mb = a['tasks'][t]['status'] == 'MERGED', b['tasks'][t]['status'] == 'MERGED'
|
|
375
|
+
out['both_merged' if ma and mb else 'merged_only_a' if ma else 'merged_only_b' if mb else 'neither'].append(t)
|
|
376
|
+
for label, side in (('a', a), ('b', b)):
|
|
377
|
+
rows = [side['tasks'][t] for t in ids]
|
|
378
|
+
out[label] = dict(first_try=sum(1 for r in rows if r['first'] == 'PASS'), attempts=sum(r['attempts'] for r in rows),
|
|
379
|
+
tokens=sum(r['tokens'] for r in rows if r['tokens'] is not None) if any(r['tokens'] is not None for r in rows) else None,
|
|
380
|
+
tokens_known=sum(1 for r in rows if r['tokens'] is not None),
|
|
381
|
+
seconds=sum(r['seconds'] for r in rows if r['seconds'] is not None) if any(r['seconds'] is not None for r in rows) else None)
|
|
382
|
+
return out
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def cell(a, b, fmt=str):
|
|
386
|
+
return '%s → %s' % (fmt(a) if a is not None else '-', fmt(b) if b is not None else '-')
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def diff_text(d):
|
|
390
|
+
return '-' if d is None else '+%d/-%d' % d
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def report(a: dict, b: dict, s: dict) -> list:
|
|
394
|
+
out = ['forge runs compare']
|
|
395
|
+
for label, side in (('A', a), ('B', b)):
|
|
396
|
+
specs = sorted({t['dwarf'] for t in side['tasks'].values()})
|
|
397
|
+
out.append(' %s %s (%s; %d task%s) %s' % (label, side['run_id'], ', '.join(specs) or '?', len(side['tasks']),
|
|
398
|
+
'' if len(side['tasks']) == 1 else 's', side['plan']))
|
|
399
|
+
if a['base'] and b['base'] and a['base'] != b['base']:
|
|
400
|
+
out.append(' note: the runs started from different commits (%s and %s), so the tasks did not see the same code' % (a['base'][:7], b['base'][:7]))
|
|
401
|
+
rows = [('task', 'tier', 'status A → B', 'attempts', 'tokens', 'time', 'diff lines')]
|
|
402
|
+
for t in [t for t in a['tasks'] if t in b['tasks']]:
|
|
403
|
+
x, y = a['tasks'][t], b['tasks'][t]
|
|
404
|
+
rows.append((t, x['tier'] or '-', cell(x['status'], y['status']), cell(x['attempts'], y['attempts']),
|
|
405
|
+
cell(x['tokens'], y['tokens'], human_tokens), cell(x['seconds'], y['seconds'], human_time),
|
|
406
|
+
cell(x['diff'], y['diff'], diff_text)))
|
|
407
|
+
widths = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))]
|
|
408
|
+
out.append('')
|
|
409
|
+
for r in rows:
|
|
410
|
+
out.append(' ' + ' '.join(c.ljust(w) for c, w in zip(r, widths)).rstrip())
|
|
411
|
+
for label, ids in (('only in A', s['only_a']), ('only in B', s['only_b'])):
|
|
412
|
+
if ids:
|
|
413
|
+
out.append(' %s: %s' % (label, ', '.join(ids)))
|
|
414
|
+
out.append('')
|
|
415
|
+
out.append(' %d task%s in both: merged in both %d, only A %d, only B %d, neither %d' % (
|
|
416
|
+
s['tasks'], '' if s['tasks'] == 1 else 's', len(s['both_merged']), len(s['merged_only_a']), len(s['merged_only_b']), len(s['neither'])))
|
|
417
|
+
out.append(' first try PASS: A %d, B %d; attempts: A %d, B %d' % (s['a']['first_try'], s['b']['first_try'], s['a']['attempts'], s['b']['attempts']))
|
|
418
|
+
if s['a']['tokens'] is not None or s['b']['tokens'] is not None:
|
|
419
|
+
out.append(' tokens: %s; time: %s' % (cell(s['a']['tokens'], s['b']['tokens'], human_tokens),
|
|
420
|
+
cell(s['a']['seconds'], s['b']['seconds'], human_time)))
|
|
421
|
+
if s['tasks'] and (s['a']['tokens_known'] < s['tasks'] or s['b']['tokens_known'] < s['tasks']):
|
|
422
|
+
out.append(' (totals cover only the tasks the dataset recorded)')
|
|
423
|
+
else:
|
|
424
|
+
out.append(' tokens and time: not in the dataset for these runs')
|
|
425
|
+
out.append(' One pair of runs is one sample: a different outcome can be the model\'s day, not the model.')
|
|
426
|
+
return out
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def record_pair(a: dict, b: dict, s: dict) -> str:
|
|
430
|
+
"""Write the comparison as one dataset event; return a line saying what happened, or ''."""
|
|
431
|
+
missing = [label for label, side in (('A', a), ('B', b)) if not side['uid']]
|
|
432
|
+
if missing:
|
|
433
|
+
return 'not recorded: run %s has no dataset uid (it has not run yet)' % ' and '.join(missing)
|
|
434
|
+
idle = [label for label, side in (('A', a), ('B', b)) if not any(t['attempts'] for t in side['tasks'].values())]
|
|
435
|
+
if idle:
|
|
436
|
+
return 'not recorded: run %s has not attempted a task yet' % ' and '.join(idle)
|
|
437
|
+
from forge_dataset import record
|
|
438
|
+
body = dict(a=dict(run=a['uid'], run_id=a['run_id'], base=a['base'], tasks=a['tasks']),
|
|
439
|
+
b=dict(run=b['uid'], run_id=b['run_id'], base=b['base'], tasks=b['tasks']), summary=s)
|
|
440
|
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
|
441
|
+
event = dict(rid='comparison:%s:%s:%s' % (a['uid'], b['uid'], digest), kind='comparison', ts=time.time(), src='live',
|
|
442
|
+
run=b['uid'], run_id=b['run_id'], mode='parallel', task=None, data=body)
|
|
443
|
+
added = record([event], repo=b['repo'] or None, where='comparison')
|
|
444
|
+
return 'recorded in the dataset as a comparison event' if added else ''
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def compare(argv) -> int:
|
|
448
|
+
parser = argparse.ArgumentParser(prog='forge runs compare', description='Two runs of one plan, side by side, per task. '
|
|
449
|
+
'Records the pair in the dataset unless --no-record.')
|
|
450
|
+
parser.add_argument('run_a', metavar='RUN_DIR_A')
|
|
451
|
+
parser.add_argument('run_b', metavar='RUN_DIR_B')
|
|
452
|
+
parser.add_argument('--json', action='store_true', help='print the comparison as JSON')
|
|
453
|
+
parser.add_argument('--no-record', action='store_true', help='do not write the comparison event to the dataset')
|
|
454
|
+
args = parser.parse_args(argv)
|
|
455
|
+
try:
|
|
456
|
+
runs = history()
|
|
457
|
+
a, b = load_side(args.run_a, runs), load_side(args.run_b, runs)
|
|
458
|
+
if a['plan'] == b['plan']:
|
|
459
|
+
raise Refusal('both arguments are the same run', 2)
|
|
460
|
+
if a['repo'] and b['repo'] and os.path.realpath(a['repo']) != os.path.realpath(b['repo']):
|
|
461
|
+
raise Refusal('the runs belong to different repositories (%s and %s)' % (a['repo'], b['repo']))
|
|
462
|
+
s = summary(a, b)
|
|
463
|
+
if not s['tasks']:
|
|
464
|
+
raise Refusal('the runs have no task in common')
|
|
465
|
+
except Refusal as refusal:
|
|
466
|
+
print('forge runs compare: %s' % refusal, file=sys.stderr)
|
|
467
|
+
return refusal.code
|
|
468
|
+
note = '' if args.no_record else record_pair(a, b, s)
|
|
469
|
+
if args.json:
|
|
470
|
+
json.dump(dict(a=a, b=b, summary=s), sys.stdout, indent=2, default=str)
|
|
471
|
+
sys.stdout.write('\n')
|
|
472
|
+
return 0
|
|
473
|
+
for line in report(a, b, s):
|
|
474
|
+
print(line)
|
|
475
|
+
if note:
|
|
476
|
+
print(' ' + note)
|
|
477
|
+
return 0
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def main(argv=None) -> int:
|
|
481
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
482
|
+
if argv[:1] == ['rerun']:
|
|
483
|
+
return rerun(argv[1:])
|
|
484
|
+
if argv[:1] == ['compare']:
|
|
485
|
+
return compare(argv[1:])
|
|
486
|
+
print('usage: forge-compare.py rerun|compare ...', file=sys.stderr)
|
|
487
|
+
return 2
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
if __name__ == '__main__':
|
|
491
|
+
sys.exit(main())
|
package/scripts/forge-config.py
CHANGED
|
@@ -523,17 +523,17 @@ def set_decide(args):
|
|
|
523
523
|
def parser():
|
|
524
524
|
p = argparse.ArgumentParser(prog='forge config', description=__doc__.split('\n\n')[0])
|
|
525
525
|
sub = p.add_subparsers(dest='cmd', required=True)
|
|
526
|
-
s = sub.add_parser('show')
|
|
526
|
+
s = sub.add_parser('show', help="every config source: registry, decide, the repo's .forge files, dataset, FORGE_* env")
|
|
527
527
|
s.add_argument('--repo')
|
|
528
528
|
s.add_argument('--json', action='store_true')
|
|
529
529
|
s.set_defaults(fn=cmd_show)
|
|
530
|
-
s = sub.add_parser('set')
|
|
530
|
+
s = sub.add_parser('set', help='set repo.verify, repo.setup, repo.verify-subset or decide.gate.<gate>')
|
|
531
531
|
s.add_argument('key')
|
|
532
532
|
s.add_argument('value')
|
|
533
533
|
s.add_argument('--repo')
|
|
534
534
|
s.add_argument('--json', action='store_true')
|
|
535
535
|
s.set_defaults(fn=cmd_set)
|
|
536
|
-
s = sub.add_parser('unset')
|
|
536
|
+
s = sub.add_parser('unset', help='remove repo.verify, repo.setup or repo.verify-subset')
|
|
537
537
|
s.add_argument('key')
|
|
538
538
|
s.add_argument('--repo')
|
|
539
539
|
s.add_argument('--json', action='store_true')
|
|
@@ -149,6 +149,9 @@ _FINDINGS = [
|
|
|
149
149
|
'what breaks, and a concrete input that triggers it. Mark each CONFIRMED if you traced',
|
|
150
150
|
'it in the code, or PLAUSIBLE if you could not fully verify it.',
|
|
151
151
|
]
|
|
152
|
+
# #69: task reviews returned a few findings per round. These two lines follow _FINDINGS for
|
|
153
|
+
# task and solo only, so the findings rules stay one paragraph. Final and sweep omit them.
|
|
154
|
+
_ALL_CONFIRMED = ['List every CONFIRMED finding you find, not only the most important few.']
|
|
152
155
|
_SOLO_EXTRA = ['If the diff is correct, say so plainly rather than inventing something to report.']
|
|
153
156
|
|
|
154
157
|
# The reviewer's own verification, bounded to the change (#89): one reviewer re-ran a whole
|
|
@@ -221,7 +224,9 @@ def qa_text(part: str, kind: str = 'task', threshold=None) -> str:
|
|
|
221
224
|
return '\n'.join(_HEAD[kind]) + '\n'
|
|
222
225
|
if part != 'tail':
|
|
223
226
|
raise ValueError('part must be head or tail')
|
|
224
|
-
lines = list(_SWEEP_FINDINGS if kind == 'sweep' else _FINDINGS)
|
|
227
|
+
lines = list(_SWEEP_FINDINGS if kind == 'sweep' else _FINDINGS)
|
|
228
|
+
if kind in ('task', 'solo'):
|
|
229
|
+
lines += _ALL_CONFIRMED + _SOLO_EXTRA
|
|
225
230
|
lines += [''] + _VERIFY
|
|
226
231
|
lines += [''] + _SEVERITY
|
|
227
232
|
lines += [''] + _threshold_clause(rank, kind) + _CHECKED
|
|
@@ -238,14 +243,27 @@ def qa_text(part: str, kind: str = 'task', threshold=None) -> str:
|
|
|
238
243
|
return '\n'.join(lines) + '\n'
|
|
239
244
|
|
|
240
245
|
|
|
246
|
+
_VERIFY_SCOPE = (
|
|
247
|
+
'- Verify within your change: run the tests the change affects (the task\'s own tests and the',
|
|
248
|
+
' tests of the modules you changed). Do not run the whole suite or repo-wide lint, format or',
|
|
249
|
+
' type checks unless the task asks for them.',
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# When the run verifies the repository after each merge, a task that names the whole suite in its
|
|
253
|
+
# acceptance criteria no longer buys a full run per attempt: forge runs it once, after the merge.
|
|
254
|
+
_VERIFY_SCOPE_AFTER_MERGE = (
|
|
255
|
+
'- Verify within your change: run the tests the change affects (the task\'s own tests and the',
|
|
256
|
+
' tests of the modules you changed). Never run the whole suite or repo-wide lint, format or',
|
|
257
|
+
' type checks, even when the task or its acceptance criteria name them: forge runs the',
|
|
258
|
+
' repository\'s verification after the merge. Report that check as left to forge.',
|
|
259
|
+
)
|
|
260
|
+
|
|
241
261
|
_DWARF = [
|
|
242
262
|
'## Implementer rules',
|
|
243
263
|
'- Do not run git commit, checkout, switch, reset, stash or rebase. The harness captures',
|
|
244
264
|
' the working tree itself; a self-commit makes the change set ambiguous.',
|
|
245
265
|
'- Do not start background processes, and leave nothing running when you finish.',
|
|
246
|
-
|
|
247
|
-
' tests of the modules you changed). Do not run the whole suite or repo-wide lint, format or',
|
|
248
|
-
' type checks unless the task asks for them.',
|
|
266
|
+
_VERIFY_SCOPE,
|
|
249
267
|
'- Finish every measurement and test run BEFORE your last message and report its actual',
|
|
250
268
|
' result. If you could not run something, say so explicitly instead of claiming it passed.',
|
|
251
269
|
'- State precisely which verification commands you ran and what each one returned.',
|
|
@@ -258,9 +276,15 @@ _DWARF_PRE_REVIEW = [
|
|
|
258
276
|
]
|
|
259
277
|
|
|
260
278
|
|
|
261
|
-
def dwarf_text(pre_review: bool = False) -> str:
|
|
279
|
+
def dwarf_text(pre_review: bool = False, verify_after_merge: bool = False) -> str:
|
|
262
280
|
"""The implementer rules block, newline-terminated."""
|
|
263
|
-
|
|
281
|
+
lines = []
|
|
282
|
+
for line in _DWARF:
|
|
283
|
+
if line is _VERIFY_SCOPE:
|
|
284
|
+
lines.extend(_VERIFY_SCOPE_AFTER_MERGE if verify_after_merge else _VERIFY_SCOPE)
|
|
285
|
+
else:
|
|
286
|
+
lines.append(line)
|
|
287
|
+
return '\n'.join(lines + (_DWARF_PRE_REVIEW if pre_review else [])) + '\n'
|
|
264
288
|
|
|
265
289
|
|
|
266
290
|
# --- parsing ---------------------------------------------------------------------
|
|
@@ -288,7 +312,7 @@ def _collapse(text: str) -> str:
|
|
|
288
312
|
|
|
289
313
|
@functools.lru_cache(maxsize=None)
|
|
290
314
|
def _contract_flat() -> str:
|
|
291
|
-
parts = [dwarf_text()]
|
|
315
|
+
parts = [dwarf_text(), dwarf_text(verify_after_merge=True)]
|
|
292
316
|
for kind in KINDS:
|
|
293
317
|
for part in ('head', 'tail'):
|
|
294
318
|
for threshold in SEVERITIES: # None and `none` render one of these
|
|
@@ -450,6 +474,8 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
450
474
|
help='least severe level that still blocks; none = P3 (default: %s)' % DEFAULT_THRESHOLD)
|
|
451
475
|
dwarf = sub.add_parser('dwarf', help='print the implementer rules block')
|
|
452
476
|
dwarf.add_argument('--pre-review', action='store_true', help='forge runs the affected tests before the review')
|
|
477
|
+
dwarf.add_argument('--verify-after-merge', action='store_true',
|
|
478
|
+
help='the run verifies the repository after each merge, so the whole suite is left to it')
|
|
453
479
|
gate_parser = sub.add_parser(
|
|
454
480
|
'gate', help='print: decision (accept|fail|keep), worst_confirmed, n_confirmed, n_unlabelled, n_below')
|
|
455
481
|
gate_parser.add_argument('--verdict', required=True, choices=('PASS', 'FAIL', 'UNKNOWN'))
|
|
@@ -468,7 +494,7 @@ def main(argv=None) -> int:
|
|
|
468
494
|
_emit(qa_text(args.part, args.kind, args.threshold))
|
|
469
495
|
return 0
|
|
470
496
|
if args.command == 'dwarf':
|
|
471
|
-
_emit(dwarf_text(args.pre_review))
|
|
497
|
+
_emit(dwarf_text(args.pre_review, args.verify_after_merge))
|
|
472
498
|
return 0
|
|
473
499
|
try:
|
|
474
500
|
with open(args.qa_last, 'rb') as handle:
|