@giamme/forge 0.14.1 → 0.16.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 (81) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -1
  5. package/docs/commands.md +302 -9
  6. package/docs/forge-ui.md +14 -0
  7. package/docs/memory.md +22 -0
  8. package/docs/models.md +53 -0
  9. package/docs/reviews.md +7 -0
  10. package/forge +11 -0
  11. package/package.json +1 -1
  12. package/references/dataset.md +16 -4
  13. package/references/decompose.md +154 -9
  14. package/references/harnesses.md +21 -1
  15. package/references/planning.md +59 -0
  16. package/references/solo.md +5 -1
  17. package/references/ui.md +48 -1
  18. package/scripts/forge-artifact.sh +53 -0
  19. package/scripts/forge-compare.py +6 -3
  20. package/scripts/forge-config.py +531 -4
  21. package/scripts/forge-contract.py +55 -8
  22. package/scripts/forge-control.py +0 -2
  23. package/scripts/forge-dispatch.sh +84 -14
  24. package/scripts/forge-fail-first.py +3 -1
  25. package/scripts/forge-guard.py +247 -8
  26. package/scripts/forge-issues.py +12 -0
  27. package/scripts/forge-lib-adopt.sh +260 -0
  28. package/scripts/forge-lib-attribute.sh +10 -2
  29. package/scripts/forge-lib-plans.sh +35 -6
  30. package/scripts/forge-lib-review.sh +13 -5
  31. package/scripts/forge-lib-task.sh +138 -5
  32. package/scripts/forge-memory.sh +41 -4
  33. package/scripts/forge-metrics.sh +7 -0
  34. package/scripts/forge-parallel-options.sh +12 -6
  35. package/scripts/forge-parallel.sh +659 -32
  36. package/scripts/forge-plan-check.py +591 -8
  37. package/scripts/forge-planner.py +480 -0
  38. package/scripts/forge-route.py +16 -2
  39. package/scripts/forge-runs-rm.py +23 -7
  40. package/scripts/forge-runtime.py +111 -2
  41. package/scripts/forge-schedule.py +5 -2
  42. package/scripts/forge-shadow.py +53 -7
  43. package/scripts/forge-solo.sh +87 -7
  44. package/scripts/forge_dataset/cli.py +26 -0
  45. package/scripts/forge_dataset/efforts.py +215 -0
  46. package/scripts/forge_dataset/export.py +1 -0
  47. package/scripts/forge_dataset/harvest.py +55 -0
  48. package/scripts/forge_dataset/history.py +126 -0
  49. package/scripts/forge_dataset/worktrees.py +95 -0
  50. package/scripts/forge_decide/__init__.py +19 -1
  51. package/scripts/forge_decide/builtin_profiles.json +25 -0
  52. package/scripts/forge_decide/cli.py +12 -0
  53. package/scripts/forge_decide/profiles.py +866 -0
  54. package/scripts/forge_decide/resolve.py +38 -6
  55. package/scripts/forge_memory_list.py +153 -0
  56. package/scripts/forge_worktrees.py +88 -0
  57. package/ui/README.md +31 -0
  58. package/ui/docs/api.md +168 -12
  59. package/ui/forge_ui/__init__.py +14 -1
  60. package/ui/forge_ui/__main__.py +1 -1
  61. package/ui/forge_ui/control.py +250 -12
  62. package/ui/forge_ui/executions.py +28 -8
  63. package/ui/forge_ui/findings.py +7 -0
  64. package/ui/forge_ui/models.py +60 -1
  65. package/ui/forge_ui/projects.py +571 -0
  66. package/ui/forge_ui/reader.py +48 -8
  67. package/ui/forge_ui/static/app.js +99 -21
  68. package/ui/forge_ui/static/cloudui.js +6 -2
  69. package/ui/forge_ui/static/convo.js +1 -1
  70. package/ui/forge_ui/static/diffview.js +2 -2
  71. package/ui/forge_ui/static/files.js +1 -1
  72. package/ui/forge_ui/static/index.html +5 -1
  73. package/ui/forge_ui/static/leaderboard.js +5 -1
  74. package/ui/forge_ui/static/modelstats.js +25 -1
  75. package/ui/forge_ui/static/panel.js +47 -4
  76. package/ui/forge_ui/static/projectsview.js +372 -0
  77. package/ui/forge_ui/static/settings.js +924 -29
  78. package/ui/forge_ui/static/style.css +116 -3
  79. package/ui/forge_ui/static/uikit.js +94 -1
  80. package/ui/forge_ui/static/worktreesview.js +250 -0
  81. package/ui/forge_ui/worktrees.py +570 -0
