@giamme/forge 0.15.0 → 0.17.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 (80) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/VERSION +1 -1
  3. package/docs/artifacts.md +1 -1
  4. package/docs/commands.md +14 -3
  5. package/docs/dataset.md +8 -0
  6. package/docs/forge-ui.md +14 -0
  7. package/docs/memory.md +22 -0
  8. package/docs/reviews.md +22 -1
  9. package/forge +11 -0
  10. package/package.json +1 -1
  11. package/references/dataset.md +129 -7
  12. package/references/decision-models.md +15 -2
  13. package/references/decompose.md +95 -13
  14. package/references/harnesses.md +4 -1
  15. package/references/planning.md +3 -2
  16. package/references/solo.md +5 -1
  17. package/references/ui.md +10 -1
  18. package/scripts/forge-artifact.sh +53 -0
  19. package/scripts/forge-contract.py +107 -9
  20. package/scripts/forge-control.py +0 -2
  21. package/scripts/forge-dispatch.sh +28 -12
  22. package/scripts/forge-fail-first.py +3 -1
  23. package/scripts/forge-guard.py +247 -8
  24. package/scripts/forge-issues.py +16 -3
  25. package/scripts/forge-ledger.py +3 -1
  26. package/scripts/forge-lib-adopt.sh +266 -0
  27. package/scripts/forge-lib-attribute.sh +10 -2
  28. package/scripts/forge-lib-plans.sh +16 -4
  29. package/scripts/forge-lib-review.sh +8 -2
  30. package/scripts/forge-lib-task.sh +19 -5
  31. package/scripts/forge-memory.sh +41 -4
  32. package/scripts/forge-metrics.sh +29 -0
  33. package/scripts/forge-parallel.sh +99 -14
  34. package/scripts/forge-plan-check.py +25 -2
  35. package/scripts/forge-planner.py +20 -6
  36. package/scripts/forge-route.py +16 -2
  37. package/scripts/forge-runs-rm.py +23 -7
  38. package/scripts/forge-runtime.py +25 -2
  39. package/scripts/forge-schedule.py +5 -2
  40. package/scripts/forge-shadow.py +30 -9
  41. package/scripts/forge-solo.sh +6 -0
  42. package/scripts/forge-sweep.py +25 -10
  43. package/scripts/forge_dataset/cli.py +99 -0
  44. package/scripts/forge_dataset/export.py +1 -0
  45. package/scripts/forge_dataset/facts.py +278 -0
  46. package/scripts/forge_dataset/harvest.py +27 -3
  47. package/scripts/forge_dataset/history.py +126 -0
  48. package/scripts/forge_dataset/outcomes.py +206 -58
  49. package/scripts/forge_dataset/pairs.py +174 -0
  50. package/scripts/forge_dataset/risk.py +108 -0
  51. package/scripts/forge_dataset/tiers.py +427 -0
  52. package/scripts/forge_dataset/worktrees.py +95 -0
  53. package/scripts/forge_decide/cli.py +23 -2
  54. package/scripts/forge_decide/labels.py +30 -6
  55. package/scripts/forge_decide/replay.py +10 -4
  56. package/scripts/forge_memory_list.py +153 -0
  57. package/scripts/forge_worktrees.py +88 -0
  58. package/ui/README.md +31 -0
  59. package/ui/docs/api.md +92 -6
  60. package/ui/forge_ui/__init__.py +14 -1
  61. package/ui/forge_ui/__main__.py +1 -1
  62. package/ui/forge_ui/control.py +77 -0
  63. package/ui/forge_ui/export.py +9 -2
  64. package/ui/forge_ui/findings.py +11 -2
  65. package/ui/forge_ui/projects.py +571 -0
  66. package/ui/forge_ui/reader.py +96 -9
  67. package/ui/forge_ui/server.py +8 -0
  68. package/ui/forge_ui/static/app.js +105 -22
  69. package/ui/forge_ui/static/cloudui.js +6 -2
  70. package/ui/forge_ui/static/convo.js +1 -1
  71. package/ui/forge_ui/static/diffview.js +9 -5
  72. package/ui/forge_ui/static/files.js +1 -1
  73. package/ui/forge_ui/static/index.html +5 -1
  74. package/ui/forge_ui/static/panel.js +69 -2
  75. package/ui/forge_ui/static/projectsview.js +372 -0
  76. package/ui/forge_ui/static/settings.js +136 -4
  77. package/ui/forge_ui/static/style.css +94 -3
  78. package/ui/forge_ui/static/uikit.js +94 -1
  79. package/ui/forge_ui/static/worktreesview.js +250 -0
  80. package/ui/forge_ui/worktrees.py +570 -0
