@giamme/forge 0.16.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 (38) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/VERSION +1 -1
  3. package/docs/dataset.md +8 -0
  4. package/docs/reviews.md +15 -1
  5. package/package.json +1 -1
  6. package/references/dataset.md +124 -5
  7. package/references/decision-models.md +15 -2
  8. package/references/decompose.md +46 -10
  9. package/references/planning.md +3 -2
  10. package/scripts/forge-contract.py +52 -1
  11. package/scripts/forge-issues.py +4 -3
  12. package/scripts/forge-ledger.py +3 -1
  13. package/scripts/forge-lib-adopt.sh +7 -1
  14. package/scripts/forge-metrics.sh +22 -0
  15. package/scripts/forge-parallel.sh +3 -1
  16. package/scripts/forge-plan-check.py +25 -2
  17. package/scripts/forge-planner.py +20 -6
  18. package/scripts/forge-shadow.py +28 -9
  19. package/scripts/forge-sweep.py +25 -10
  20. package/scripts/forge_dataset/cli.py +83 -0
  21. package/scripts/forge_dataset/facts.py +278 -0
  22. package/scripts/forge_dataset/harvest.py +16 -3
  23. package/scripts/forge_dataset/outcomes.py +206 -58
  24. package/scripts/forge_dataset/pairs.py +174 -0
  25. package/scripts/forge_dataset/risk.py +108 -0
  26. package/scripts/forge_dataset/tiers.py +427 -0
  27. package/scripts/forge_decide/cli.py +23 -2
  28. package/scripts/forge_decide/labels.py +30 -6
  29. package/scripts/forge_decide/replay.py +10 -4
  30. package/ui/docs/api.md +12 -3
  31. package/ui/forge_ui/export.py +9 -2
  32. package/ui/forge_ui/findings.py +4 -2
  33. package/ui/forge_ui/reader.py +71 -4
  34. package/ui/forge_ui/server.py +8 -0
  35. package/ui/forge_ui/static/app.js +6 -1
  36. package/ui/forge_ui/static/diffview.js +7 -3
  37. package/ui/forge_ui/static/panel.js +43 -2
  38. package/ui/forge_ui/static/style.css +1 -0
