@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
@@ -27,11 +27,14 @@ Guarantees, because the task waits for this process before it writes any status:
27
27
  timeout, error, invalid (the reviewer changed its snapshot), overtime, stopped, orphaned.
28
28
  Only a `done` review counts as a second opinion.
29
29
  Forge never picks a model: the reviewer is one the user listed, preferring a different
30
- model family from the primary reviewer's, so two reviewers do not share one blind spot.
30
+ model family from the primary reviewer's, so two reviewers do not share one blind spot. A listed
31
+ spec that resolves to the primary's own harness, model and effort is picked last, as a `control`:
32
+ it measures a reviewer's noise, not what another effort or model buys (#121).
31
33
  """
32
34
  from __future__ import annotations
33
35
 
34
36
  import argparse
37
+ import functools
35
38
  import hashlib
36
39
  import json
37
40
  import os
@@ -115,8 +118,9 @@ def family(model: str) -> str:
115
118
  return m
116
119
 
117
120
 
118
- def resolved_model(spec: str) -> str | None:
119
- """The model a qa dispatch of `spec` would use, by dispatch's own dry run."""
121
+ @functools.lru_cache(maxsize=None)
122
+ def resolution(spec: str) -> tuple | None:
123
+ """(harness, model, effort) a qa dispatch of `spec` would use, by dispatch's own dry run; None when it fails."""
120
124
  with tempfile.TemporaryDirectory(prefix='forge-shadow-resolve-') as tmp:
121
125
  prompt = Path(tmp) / 'input'
122
126
  prompt.write_text('Offline resolution')
@@ -127,7 +131,9 @@ def resolved_model(spec: str) -> str | None:
127
131
  except (OSError, subprocess.SubprocessError):
128
132
  return None
129
133
  fields = dict(line.split('=', 1) for line in out.stdout.splitlines() if '=' in line)
130
- return fields.get('model') or None
134
+ if not fields.get('model'):
135
+ return None
136
+ return fields.get('harness') or None, fields['model'], fields.get('effort') or None
131
137
 
132
138
 
133
139
  def candidates(plan: Path) -> list:
@@ -140,14 +146,27 @@ def candidates(plan: Path) -> list:
140
146
 
141
147
 
142
148
  def pick(listed: list, primary: str) -> tuple[str | None, str | None]:
143
- """(spec, why): the first listed spec of another family than the primary's, else the first."""
149
+ """(spec, why): the first listed spec of another family than the primary's (`other_family`); else the
150
+ first one of its family that does not resolve to the primary's own harness, model and effort
151
+ (`same_model` when only the effort or harness differs, `same_family` for another model); else the
152
+ first listed, labelled `control` (#121). A control reviews the diff with the primary's own settings,
153
+ so it measures noise and never counts as an effort comparison. A spec that does not resolve is
154
+ compared by its text."""
144
155
  if not listed:
145
156
  return None, None
146
- mine = family(resolved_model(primary) or primary)
147
- for spec in listed:
148
- if family(resolved_model(spec) or spec) != mine:
157
+ me = resolution(primary)
158
+ mine = family(me[1] if me else primary)
159
+ resolved = [(spec, resolution(spec)) for spec in listed]
160
+ for spec, found in resolved:
161
+ if family(found[1] if found else spec) != mine:
149
162
  return spec, 'other_family'
150
- return listed[0], 'same_family'
163
+ for spec, found in resolved:
164
+ if me and found:
165
+ if found != me:
166
+ return spec, 'same_model' if found[1] == me[1] else 'same_family'
167
+ elif spec.strip().lower() != primary.strip().lower():
168
+ return spec, 'same_family'
169
+ return listed[0], 'control'
151
170
 
152
171
 
153
172
  def fresh_dir(base: Path, attempt: str) -> Path:
@@ -229,6 +248,8 @@ def run(args) -> int:
229
248
  if bash('forge_review_snapshot', args.worktree, args.base, args.reviewed, str(review)).returncode:
230
249
  status = 'error'
231
250
  return 0
251
+ # The prompt is the primary's, so this checkout has to hold what it says.
252
+ bash('forge_review_deps', args.worktree, str(review), os.devnull)
232
253
  before = bash('forge_fingerprint', str(review), '--tracked').stdout.strip()