@@ -0,0 +1,427 @@
1
+ """`forge dataset tiers`: what explains results inside a difficulty tier (#123), before anyone adds a tier.
2
+
3
+ Difficulty works as a label, but `high` holds most of the unfinished tasks and may mix groups that behave
4
+ very differently. This report looks inside each tier with only what the dataset already has, and changes
5
+ nothing in a run.
6
+
7
+ Population: the tasks `forge dataset routing` counts, whose first attempt says something about the
8
+ implementer (fractal runs left out). Each task is described by:
9
+
10
+ plan time known before dispatch, so a rule could route on it: declared files, dependencies, wave,
11
+ the size of the task's prompt (KB)
12
+ afterwards known only once the first attempt ran, so it can explain a result but never route one:
13
+ lines in that attempt's diff, files it changed
14
+
15
+ and three outcomes: first attempt passed, attempts taken, unfinished (never passed and not accepted).
16
+
17
+ For each fact inside a tier:
18
+
19
+ bins the tier split into thirds of that fact, each with tasks, runs, first pass (Wilson 95%),
20
+ mean attempts and unfinished. Descriptive: a run's tasks are correlated and routing chose
21
+ who ran what, so read the intervals as optimistic.
22
+ held out whether a split on the fact predicts an outcome on runs it never saw. Runs go to FOLDS
23
+ folds by a hash of their id. On the other folds' runs, each candidate threshold (the
24
+ training values' quartiles) is scored on outcomes adjusted for the implementer: an
25
+ outcome minus its model's mean in that tier, shrunk toward the tier's mean by SHRINK
26
+ tasks, so a harder model mix is not read as harder tasks. The best threshold, and the
27
+ side it says scores higher, is then applied to the held-out runs, adjusted by the
28
+ training runs' model means. `lift` is the held-out difference between the side
29
+ predicted higher and the other, in the outcome's units; above 0 means the training
30
+ direction held. Its interval resamples held-out runs (BOOTSTRAP draws). A tier with
31
+ fewer than MIN_RUNS runs, or no threshold leaving MIN_SIDE tasks on each side, gets
32
+ none.
33
+
34
+ Repos are listed per tier too (first pass and the implementer-adjusted residual, with a run bootstrap),
35
+ but not held out: a repo's runs mostly sit in that repo, so a fold would just learn the repo.
36
+
37
+ Label noise: `--sample N --out DIR` writes N past task prompts (one task per run where it can, tiers
38
+ hidden) to DIR/prompts/<n>.md and DIR/sample.tsv; whoever rates them blind writes DIR/ratings.tsv as
39
+ `<n><TAB>low|medium|high`. `--blind DIR` then reports how often the blind rating matches the recorded
40
+ tier (Wilson 95%), Cohen's kappa and the confusion table. Rating costs model calls or a person's time,
41
+ so this report never starts one.
42
+
43
+ Advisory only: nothing that routes or plans reads it.
44
+ """
45
+ from __future__ import annotations
46
+
47
+ import hashlib
48
+ import json
49
+ import os
50
+ import random
51
+ import statistics
52
+ from collections import Counter, defaultdict
53
+ from pathlib import Path
54
+
55
+ from . import connect, dataset_dir
56
+ from .export import Runs, Store, _attempts
57
+ from .facts import _kappa
58
+ from .harvest import split_list
59
+ from .routing import tasks as routing_tasks, wilson
60
+
61
+ LEVELS = ('low', 'medium', 'high')
62
+ OUTCOMES = ('first_pass', 'attempts', 'unfinished')
63
+ PLAN_FACTS = ('files', 'deps', 'wave', 'prompt_kb')
64
+ AFTER_FACTS = ('diff_lines', 'changed_files')
65
+ FOLDS = 5
66
+ MIN_RUNS = 10
67
+ MIN_SIDE = 5
68
+ SHRINK = 5
69
+ BOOTSTRAP = 1000
70
+ MIN_REPO = 10
71
+
72
+
73
+ def _fold(run) -> int:
74
+ return int(hashlib.sha1(str(run).encode()).hexdigest(), 16) % FOLDS
75
+
76
+
77
+ def _held(runs: Runs) -> dict:
78
+ """(run, task) -> (plan revision, row): the latest revision that held the task, as routing reads it."""
79
+ held = {}
80
+ for run, revisions in runs.plans.items():
81
+ for plan in revisions:
82
+ for tid, row in (plan['d'].get('tasks') or {}).items():
83
+ held[(run, tid)] = (plan, row)
84
+ return held
85
+
86
+
87
+ def _diff(first) -> tuple:
88
+ for e in reversed(first['events']):
89
+ numstat = e['d'].get('numstat')
90
+ if isinstance(numstat, dict) and (numstat or e['d'].get('changed_files') is not None):
91
+ lines = sum(x for counts in numstat.values() if isinstance(counts, (list, tuple))
92
+ for x in counts if isinstance(x, int))
93
+ return lines, len(e['d'].get('changed_files') or numstat)
94
+ return None, None
95
+
96
+
97
+ def _repo_name(runs: Runs, repo, names) -> str | None:
98
+ if repo is None:
99
+ return None
100
+ if names and names.get(repo):
101
+ return names[repo]
102
+ path = runs.store.repo_paths.get(repo)
103
+ return os.path.basename(path.rstrip('/')) if path else repo
104
+
105
+
106
+ def records(runs: Runs, repo: str = None, names: dict = None) -> list:
107
+ held = _held(runs)
108
+ out = []
109
+ for r in routing_tasks(runs, repo=repo):
110
+ if r['first_pass'] is None or r['tier'] not in LEVELS or (r['run'], r['task']) not in held:
111
+ continue
112
+ plan, row = held[(r['run'], r['task'])]
113
+ attempts = _attempts(runs, r['run'], r['task'], runs.attempts.get((r['run'], r['task']), []))
114
+ lines, changed = _diff(attempts[0]) if attempts else (None, None)
115
+ prompt = runs.store.text(row.get('prompt')) or ''
116
+ wave = (plan['d'].get('waves') or {}).get(r['task'])
117
+ out.append(dict(
118
+ run=r['run'], task=r['task'], tier=r['tier'], model=r['model'] or r['ran'] or '?',
119
+ repo=_repo_name(runs, plan.get('repo'), names),
120
+ first_pass=int(bool(r['first_pass'])), attempts=r['attempts'], unfinished=int(not r['passed']),
121
+ facts=dict(files=len(split_list(row.get('files'))), deps=len(split_list(row.get('deps'))),
122
+ wave=wave if isinstance(wave, int) else None,
123
+ prompt_kb=round(len(prompt.encode()) / 1024, 1) if prompt.strip() else None,
124
+ diff_lines=lines, changed_files=changed)))
125
+ return out
126
+
127
+
128
+ def _summary(rows) -> dict:
129
+ n = len(rows)
130
+ k = sum(r['first_pass'] for r in rows)
131
+ low, high = wilson(k, n)
132
+ return dict(tasks=n, runs=len({r['run'] for r in rows}), first_pass=k / n if n else None,
133
+ ci=[low, high], attempts=statistics.mean(r['attempts'] for r in rows) if n else None,
134
+ unfinished=sum(r['unfinished'] for r in rows))
135
+
136
+
137
+ def _bins(rows, fact) -> list:
138
+ rows = sorted((r for r in rows if r['facts'][fact] is not None), key=lambda r: r['facts'][fact])
139
+ values = [r['facts'][fact] for r in rows]
140
+ if not values:
141
+ return []
142
+ cuts = sorted(set(statistics.quantiles(values, n=3, method='inclusive'))) if len(set(values)) > 1 else []
143
+ groups = defaultdict(list)
144
+ for r in rows:
145
+ groups[sum(r['facts'][fact] > c for c in cuts)].append(r)
146
+ out = []
147
+ for _, group in sorted(groups.items()):
148
+ lo, hi = group[0]['facts'][fact], group[-1]['facts'][fact]
149
+ out.append(dict(_summary(group), lo=lo, hi=hi))
150
+ return out
151
+
152
+
153
+ def _residuals(rows, outcome, train) -> list:
154
+ base = statistics.mean(r[outcome] for r in train)
155
+ by = defaultdict(list)
156
+ for r in train:
157
+ by[r['model']].append(r[outcome])
158
+ means = {m: (sum(v) + SHRINK * base) / (len(v) + SHRINK) for m, v in by.items()}
159
+ return [r[outcome] - means.get(r['model'], base) for r in rows]
160
+
161
+
162
+ def _candidates(values) -> list:
163
+ return sorted(set(statistics.quantiles(values, n=4, method='inclusive'))) if len(set(values)) > 1 else []
164
+
165
+
166
+ def _lift(per_run, chosen) -> float | None:
167
+ hi_n = hi_s = lo_n = lo_s = 0
168
+ for run in chosen:
169
+ a, b, c, d = per_run[run]
170
+ hi_n, hi_s, lo_n, lo_s = hi_n + a, hi_s + b, lo_n + c, lo_s + d
171
+ return hi_s / hi_n - lo_s / lo_n if hi_n and lo_n else None
172
+
173
+
174
+ def heldout(rows, fact, outcome, seed: int = 7) -> dict:
175
+ rows = [r for r in rows if r['facts'][fact] is not None]
176
+ runs = {r['run'] for r in rows}
177
+ if len(runs) < MIN_RUNS:
178
+ return dict(lift=None, reason='under %d runs' % MIN_RUNS, runs=len(runs))
179
+ per_run = defaultdict(lambda: [0, 0.0, 0, 0.0])
180
+ picks = Counter()
181
+ for k in range(FOLDS):
182
+ train = [r for r in rows if _fold(r['run']) != k]
183
+ test = [r for r in rows if _fold(r['run']) == k]
184
+ if not train or not test:
185
+ continue
186
+ res = _residuals(train, outcome, train)
187
+ best = None
188
+ for t in _candidates([r['facts'][fact] for r in train]):
189
+ above = [e for r, e in zip(train, res) if r['facts'][fact] > t]
190
+ below = [e for r, e in zip(train, res) if r['facts'][fact] <= t]
191
+ if len(above) < MIN_SIDE or len(below) < MIN_SIDE:
192
+ continue
193
+ d = statistics.mean(above) - statistics.mean(below)
194
+ if best is None or abs(d) > abs(best[1]):
195
+ best = (t, d)
196
+ if best is None:
197
+ continue
198
+ t, d = best
199
+ picks[(t, d > 0)] += 1
200
+ for r, e in zip(test, _residuals(test, outcome, train)):
201
+ cell = per_run[r['run']]
202
+ if (r['facts'][fact] > t) == (d > 0):
203
+ cell[0] += 1
204
+ cell[1] += e
205
+ else:
206
+ cell[2] += 1
207
+ cell[3] += e
208
+ scored = sorted(per_run)
209
+ lift = _lift(per_run, scored)
210
+ if lift is None:
211
+ return dict(lift=None, reason='no split leaves %d tasks a side' % MIN_SIDE, runs=len(runs))
212
+ rng = random.Random(seed)
213
+ draws = sorted(x for x in (_lift(per_run, [rng.choice(scored) for _ in scored]) for _ in range(BOOTSTRAP))
214
+ if x is not None)
215
+ (t, above_higher), folds = picks.most_common(1)[0]
216
+ return dict(lift=lift, ci=[draws[int(0.025 * len(draws))], draws[int(0.975 * len(draws)) - 1]] if draws else None,
217
+ tasks=sum(per_run[r][0] + per_run[r][2] for r in scored), runs=len(scored),
218
+ threshold=t, above_higher=above_higher, folds=folds, of=sum(picks.values()))
219
+
220
+
221
+ def _repos(rows, seed: int = 7) -> list:
222
+ res = dict(zip((id(r) for r in rows), _residuals(rows, 'first_pass', rows))) if rows else {}
223
+ counts = Counter(r['repo'] for r in rows)
224
+ groups = defaultdict(list)
225
+ for r in rows:
226
+ groups[r['repo'] if counts[r['repo']] >= MIN_REPO else None].append(r)
227
+ out = []
228
+ rng = random.Random(seed)
229
+ for name, group in sorted(groups.items(), key=lambda kv: (kv[0] is None, -len(kv[1]), str(kv[0]))):
230
+ by_run = defaultdict(list)
231
+ for r in group:
232
+ by_run[r['run']].append(res[id(r)])
233
+ keys = sorted(by_run)
234
+ draws = []
235
+ for _ in range(BOOTSTRAP):
236
+ pick = [x for _ in keys for x in by_run[rng.choice(keys)]]
237
+ draws.append(sum(pick) / len(pick))
238
+ draws.sort()
239
+ values = [res[id(r)] for r in group]
240
+ out.append(dict(_summary(group), repo=name, adjusted=sum(values) / len(values),
241
+ adjusted_ci=[draws[int(0.025 * BOOTSTRAP)], draws[int(0.975 * BOOTSTRAP) - 1]]))
242
+ return out
243
+
244
+
245
+ def tier_report(rows) -> dict:
246
+ facts = []
247
+ for phase, names in (('plan', PLAN_FACTS), ('after', AFTER_FACTS)):
248
+ for fact in names:
249
+ facts.append(dict(fact=fact, phase=phase, known=sum(r['facts'][fact] is not None for r in rows),
250
+ bins=_bins(rows, fact), heldout={o: heldout(rows, fact, o) for o in OUTCOMES}))
251
+ return dict(_summary(rows), facts=facts, repos=_repos(rows))
252
+
253
+
254
+ def _recorded(runs: Runs) -> dict:
255
+ return {key: row.get('declared_difficulty') or row.get('difficulty') for key, (_, row) in _held(runs).items()}
256
+
257
+
258
+ def sample(runs: Runs, n: int, out: Path, seed: int = 7) -> int:
259
+ """Write n past prompts for blind rating, spread one task per run before any run gives a second."""
260
+ out = Path(out)
261
+ if out.exists() and any(out.iterdir()):
262
+ raise SystemExit('forge dataset tiers: %s is not empty; pick a new directory' % out)
263
+ recorded = _recorded(runs)
264
+ held = _held(runs)
265
+ by_run = defaultdict(list)
266
+ for (run, task), tier in sorted(recorded.items()):
267
+ if tier in LEVELS and (runs.store.text(held[(run, task)][1].get('prompt')) or '').strip():
268
+ by_run[run].append(task)
269
+ rng = random.Random(seed)
270
+ queues = [[(run, task) for task in rng.sample(by_run[run], len(by_run[run]))]
271
+ for run in rng.sample(sorted(by_run), len(by_run))]
272
+ chosen = []
273
+ while len(chosen) < n and any(queues):
274
+ for queue in queues:
275
+ if queue and len(chosen) < n:
276
+ chosen.append(queue.pop(0))
277
+ (out / 'prompts').mkdir(parents=True, exist_ok=True)
278
+ lines = ['# n\trun\ttask (rate prompts/<n>.md blind; write ratings.tsv as <n><TAB>low|medium|high)']
279
+ for i, (run, task) in enumerate(chosen, 1):
280
+ (out / 'prompts' / ('%d.md' % i)).write_text(runs.store.text(held[(run, task)][1].get('prompt')))
281
+ lines.append('%d\t%s\t%s' % (i, run, task))
282
+ (out / 'sample.tsv').write_text('\n'.join(lines) + '\n')
283
+ return len(chosen)
284
+
285
+
286
+ def blind(runs: Runs, where: Path) -> dict:
287
+ where = Path(where)
288
+ numbered = {}
289
+ for line in (where / 'sample.tsv').read_text().splitlines():
290
+ cells = line.split('\t')
291
+ if len(cells) >= 3 and cells[0].isdigit():
292
+ numbered[cells[0]] = (cells[1], cells[2])
293
+ recorded = _recorded(runs)
294
+ pairs, unknown, invalid = [], 0, 0
295
+ for line in (where / 'ratings.tsv').read_text().splitlines():
296
+ cells = line.strip().split('\t')
297
+ if len(cells) < 2 or not cells[0].isdigit():
298
+ continue
299
+ rating = cells[1].strip().lower()
300
+ key = numbered.get(cells[0])
301
+ if rating not in LEVELS:
302
+ invalid += 1
303
+ elif key is None or recorded.get(key) not in LEVELS:
304
+ unknown += 1
305
+ else:
306
+ pairs.append((recorded[key], rating))
307
+ agree = sum(a == b for a, b in pairs)
308
+ low, high = wilson(agree, len(pairs))
309
+ kappa = _kappa(pairs)
310
+ confusion = {a: {b: sum(1 for x, y in pairs if (x, y) == (a, b)) for b in LEVELS} for a in LEVELS}
311
+ return dict(rated=len(pairs), agree=agree, rate=agree / len(pairs) if pairs else None, ci=[low, high],
312
+ kappa=None if kappa is None else round(kappa, 3), confusion=confusion, unknown=unknown, invalid=invalid)
313
+
314
+
315
+ def report(runs: Runs, repo: str = None, names: dict = None, tier: str = None) -> dict:
316
+ rows = records(runs, repo=repo, names=names)
317
+ tiers = {}
318
+ for level in LEVELS:
319
+ group = [r for r in rows if r['tier'] == level]
320
+ if group and (tier is None or tier == level):
321
+ tiers[level] = tier_report(group)
322
+ return dict(tasks=len(rows), runs=len({r['run'] for r in rows}), tiers=tiers,
323
+ settings=dict(folds=FOLDS, min_runs=MIN_RUNS, min_side=MIN_SIDE, shrink=SHRINK, bootstrap=BOOTSTRAP))
324
+
325
+
326
+ def _names(db) -> dict:
327
+ out = {}
328
+ for repo, origin, path in db.execute('SELECT repo, origin, path FROM repos'):
329
+ source = (origin or '').rstrip('/') or (path or '').rstrip('/')
330
+ name = source.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
331
+ out[repo] = name[:-4] if name.endswith('.git') else (name or None)
332
+ return out
333
+
334
+
335
+ def _runs():
336
+ if not (dataset_dir() / 'dataset.sqlite').exists():
337
+ return None, {}
338
+ db = connect()
339
+ try:
340
+ return Runs(Store(db)), _names(db)
341
+ finally:
342
+ db.close()
343
+
344
+
345
+ def _pct(x):
346
+ return '-' if x is None else '%.0f%%' % (100 * x)
347
+
348
+
349
+ def _signed(x, outcome):
350
+ return ('%+.0f pts' % (100 * x)) if outcome != 'attempts' else '%+.2f' % x
351
+
352
+
353
+ def _range(b):
354
+ return ('%g' % b['lo']) if b['lo'] == b['hi'] else '%g-%g' % (b['lo'], b['hi'])
355
+
356
+
357
+ def _line(s):
358
+ return '%4d tasks %3d runs first pass %4s (%s-%s) %.2f attempts %d unfinished' % (
359
+ s['tasks'], s['runs'], _pct(s['first_pass']), _pct(s['ci'][0]), _pct(s['ci'][1]), s['attempts'], s['unfinished'])
360
+
361
+
362
+ def _held_line(fact, outcome, h):
363
+ if h.get('lift') is None:
364
+ return '%s: none (%s)' % (outcome.replace('_', ' '), h['reason'])
365
+ side = ('> %g' if h['above_higher'] else '<= %g') % h['threshold']
366
+ ci = ' [%s, %s]' % (_signed(h['ci'][0], outcome), _signed(h['ci'][1], outcome)) if h.get('ci') else ''
367
+ return '%s %s%s, higher at %s %s (%d/%d folds), %d runs' % (
368
+ outcome.replace('_', ' '), _signed(h['lift'], outcome), ci, fact, side, h['folds'], h['of'], h['runs'])
369
+
370
+
371
+ def main(args) -> int:
372
+ runs, names = _runs()
373
+ if getattr(args, 'sample', None):
374
+ if not args.out:
375
+ raise SystemExit('forge dataset tiers: --sample needs --out DIR')
376
+ if runs is None:
377
+ raise SystemExit('forge dataset tiers: no dataset yet')
378
+ n = sample(runs, args.sample, Path(args.out))
379
+ print('wrote %d prompts to %s/prompts; rate them blind into %s/ratings.tsv, then: forge dataset tiers --blind %s'
380
+ % (n, args.out, args.out, args.out))
381
+ return 0
382
+ if getattr(args, 'blind', None):
383
+ if runs is None:
384
+ raise SystemExit('forge dataset tiers: no dataset yet')
385
+ rep = blind(runs, Path(args.blind))
386
+ if args.json:
387
+ print(json.dumps(rep, indent=2, sort_keys=True))
388
+ return 0
389
+ print('blind ratings: %d matched to a recorded tier%s' % (
390
+ rep['rated'], ''.join(', %d %s' % (rep[k], k) for k in ('unknown', 'invalid') if rep[k])))
391
+ if rep['rated']:
392
+ kappa = '' if rep['kappa'] is None else ', kappa %.2f' % rep['kappa']
393
+ print(' agree %d of %d: %s (%s-%s)%s' % (rep['agree'], rep['rated'], _pct(rep['rate']),
394
+ _pct(rep['ci'][0]), _pct(rep['ci'][1]), kappa))
395
+ print(' %-10s %s' % ('recorded', ' '.join('%7s' % b for b in LEVELS)))
396
+ for a in LEVELS:
397
+ print(' %-10s %s' % (a, ' '.join('%7d' % rep['confusion'][a][b] for b in LEVELS)))
398
+ return 0
399
+ rep = report(runs, repo=os.path.realpath(args.repo) if args.repo else None, names=names,
400
+ tier=getattr(args, 'tier', None)) if runs else report_empty()
401
+ if args.json:
402
+ print(json.dumps(rep, indent=2, sort_keys=True))
403
+ return 0
404
+ print('tiers: %d tasks whose first attempt says something, in %d runs; advisory only' % (rep['tasks'], rep['runs']))
405
+ if not rep['tasks']:
406
+ return 0
407
+ for level, t in rep['tiers'].items():
408
+ print()
409
+ print('%s: %s' % (level, _line(t).strip()))
410
+ for f in t['facts']:
411
+ print(' %s (%s, known for %d)' % (f['fact'], 'plan time' if f['phase'] == 'plan' else 'afterwards', f['known']))
412
+ for b in f['bins']:
413
+ print(' %-10s %s' % (_range(b), _line(b)))
414
+ for o in OUTCOMES:
415
+ print(' held out: %s' % _held_line(f['fact'], o, f['heldout'][o]))
416
+ print(' repos (first pass; adjusted = vs the same implementers elsewhere in the tier)')
417
+ for r in t['repos']:
418
+ print(' %-28s %s adjusted %s [%s, %s]' % (
419
+ (r['repo'] or 'other (under %d tasks each)' % MIN_REPO)[:28], _line(r),
420
+ _signed(r['adjusted'], 'first_pass'), _signed(r['adjusted_ci'][0], 'first_pass'),
421
+ _signed(r['adjusted_ci'][1], 'first_pass')))
422
+ return 0
423
+
424
+
425
+ def report_empty() -> dict:
426
+ return dict(tasks=0, runs=0, tiers={},
427
+ settings=dict(folds=FOLDS, min_runs=MIN_RUNS, min_side=MIN_SIDE, shrink=SHRINK, bootstrap=BOOTSTRAP))
@@ -0,0 +1,95 @@
1
+ """`forge dataset worktrees`: what the dataset knows about the worktrees forge created (#125).
2
+
3
+ forge-ui's Worktrees screen reads this through the CLI (forge_ui never opens the store itself) and adds
4
+ what git and the run dirs say now. Three kinds of record:
5
+
6
+ events every `worktree_created` and `worktree_removed` event: when forge added or removed a
7
+ worktree, with its repository, run, task, path, branch and kind
8
+ attempts each (repository, run id, task) a parallel attempt was recorded for: a task worktree
9
+ existed at the derived path, before the events were recorded (no dates)
10
+ integrated each (repository, run id) whose integrate moved the user's branch (`integrate_advanced`)
11
+
12
+ `since` is the time of the first worktree event: the list of removed worktrees is complete only from
13
+ then on. With the dataset off, or no store yet, everything is empty and `enabled` says which.
14
+ Read-only: it never creates a store.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import time
20
+
21
+ from . import connect, dataset_dir, enabled
22
+
23
+ _NAMES = ('worktree_created', 'worktree_removed')
24
+ _FIELDS = ('path', 'branch', 'kind', 'repo_path', 'by')
25
+
26
+
27
+ def _empty(on):
28
+ return dict(enabled=on, since=None, events=[], attempts=[], integrated=[], repos=[])
29
+
30
+
31
+ def load() -> dict:
32
+ if not enabled():
33
+ return _empty(False)
34
+ if not (dataset_dir() / 'dataset.sqlite').exists():
35
+ return _empty(True)
36
+ db = connect()
37
+ try:
38
+ paths = dict(db.execute('SELECT repo, path FROM repos'))
39
+ out = _empty(True)
40
+ out['repos'] = [dict(repo=key, path=path) for key, path in sorted(paths.items()) if path]
41
+ rows = db.execute("SELECT ts, repo, run, run_id, task, data FROM events WHERE kind = 'event' "
42
+ "AND (data LIKE '%\"name\": \"worktree_created\"%' OR data LIKE '%\"name\": \"worktree_removed\"%' "
43
+ "OR data LIKE '%\"name\": \"integrate_advanced\"%') ORDER BY ts")
44
+ integrated = set()
45
+ for ts, repo, run, run_id, task, data in rows:
46
+ try:
47
+ d = json.loads(data)
48
+ except ValueError:
49
+ continue
50
+ name = d.get('name')
51
+ if name == 'integrate_advanced':
52
+ if run_id and paths.get(repo):
53
+ integrated.add((paths[repo], run_id))
54
+ continue
55
+ if name not in _NAMES or not isinstance(d.get('path'), str):
56
+ continue
57
+ event = dict(name=name, ts=ts, run=run, run_id=run_id, task=task)
58
+ event.update({k: d.get(k) if isinstance(d.get(k), str) else None for k in _FIELDS})
59
+ if event['branch'] == '-':
60
+ event['branch'] = None
61
+ event['repo_path'] = event['repo_path'] or paths.get(repo)
62
+ out['events'].append(event)
63
+ out['since'] = out['events'][0]['ts'] if out['events'] else None
64
+ out['integrated'] = [dict(repo_path=p, run_id=r) for p, r in sorted(integrated)]
65
+ seen = set()
66
+ for repo, run_id, task in db.execute("SELECT DISTINCT repo, run_id, task FROM events WHERE kind = 'attempt' "
67
+ "AND mode = 'parallel' AND task IS NOT NULL AND run_id IS NOT NULL"):
68
+ if paths.get(repo) and (paths[repo], run_id, task) not in seen:
69
+ seen.add((paths[repo], run_id, task))
70
+ out['attempts'] = [dict(repo_path=p, run_id=r, task=t) for p, r, t in sorted(seen)]
71
+ return out
72
+ finally:
73
+ db.close()
74
+
75
+
76
+ def main(args) -> int:
77
+ rep = load()
78
+ if args.json:
79
+ print(json.dumps(rep, sort_keys=True))
80
+ return 0
81
+ if not rep['enabled']:
82
+ print('the dataset is off (FORGE_DATASET=off): no worktree history is recorded')
83
+ return 0
84
+ created = sum(1 for e in rep['events'] if e['name'] == 'worktree_created')
85
+ removed = sum(1 for e in rep['events'] if e['name'] == 'worktree_removed')
86
+ print('worktree events: %d created, %d removed%s' % (created, removed, '' if rep['since'] is None else
87
+ ' (recorded since %s)' % _when(rep['since'])))
88
+ print('tasks with an attempt (worktrees before the record): %d' % len(rep['attempts']))
89
+ print("forge-ui's Worktrees screen (#/worktrees) adds what git and the run dirs say now.")
90
+ return 0
91
+
92
+
93
+ def _when(ts):
94
+ return time.strftime('%Y-%m-%d %H:%M', time.localtime(ts))
95
+
@@ -11,7 +11,7 @@
11
11
  doctor [--live] [--json] [--repo DIR]
12
12
  migrate [--force] [--json]
13
13
  report [--runs N] [--run DIR]... [--site S] [--all] [--json]
14
- replay --site S --provider P --model M [--runs N] [--send] [--workers 3] [--seed 7]
14
+ replay --site S --provider P --model M [--runs N] [--send | --label V] [--workers 3] [--seed 7]
15
15
  [--margin 0.02] [--json]
16
16
 
17
17
  `report` sums each site's jev.jsonl calls, cache hits, skips, tokens and cost over the newest
@@ -24,6 +24,8 @@ provider, else the legacy typesafe/cloudflare transport) with model M (forge_dec
24
24
  Without --send it only prints the count, estimated input tokens and cost. With --send it asks
25
25
  the unanswered ones, outside any budget, then judges replay, baseline and live answers on the
26
26
  newer half of the runs and records the result in replays/<gate>.json, which `gate on` reads.
27
+ --label V judges the answers already stored on another label of the site instead (jev-drift:
28
+ first-attempt, the 2026-10-16 label); it sends nothing and records nothing.
27
29
  Its --json is the dry run's estimate, or the evaluation (also `sent`). An unknown provider is
28
30
  exit 2, a provider with no key that is not local exit 1.
29
31
 
@@ -798,6 +800,7 @@ def cmd_report(args) -> int:
798
800
 
799
801
 
800
802
  def cmd_replay(args) -> int:
803
+ from . import labels as labels_module
801
804
  from . import replay as replay_module
802
805
  from . import sites as sites_module
803
806
  record = sites_module.site(args.site)
@@ -820,7 +823,23 @@ def cmd_replay(args) -> int:
820
823
  if not spec['key'] and not spec['local']:
821
824
  raise Failed('provider %s has no key (forge decide provider add ... --key-stdin, or its key_env)'
822
825
  % args.provider)
823
- plan = replay_module.plan(args.site, spec['name'], spec['model'], spec, runs=args.runs)
826
+ if args.label is not None:
827
+ if args.label not in labels_module.VARIANTS.get(args.site, {}):
828
+ raise Usage('%s has no label variant %s (variants: %s)' % (
829
+ args.site, args.label, ', '.join(sorted(labels_module.VARIANTS.get(args.site, {}))) or 'none'))
830
+ if args.send:
831
+ raise Usage('a label variant judges the answers already stored and records nothing: drop --send')
832
+ plan = replay_module.plan(args.site, spec['name'], spec['model'], spec, runs=args.runs, variant=args.label)
833
+ if args.label is not None:
834
+ result = replay_module.evaluate(plan, seed=args.seed, margin=args.margin)
835
+ result.update(label=args.label, recorded=None)
836
+ if args.json:
837
+ print(json.dumps(result, indent=2))
838
+ else:
839
+ print(replay_module.render(result))
840
+ print('label %s: judged on the %d answered of %d requests; not recorded (promotion reads the '
841
+ "site's own label)" % (args.label, result['answered'], result['requests']))
842
+ return 0
824
843
  if not args.send:
825
844
  data = replay_module.estimate(plan)
826
845
  print(json.dumps(data, indent=2) if args.json else replay_module.render_estimate(data))
@@ -928,6 +947,8 @@ def parser() -> argparse.ArgumentParser:
928
947
  s.add_argument('--model', required=True, metavar='M')
929
948
  s.add_argument('--runs', type=int, metavar='N', help='only the newest N dataset runs')
930
949
  s.add_argument('--send', action='store_true', help='ask the provider (without it: a dry run)')
950
+ s.add_argument('--label', metavar='V', help='judge the stored answers on another label of the site '
951
+ '(jev-drift: first-attempt); sends and records nothing')
931
952
  s.add_argument('--workers', type=int, default=3)
932
953
  s.add_argument('--seed', type=int, default=7, help='bootstrap seed of the reported interval')
933
954
  s.add_argument('--margin', type=float, default=0.02)
@@ -161,13 +161,23 @@ def _drift_added(index: _Index, run, task) -> set:
161
161
  return out
162
162
 
163
163
 
164
- def _drift(index: _Index, record, event, body) -> dict:
164
+ def _first_attempt(rows):
165
+ """The last execution of the task's first real attempt, passed or not: what attempt 1 edited.
166
+ A refunded or infra-stopped execution spent no attempt (export._attempts)."""
167
+ real = [e for e in rows if e['d'].get('status') and not e['d'].get('refunded') and not e['d'].get('infra')]
168
+ if not real:
169
+ return None
170
+ first = min(e['attempt'] or 0 for e in real)
171
+ return [e for e in real if (e['attempt'] or 0) == first][-1]
172
+
173
+
174
+ def _drift(index: _Index, record, event, body, pick=export.final_pass) -> dict:
165
175
  state = _state(body)
166
176
  task = state.get('task') if isinstance(state.get('task'), dict) else {}
167
177
  task_id = task.get('id')
168
178
  if not task_id:
169
179
  return {}
170
- final = export.final_pass(index.attempts(event['run'], event['repo'], task_id, event['ts']))
180
+ final = pick(index.attempts(event['run'], event['repo'], task_id, event['ts']))
171
181
  if final is None:
172
182
  return {}
173
183
  changed = set(export.words(final['d'].get('changed_files')))
@@ -293,14 +303,28 @@ LABELLERS = {
293
303
  }
294
304
 
295
305
 
296
- def collect(site: str, *, store: export.Store | None = None, runs=None) -> list[dict]:
306
+ def _drift_first_attempt(index: _Index, record, event, body) -> dict:
307
+ return _drift(index, record, event, body, pick=_first_attempt)
308
+
309
+
310
+ # Other labels of a site, to check a past result against (`forge decide replay --label`). A
311
+ # variant's replay is never recorded, so promotion only ever reads the site's own label.
312
+ # drift first-attempt: the 2026-10-16 drift replay's label, "the file is in attempt 1's
313
+ # changed files", where the site's own is the final passing attempt's.
314
+ VARIANTS = {
315
+ 'jev-drift': {'first-attempt': _drift_first_attempt},
316
+ }
317
+
318
+
319
+ def collect(site: str, *, store: export.Store | None = None, runs=None, variant: str | None = None) -> list[dict]:
297
320
  """One row per stored live request of `site` with at least one labelled decision.
298
321
 
299
322
  `store` is an already-open forge_dataset.export.Store; without one the store is opened
300
- read-only. `runs`, when given, keeps only those dataset run uids. A site with no label
301
- (prompt, memory-curate, memory-stale) or an unknown one returns []."""
323
+ read-only. `runs`, when given, keeps only those dataset run uids. `variant` names one of the
324
+ site's VARIANTS instead of its own label. A site with no label (prompt, memory-curate,
325
+ memory-stale), an unknown one, or an unknown variant returns []."""
302
326
  record = sites.site(site)
303
- labeller = LABELLERS.get(site)
327
+ labeller = LABELLERS.get(site) if variant is None else VARIANTS.get(site, {}).get(variant)
304
328
  if record is None or record.label is None or labeller is None:
305
329
  return []
306
330
  if store is None: