@giamme/forge 0.18.0 → 0.20.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 (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -184,13 +184,14 @@ def plan_notes(plan) -> list:
184
184
  """`note:` lines for the distinct slow specs in a plan's dwarf and qa columns.
185
185
 
186
186
  After routing, tasks.tsv holds concrete specs. The same spec twice is one line. A
187
- missing table prints nothing.
187
+ missing table prints nothing. A dwarf cell of `script` is a task kind, not a model spec.
188
188
  """
189
189
  from .harvest import tasks_rows
190
190
  seen, out = set(), []
191
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()
192
+ dwarf = (row.get('dwarf') or '').strip()
193
+ qa = (row.get('qa') or '').strip()
194
+ for spec in (('' if dwarf == 'script' else dwarf), qa):
194
195
  if not spec or spec == '-' or spec in seen:
195
196
  continue
196
197
  seen.add(spec)
@@ -239,7 +239,9 @@ class Runs:
239
239
  rows.sort(key=lambda e: (e['attempt'] or 0, e['d'].get('wall_started') or e['ts']))
240
240
  self.dispatches = defaultdict(list)
241
241
  for e in store.of('dispatch'):
242
- if e['task']:
242
+ # A group review names no task. scope group stays out of per-task indexes even
243
+ # if a task was recorded, the way a side dispatch stays out of attempt statistics.
244
+ if e['task'] and e['d'].get('scope') != 'group':
243
245
  self.dispatches[(e['run'], e['task'], e['d'].get('role'))].append(e)
244
246
  # Store order is import order. A reader that takes [-1] means the dispatch
245
247
  # the attempt ended on, so each list is chronological; a tie keeps store order.
@@ -328,15 +330,18 @@ def _siblings(plan, task_id) -> list:
328
330
  def _attempts(runs: Runs, run, task, rows) -> list:
329
331
  """One entry per real attempt number, oldest first: {n, events, outcome, reason}.
330
332
 
331
- Refunded and infra-stopped executions spent no attempt. A QA-only rerun keeps its
332
- attempt's number, so the number's last execution holds its final status. outcome is
333
- True or False, or None when the attempt says nothing about the implementer (reason
334
- names why): a later success must never be labeled as the first attempt's.
333
+ Refunded and infra-stopped executions spent no attempt. So did one whose prompt or
334
+ approach changed while it ran (`prompt_changed`): the plan moved, not the implementer.
335
+ A row stored before that field exists has no key and is counted, the same as an
336
+ explicit false. A QA-only rerun keeps its attempt's number, so the number's last
337
+ execution holds its final status. outcome is True or False, or None when the attempt
338
+ says nothing about the implementer (reason names why): a later success must never be
339
+ labeled as the first attempt's.
335
340
  """
336
341
  by_n = {}
337
342
  for e in rows:
338
343
  d = e['d']
339
- if d.get('refunded') or d.get('infra') or not d.get('status'):
344
+ if d.get('refunded') or d.get('infra') or d.get('prompt_changed') or not d.get('status'):
340
345
  continue
341
346
  by_n.setdefault(e['attempt'] or 0, []).append(e)
342
347
  out = []
@@ -586,15 +591,19 @@ def _ending_qa(rows) -> dict:
586
591
  return ending
587
592
 
588
593
 
589
- def not_an_attempt(role) -> bool:
590
- """A shadow review or a side dispatch: in the run's tokens, not in its attempt statistics.
594
+ def not_an_attempt(role, data=None) -> bool:
595
+ """A shadow review, a side dispatch, or a group review: tokens stay, attempt statistics do not.
591
596
 
592
597
  `qa_shadow` is the second reviewer. A harvested side call is `side_<kind>`
593
598
  (`is_side_role`); the dir on disk, and a side dispatch harvested outside
594
- `side/<kind>/`, keeps the role `side`. None of these is the review of record.
595
- Shadow agreement still reads `qa_shadow`. This does not drop a side dispatch's tokens.
599
+ `side/<kind>/`, keeps the role `side`. A group review is one QA dispatch for
600
+ several tasks (`scope` `group`); it is not any one task's review. `data` is the
601
+ dispatch's data, when the caller has it. None of these is the review of record.
602
+ Shadow agreement still reads `qa_shadow`. This does not drop the dispatch's tokens.
596
603
  """
597
- return role == 'qa_shadow' or role == 'side' or is_side_role(role)
604
+ if role == 'qa_shadow' or role == 'side' or is_side_role(role):
605
+ return True
606
+ return isinstance(data, dict) and data.get('scope') == 'group'
598
607
 
599
608
 
600
609
  def _qa_rows(runs: Runs):
@@ -621,7 +630,8 @@ def _qa_rows(runs: Runs):
621
630
  word, _, conf = text.strip().partition('\t')
622
631
  effort[(run, task, e['attempt'])] = (word, _float(conf))
623
632
  for (run, task, role), rows in runs.dispatches.items():
624
- # The review of record only. A shadow pair is selected below; a side dispatch is not a row.
633
+ # The review of record only. A shadow pair is selected below; a side dispatch, and a
634
+ # group review of several tasks, is not a row.
625
635
  if not_an_attempt(role) or role != 'qa':
626
636
  continue
627
637
  ending = _ending_qa(rows)
@@ -629,6 +639,8 @@ def _qa_rows(runs: Runs):
629
639
  if session_continued(e):
630
640
  continue
631
641
  d = e['d']
642
+ if not_an_attempt(role, d):
643
+ continue
632
644
  if d.get('verdict') not in ('PASS', 'FAIL'):
633
645
  continue
634
646
  prompt = store.text((d.get('blobs') or {}).get('prompt'))
@@ -157,8 +157,10 @@ def report(runs: Runs, repo: str = None) -> dict:
157
157
  for e in runs.store.of('dispatch'):
158
158
  d = e['d']
159
159
  role = d.get('role')
160
- # qa and qa_shadow are reviews. A side dispatch is neither, even when it carries a findings list.
161
- if role not in ('qa', 'qa_shadow') or is_side_role(role) or not mine(e) or not isinstance(d.get('findings'), list):
160
+ # qa and qa_shadow are reviews. A side dispatch is neither, even when it carries a
161
+ # findings list. A group review is one dispatch for several tasks, not one review.
162
+ if (role not in ('qa', 'qa_shadow') or is_side_role(role) or d.get('scope') == 'group'
163
+ or not mine(e) or not isinstance(d.get('findings'), list)):
162
164
  continue
163
165
  found = [f for f in d['findings'] if isinstance(f, dict)]
164
166
  cov['reviews'] += 1
@@ -196,7 +198,7 @@ def report(runs: Runs, repo: str = None) -> dict:
196
198
 
197
199
  rules = out['rules']
198
200
  for (run, task, role), rows in runs.dispatches.items():
199
- if not_an_attempt(role) or role != 'qa' or not rows or not mine(rows[0]):
201
+ if not rows or not_an_attempt(role, rows[0].get('d')) or role != 'qa' or not mine(rows[0]):
200
202
  continue
201
203
  ended = sorted(_ending_qa(rows).items(), key=lambda item: item[0] or 0)
202
204
  attempts = [n for n, _ in ended]
@@ -33,6 +33,7 @@ from pathlib import Path
33
33
 
34
34
  from . import SKILL, connect, dataset_dir, record
35
35
  from .export import Runs, Store
36
+ from .names import registry_models # noqa: F401 (forge-route, forge-compare and efforts import it from here)
36
37
  from .routing import tasks as routing_tasks, wilson
37
38
 
38
39
  MIN_HISTORY = 5
@@ -43,23 +44,6 @@ OFF = {'0', 'off', 'false', 'no'}
43
44
 
44
45
  # --- the registry, as forge-route.py reads it (that module's name is not importable) ---
45
46
 
46
- def registry_models() -> dict:
47
- """{alias: {harness: model id}}; the first row of an alias is its default."""
48
- out = {}
49
- path = Path(os.environ.get('FORGE_REGISTRY') or str(SKILL / 'registry.tsv'))
50
- try:
51
- lines = path.read_text().splitlines()
52
- except OSError:
53
- return out
54
- for line in lines:
55
- if not line.strip() or line.startswith('#'):
56
- continue
57
- cells = line.split('\t')
58
- if len(cells) >= 3:
59
- out.setdefault(cells[0], {}).setdefault(cells[1], cells[2])
60
- return out
61
-
62
-
63
47
  def resolve(spec, registry: dict) -> tuple:
64
48
  """(model id, effort or None) a dwarf spec such as `sol`, `sol:high` or `sol:high:codex` runs."""
65
49
  parts = str(spec or '').split(':')
@@ -86,13 +70,19 @@ def _tsv(path: Path) -> list:
86
70
 
87
71
 
88
72
  def plan_tasks(plan: Path) -> tuple:
89
- """([task dicts to forecast], [ids already merged]) from tasks.tsv (declared tier when kept)."""
73
+ """([task dicts to forecast], [ids already merged]) from tasks.tsv (declared tier when kept).
74
+
75
+ A dwarf cell of `script` is a task that runs `tasks/<id>/run`, not a model to price. Those
76
+ rows are left out of both lists: not forecast, and not reported as already merged.
77
+ """
90
78
  declared = {r['id']: r for r in _tsv(plan / 'tasks.declared.tsv')}
91
79
  out, merged = [], []
92
80
  for row in _tsv(plan / 'tasks.tsv'):
93
81
  tid = row.get('id')
94
82
  if not tid:
95
83
  continue
84
+ if (row.get('dwarf') or '').strip() == 'script':
85
+ continue
96
86
  if (plan / 'tasks' / tid / 'merged').exists():
97
87
  merged.append(tid)
98
88
  continue
@@ -28,13 +28,15 @@ from . import SCRIPTS, put_blob, put_file, sha256
28
28
  DISPATCH_ROLES = ('dwarf', 'qa', 'planner', 'side')
29
29
  # The file role stays `side`. Harvest records side_<kind> (see dispatch_event);
30
30
  # attempt statistics tell those apart with forge_dataset.is_side_role.
31
- PIPELINE_ROLES = ('task', 'solo', 'verification', 'parallel')
31
+ # `script` is tasks/<id>/run, not a model dispatch. Import and live capture treat
32
+ # attempts/script-* as a pipeline execution, so events_for records no dispatch for it.
33
+ PIPELINE_ROLES = ('task', 'solo', 'verification', 'parallel', 'script')
32
34
  TASKS_COLS = ('id', 'deps', 'difficulty', 'files', 'dwarf', 'qa', 'title')
33
35
  STRUCTURED = ('codex', 'claude', 'openclaude', 'grok', 'opencode') # as forge-runtime.py's: .last is the message, not the log
34
36
  # Plan files that change what a plan decides, added to its rid only when present (see plan_event).
35
- PLAN_RID_LATER = ('decompose_level', 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session',
37
+ PLAN_RID_LATER = ('decompose_level', 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session', 'reviewer_session_rate',
36
38
  'implementer_session', 'pre_review_tests', 'retro_mode', 'brief', 'brief_scope', 'brief_model',
37
- 'summaries', 'summaries_model')
39
+ 'summaries', 'summaries_model', 'retry_per_model')
38
40
 
39
41
  # Files a task or solo execution may write. begin() snapshots their signatures so
40
42
  # finish() can tell this execution's outputs from what an earlier one left behind.
@@ -50,6 +52,7 @@ WATCHED = (
50
52
  'verification.lanes.json', 'results.tsv',
51
53
  'prereview.failed', 'bounced', 'message.failed', 'needs_input.md', 'lateral.tsv',
52
54
  'decision.md', 'decisions.tsv', 'ledger.tsv',
55
+ 'prompt.md', 'approach.md', 'prompt.dispatched', 'approach.dispatched', 'stale.diff',
53
56
  )
54
57
 
55
58
  # The markers of an attempt forge sent back without a review, and the kind each one records.
@@ -325,6 +328,11 @@ def locate(root: str | Path, role: str | None = None) -> dict:
325
328
  kind = p.parent.parent.name
326
329
  plan, ctx['task'], ctx['scope'], ctx['side'] = (
327
330
  p.parent.parent.parent.parent, p.parent.name, 'task', kind)
331
+ elif p.parent.name == 'groups' and (p.parent.parent / 'tasks.tsv').exists():
332
+ # <plan>/groups/<gid>: one QA dispatch for a review=group group. Not a task.
333
+ # Checked after shadow and side, and before a name prefix (final-review-*,
334
+ # integrate-*), so a group id with one of those names stays a group.
335
+ plan, ctx['task'], ctx['scope'], ctx['group'] = p.parent.parent, None, 'group', p.name
328
336
  elif p.parent.name == 'tasks' and (p.parent.parent / 'tasks.tsv').exists():
329
337
  plan, ctx['task'], ctx['scope'] = p.parent.parent, p.name, 'task'
330
338
  elif p.name.startswith('final-review-') and (p.parent / 'tasks.tsv').exists():
@@ -447,6 +455,150 @@ def side_kind(root: Path, role: str, prov: dict | None = None) -> str | None:
447
455
  return locate(root, role).get('side')
448
456
 
449
457
 
458
+ def group_members(plan: Path, gid: str) -> list:
459
+ """Task ids of `gid` in groups.tsv, in file order. Empty when the group is absent."""
460
+ for line in (text(plan / 'groups.tsv') or '').splitlines():
461
+ if not line.strip() or line.startswith('#'):
462
+ continue
463
+ cells = line.split('\t')
464
+ if len(cells) < 4 or cells[0] != gid:
465
+ continue
466
+ raw = cells[3].strip()
467
+ if raw in ('', '-'):
468
+ return []
469
+ return [item.strip() for item in raw.split(',') if item.strip() and item.strip() != '-']
470
+ return []
471
+
472
+
473
+ def member_rows(group_dir: Path) -> list:
474
+ """members.tsv rows: round, task, reviewed commit, attempt. One row per member per round."""
475
+ rows = []
476
+ for line in (text(group_dir / 'members.tsv') or '').splitlines():
477
+ if not line.strip() or line.startswith('#'):
478
+ continue
479
+ cells = line.split('\t')
480
+ if len(cells) < 4 or not cells[0].isdigit():
481
+ continue
482
+ rows.append(dict(round=int(cells[0]), task=cells[1], commit=cells[2], attempt=as_int(cells[3])))
483
+ return rows
484
+
485
+
486
+ def _group_rounds(rows: list) -> list:
487
+ rounds = []
488
+ for row in rows:
489
+ if row['round'] not in rounds:
490
+ rounds.append(row['round'])
491
+ return rounds
492
+
493
+
494
+ def group_qa_attempts(group_dir: Path) -> list:
495
+ """QA attempt dirs under a group root, oldest first."""
496
+ attempts = [path for path in (group_dir / 'attempts').glob('qa-*') if path.is_dir()]
497
+
498
+ def started(path: Path):
499
+ return ((read_json(path / 'metrics.json') or {}).get('wall_started') or 0, path.name)
500
+
501
+ return sorted(attempts, key=started)
502
+
503
+
504
+ def assign_group_rounds(group_dir: Path) -> dict:
505
+ """qa attempt dir name -> round, for an import. The round file is not the source.
506
+
507
+ The file is incremented when the next round starts, so it may already name a round
508
+ this dispatch did not review. members.tsv names the rounds that built a candidate.
509
+ A dispatch that recorded its round (`group.round`, written by `_group` since the
510
+ dispatch ended) is that round's. For the others: a reply copied to qa.round-<n>.last
511
+ is that round's; remaining dispatches zip onto the rounds that have such a file, or
512
+ onto every members.tsv round when none does. An oversized round writes members.tsv
513
+ and no reply, so it takes no dispatch.
514
+ """
515
+ rounds = _group_rounds(member_rows(group_dir))
516
+ assignment = {}
517
+ used = set()
518
+ unmatched = []
519
+ attempts = []
520
+ for attempt in group_qa_attempts(group_dir):
521
+ recorded = (text(attempt / 'group.round') or '').strip()
522
+ if recorded.isdigit():
523
+ assignment[attempt.name] = int(recorded)
524
+ used.add(int(recorded))
525
+ else:
526
+ attempts.append(attempt)
527
+ for attempt in attempts:
528
+ last = text(attempt / 'qa.last')
529
+ matched = None
530
+ if last is not None:
531
+ for number in rounds:
532
+ if number in used:
533
+ continue
534
+ copy = group_dir / ('qa.round-%d.last' % number)
535
+ if copy.is_file() and text(copy) == last:
536
+ matched = number
537
+ break
538
+ if matched is None:
539
+ unmatched.append(attempt)
540
+ else:
541
+ assignment[attempt.name] = matched
542
+ used.add(matched)
543
+ reviewed = [number for number in rounds if (group_dir / ('qa.round-%d.last' % number)).is_file()]
544
+ pool = [number for number in (reviewed or rounds) if number not in used]
545
+ for attempt, number in zip(unmatched, pool):
546
+ assignment[attempt.name] = number
547
+ return assignment
548
+
549
+
550
+ def group_judgments(plan: Path) -> dict:
551
+ """(task id, attempt number) -> {group, round} for attempts a group QA dispatch judged.
552
+
553
+ A members.tsv row whose round has no QA dispatch did not judge. The latest judged
554
+ round for a pair wins.
555
+ """
556
+ judged = {}
557
+ groups = Path(plan) / 'groups'
558
+ if not groups.is_dir():
559
+ return judged
560
+ for group_dir in sorted(path for path in groups.iterdir() if path.is_dir()):
561
+ assigned = set(assign_group_rounds(group_dir).values())
562
+ if not assigned:
563
+ continue
564
+ for row in member_rows(group_dir):
565
+ if row['round'] not in assigned or row['attempt'] is None or not row['task']:
566
+ continue
567
+ judged[(row['task'], row['attempt'])] = dict(group=group_dir.name, round=row['round'])
568
+ return judged
569
+
570
+
571
+ def annotate_group_attempt(event: dict, tdir: Path) -> None:
572
+ """Point a member attempt at the group review that judged it, and drop the copied task review.
573
+
574
+ Settle and merge write that member's qa.last and qa.gate onto the task dir. Those are
575
+ not a task-level review: the attempt keeps the link (`review_scope`, `group`, `round`)
576
+ and the per-task review fields stay empty. An attempt with its own qa dispatch is
577
+ left unchanged. An attempt no group judged gains no key, so a plan without a group
578
+ review imports the same events as before.
579
+ """
580
+ if event.get('kind') != 'attempt' or Path(tdir).parent.name != 'tasks':
581
+ return
582
+ data = event.get('data')
583
+ if not isinstance(data, dict):
584
+ return
585
+ if any(str(name).startswith('qa-') for name in (data.get('children') or [])):
586
+ return
587
+ plan = Path(tdir).parent.parent
588
+ if not (plan / 'tasks.tsv').is_file():
589
+ return
590
+ link = group_judgments(plan).get((Path(tdir).name, event.get('attempt')))
591
+ if not link:
592
+ return
593
+ data['review_scope'] = 'group'
594
+ data['group'] = link['group']
595
+ data['round'] = link['round']
596
+ data['gate'] = None
597
+ blobs = data.get('blobs')
598
+ if isinstance(blobs, dict):
599
+ blobs.pop('forge_note', None)
600
+
601
+
450
602
  def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov: dict, src: str = 'live') -> dict:
451
603
  metrics = read_json(attempt / 'metrics.json') or {}
452
604
  resolved = kv(attempt / (role + '.resolved'))
@@ -462,10 +614,17 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
462
614
  found, parsed = parse_review(message) if role == 'qa' else ([], True)
463
615
  shadow = prov.get('shadow')
464
616
  kind = side_kind(root, role, prov)
617
+ located = locate(root, role)
618
+ # A group root stays a group even when an older provenance named a task. The dispatch
619
+ # is one review of several tasks, so the event's task stays empty.
620
+ group_root = located.get('scope') == 'group' or prov.get('scope') == 'group'
621
+ scope = 'group' if group_root else prov.get('scope')
622
+ task_id = None if group_root else prov.get('task')
465
623
  # A shadow review keeps the qa files and contract but is never a task's review, so it
466
624
  # gets its own role: nothing that reads qa dispatches mistakes it for the one that decided.
467
625
  # A side dispatch keeps the side files and is recorded as side_<kind>, so attempt
468
- # statistics can leave it out (forge_dataset.is_side_role).
626
+ # statistics can leave it out (forge_dataset.is_side_role). A group review keeps the
627
+ # role qa; scope group is what leaves it out of one task's statistics.
469
628
  if kind:
470
629
  recorded_role = 'side_' + kind
471
630
  elif shadow and role == 'qa':
@@ -493,14 +652,25 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
493
652
  findings_parse=review_completeness(verdict, found, parsed) if role == 'qa' else None,
494
653
  tests=review_tests(message) if role == 'qa' else None,
495
654
  session_id=session_id, session_continue=session_continue,
496
- root=str(root), scope=prov.get('scope'), trigger=prov.get('trigger'),
655
+ root=str(root), scope=scope, trigger=prov.get('trigger'),
497
656
  **({'shadow': shadow} if shadow else {}),
498
657
  )
658
+ if group_root and role == 'qa':
659
+ gid = located.get('group') or Path(root).name
660
+ plan = located.get('plan') or Path(root).resolve().parent.parent
661
+ # Live capture reads the round file, which holds the round in progress. An import
662
+ # reads members.tsv: the file advances when the next round starts.
663
+ data['group'] = gid
664
+ data['members'] = group_members(plan, gid)
665
+ if src == 'import':
666
+ data['round'] = assign_group_rounds(Path(root)).get(Path(attempt).name)
667
+ else:
668
+ data['round'] = as_int(first_line(Path(root) / 'round'))
499
669
  prompt = None if delivery == 'native_review' else put_file(attempt / (role + '.prompt'), 'prompt')
500
670
  last = put_file(attempt / (role + '.last'), 'message' if final_source == 'structured' else 'log')
501
671
  return dict(rid=attempt.name, kind='dispatch', ts=prov.get('wall_ended') or time.time(), src=src,
502
672
  run=prov.get('run'), run_id=prov.get('run_id'), mode=prov.get('mode'),
503
- task=prov.get('task'), attempt=prov.get('attempt_now'), parent=prov.get('parent'),
673
+ task=task_id, attempt=prov.get('attempt_now'), parent=prov.get('parent'),
504
674
  inv=prov.get('inv'), data=dict(data, blobs=blobs(prompt=prompt, message=last)))
505
675
 
506
676
 
@@ -533,6 +703,30 @@ def children(root: Path, parent: str) -> list:
533
703
  return found
534
704
 
535
705
 
706
+ def attempt_prompt_changed(status) -> bool:
707
+ """Whether this attempt stopped unreviewed because its prompt or approach changed (#150).
708
+
709
+ A store row from before the field exists reads as false: `.get` of a missing key, and
710
+ this function is what writes the key. No re-import is required.
711
+ """
712
+ return status == 'STALE'
713
+
714
+
715
+ def requirement_blob(tdir: Path, stem: str):
716
+ """The prompt or approach the implementer was dispatched with.
717
+
718
+ `<stem>.dispatched` is that text when the attempt recorded it. An attempt from before
719
+ the record falls back to `<stem>.md`. An empty `approach.dispatched` means there was
720
+ no approach, stored the same way as a missing approach.md: no blob.
721
+ """
722
+ dispatched = tdir / (stem + '.dispatched')
723
+ if dispatched.is_file():
724
+ if stem == 'approach' and text(dispatched) == '':
725
+ return None
726
+ return put_file(dispatched, 'prompt')
727
+ return put_file(tdir / (stem + '.md'), 'prompt')
728
+
729
+
536
730
  def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') -> dict:
537
731
  before = prov.get('files')
538
732
  made = lambda name: produced(tdir, before, name)
@@ -557,6 +751,7 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
557
751
  sent_back=next((kind for marker, kind in SENT_BACK if made(marker)), None),
558
752
  retry_source=first_line(tdir / 'retry_findings.source'),
559
753
  identical_retry=bool(diff) and made('changes.prev.diff') and diff == text(tdir / 'changes.prev.diff'),
754
+ prompt_changed=attempt_prompt_changed(status),
560
755
  produced=sorted(n for n in WATCHED if made(n)),
561
756
  carried=sorted(n for n in WATCHED if (tdir / n).exists() and not made(n)),
562
757
  children=children(tdir, attempt.name),
@@ -575,7 +770,7 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
575
770
  qa_effort_jev=put_file(tdir / 'qa.effort.jev') if made('qa.effort.jev') else None,
576
771
  review_triage_jev=put_file(tdir / 'qa.jev.json') if made('qa.jev.json') else None,
577
772
  routing_jev=put_file(tdir / 'jev.json'),
578
- prompt=put_file(tdir / 'prompt.md', 'prompt'), approach=put_file(tdir / 'approach.md', 'prompt'),
773
+ prompt=requirement_blob(tdir, 'prompt'), approach=requirement_blob(tdir, 'approach'),
579
774
  )
580
775
  data['blobs'] = refs
581
776
  return dict(rid=attempt.name, kind='attempt', ts=prov.get('wall_ended') or time.time(), src=src,
@@ -806,9 +1001,9 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
806
1001
  fractal_selection=read_json(plan / 'fractal-selection.json'),
807
1002
  jev_coupling=read_json(plan / 'jev-coupling.json'),
808
1003
  options=dict({name: first_line(plan / name) for name in ('verify_retries', 'timeout', 'final_qa',
809
- 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session',
1004
+ 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session', 'reviewer_session_rate',
810
1005
  'implementer_session', 'retro_mode', 'brief', 'brief_scope',
811
- 'brief_model', 'summaries', 'summaries_model')
1006
+ 'brief_model', 'summaries', 'summaries_model', 'retry_per_model')
812
1007
  if (plan / name).exists()}, qa_threshold=threshold, qa_threshold_source=threshold_source),
813
1008
  flags=sorted(name for name in ('no_memory', 'no_ripwire', 'yolo_dwarf', 'yolo_qa', 'pre_review_tests')
814
1009
  if (plan / name).exists()),
@@ -6,9 +6,11 @@ belongs to (the same base-commit rule forge-ui's repos.py uses for a run whose c
6
6
 
7
7
  runs {run (dataset uid), run_id, mode, repo_path, base, first, last}
8
8
  findings one per review dispatch (qa, qa_shadow) that listed findings. A side dispatch
9
- (`side_*`, or the bare role `side`) is not a review and is left out: {run, run_id, task, attempt, role,
10
- scope, reviewer, verdict, ts, findings: [{head, severity (0-3 or null), status, line}]}, as the
11
- capture parsed them with forge-contract.py (no second parser)
9
+ (`side_*`, or the bare role `side`) is not a review and is left out, and so is a
10
+ group review (`scope` `group`): one QA dispatch for several tasks. Each row is
11
+ {run, run_id, task, attempt, role, scope, reviewer, verdict, ts, findings:
12
+ [{head, severity (0-3 or null), status, line}]}, as the capture parsed them
13
+ with forge-contract.py (no second parser)
12
14
  learnings one per FORGE_LEARNING line a dispatch emitted: {run, run_id, task, role, model, ts, category, text}
13
15
  ledger the ledger rows `forge dataset import --ledger` stored: {repo_path, ts, run_id, task, role, model,
14
16
  category, key, text, injectable}
@@ -20,6 +22,7 @@ from __future__ import annotations
20
22
  import json
21
23
 
22
24
  from . import connect, dataset_dir, enabled, is_side_role
25
+ from .names import dispatch_name
23
26
 
24
27
  _HEAD_MAX = 400
25
28
  _TEXT_MAX = 2000
@@ -72,12 +75,14 @@ def load() -> dict:
72
75
  if task is None and parent in attempt_task:
73
76
  task, attempt = task or attempt_task[parent][0], attempt or attempt_task[parent][1]
74
77
  role = d.get('role')
75
- spec = d.get('alias') or d.get('model')
78
+ spec = dispatch_name(d)
76
79
  if d.get('effort') and spec and ':' not in str(spec):
77
80
  spec = '%s:%s' % (spec, d['effort'])
78
81
  found = d.get('findings')
79
- # qa and qa_shadow only. side_* is not a review, so its findings are not history.
80
- if role in ('qa', 'qa_shadow') and not is_side_role(role) and isinstance(found, list) and found:
82
+ # qa and qa_shadow only. side_* is not a review, and neither is a group review
83
+ # (scope group): one dispatch for several tasks, so its findings are not history.
84
+ if (role in ('qa', 'qa_shadow') and not is_side_role(role) and d.get('scope') != 'group'
85
+ and isinstance(found, list) and found):
81
86
  items = []
82
87
  for f in found:
83
88
  if not isinstance(f, dict) or not isinstance(f.get('head'), str):
@@ -27,7 +27,7 @@ import time
27
27
  from pathlib import Path
28
28
  from types import SimpleNamespace
29
29
 
30
- from . import (BUSY_TIMEOUT_S, DatasetError, config_runs_dir, data_home, dataset_dir, enabled,
30
+ from . import (BUSY_TIMEOUT_S, DatasetError, config_runs_dir, connect, data_home, dataset_dir, enabled,
31
31
  location_refused, put_blob, put_file, record, record_strict, repo_id, sha256, watch_blob_failures)
32
32
  from . import harvest as h
33
33
  from . import capture
@@ -196,6 +196,9 @@ def legacy_task_events(tdir: Path, task_attempts: list[Path], prov_base: dict) -
196
196
  verdict = h.verdict_of(h.text(qa[-1] / 'qa.last')) if qa else None
197
197
  data['status'], data['status_source'] = ((row['status'], 'attempts.tsv') if row else
198
198
  (verdict, 'qa_verdict') if verdict else (None, None))
199
+ # task_event read the task dir's current status. This attempt's status is the
200
+ # attempts.tsv row, so the prompt_changed flag has to follow the row.
201
+ data['prompt_changed'] = h.attempt_prompt_changed(data.get('status'))
199
202
  event['attempt'], data['attempt_source'] = ((row['attempt'], 'attempts.tsv') if row else
200
203
  (index + 1, 'order'))
201
204
  blocks = _DIFF_BLOCK.findall(h.text(qa[-1] / 'qa.prompt') or '') if qa else []
@@ -206,6 +209,7 @@ def legacy_task_events(tdir: Path, task_attempts: list[Path], prov_base: dict) -
206
209
  else:
207
210
  event['attempt'] = h.as_int(h.first_line(tdir / 'attempt'))
208
211
  data['attempt_source'] = 'attempt_file'
212
+ h.annotate_group_attempt(event, tdir)
209
213
  events.append(event)
210
214
  return events
211
215
 
@@ -274,6 +278,8 @@ def import_tree(top: Path, mapper: Mapper, args, counts: dict) -> list[tuple[lis
274
278
  for event in events:
275
279
  if isinstance(event.get('data'), dict) and event['data'].get('root'):
276
280
  event['data']['root'] = str(mapper(event['data']['root']))
281
+ if role == 'task' and event.get('kind') == 'attempt':
282
+ h.annotate_group_attempt(event, root)
277
283
  # A live begin() recorded which code the execution started with; keep it.
278
284
  capture.stamp(events, (stored or {}).get('provenance'), check_change=False)
279
285
  batches.append((events, repo))
@@ -545,6 +551,57 @@ def _archive_mapper(work: Path, source: Path | None) -> tuple[Path, Mapper]:
545
551
  return root, mapper
546
552
 
547
553
 
554
+ def link_stored_group_attempts(events: list) -> None:
555
+ """Fill the group link onto an attempt live capture stored before the group judged it.
556
+
557
+ The rid stays the attempt dir name, so the import does not add a second event. Only
558
+ `review_scope`, `group` and `round` are written, and a copied task-level review
559
+ (`gate`, `blobs.forge_note`) is removed. A row that already carries the same link
560
+ is left as it was.
561
+ """
562
+ pending = [event for event in events
563
+ if event.get('kind') == 'attempt' and isinstance(event.get('data'), dict)
564
+ and event['data'].get('review_scope') == 'group']
565
+ if not pending or not enabled():
566
+ return
567
+ db = connect()
568
+ try:
569
+ db.execute('BEGIN IMMEDIATE')
570
+ for event in pending:
571
+ row = db.execute('SELECT data FROM events WHERE rid = ?', (event['rid'],)).fetchone()
572
+ if not row:
573
+ continue
574
+ try:
575
+ data = json.loads(row[0])
576
+ except ValueError:
577
+ continue
578
+ if not isinstance(data, dict):
579
+ continue
580
+ blobs = data.get('blobs') if isinstance(data.get('blobs'), dict) else {}
581
+ same = (data.get('review_scope') == 'group' and data.get('group') == event['data'].get('group')
582
+ and data.get('round') == event['data'].get('round') and not data.get('gate')
583
+ and 'forge_note' not in blobs)
584
+ if same:
585
+ continue
586
+ data['review_scope'] = 'group'
587
+ data['group'] = event['data'].get('group')
588
+ data['round'] = event['data'].get('round')
589
+ data['gate'] = None
590
+ if isinstance(data.get('blobs'), dict):
591
+ data['blobs'].pop('forge_note', None)
592
+ db.execute('UPDATE events SET data = ? WHERE rid = ?',
593
+ (json.dumps(data, sort_keys=True, default=str), event['rid']))
594
+ db.execute('COMMIT')
595
+ except BaseException:
596
+ try:
597
+ db.execute('ROLLBACK')
598
+ except sqlite3.Error:
599
+ pass
600
+ raise
601
+ finally:
602
+ db.close()
603
+
604
+
548
605
  def import_run(path, strict: bool = True, include_temp: bool = True) -> dict:
549
606
  """Import one run dir or `.tar.gz` and say exactly what happened: {events, new, failed, ...}.
550
607
 
@@ -561,6 +618,7 @@ def import_run(path, strict: bool = True, include_temp: bool = True) -> dict:
561
618
  writer = record_strict if strict else record
562
619
 
563
620
  def write(batches, blob_failures):
621
+ pending = []
564
622
  for events, repo in batches:
565
623
  if events:
566
624
  counts['events'] += len(events)
@@ -574,8 +632,14 @@ def import_run(path, strict: bool = True, include_temp: bool = True) -> dict:
574
632
  except DatasetError as error:
575
633
  counts.setdefault('failed', []).append('store: %s' % error)
576
634
  return
635
+ pending.extend(events)
577
636
  if strict and blob_failures and not counts.get('failed'):
578
637
  counts.setdefault('failed', []).extend(blob_failures)
638
+ if not counts.get('failed'):
639
+ try:
640
+ link_stored_group_attempts(pending)
641
+ except Exception as error:
642
+ counts.setdefault('failed', []).append('store: %s' % error)
579
643
 
580
644
  with watch_blob_failures() as blob_failures:
581
645
  if path.is_dir():