233
254
  shutil.copyfile(Path(args.tdir) / 'qa.input', out / 'qa.input')
234
255
  env = dict(os.environ, FORGE_SHADOW='1', FORGE_SHADOW_ATTEMPT=args.attempt,
@@ -362,6 +362,7 @@ fi
362
362
 
363
363
  REVIEW="$RUN/review-$(date +%s)-$$"
364
364
  forge_review_snapshot "$REPO" "$START" "$END" "$REVIEW" || die "cannot create review snapshot" 3
365
+ forge_review_deps "$REPO" "$REVIEW" "$RUN/review.deps"
365
366
  SOURCE_FP="$(forge_fingerprint "$REPO")" || exit 3
366
367
  [ "$(forge_tree "$REPO")" = "$END" ] || { echo INVALIDATED > "$RUN/verdict"; die "source changed while preparing QA" 5; }
367
368
  # The review snapshot is a commit; the reviewer's untracked leftovers there do not count (#95).
@@ -387,6 +388,9 @@ fi
387
388
  python3 "$SKILL_DIR/scripts/forge-prompt.py" --requirements "$RUN/prompt.md" --approach "$APPROACH" --goal "$RUN/goal.txt" --memory "$RUN/dwarf.memory" --memory "$RUN/qa.memory"
388
389
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind solo
389
390
  echo
391
+ cat "$RUN/review.deps"
392
+ [ -s "$RUN/failfirst.txt" ] || echo "Forge ran no tests of its own on this attempt, so nothing here stands in for yours."
393
+ echo
390
394
  if [ -s "$RUN/failfirst.txt" ]; then cat "$RUN/failfirst.txt"; echo; fi
391
395
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo --threshold "$THR"
392
396
  echo
@@ -422,6 +426,8 @@ dur_qa="$(sed -n 's/^duration_s=//p' "$RUN/qa.resolved" 2>/dev/null | tail -1)"
422
426
  # Otherwise forge enforces the severity rule itself, as a decomposed task's gate does; a gate
423
427
  # that cannot run (no output) keeps the reviewer's verdict.
424
428
  gate_note=""
429
+ tests_note="$(forge_tests_note "$RUN/qa.last")"
430
+ [ -z "$tests_note" ] || note "the reviewer's tests could not run: $tests_note"
425
431
  if [ -z "$NATIVE" ]; then
426
432
  gate_line="$(python3 "$SKILL_DIR/scripts/forge-contract.py" gate --verdict "${verdict:-UNKNOWN}" \
427
433
  --qa-last "$RUN/qa.last" --threshold "$THR" --known-issues "$RUN/known_issues.md" 2>/dev/null)" || gate_line=""
@@ -25,8 +25,12 @@ least as severe as --severity, from a task that is not itself a sweep task (one
25
25
  review finds goes to `forge issues`), not dismissed (`forge issues --dismiss`), located in a file the
26
26
  integration branch still has, and still there: when a later merge changed the file and the line the
27
27
  reviewer saw is gone from it, the finding is left for `forge issues` rather than "fixed" twice. A
28
- person's acceptance of a reviewer's FAIL (`accept`) is theirs to triage, so accepted findings are never
29
- swept. Every finding left out is listed in the plan with its reason.
28
+ person's acceptance of a reviewer's FAIL (`accept`, or `adopt --approved`) is theirs to triage, so accepted
29
+ findings are never swept. Every finding left out is listed in the plan with its reason.
30
+
31
+ A range `adopt` brought in has no task row, and what its review tolerated is swept like a task's (#131):
32
+ its fix task's reviewer is the adoption's reviewer, and its implementer the plan's low tier, else the
33
+ implementer of the run's first task.
30
34
 
31
35
  Each fix task gets at most GROUP_CAP findings; --max (default DEFAULT_MAX) caps the tasks, worst
32
36
  severity first. Its implementer is the plan's low tier (the first spec of --dwarf-low, else of