@@ -0,0 +1,278 @@
1
+ """`forge dataset facts`: the reach, origin and evidence reviewers give each finding (#119), measured in shadow.
2
+
3
+ A reviewer ends a finding's first line with `{reach=main|realistic|unusual origin=new|existing
4
+ evidence=ran|traced|suspected}`. Nothing in forge decides on these facts yet. This report says whether
5
+ a gate that did would be better than the severity line alone:
6
+
7
+ coverage how many findings carry the facts, and how reach splits by severity
8
+ agreement pairs of reviews of one attempt (`--shadow-qa`): of the findings both reviewers name (same
9
+ file, lines at most LINE_WINDOW apart), how often they agree on the severity and on each
10
+ fact, raw and chance-corrected (Cohen's kappa, since severity has four values and reach three)
11
+ rules each candidate rule replayed on the review every task attempt ended on, against the same
12
+ replay without it: the reviews that would have passed, the attempts after them that would
13
+ not have run, and the findings that would have stopped blocking, to check by hand whether
14
+ they were bugs that mattered
15
+
16
+ The rules only relax: a finding they release is CONFIRMED with a severity at the threshold or worse.
17
+ `unusual` releases reach=unusual unless it is P0 (P0 is data loss, a security hole or a crash: the
18
+ "unless security or data loss" exception), `existing` releases origin=existing (it would go to the
19
+ backlog), `both` does both. An unlabelled finding is never released, as it blocks at every threshold.
20
+
21
+ Advisory only: nothing that builds a prompt, gates or routes reads this report.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ import sys
29
+ from collections import Counter, defaultdict
30
+
31
+ from . import connect, dataset_dir
32
+ from .export import Runs, Store, _ending_qa, _gate_decision, shadow_pairs
33
+
34
+ FACTS = {'reach': ('main', 'realistic', 'unusual'), 'origin': ('new', 'existing'),
35
+ 'evidence': ('ran', 'traced', 'suspected')}
36
+ LINE_WINDOW = 10
37
+ EXAMPLES = 50
38
+ RULES = {
39
+ 'unusual': 'unusual reach does not block unless P0',
40
+ 'existing': 'existing findings do not block',
41
+ 'both': 'both of the above',
42
+ }
43
+ _WHERE = re.compile(r'([\w./\\-]+\.\w+|[\w./\\-]+/[\w.-]+):(\d+)')
44
+
45
+
46
+ def _facts(f) -> dict:
47
+ found = f.get('facts')
48
+ return found if isinstance(found, dict) else {}
49
+
50
+
51
+ def _released(rule):
52
+ def release(f):
53
+ sev, facts = f.get('severity'), _facts(f)
54
+ if f.get('status') not in ('CONFIRMED', 'UNSTATED') or sev is None:
55
+ return False
56
+ unusual = facts.get('reach') == 'unusual' and sev > 0
57
+ existing = facts.get('origin') == 'existing'
58
+ return {'unusual': unusual, 'existing': existing, 'both': unusual or existing}[rule]
59
+ return release
60
+
61
+
62
+ def decide(verdict, found, rank, release=lambda f: False) -> str:
63
+ """pass or fail: forge-contract's gate on recorded findings, with `release`d findings tolerated.
64
+
65
+ Without a release it is the gate itself: a PASS fails on a blocking finding (CONFIRMED or UNSTATED,
66
+ at the threshold or worse, or unlabelled); a FAIL passes when it has CONFIRMED findings, none
67
+ UNSTATED, and every CONFIRMED one is labelled below the threshold. A released finding counts as
68
+ tolerated, so a FAIL whose blocking findings are all released passes."""
69
+ def tolerated(f):
70
+ return release(f) or (f.get('severity') is not None and f['severity'] > rank)
71
+ if verdict == 'PASS':
72
+ return 'fail' if any(f.get('status') in ('CONFIRMED', 'UNSTATED') and not tolerated(f) for f in found) else 'pass'
73
+ confirmed = [f for f in found if f.get('status') == 'CONFIRMED']
74
+ if not confirmed or any(f.get('status') == 'UNSTATED' and not release(f) for f in found):
75
+ return 'fail'
76
+ return 'pass' if all(tolerated(f) for f in confirmed) else 'fail'
77
+
78
+
79
+ def _rank(value) -> int:
80
+ value = (value or '').strip().upper()
81
+ if value == 'NONE':
82
+ return 3
83
+ return int(value[1]) if value in ('P0', 'P1', 'P2', 'P3') else 2
84
+
85
+
86
+ def _threshold(runs, run, task, attempt):
87
+ """The threshold the attempt's gate ran with (its qa.gate line), else the plan's, else P2."""
88
+ for e in runs.attempts.get((run, task), []):
89
+ if e['attempt'] == attempt:
90
+ cells = (e['d'].get('gate') or '').split('\t')
91
+ if cells[0].strip():
92
+ return _rank(cells[0])
93
+ plans = runs.plans.get(run) or []
94
+ return _rank(((plans[-1]['d'].get('options') or {}).get('qa_threshold')) if plans else None)
95
+
96
+
97
+ def _kappa(pairs) -> float | None:
98
+ if not pairs:
99
+ return None
100
+ n = len(pairs)
101
+ seen = sum(a == b for a, b in pairs) / n
102
+ left, right = Counter(a for a, _ in pairs), Counter(b for _, b in pairs)
103
+ chance = sum(left[c] * right[c] for c in left) / (n * n)
104
+ return None if chance >= 1 else (seen - chance) / (1 - chance)
105
+
106
+
107
+ def _where(f):
108
+ match = _WHERE.search(f.get('head') or '')
109
+ return (match.group(1), int(match.group(2))) if match else None
110
+
111
+
112
+ def _matched(a_found, b_found) -> list:
113
+ """(a, b) findings two reviewers both named: same file, the nearest line at most LINE_WINDOW apart."""
114
+ out, used = [], set()
115
+ for a in a_found:
116
+ at = _where(a)
117
+ if at is None:
118
+ continue
119
+ best = None
120
+ for i, b in enumerate(b_found):
121
+ bt = _where(b)
122
+ if i in used or bt is None or bt[0] != at[0] or abs(bt[1] - at[1]) > LINE_WINDOW:
123
+ continue
124
+ if best is None or abs(bt[1] - at[1]) < best[0]:
125
+ best = (abs(bt[1] - at[1]), i)
126
+ if best is not None:
127
+ used.add(best[1])
128
+ out.append((a, b_found[best[1]]))
129
+ return out
130
+
131
+
132
+ def _measure(pairs) -> dict:
133
+ return dict(compared=len(pairs), agree=sum(a == b for a, b in pairs),
134
+ kappa=None if _kappa(pairs) is None else round(_kappa(pairs), 3))
135
+
136
+
137
+ def _empty():
138
+ return dict(coverage=dict(reviews=0, reviews_with_facts=0, findings=0, findings_with_facts=0,
139
+ values={k: {} for k in FACTS}, reach_by_severity={}),
140
+ agreement=dict(pairs=0, matched=0, severity=_measure([]), **{k: _measure([]) for k in FACTS}),
141
+ rules=dict(reviews=0, reviews_with_facts=0,
142
+ **{name: dict(label=label, would_pass=0, attempts_saved=0, released=[])
143
+ for name, label in RULES.items()}),
144
+ line_window=LINE_WINDOW)
145
+
146
+
147
+ def report(runs: Runs, repo: str = None) -> dict:
148
+ out = _empty()
149
+ paths = runs.store.repo_paths
150
+
151
+ def mine(e):
152
+ return not repo or paths.get(e['repo']) == repo
153
+
154
+ cov = out['coverage']
155
+ values = {k: Counter() for k in FACTS}
156
+ by_sev = defaultdict(Counter)
157
+ for e in runs.store.of('dispatch'):
158
+ d = e['d']
159
+ if d.get('role') not in ('qa', 'qa_shadow') or not mine(e) or not isinstance(d.get('findings'), list):
160
+ continue
161
+ found = [f for f in d['findings'] if isinstance(f, dict)]
162
+ cov['reviews'] += 1
163
+ cov['reviews_with_facts'] += any(_facts(f) for f in found)
164
+ for f in found:
165
+ cov['findings'] += 1
166
+ facts = _facts(f)
167
+ if not facts:
168
+ continue
169
+ cov['findings_with_facts'] += 1
170
+ for key in FACTS:
171
+ values[key][facts.get(key) or 'unreadable'] += 1
172
+ sev = f.get('severity')
173
+ by_sev['P%d' % sev if isinstance(sev, int) else 'unlabelled'][facts.get('reach') or 'unreadable'] += 1
174
+ cov['values'] = {k: dict(sorted(c.items())) for k, c in values.items()}
175
+ cov['reach_by_severity'] = {s: dict(sorted(c.items())) for s, c in sorted(by_sev.items())}
176
+
177
+ agree = out['agreement']
178
+ severity, per_fact = [], {k: [] for k in FACTS}
179
+ for primary, shadow in shadow_pairs(runs).values():
180
+ if not mine(primary):
181
+ continue
182
+ agree['pairs'] += 1
183
+ for a, b in _matched(primary['d'].get('findings') or [], shadow['d'].get('findings') or []):
184
+ agree['matched'] += 1
185
+ if a.get('severity') is not None and b.get('severity') is not None:
186
+ severity.append((a['severity'], b['severity']))
187
+ for key in FACTS:
188
+ x, y = _facts(a).get(key), _facts(b).get(key)
189
+ if x and y:
190
+ per_fact[key].append((x, y))
191
+ agree['severity'] = _measure(severity)
192
+ for key in FACTS:
193
+ agree[key] = _measure(per_fact[key])
194
+
195
+ rules = out['rules']
196
+ for (run, task, role), rows in runs.dispatches.items():
197
+ if role != 'qa' or not rows or not mine(rows[0]):
198
+ continue
199
+ ended = sorted(_ending_qa(rows).items(), key=lambda item: item[0] or 0)
200
+ attempts = [n for n, _ in ended]
201
+ for name in RULES:
202
+ release = _released(name)
203
+ for n, index in ended:
204
+ d = rows[index]['d']
205
+ found = [f for f in d.get('findings') or [] if isinstance(f, dict)]
206
+ rank = _threshold(runs, run, task, n)
207
+ if decide(d['verdict'], found, rank) == 'fail' and decide(d['verdict'], found, rank, release) == 'pass':
208
+ item = rules[name]
209
+ item['would_pass'] += 1
210
+ # The first review this rule would have passed ends the task: the attempts after it did not need to run.
211
+ item['attempts_saved'] += sum(1 for m in attempts if (m or 0) > (n or 0))
212
+ for f in found:
213
+ if release(f) and not (f['severity'] > rank) and len(item['released']) < EXAMPLES:
214
+ item['released'].append(dict(run=run, task=task, attempt=n, severity='P%d' % f['severity'],
215
+ facts=_facts(f), head=f.get('head')))
216
+ break
217
+ for n, index in ended:
218
+ found = rows[index]['d'].get('findings') or []
219
+ rules['reviews'] += 1
220
+ rules['reviews_with_facts'] += any(_facts(f) for f in found if isinstance(f, dict))
221
+ return out
222
+
223
+
224
+ def load(repo: str = None) -> dict:
225
+ # Reading must not create a store: a fresh machine gets an empty report.
226
+ if not (dataset_dir() / 'dataset.sqlite').exists():
227
+ return _empty()
228
+ db = connect()
229
+ try:
230
+ runs = Runs(Store(db))
231
+ finally:
232
+ db.close()
233
+ return report(runs, repo=repo)
234
+
235
+
236
+ def _pct(n, d):
237
+ return '%d%%' % round(100 * n / d) if d else '-'
238
+
239
+
240
+ def _line(name, m):
241
+ if not m['compared']:
242
+ return ' %-9s not compared yet' % name
243
+ kappa = '' if m['kappa'] is None else ', kappa %.2f' % m['kappa']
244
+ return ' %-9s %d of %d agree (%s%s)' % (name, m['agree'], m['compared'], _pct(m['agree'], m['compared']), kappa)
245
+
246
+
247
+ def main(args) -> int:
248
+ rep = load(os.path.realpath(args.repo) if args.repo else None)
249
+ if args.json:
250
+ print(json.dumps(rep, indent=2, sort_keys=True))
251
+ return 0
252
+ cov, agree, rules = rep['coverage'], rep['agreement'], rep['rules']
253
+ print('facts: %d of %d findings carry reach, origin and evidence (%s), in %d of %d reviews'
254
+ % (cov['findings_with_facts'], cov['findings'], _pct(cov['findings_with_facts'], cov['findings']),
255
+ cov['reviews_with_facts'], cov['reviews']))
256
+ print(' (recorded in shadow: nothing in forge decides on them; advisory only)')
257
+ for key in FACTS:
258
+ if cov['values'][key]:
259
+ print(' %-9s %s' % (key, ' '.join('%s %d' % kv for kv in cov['values'][key].items())))
260
+ for sev, counts in cov['reach_by_severity'].items():
261
+ print(' %-9s reach %s' % (sev, ' '.join('%s %d' % kv for kv in counts.items())))
262
+ print('agreement: %d shadow pairs, %d findings both reviewers named (same file, lines within %d)'
263
+ % (agree['pairs'], agree['matched'], rep['line_window']))
264
+ for key in ('severity',) + tuple(FACTS):
265
+ print(_line(key, agree[key]))
266
+ print('rules: replayed on the review each of %d task attempts ended on (%d with facts)'
267
+ % (rules['reviews'], rules['reviews_with_facts']))
268
+ for name, label in RULES.items():
269
+ item = rules[name]
270
+ print(' %-9s %s: %d reviews would have passed, %d later attempts not run'
271
+ % (name, label, item['would_pass'], item['attempts_saved']))
272
+ shown = rules['both']['released']
273
+ if shown:
274
+ print('findings that would have stopped blocking (were they real bugs that mattered?):')
275
+ for f in shown:
276
+ facts = '/'.join(f['facts'].get(k) or '?' for k in FACTS)
277
+ print(' %s %s#%s %s %s %s' % (f['run'], f['task'], f['attempt'], f['severity'], facts, f['head']))
278
+ return 0
@@ -183,11 +183,21 @@ def parse_review(message: str | None) -> tuple[list, bool]:
183
183
  if not message:
184
184
  return [], True
185
185
  try:
186
- parsed = contract().parse_findings(message)
186
+ module = contract()
187
+ parsed = module.parse_findings(message)
187
188
  except Exception:
188
189
  return [], False
189
- return [dict(status=f.status, severity=f.severity, located=f.located, line=f.line,
190
- head=f.text.splitlines()[0][:300] if f.text else '') for f in parsed], True
190
+ out = []
191
+ for f in parsed:
192
+ head = f.text.splitlines()[0] if f.text else ''
193
+ item = dict(status=f.status, severity=f.severity, located=f.located, line=f.line,
194
+ head=module.split_facts(head)[0][:300])
195
+ # #119: the facts suffix is kept apart, so a head reads as it did before it existed.
196
+ found = module.facts(f.text)
197
+ if found is not None:
198
+ item['facts'] = found
199
+ out.append(item)
200
+ return out, True
191
201
 
192
202
 
193
203
  def review_completeness(verdict: str | None, found: list, parsed: bool = True) -> str | None:
@@ -711,7 +721,10 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
711
721
  source = 'planner'
712
722
  else:
713
723
  source = 'orchestrator'
724
+ risk = (text(tdir / 'risk') or '').split()
714
725
  per_task[tid] = dict(row, declared_difficulty=declared_tier, difficulty_source=source,
726
+ # #122: the task's risk, recorded in shadow beside its difficulty (None: not rated)
727
+ risk=risk[0] if risk and risk[0] in ('low', 'medium', 'high') else None,
715
728
  routing=routing, prompt=put_file(tdir / 'prompt.md', 'prompt'),
716
729
  approach=put_file(tdir / 'approach.md', 'prompt'))
717
730
  decisions = jsonl(tdir / 'route.jsonl')