@@ -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())
@@ -635,6 +635,7 @@ def _qa_rows(runs: Runs):
635
635
  # Receipts from before findings_parse existed: an empty list then cannot
636
636
  # tell a clean review from a parser failure, which was rare; read it as clean.
637
637
  completeness=d.get('findings_parse') or review_completeness(d['verdict'], found),
638
+ tests=d.get('tests'),
638
639
  worst=_worst(found),
639
640
  # The dispatch this row was built from. A shadow pair names that event,
640
641
  # so an earlier execution of the same attempt cannot claim it.
@@ -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()
@@ -162,6 +170,14 @@ def findings(message: str | None) -> list:
162
170
  return parse_review(message)[0]
163
171
 
164
172
 
173
+ def review_tests(message: str | None) -> dict | None:
174
+ """What a QA reply says about its tests; None when it does not, or the contract cannot load."""
175
+ try:
176
+ return contract().tests_report(message) if message else None
177
+ except Exception:
178
+ return None
179
+
180
+
165
181
  def parse_review(message: str | None) -> tuple[list, bool]:
166
182
  """(findings, parsed): parsed is False when the contract's parser raised."""
167
183
  if not message:
@@ -297,6 +313,8 @@ def locate(root: str | Path, role: str | None = None) -> dict:
297
313
  plan, ctx['scope'] = p.parent.parent, 'final_review'
298
314
  elif p.name.startswith('integrate-') and (p.parent / 'tasks.tsv').exists():
299
315
  plan, ctx['scope'] = p.parent, 'integrate'
316
+ elif p.name.startswith('adopt-') and (p.parent / 'tasks.tsv').exists():
317
+ plan, ctx['scope'] = p.parent, 'adopt'
300
318
  elif (p / 'tasks.tsv').exists() or (p / 'run_id').exists():
301
319
  plan, ctx['scope'] = p, 'plan'
302
320
  if plan is not None:
@@ -414,6 +432,10 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
414
432
  # gets its own role: nothing that reads qa dispatches mistakes it for the one that decided.
415
433
  role='qa_shadow' if shadow and role == 'qa' else role, alias=resolved.get('alias'), harness=harness, model=resolved.get('model'),
416
434
  effort=None if not effort or effort.startswith('<') else effort,
435
+ # metrics.json is the record finish() wrote. A run from before that record falls
436
+ # back to the resolved line, which exists only when a tier was asked.
437
+ service_tier=as_text(metrics.get('service_tier')) or as_text(resolved.get('service_tier')),
438
+ speed=as_text(metrics.get('speed')), speed_reason=as_text(metrics.get('speed_reason')),
417
439
  yolo=resolved.get('yolo') == 'ON', passthrough=resolved.get('passthrough') == 'yes',
418
440
  clamped=resolved.get('clamped'), timeout=as_int(resolved.get('timeout')),
419
441
  timeout_source=resolved.get('timeout_source'), delivery=delivery,
@@ -426,6 +448,7 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
426
448
  prompt_bytes=metrics.get('prompt_bytes'), final_source=final_source,
427
449
  verdict=verdict, findings=found, learnings=learnings(message),
428
450
  findings_parse=review_completeness(verdict, found, parsed) if role == 'qa' else None,
451
+ tests=review_tests(message) if role == 'qa' else None,
429
452
  session_id=session_id, session_continue=session_continue,
430
453
  root=str(root), scope=prov.get('scope'), trigger=prov.get('trigger'),
431
454
  **({'shadow': shadow} if shadow else {}),
@@ -710,6 +733,18 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
710
733
  plan_gates = read_json(plan / 'plan-gates.json')
711
734
  if plan_gates is not None:
712
735
  later['plan_gates'] = plan_gates