@@ -67,6 +71,7 @@ REASONS = {
67
71
  'group-cap': 'over the %d findings one fix task takes' % GROUP_CAP,
68
72
  'over-max': 'over --sweep-max fix tasks',
69
73
  'no-model': 'no implementer or reviewer to give its fix task',
74
+ 'accepted': 'a person kept it over the review (accept, or adopt --approved): theirs to triage',
70
75
  }
71
76
 
72
77
  _ISSUES = None
@@ -218,13 +223,19 @@ def triage(ctx: Context, found: list, severity: str, plausible: bool) -> tuple:
218
223
  kept, dropped, seen = [], [], {}
219
224
  tip_text = {}
220
225
  for f in sorted(found, key=lambda f: SEVERITIES.index(f['severity'])):
221
- if f['origin'] not in origins or not f.get('task') or is_sweep_task(ctx.plan, f['task']):
226
+ if not f.get('task') or is_sweep_task(ctx.plan, f['task']):
227
+ continue
228
+ if f['origin'] not in origins and f['origin'] != 'accepted':
222
229
  continue
223
230
  f = dict(f, key=mod.finding_key(f))
224
231
 
225
232
  def drop(reason, **detail):
226
233
  dropped.append(dict(f, reason=reason, detail=detail))
227
234
 
235
+ if f['origin'] == 'accepted':
236
+ drop('accepted')
237
+ continue
238
+
228
239
  if SEVERITIES.index(f['severity']) > cut:
229
240
  drop('below-severity')
230
241
  continue
@@ -279,18 +290,22 @@ def pools(plan: Path) -> dict:
279
290
  return data if isinstance(data, dict) else {}
280
291
 
281
292
 
282
- def models(plan: Path, source: 'list | None') -> tuple:
283
- """(dwarf, qa) for a fix task whose worst finding came from the task with row `source` (None when
284
- that task is not in tasks.tsv); an empty string where there is no spec to use."""
293
+ def models(plan: Path, source: 'list | None', finding: 'dict | None' = None, table: list = ()) -> tuple:
294
+ """(dwarf, qa) for a fix task whose worst finding came from the task with row `source`; an empty string
295
+ where there is no spec to use. Without a row (an adopted range, #131) the reviewer is the finding's own
296
+ (the adoption's spec) and the implementer, below the low tier, the run's first task's."""
285
297
  def usable(spec):
286
298
  return spec if isinstance(spec, str) and spec not in ('', '-', 'UNASSIGNED') else ''
287
- qa = usable(source[5]) if source else ''
299
+ qa = usable(source[5]) if source else usable((finding or {}).get('reviewer'))
288
300
  routing = pools(plan)
289
301
  for tier in ('low', 'any'):
290
302
  specs = routing.get(tier)
291
303
  if isinstance(specs, list) and specs and usable(specs[0]):
292
304
  return specs[0], qa
293
- return (usable(source[4]) if source else ''), qa
305
+ if source:
306
+ return usable(source[4]), qa
307
+ first = next((row for row in table if len(row) > 4 and not is_sweep_task(plan, row[0])), None)
308
+ return (usable(first[4]) if first else ''), qa
294
309
 
295
310
 
296
311
  def free_ids(taken: set, count: int) -> list:
@@ -368,7 +383,7 @@ def cmd_plan(args) -> int:
368
383
  run_id = read(plan / 'run_id') or plan.name
369
384
  tasks, new_rows = [], []
370
385
  for path, items in list(chosen):
371
- if not all(models(plan, by_id.get(items[0]['task']))):
386
+ if not all(models(plan, by_id.get(items[0]['task']), items[0], table)):
372
387
  chosen.remove((path, items))
373
388
  dropped += [dict(f, reason='no-model', detail={}) for f in items]
374
389
  for ident, (path, items) in zip(ids, chosen):
@@ -376,7 +391,7 @@ def cmd_plan(args) -> int:
376
391
  origin=f['origin'], task=f['task'], file=f['file'], line=f.get('line'), path=path,
377
392
  location=location(f, path), text=f['text'], raw=f['raw'])
378
393
  for n, f in enumerate(items, 1)]
379
- dwarf, qa = models(plan, by_id.get(items[0]['task']))
394
+ dwarf, qa = models(plan, by_id.get(items[0]['task']), items[0], table)
380
395
  title = 'Fix %d review finding%s in %s' % (len(entries), '' if len(entries) == 1 else 's', path)
381
396
  root = plan / 'tasks' / ident
382
397
  root.mkdir(parents=True, exist_ok=True)
@@ -6,6 +6,8 @@ silent): event, invocation, plan.
6
6
  from __future__ import annotations
7
7
 
8
8
  import argparse
9
+ import os
10
+ from collections import Counter
9
11
  import json
10
12
  import sys
11
13
  import time
@@ -49,6 +51,35 @@ def _continued_sessions(db) -> dict:
49
51
  return counts
50
52
 
51
53
 
54
+ def _outcomes(db) -> dict:
55
+ """Recorded survival outcomes by status, and what the last harvest that wrote did (#120)."""
56
+ from . import outcomes
57
+ recorded = Counter()
58
+ for (raw,) in db.execute("SELECT data FROM events WHERE kind = 'outcome'"):
59
+ data = json.loads(raw)
60
+ if data.get('name') == 'survival':
61
+ recorded[data.get('status') or 'unknown'] += 1
62
+ return dict(recorded=dict(recorded), last=outcomes.last_harvest())
63
+
64
+
65
+ def _outcomes_line(found) -> str | None:
66
+ recorded, last = found.get('recorded') or {}, found.get('last')
67
+ total = sum(recorded.values())
68
+ line = 'outcomes: %d recorded' % total
69
+ if total:
70
+ line += ' (%s)' % ', '.join('%d %s' % (recorded[k], k.replace('_', ' ')) for k in sorted(recorded))
71
+ if last and isinstance(last.get('at'), (int, float)):
72
+ counts = last.get('counts') or {}
73
+ where = os.path.basename(last['repo']) if last.get('repo') else 'every repo'
74
+ extra = ', '.join('%d %s' % (counts[k], k.replace('_', ' ')) for k in ('not_landed', 'pending', 'deferred', 'git_error')
75
+ if counts.get(k))
76
+ line += '; last harvested %s for %s: %d recorded%s' % (time.strftime('%Y-%m-%d %H:%M', time.localtime(last['at'])),
77
+ where, last.get('recorded') or 0, ', ' + extra if extra else '')
78
+ else:
79
+ line += '; never harvested (`forge dataset outcomes`, or the end of a run)'
80
+ return line
81
+
82
+
52
83
  def status(args) -> int:
53
84
  from . import checks
54
85
  directory = dataset_dir()
@@ -65,6 +96,7 @@ def status(args) -> int:
65
96
  summary['last_event'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last)) if last else None
66
97
  summary['checks'] = checks.run(db, verbose=args.verbose)
67
98
  summary.update(_continued_sessions(db))
99
+ summary['outcomes'] = _outcomes(db)
68
100
  if summary['events'].get('dispatch'):
69
101
  from . import export
70
102
  if db.execute("SELECT 1 FROM events WHERE kind = 'dispatch' AND data LIKE '%qa_shadow%' LIMIT 1").fetchone():
@@ -99,6 +131,10 @@ def status(args) -> int:
99
131
  % (shadow['shadow_reviews'], shadow['pairs'], shadow['agree'], rate))
100
132
  for pair, n in shadow['by_pair'].items():
101
133
  print(' %s: %d of %d agree' % (pair, n['agree'], n['pairs']))
134
+ print(' by effort, model and family: forge dataset pairs')
135
+ line = _outcomes_line(summary.get('outcomes') or {})
136
+ if line:
137
+ print(' ' + line)
102
138
  if summary.get('continued_reviews') or summary.get('failed_continues'):
103
139
  print(' continued reviews: %d' % summary['continued_reviews'])
104
140
  print(' failed continues: %d' % summary['failed_continues'])
@@ -196,6 +232,36 @@ def run_reviewers(args) -> int:
196
232
  return reviewers.main(args)
197
233
 
198
234
 