736
+ # Same rule as plan_gates: hashed only when the file is there, so a plan from before
737
+ # these records keeps its id. plan-gate.json is the planner's one-task-or-plan record
738
+ # (plan-gates.json, plural, is the decision-model gates).
739
+ plan_shape = read_json(plan / 'plan-shape.json')
740
+ collapsed_record = read_json(plan / 'collapsed.json')
741
+ plan_gate = read_json(plan / 'plan-gate.json')
742
+ if plan_shape is not None:
743
+ later['plan_shape'] = plan_shape
744
+ if collapsed_record is not None:
745
+ later['collapsed'] = collapsed_record
746
+ if plan_gate is not None:
747
+ later['plan_gate'] = plan_gate
713
748
  inputs = json.dumps([text(plan / 'goal.txt'), text(plan / 'tasks.tsv'), text(declared_path),
714
749
  {t: [r['prompt'], r['approach']] for t, r in per_task.items()}] + ([later] if later else []),
715
750
  sort_keys=True, default=str)
@@ -739,6 +774,26 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
739
774
  )
740
775
  if plan_gates is not None:
741
776
  data['plan_gates'] = plan_gates
777
+ if plan_shape is not None:
778
+ # shape, widest and the count of waves come from plan-shape.json. The count is
779
+ # `wave_count`: `waves` stays the task→wave map on every plan, one type across the store.
780
+ if 'shape' in plan_shape:
781
+ data['shape'] = plan_shape['shape']
782
+ if 'widest' in plan_shape:
783
+ data['widest'] = plan_shape['widest']
784
+ if 'waves' in plan_shape:
785
+ data['wave_count'] = plan_shape['waves']
786
+ if collapsed_record is not None:
787
+ data['collapsed'] = True
788
+ origin = collapsed_record.get('from')
789
+ if isinstance(origin, list):
790
+ data['collapsed_from'] = origin
791
+ if plan_gate is not None:
792
+ data['plan_gate'] = plan_gate
793
+ # Who started the plan: `auto` for forge-parallel.sh auto. Absent for a plan built by hand.
794
+ orchestrator = first_line(plan / 'orchestrator')
795
+ if orchestrator:
796
+ data['orchestrator'] = orchestrator
742
797
  return dict(rid='plan:%s:%s' % (prov.get('run'), sha256(inputs.encode())[:16]), kind='plan',
743
798
  ts=time.time(), src=src, run=prov.get('run'), run_id=prov.get('run_id'), mode='parallel',
744
799
  inv=prov.get('inv'), data=data)