235
+ def run_facts(args) -> int:
236
+ from . import facts
237
+ return facts.main(args)
238
+
239
+
240
+ def run_pairs(args) -> int:
241
+ from . import pairs
242
+ return pairs.main(args)
243
+
244
+
245
+ def run_risk(args) -> int:
246
+ from . import risk
247
+ return risk.main(args)
248
+
249
+
250
+ def run_tiers(args) -> int:
251
+ from . import tiers
252
+ return tiers.main(args)
253
+
254
+
255
+ def run_history(args) -> int:
256
+ from . import history
257
+ return history.main(args)
258
+
259
+
260
+ def run_worktrees(args) -> int:
261
+ from . import worktrees
262
+ return worktrees.main(args)
263
+
264
+
199
265
  def run_forecast(args) -> int:
200
266
  from . import forecast
201
267
  return forecast.main(args)
@@ -243,6 +309,9 @@ def parser() -> argparse.ArgumentParser:
243
309
  p.add_argument('--repo', help='only this repo')
244
310
  p.add_argument('--include-temp', action='store_true', help='also repos under temp dirs (test runs)')
245
311
  p.add_argument('--dry-run', action='store_true', help='report what would be recorded, write nothing')
312
+ p.add_argument('--deadline', type=float, metavar='SECONDS',
313
+ help='start no new integration after this long; the rest waits for the next harvest')
314
+ p.add_argument('--quiet', action='store_true', help='print nothing (the automatic harvest at the end of a run)')
246
315
  p.set_defaults(func=run_outcomes)
247
316
  p = sub.add_parser('routing', help='pass rate and runtime per tier and model, and what the --explore draws say')
248
317
  p.add_argument('--repo', help='only this repo')
@@ -254,6 +323,36 @@ def parser() -> argparse.ArgumentParser:
254
323
  p.add_argument('--repo', help='only this repo')
255
324
  p.add_argument('--json', action='store_true')
256
325
  p.set_defaults(func=run_reviewers)
326
+ p = sub.add_parser('facts', help="the reach, origin and evidence reviewers give findings: agreement, and what "
327
+ "a gate on them would have changed (advisory)")
328
+ p.add_argument('--repo', help='only this repo')
329
+ p.add_argument('--json', action='store_true')
330
+ p.set_defaults(func=run_facts)
331
+ p = sub.add_parser('pairs', help='two reviewers of one attempt, per pair of settings: effort within one model apart '
332
+ 'from model and family comparisons and controls (advisory)')
333
+ p.add_argument('--repo', help='only this repo')
334
+ p.add_argument('--json', action='store_true')
335
+ p.set_defaults(func=run_pairs)
336
+ p = sub.add_parser('risk', help="tasks by difficulty and risk together: how often they differ, and how each "
337
+ "pair fared (advisory)")
338
+ p.add_argument('--repo', help='only this repo')
339
+ p.add_argument('--json', action='store_true')
340
+ p.set_defaults(func=run_risk)
341
+ p = sub.add_parser('tiers', help="what explains results inside each difficulty tier: plan-time facts held out by "
342
+ "run and adjusted for the implementer, and blind-rating agreement (advisory)")
343
+ p.add_argument('--repo', help='only this repo')
344
+ p.add_argument('--tier', choices=('low', 'medium', 'high'), help='only this tier')
345
+ p.add_argument('--sample', type=int, metavar='N', help='write N past prompts for blind rating into --out')
346
+ p.add_argument('--out', help='an empty directory for --sample')
347
+ p.add_argument('--blind', metavar='DIR', help='agreement of DIR/ratings.tsv with the recorded tiers')
348
+ p.add_argument('--json', action='store_true')
349
+ p.set_defaults(func=run_tiers)
350
+ p = sub.add_parser('history', help="every review's findings and every learning, for forge-ui's Projects screen")
351
+ p.add_argument('--json', action='store_true')
352
+ p.set_defaults(func=run_history)
353
+ p = sub.add_parser('worktrees', help="the worktrees forge created and removed, for forge-ui's Worktrees screen")
354
+ p.add_argument('--json', action='store_true')
355
+ p.set_defaults(func=run_worktrees)
257
356
  p = sub.add_parser('forecast', help="a plan's likely tokens, time and first-try pass rate, from past tasks (advisory)")
258
357
  p.add_argument('plan', help='the plan dir')
259
358
  p.add_argument('--repo', help='only history from this repo')
@@ -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.
@@ -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