@@ -0,0 +1,126 @@
1
+ """`forge dataset history`: the reviews' findings and the learnings the dataset keeps, for runs whose dir is gone (#126).
2
+
3
+ forge-ui's Projects screen reads run dirs first; this is what it adds for the runs and checkouts that no longer
4
+ exist. Each run is one record with its repository and base commit, so the screen can tell which project it
5
+ belongs to (the same base-commit rule forge-ui's repos.py uses for a run whose checkout is gone):
6
+
7
+ runs {run (dataset uid), run_id, mode, repo_path, base, first, last}
8
+ findings one per review dispatch (qa, qa_shadow) that listed findings: {run, run_id, task, attempt, role,
9
+ scope, reviewer, verdict, ts, findings: [{head, severity (0-3 or null), status, line}]}, as the
10
+ capture parsed them with forge-contract.py (no second parser)
11
+ learnings one per FORGE_LEARNING line a dispatch emitted: {run, run_id, task, role, model, ts, category, text}
12
+ ledger the ledger rows `forge dataset import --ledger` stored: {repo_path, ts, run_id, task, role, model,
13
+ category, key, text, injectable}
14
+
15
+ Read-only: it never creates a store. With the dataset off everything is empty and `enabled` is false.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+
21
+ from . import connect, dataset_dir, enabled
22
+
23
+ _HEAD_MAX = 400
24
+ _TEXT_MAX = 2000
25
+
26
+
27
+ def _empty(on):
28
+ return dict(enabled=on, runs=[], findings=[], learnings=[], ledger=[])
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
+ runs = {}
41
+
42
+ def note(run, run_id, mode, repo, ts):
43
+ if not run:
44
+ return None
45
+ r = runs.setdefault(run, dict(run=run, run_id=run_id, mode=mode, repo_path=paths.get(repo), base=None,
46
+ first=ts, last=ts))
47
+ r['first'], r['last'] = min(r['first'], ts), max(r['last'], ts)
48
+ r['run_id'] = r['run_id'] or run_id
49
+ r['repo_path'] = r['repo_path'] or paths.get(repo)
50
+ return r
51
+
52
+ attempt_task = {}
53
+ for rid, run, run_id, mode, repo, task, attempt, ts, data in db.execute(
54
+ "SELECT rid, run, run_id, mode, repo, task, attempt, ts, data FROM events WHERE kind = 'attempt' ORDER BY ts"):
55
+ r = note(run, run_id, mode, repo, ts)
56
+ attempt_task[rid] = (task, attempt)
57
+ if r is not None and r['base'] is None:
58
+ try:
59
+ base = json.loads(data).get('base_ref')
60
+ except ValueError:
61
+ base = None
62
+ if isinstance(base, str) and len(base) in (40, 64):
63
+ r['base'] = base.lower()
64
+ for run, run_id, mode, repo, task, attempt, parent, ts, data in db.execute(
65
+ "SELECT run, run_id, mode, repo, task, attempt, parent, ts, data FROM events WHERE kind = 'dispatch' ORDER BY ts"):
66
+ try:
67
+ d = json.loads(data)
68
+ except ValueError:
69
+ continue
70
+ note(run, run_id, mode, repo, ts)
71
+ if task is None and parent in attempt_task:
72
+ task, attempt = task or attempt_task[parent][0], attempt or attempt_task[parent][1]
73
+ role = d.get('role')
74
+ spec = d.get('alias') or d.get('model')
75
+ if d.get('effort') and spec and ':' not in str(spec):
76
+ spec = '%s:%s' % (spec, d['effort'])
77
+ found = d.get('findings')
78
+ if role in ('qa', 'qa_shadow') and isinstance(found, list) and found:
79
+ items = []
80
+ for f in found:
81
+ if not isinstance(f, dict) or not isinstance(f.get('head'), str):
82
+ continue
83
+ sev = f.get('severity')
84
+ items.append(dict(head=f['head'][:_HEAD_MAX], severity=sev if type(sev) is int and 0 <= sev <= 3 else None,
85
+ status=f.get('status') if f.get('status') in ('CONFIRMED', 'PLAUSIBLE', 'UNSTATED') else None,
86
+ line=f.get('line') if type(f.get('line')) is int else None))
87
+ if items:
88
+ out['findings'].append(dict(run=run, run_id=run_id, task=task, attempt=attempt, role=role,
89
+ scope=d.get('scope'), reviewer=spec, verdict=d.get('verdict'), ts=ts,
90
+ findings=items))
91
+ for line in d.get('learnings') or []:
92
+ if not isinstance(line, str):
93
+ continue
94
+ category, sep, text = line.partition('|')
95
+ if not sep:
96
+ continue
97
+ out['learnings'].append(dict(run=run, run_id=run_id, task=task, role=role, model=spec, ts=ts,
98
+ category=category.strip().lower(), text=text.strip()[:_TEXT_MAX]))
99
+ for repo, data in db.execute("SELECT repo, data FROM events WHERE kind = 'ledger' ORDER BY ts"):
100
+ try:
101
+ d = json.loads(data)
102
+ except ValueError:
103
+ continue
104
+ if not isinstance(d.get('text'), str) or d.get('category') in (None, '-'):
105
+ continue
106
+ out['ledger'].append(dict(repo_path=paths.get(repo), ts=d.get('ts'), run_id=d.get('run_id'), task=d.get('task'),
107
+ role=d.get('role'), model=d.get('model'), category=d.get('category'),
108
+ key=d.get('key'), text=d['text'][:_TEXT_MAX], injectable=d.get('injectable') != '0'))
109
+ out['runs'] = sorted(runs.values(), key=lambda r: r['first'])
110
+ return out
111
+ finally:
112
+ db.close()
113
+
114
+
115
+ def main(args) -> int:
116
+ rep = load()
117
+ if args.json:
118
+ print(json.dumps(rep, sort_keys=True))
119
+ return 0
120
+ if not rep['enabled']:
121
+ print('the dataset is off (FORGE_DATASET=off)')
122
+ return 0
123
+ print('runs: %d, reviews with findings: %d, learnings: %d, ledger rows: %d' % (
124
+ len(rep['runs']), len(rep['findings']), len(rep['learnings']), len(rep['ledger'])))
125
+ print("forge-ui's Projects screen (#/projects) shows them by repository.")
126
+ return 0
@@ -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
+
@@ -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.