@giamme/forge 0.17.0 → 0.19.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -10,10 +10,11 @@ from pathlib import Path
10
10
  import posixpath
11
11
  import re
12
12
  import stat
13
+ import sys
13
14
  import time
14
15
  import urllib.parse
15
16
 
16
- from forge_ui import checks, diffs, executions, findings, fractal, repos, transcripts
17
+ from forge_ui import checks, diffs, executions, findings, fractal, groups, links, repos, transcripts
17
18
  from forge_ui.findings import verdict as _verdict
18
19
 
19
20
 
@@ -318,6 +319,11 @@ def _nullable(value):
318
319
  return None if value in ('', '-', 'UNASSIGNED') else value
319
320
 
320
321
 
322
+ def _model_name(spec):
323
+ """A dwarf or qa cell that names a model. `script` runs tasks/<id>/run, so it is not one."""
324
+ return None if not spec or spec == 'script' else spec
325
+
326
+
321
327
  def _tasks(reader):
322
328
  tasks = []
323
329
  for label, row in reader.rows('tasks.tsv', 7):
@@ -361,6 +367,75 @@ def _brief(title):
361
367
  return title if len(title) <= _TITLE_CAP else title[:_TITLE_CAP] + '…'
362
368
 
363
369
 
370
+ def _real_path(value):
371
+ try:
372
+ return os.path.realpath(value)
373
+ except (OSError, ValueError):
374
+ return os.fspath(value)
375
+
376
+
377
+ def _first_line(directory, name):
378
+ """The first line of `directory/name`, or None when the file cannot be read.
379
+
380
+ One open. A missing file, a missing directory and a directory in the way are all None:
381
+ a chain link is never worth an exception.
382
+ """
383
+ try:
384
+ with open(os.path.join(os.fspath(directory), name), encoding='utf-8', errors='replace') as stream:
385
+ line = stream.readline()
386
+ except OSError:
387
+ return None
388
+ return line.strip() or None
389
+
390
+
391
+ def _predecessor(reader):
392
+ """`{key, run_id, path}` of the plan this run follows, from its `after` file, or None.
393
+
394
+ `reader.line` is the one read: a run with no `after` file costs that one failed stat and
395
+ nothing else. A named directory that is gone still yields a key and a path, with `run_id`
396
+ null, so the chain stays visible.
397
+ """
398
+ named = reader.line('after')
399
+ if not named:
400
+ return None
401
+ path = _real_path(named)
402
+ return dict(key=run_key(path), run_id=_first_line(path, 'run_id'), path=path)
403
+
404
+
405
+ def _note_followers(runs):
406
+ """Set `followed_by` on each listed run: `{key, run_id}` of the runs whose `after` names it.
407
+
408
+ Paths are the resolved ones `_predecessor` stored, so a symlink in an `after` file still matches.
409
+ """
410
+ by_predecessor = {}
411
+ for run in runs:
412
+ after = run.get('after')
413
+ if not after or not after.get('path'):
414
+ continue
415
+ by_predecessor.setdefault(after['path'], []).append(dict(key=run['key'], run_id=run['run_id']))
416
+ for run in runs:
417
+ run['followed_by'] = by_predecessor.get(run['path'], [])
418
+
419
+
420
+ def _followers(listed, target):
421
+ """`{key, run_id}` of the listed runs whose `after` names `target`, in list order.
422
+
423
+ Reads each other dir's `after` file and, on a hit, its `run_id`. Does not summarize them.
424
+ Skips `target` itself: its `after` was already read to fill the predecessor, and a dir with
425
+ no `after` file must not be read twice.
426
+ """
427
+ want = _real_path(target)
428
+ found = []
429
+ for path, _source, _entry in listed:
430
+ if _real_path(path) == want:
431
+ continue
432
+ named = _first_line(path, 'after')
433
+ if named is None or _real_path(named) != want:
434
+ continue
435
+ found.append(dict(key=run_key(path), run_id=_first_line(path, 'run_id')))
436
+ return found
437
+
438
+
364
439
  def _summary(reader, source):
365
440
  result = dict(key=run_key(reader.path), path=str(reader.path), source=source, kind='plan',
366
441
  run_id=reader.line('run_id'), repo=reader.line('repo'),
@@ -371,17 +446,20 @@ def _summary(reader, source):
371
446
  for task in tasks:
372
447
  counts[task['status']] = counts.get(task['status'], 0) + 1
373
448
  final_review = reader.word('final-review.verdict')
374
- dwarf_models = sorted({task['dwarf'] for task in tasks if task['dwarf']})
375
- qa_models = sorted({task['qa'] for task in tasks if task['qa']})
449
+ dwarf_models = sorted({task['dwarf'] for task in tasks if _model_name(task['dwarf'])})
450
+ qa_models = sorted({task['qa'] for task in tasks if _model_name(task['qa'])})
451
+ scripted = sum(1 for task in tasks if task['dwarf'] == 'script')
376
452
  # Before snapshotting `updated`: these reads are files the summary read, so a newer
377
453
  # accepted.integration (or the published verdict / review.meta) moves the activity time.
378
454
  final_review_outdated = _published_outdated(reader, tasks)
455
+ after = _predecessor(reader)
379
456
  result.update(updated=reader.updated, created=_created(reader.path, _PLAN_START_FILES),
380
457
  task_count=len(tasks), counts=counts,
381
458
  task_statuses=[dict(id=task['id'], status=task['status'], difficulty=task['difficulty'] or None,
382
459
  title=_brief(task['title']), accepted=task['accepted']) for task in tasks],
383
460
  models=sorted(set(dwarf_models) | set(qa_models)), dwarf_models=dwarf_models, qa_models=qa_models,
384
- final_review=final_review, final_review_outdated=final_review_outdated)
461
+ scripted=scripted, final_review=final_review, final_review_outdated=final_review_outdated,
462
+ after=after)
385
463
  return result, tasks
386
464
 
387
465
 
@@ -406,7 +484,11 @@ def _solo_summary(reader, source):
406
484
  reader.exists('dwarf.log')
407
485
  reader.exists('qa.log')
408
486
  dwarf, qa = _role_spec(reader, 'dwarf'), _role_spec(reader, 'qa')
487
+ # The task payload keeps a dwarf spec of `script`. The model lists do not: it is not a model.
488
+ model_dwarf, model_qa = _model_name(dwarf), _model_name(qa)
409
489
  goal = reader.line('goal.txt')
490
+ # Before `updated` is copied out: a present `after` file is part of what the summary read.
491
+ after = _predecessor(reader)
410
492
  return dict(key=run_key(reader.path), path=str(reader.path), source=source, kind='solo',
411
493
  run_id=reader.path.name, repo=reader.line('repo'), goal=goal,
412
494
  decompose_level=None, verification_status=None, updated=reader.updated,
@@ -414,8 +496,10 @@ def _solo_summary(reader, source):
414
496
  task_count=1, counts={status: 1},
415
497
  task_statuses=[dict(id='solo', status=status, difficulty=None, title=_brief(goal or 'Solo run'),
416
498
  accepted=False)],
417
- models=sorted({dwarf, qa} - {None}), dwarf_models=[dwarf] if dwarf else [],
418
- qa_models=[qa] if qa else [], final_review=None, final_review_outdated=None)
499
+ models=sorted({model_dwarf, model_qa} - {None}),
500
+ dwarf_models=[model_dwarf] if model_dwarf else [],
501
+ qa_models=[model_qa] if model_qa else [], scripted=1 if dwarf == 'script' else 0,
502
+ final_review=None, final_review_outdated=None, after=after)
419
503
 
420
504
 
421
505
  def summarize(path, source='plan') -> dict:
@@ -425,9 +509,43 @@ def summarize(path, source='plan') -> dict:
425
509
  return _summary(reader, source)[0]
426
510
 
427
511
 
512
+ def _attempt_log(reader, name):
513
+ """attempts.tsv rows, oldest first, including the dwarf column the public attempt omits.
514
+
515
+ The public attempt stays `{at, attempt, status, infra}`: callers compare that dict exactly.
516
+ """
517
+ result = []
518
+ for label, row in reader.rows(name, 3):
519
+ try:
520
+ at, attempt = float(row[0]), int(row[1])
521
+ if not math.isfinite(at):
522
+ raise ValueError()
523
+ except (ValueError, OverflowError):
524
+ reader.warn(label, 'invalid epoch or attempt')
525
+ continue
526
+ dwarf = row[4].strip() if len(row) > 4 else ''
527
+ result.append(dict(at=at, attempt=attempt, status=row[2],
528
+ infra=_nullable(row[3]) if len(row) > 3 else None, dwarf=_nullable(dwarf)))
529
+ return result
530
+
531
+
532
+ def _public_attempt(row):
533
+ return dict(at=row['at'], attempt=row['attempt'], status=row['status'], infra=row['infra'])
534
+
535
+
536
+ def _attempt_view(reader, name, number_file):
537
+ rows = _attempt_log(reader, name)
538
+ attempt = reader.number(number_file, int) if number_file else None
539
+ if attempt is None:
540
+ attempt = max((item['attempt'] for item in rows), default=None)
541
+ return rows, attempt
542
+
543
+
428
544
  def _history(reader, name, escalation=False):
545
+ if not escalation:
546
+ return [_public_attempt(row) for row in _attempt_log(reader, name)]
429
547
  result = []
430
- for label, row in reader.rows(name, 4 if escalation else 3):
548
+ for label, row in reader.rows(name, 4):
431
549
  try:
432
550
  at, attempt = float(row[0]), int(row[1])
433
551
  if not math.isfinite(at):
@@ -435,23 +553,15 @@ def _history(reader, name, escalation=False):
435
553
  except (ValueError, OverflowError):
436
554
  reader.warn(label, 'invalid epoch or attempt')
437
555
  continue
438
- entry = dict(at=at, attempt=attempt)
439
- if escalation:
440
- # the 5th column says who decided (policy, a human's retry --dwarf, a pin); older rows have 4
441
- source = row[4].strip() if len(row) > 4 else ''
442
- entry.update({'from': row[2], 'to': row[3], 'source': source or 'policy'})
443
- else:
444
- entry.update(status=row[2], infra=_nullable(row[3]) if len(row) > 3 else None)
445
- result.append(entry)
556
+ # the 5th column says who decided (policy, a human's retry --dwarf, a pin); older rows have 4
557
+ source = row[4].strip() if len(row) > 4 else ''
558
+ result.append(dict(at=at, attempt=attempt, **{'from': row[2], 'to': row[3], 'source': source or 'policy'}))
446
559
  return result
447
560
 
448
561
 
449
562
  def _attempt_state(reader, prefix):
450
- attempts = _history(reader, prefix + '/attempts.tsv')
451
- attempt = reader.number(prefix + '/attempt', int)
452
- if attempt is None:
453
- attempt = max((item['attempt'] for item in attempts), default=None)
454
- return attempts, attempt
563
+ rows, attempt = _attempt_view(reader, prefix + '/attempts.tsv', prefix + '/attempt')
564
+ return [_public_attempt(row) for row in rows], attempt
455
565
 
456
566
 
457
567
  def _gate(reader, name):
@@ -468,7 +578,8 @@ def _nonempty(reader, name):
468
578
 
469
579
 
470
580
  def _task_execs(reader, task):
471
- execs = executions.scan(reader, f'tasks/{task["id"]}/attempts', task['status'] == 'RUNNING', ('task', 'dwarf', 'qa'))
581
+ execs = executions.scan(reader, f'tasks/{task["id"]}/attempts', task['status'] == 'RUNNING',
582
+ ('task', 'dwarf', 'qa', 'script'))
472
583
  executions.nest(execs)
473
584
  return executions.assign_attempts(execs, task['attempts'], task['attempt'])
474
585
 
@@ -566,7 +677,7 @@ def _now(reader, owner_dir, execs):
566
677
  """Task.now: where a running task (or solo run) is. The dwarf or reviewer running in it, with the call it is
567
678
  making and when its log last moved; else the task execution's own phase."""
568
679
  running = [item for item in execs if item['state'] == 'running' and not item['shadow']]
569
- agent = next((item for item in reversed(running) if item['role'] in ('dwarf', 'qa')), None)
680
+ agent = next((item for item in reversed(running) if item['role'] in ('dwarf', 'qa', 'script')), None)
570
681
  item = agent or next((item for item in reversed(running) if item['role'] in executions.CONTAINERS), None)
571
682
  if item is None:
572
683
  return None
@@ -622,7 +733,39 @@ def _scheduler(reader):
622
733
 
623
734
 
624
735
  # Not NEEDS_INPUT or NEEDS_DECISION: those wait for the user, so a task that depends on one waits rather than stops.
736
+ # IMPLEMENTED is not here either: the member's own work is in and it waits for the group's review.
737
+ # A task that depends on one waits, it does not stop.
625
738
  _STOPPED = ('FAIL', 'BLOCKED', 'INFRA', 'INTERRUPTED', 'TIMEOUT', 'ERROR', 'CONFLICT', 'NOCHANGES', 'INVALIDATED', 'UNKNOWN')
739
+
740
+ # How status_class, and through it _waiting, reads a status.
741
+ # done is MERGED only. PASS is saved and not merged yet, so a dependent still lists it.
742
+ # NOCHANGES is failed: it is in _STOPPED and will not merge. The page paints PASS and NOCHANGES
743
+ # as finished; this reader does not, because a dependent is not free of either.
744
+ # IMPLEMENTED is waiting, with NEEDS_INPUT and NEEDS_DECISION: awaiting the group's review.
745
+ # It is not done, not active and not failed.
746
+ _DONE_STATUS = frozenset(('MERGED',))
747
+ _ACTIVE_STATUS = frozenset(('RUNNING',))
748
+ _WAITING_STATUS = frozenset(('NEEDS_INPUT', 'NEEDS_DECISION', 'IMPLEMENTED'))
749
+
750
+
751
+ def status_class(status):
752
+ """'done', 'active', 'waiting' or 'failed', or None for a status in none of those buckets.
753
+
754
+ `_waiting` uses this for a dependency: 'done' drops it from `on`, 'failed' puts it in
755
+ `stopped`, and 'waiting' leaves it in `on` only. PENDING is None (not started). PASS is
756
+ None too (saved, not merged). IMPLEMENTED is 'waiting': awaiting group review.
757
+ """
758
+ if status in _DONE_STATUS:
759
+ return 'done'
760
+ if status in _ACTIVE_STATUS:
761
+ return 'active'
762
+ if status in _WAITING_STATUS:
763
+ return 'waiting'
764
+ if status in _STOPPED:
765
+ return 'failed'
766
+ return None
767
+
768
+
626
769
  _DETAIL_CAP = 400 # characters of an infra stop's detail, a short text
627
770
  _ATTEMPT_CAP = 8 # a plan without a max_attempts file
628
771
  _LEDGER_KEEP = 50 # the newest ledger rows a task keeps
@@ -808,12 +951,42 @@ def _attempt_cap(max_attempts, decisions):
808
951
  return max_attempts + sum(_grant(item['choice']) for item in decisions)
809
952
 
810
953
 
954
+ def _brief_writer_alive(reader):
955
+ """brief.pid names a running process: the question writer `run` started has not finished."""
956
+ try:
957
+ pid = int((reader.text('brief.pid') or '').split()[0])
958
+ if pid > 0:
959
+ os.kill(pid, 0)
960
+ return True
961
+ except PermissionError:
962
+ return True
963
+ except (OSError, ValueError, IndexError):
964
+ pass
965
+ return False
966
+
967
+
968
+ def _brief_wait(reader, ident):
969
+ """Why a gated plan holds this task, as forge-schedule.py tells it: the ids of its must_answer questions that
970
+ have no entry in brief.answers.json, or `[]` when it has no brief.json yet and the writer still runs.
971
+ None for any other level, or when nothing holds it."""
972
+ if reader.word('brief') != 'gated':
973
+ return None
974
+ brief = reader.object(f'tasks/{ident}/brief.json')
975
+ if brief is None:
976
+ return [] if not reader.exists(f'tasks/{ident}/brief.json') and _brief_writer_alive(reader) else None
977
+ answers = reader.object(f'tasks/{ident}/brief.answers.json') or {}
978
+ asked = [q['id'] for q in brief.get('questions') or [] if isinstance(q, dict) and q.get('must_answer') is True
979
+ and isinstance(q.get('id'), str) and q['id'] and q['id'] not in answers]
980
+ return asked or None
981
+
982
+
811
983
  def _waiting(reader, tasks, scheduler):
812
984
  """Task.waiting: why a task that is not running is not, as far as the run dir tells.
813
985
 
814
986
  escalation (the retry policy stopped it, whether or not a scheduler runs); and while one runs: infra (a pause
815
- holds it), deps (on tasks not merged yet), drained, stopping, overlap (it shares files with a running task),
816
- slot (the run is at its capacity) or next (nothing holds it: it starts at the scheduler's next turn)."""
987
+ holds it), deps (on tasks not merged yet), drained, stopping, brief (a gated plan waits for your answer),
988
+ overlap (it shares files with a running task), slot (the run is at its capacity) or next (nothing holds it:
989
+ it starts at the scheduler's next turn)."""
817
990
  status = {task['id']: task['status'] for task in tasks}
818
991
  running = [task for task in tasks if task['status'] == 'RUNNING']
819
992
  for task in tasks:
@@ -832,13 +1005,16 @@ def _waiting(reader, tasks, scheduler):
832
1005
  continue
833
1006
  if task['status'] != 'PENDING':
834
1007
  continue
835
- on = [dep for dep in task['deps'] if status.get(dep) != 'MERGED']
1008
+ on = [dep for dep in task['deps'] if status_class(status.get(dep)) != 'done']
836
1009
  if on:
837
- task['waiting'] = dict(kind='deps', on=on, stopped=[dep for dep in on if status.get(dep) in _STOPPED])
1010
+ task['waiting'] = dict(kind='deps', on=on,
1011
+ stopped=[dep for dep in on if status_class(status.get(dep)) == 'failed'])
838
1012
  elif scheduler['stopping']:
839
1013
  task['waiting'] = dict(kind='stopping', mode=scheduler['stopping'])
840
1014
  elif scheduler['drained']:
841
1015
  task['waiting'] = dict(kind='drained')
1016
+ elif (asked := _brief_wait(reader, task['id'])) is not None:
1017
+ task['waiting'] = dict(kind='brief', questions=asked)
842
1018
  else:
843
1019
  mine = [_scope(path) for path in task['files'] if path and path != '-']
844
1020
  shared = [other['id'] for other in running if _overlap(mine, [_scope(p) for p in other['files'] if p and p != '-'])]
@@ -851,7 +1027,600 @@ def _waiting(reader, tasks, scheduler):
851
1027
  task['waiting'] = dict(kind='next')
852
1028
 
853
1029
 
854
- def _task_detail(reader, task, run_id, waves, branches, max_attempts):
1030
+ # The first paragraph of a task's approach (else its prompt), after the markdown title.
1031
+ _GOAL_CAP = 600
1032
+ _ATX = re.compile(r'^[ ]{0,3}#{1,6}(?:[ \t]|$)')
1033
+ _CRITERIA = re.compile(r'^## Acceptance criteria[ \t]*:?[ \t]*$')
1034
+ _FENCE = re.compile(r'^( {0,3})(`{3,}|~{3,})(.*)$')
1035
+ # retry_sources.tsv sources. Anything else is warned and skipped; the last known row for an attempt wins.
1036
+ _RETRY_SOURCES = frozenset(('review', 'prereview', 'bounce', 'message', 'answer'))
1037
+ _DATASET = None
1038
+
1039
+
1040
+ def _open_fence(line):
1041
+ match = _FENCE.match(line)
1042
+ if match is None:
1043
+ return None
1044
+ mark, info = match.group(2), match.group(3)
1045
+ if mark[0] == '`' and '`' in info:
1046
+ return None
1047
+ return mark[0], len(mark)
1048
+
1049
+
1050
+ def _close_fence(line, opened):
1051
+ match = _FENCE.match(line)
1052
+ if match is None:
1053
+ return False
1054
+ mark, info = match.group(2), match.group(3)
1055
+ return mark[0] == opened[0] and len(mark) >= opened[1] and not info.strip()
1056
+
1057
+
1058
+ _IMAGE = re.compile(r'!\[([^\[\]]*)\]\([^)]*\)')
1059
+ _LINK = re.compile(r'\[([^\[\]]*)\]\([^)]*\)')
1060
+ # A marker inside a word (`2*3*4`) is not emphasis. Underscores are left as written.
1061
+ _STRONG = re.compile(r'(?<!\w)\*\*([^*]+)\*\*(?!\w)')
1062
+ _EM = re.compile(r'(?<!\w)\*(?!\*)(\S(?:[^*]*?\S)?)\*(?!\w)')
1063
+ _STRIKE = re.compile(r'(?<!\w)~~([^~]+)~~(?!\w)')
1064
+
1065
+
1066
+ def _hold_code(text):
1067
+ """Replace inline code spans with placeholders. Return `(text, contents)`.
1068
+
1069
+ Contents keep their characters and lose the backticks. A span that starts and ends
1070
+ with a space, and is not all spaces, loses one space on each side.
1071
+ """
1072
+ pieces, held = [], []
1073
+ index, size = 0, len(text)
1074
+ while index < size:
1075
+ if text[index] != '`':
1076
+ pieces.append(text[index])
1077
+ index += 1
1078
+ continue
1079
+ end = index
1080
+ while end < size and text[end] == '`':
1081
+ end += 1
1082
+ length, cursor, close = end - index, end, None
1083
+ while cursor < size:
1084
+ if text[cursor] != '`':
1085
+ cursor += 1
1086
+ continue
1087
+ run = cursor
1088
+ while run < size and text[run] == '`':
1089
+ run += 1
1090
+ if run - cursor == length:
1091
+ close = run
1092
+ break
1093
+ cursor = run
1094
+ if close is None:
1095
+ pieces.append(text[index:end])
1096
+ index = end
1097
+ continue
1098
+ interior = text[end:close - length]
1099
+ if len(interior) >= 2 and interior[0] == ' ' and interior[-1] == ' ' and interior.strip(' '):
1100
+ interior = interior[1:-1]
1101
+ held.append(interior)
1102
+ pieces.append(f'\ue000{len(held) - 1}\ue000')
1103
+ index = close
1104
+ return ''.join(pieces), held
1105
+
1106
+
1107
+ def _plain_inline(text):
1108
+ """Drop inline markdown. Code-span contents stay literal, and underscores stay."""
1109
+ held_text, held = _hold_code(text)
1110
+ plain = _IMAGE.sub(r'\1', held_text)
1111
+ plain = _LINK.sub(r'\1', plain)
1112
+ plain = _STRONG.sub(r'\1', plain)
1113
+ plain = _EM.sub(r'\1', plain)
1114
+ plain = _STRIKE.sub(r'\1', plain)
1115
+ for index, interior in enumerate(held):
1116
+ plain = plain.replace(f'\ue000{index}\ue000', interior)
1117
+ return plain
1118
+
1119
+
1120
+ def _goal_text(text):
1121
+ """The first prose paragraph after an optional `# ` title, as plain text, or None."""
1122
+ if not text:
1123
+ return None
1124
+ lines, index = text.splitlines(), 0
1125
+ while index < len(lines) and not lines[index].strip():
1126
+ index += 1
1127
+ if index < len(lines) and lines[index].startswith('# '):
1128
+ index += 1
1129
+ while index < len(lines) and (not lines[index].strip() or _ATX.match(lines[index])):
1130
+ index += 1
1131
+ paragraph = []
1132
+ while index < len(lines) and lines[index].strip() and not _ATX.match(lines[index]):
1133
+ paragraph.append(lines[index].strip())
1134
+ index += 1
1135
+ if not paragraph:
1136
+ return None
1137
+ return re.sub(r'\s+', ' ', _plain_inline('\n'.join(paragraph))).strip() or None
1138
+
1139
+
1140
+ def _criteria_text(text):
1141
+ """prompt.md's `## Acceptance criteria` section, up to the next `## ` heading, or None.
1142
+
1143
+ A fenced `## ` does not end the section, and a `### ` subsection stays inside it.
1144
+ """
1145
+ if not text:
1146
+ return None
1147
+ fence, started, body = None, False, []
1148
+ for line in text.splitlines():
1149
+ if fence is not None:
1150
+ if started:
1151
+ body.append(line)
1152
+ if _close_fence(line, fence):
1153
+ fence = None
1154
+ continue
1155
+ opened = _open_fence(line)
1156
+ if opened is not None:
1157
+ fence = opened
1158
+ if started:
1159
+ body.append(line)
1160
+ continue
1161
+ if not started:
1162
+ started = _CRITERIA.match(line) is not None
1163
+ continue
1164
+ if line.startswith('## '):
1165
+ break
1166
+ body.append(line)
1167
+ if not started:
1168
+ return None
1169
+ return '\n'.join(body).strip() or None
1170
+
1171
+
1172
+ def _forge_dataset():
1173
+ """forge_dataset, loaded from scripts/, or None when it cannot be imported. Cached.
1174
+
1175
+ scripts/ is on the path only while that import runs.
1176
+ """
1177
+ global _DATASET
1178
+ if _DATASET is False:
1179
+ return None
1180
+ if _DATASET is not None:
1181
+ return _DATASET
1182
+ scripts = str(Path(__file__).resolve().parents[2] / 'scripts')
1183
+ inserted = scripts not in sys.path
1184
+ if inserted:
1185
+ sys.path.insert(0, scripts)
1186
+ try:
1187
+ import forge_dataset
1188
+ except Exception:
1189
+ _DATASET = False
1190
+ return None
1191
+ finally:
1192
+ if inserted and scripts in sys.path:
1193
+ sys.path.remove(scripts)
1194
+ _DATASET = forge_dataset
1195
+ return _DATASET
1196
+
1197
+
1198
+ def _github_origin(reader):
1199
+ """The run repo's origin URL, from the plan's `repo` file then `.git/config`. No git, no network.
1200
+
1201
+ A missing config is not a warning: `#N` then has a null url.
1202
+ """
1203
+ repo = reader.line('repo')
1204
+ module = _forge_dataset() if repo else None
1205
+ if module is None:
1206
+ return None
1207
+ try:
1208
+ return module.git_origin(repo)
1209
+ except Exception:
1210
+ return None
1211
+
1212
+
1213
+ def _header(reader, title, prompt, approach, request, field, origin):
1214
+ """`{title, goal, criteria, links}` from the raw prompt, approach and request texts."""
1215
+ goal = _goal_text(approach)
1216
+ if goal is None:
1217
+ goal = _goal_text(prompt)
1218
+ found, seen = [], set()
1219
+ for name, text in (('prompt.md', prompt), ('approach.md', approach), ('request.md', request)):
1220
+ if not text:
1221
+ continue
1222
+ for item in links.extract(text, name, origin):
1223
+ key = (item['kind'], item['number'], item['url'])
1224
+ if key in seen:
1225
+ continue
1226
+ seen.add(key)
1227
+ found.append(item)
1228
+ return dict(title=title, goal=reader.cap(goal, field + '/goal', _GOAL_CAP),
1229
+ criteria=reader.cap(_criteria_text(prompt), field + '/criteria'), links=found)
1230
+
1231
+
1232
+ def _retry_sources(reader, name):
1233
+ """`{attempt: source}` from retry_sources.tsv. The last known source for an attempt wins."""
1234
+ found = {}
1235
+ for label, row in reader.rows(name, 3):
1236
+ try:
1237
+ attempt = int(row[0])
1238
+ except ValueError:
1239
+ reader.warn(label, 'invalid attempt')
1240
+ continue
1241
+ source = row[1].strip()
1242
+ if source not in _RETRY_SOURCES:
1243
+ reader.warn(label, 'unknown retry source')
1244
+ continue
1245
+ found[attempt] = source
1246
+ return found
1247
+
1248
+
1249
+ def _queued_retries(reader):
1250
+ """`{task: [epoch, ...]}` of control.log lines that queued a retry.
1251
+
1252
+ A scheduler settlement carries `outcome` and actor `scheduler`; it is not the queue.
1253
+ A line that is not JSON is skipped, with no warning.
1254
+ """
1255
+ found = {}
1256
+ for line in (reader.text('control.log') or '').splitlines():
1257
+ if not line.strip():
1258
+ continue
1259
+ try:
1260
+ obj = json.loads(line)
1261
+ except (ValueError, RecursionError):
1262
+ continue
1263
+ if not isinstance(obj, dict) or obj.get('action') != 'retry':
1264
+ continue
1265
+ if obj.get('outcome') or obj.get('actor') == 'scheduler':
1266
+ continue
1267
+ task, at = obj.get('task'), obj.get('at')
1268
+ if not isinstance(task, str) or not task:
1269
+ continue
1270
+ if isinstance(at, bool) or not isinstance(at, (int, float)) or not math.isfinite(at):
1271
+ continue
1272
+ found.setdefault(task, []).append(float(at))
1273
+ return found
1274
+
1275
+
1276
+ def _manual_indexes(rows, times):
1277
+ """Row indexes a queued retry explains.
1278
+
1279
+ attempts.tsv is written when the attempt ends, so the queue explains the next attempt:
1280
+ the first row that is not attempt 1 and whose end is at or after the queue, plus later
1281
+ rows of that same attempt number that also end then. An earlier row of the same number,
1282
+ already finished before the queue, is not that retry.
1283
+ """
1284
+ found = set()
1285
+ for moment in times:
1286
+ chosen = None
1287
+ for index, row in enumerate(rows):
1288
+ if row['attempt'] == 1 or row['at'] < moment:
1289
+ continue
1290
+ if chosen is None:
1291
+ chosen = row['attempt']
1292
+ if row['attempt'] == chosen:
1293
+ found.add(index)
1294
+ return found
1295
+
1296
+
1297
+ def _attempt_reason(index, row, rows, sources, escalations, manual):
1298
+ """Why this attempt ran: first, a recorded retry source, an escalation, a queued retry, or unknown."""
1299
+ if row['attempt'] == 1:
1300
+ return 'first'
1301
+ source = sources.get(row['attempt'])
1302
+ if source:
1303
+ return source
1304
+ # escalations.tsv names the attempt that finished, which is the previous one. The signal
1305
+ # is a dwarf change while any escalation is recorded, not that column.
1306
+ previous = rows[index - 1]['dwarf'] if index else None
1307
+ if row['dwarf'] != previous and escalations:
1308
+ return 'escalation'
1309
+ if index in manual:
1310
+ return 'manual'
1311
+ return 'unknown'
1312
+
1313
+
1314
+ def _attempt_review(execs, attempt):
1315
+ """The newest done, non-shadow qa execution of this attempt, or None."""
1316
+ chosen = None
1317
+ for item in execs:
1318
+ if item.get('shadow') or item.get('role') != 'qa' or item.get('state') != 'done':
1319
+ continue
1320
+ if item.get('attempt') != attempt:
1321
+ continue
1322
+ chosen = item
1323
+ return chosen
1324
+
1325
+
1326
+ def _trail(reader, rows, execs, sources_name, escalations, queue_times):
1327
+ """One entry per attempts.tsv row: its review, why it ran, and its execution ids."""
1328
+ sources = _retry_sources(reader, sources_name)
1329
+ manual = _manual_indexes(rows, queue_times)
1330
+ result = []
1331
+ for index, row in enumerate(rows):
1332
+ review = _attempt_review(execs, row['attempt'])
1333
+ summary = None
1334
+ verdict = None
1335
+ if review is not None:
1336
+ verdict = review.get('verdict')
1337
+ found = review.get('findings')
1338
+ summary = dict(found) if found else None
1339
+ result.append(dict(
1340
+ attempt=row['attempt'], dwarf=row['dwarf'], verdict=verdict, findings=summary,
1341
+ worst=summary.get('worst') if summary else None, reason=_attempt_reason(
1342
+ index, row, rows, sources, escalations, manual),
1343
+ executions=[item['id'] for item in execs
1344
+ if item.get('attempt') == row['attempt'] and not item.get('shadow')]))
1345
+ return result
1346
+
1347
+
1348
+ # --- generated task summaries (#133 B): tasks/<id>/summary.json, its error, and the switches -----------------------
1349
+
1350
+ _SUMMARY_SOURCES = ('attempt', 'finding')
1351
+ # The facts a summary is made from, as the reader shows them: one changed after generated_at makes it stale.
1352
+ _SUMMARY_FACTS = ('attempts.tsv', 'status', 'merged', 'qa.last')
1353
+
1354
+
1355
+ def _mode_or_none(value):
1356
+ return value if value in ('on', 'off') else None
1357
+
1358
+
1359
+ def _is_number(value):
1360
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
1361
+
1362
+
1363
+ def _summary_sources(reader, prefix, sources):
1364
+ """The well-formed `{kind, ref}` entries of a summary's sources; any other entry is dropped."""
1365
+ if not isinstance(sources, list):
1366
+ return []
1367
+ return [dict(kind=item['kind'], ref=reader.cap(item['ref'], prefix + '/summary.sources'))
1368
+ for item in sources
1369
+ if isinstance(item, dict) and item.get('kind') in _SUMMARY_SOURCES and isinstance(item.get('ref'), str)]
1370
+
1371
+
1372
+ def _task_summary(reader, prefix):
1373
+ """The task's generated summary, or None when there is no summary.json (or it is not a summary: warned)."""
1374
+ body = reader.object(prefix + '/summary.json')
1375
+ error = reader.text(prefix + '/summary.error')
1376
+ if body is None:
1377
+ return None
1378
+ text, generated = body.get('text'), body.get('generated_at')
1379
+ if not isinstance(text, str) or not _is_number(generated):
1380
+ reader.warn(prefix + '/summary.json', 'not a summary (needs text and generated_at)')
1381
+ return None
1382
+ facts = [reader.stat(f'{prefix}/{name}') for name in _SUMMARY_FACTS]
1383
+ # generated_at is whole seconds: a fact written in the second the summary was made is not after it.
1384
+ stale = any(info is not None and int(info.st_mtime) > generated for info in facts)
1385
+ sentence, model = body.get('sentence'), body.get('model')
1386
+ return dict(text=reader.cap(text, prefix + '/summary.text'),
1387
+ sentence=reader.cap(sentence, prefix + '/summary.sentence') if isinstance(sentence, str) else None,
1388
+ model=model if isinstance(model, str) else None, generated_at=generated,
1389
+ sources=_summary_sources(reader, prefix, body.get('sources')), stale=stale,
1390
+ error=reader.cap(error, prefix + '/summary.error') if error and error.strip() else None)
1391
+
1392
+
1393
+ def _run_summaries(reader):
1394
+ """The run's summary switch from its plan files. `mode` is on only when `summaries` says so (absent is off);
1395
+ `model` is the first line of `summaries_model`, or null."""
1396
+ return dict(mode='on' if reader.word('summaries') == 'on' else 'off', model=reader.line('summaries_model'))
1397
+
1398
+
1399
+ # --- brief mode (#135): tasks/<id>/brief.json, parked questions, answers and late answers ---------
1400
+ # Proposals and affected markers (#136) are read only while brief is on. Off leaves them unread, so a
1401
+ # plan without brief keeps the run JSON it had.
1402
+
1403
+ _BRIEF_LEVELS = ('advisory', 'gated', 'strict')
1404
+ # CLI proposal dirs are p1, p2, … with no leading zero (PID_RE). p0 and p0001 are not proposals.
1405
+ _PID_DIR = re.compile(r'^p[1-9][0-9]{0,5}$')
1406
+
1407
+
1408
+ def _brief_level(reader):
1409
+ """The plan's brief level, or None when brief is off (no `brief` file, `off`, or any other word)."""
1410
+ level = reader.word('brief')
1411
+ return level if level in _BRIEF_LEVELS else None
1412
+
1413
+
1414
+ def _cap_str(reader, value, field):
1415
+ return reader.cap(value, field) if isinstance(value, str) else None
1416
+
1417
+
1418
+ def _cap_options(reader, value, field):
1419
+ if not isinstance(value, list):
1420
+ return []
1421
+ return [reader.cap(item, field) for item in value if isinstance(item, str)]
1422
+
1423
+
1424
+ def _answer_map(data):
1425
+ """`{qid: entry}` from an answers or late object. Anything else is no answers."""
1426
+ if not isinstance(data, dict):
1427
+ return {}
1428
+ return {key: value if isinstance(value, dict) else {}
1429
+ for key, value in data.items() if isinstance(key, str) and key}
1430
+
1431
+
1432
+ def _entry_text(entry):
1433
+ text = entry.get('text') if isinstance(entry, dict) else None
1434
+ return text if isinstance(text, str) else None
1435
+
1436
+
1437
+ def _brief_rows(reader, prefix, body, answers, late, parked):
1438
+ """Questions from a brief.json or brief.parked.json object, in file order.
1439
+
1440
+ An entry that is not an object, or has no string id, is skipped, with one warning for the file.
1441
+ Answers apply to task questions only: `answered` beats `late`, and anything else is `open`.
1442
+ """
1443
+ if not isinstance(body, dict):
1444
+ return []
1445
+ label = f'{prefix}/brief.parked.json' if parked else f'{prefix}/brief.json'
1446
+ items = body.get('questions', [])
1447
+ if not isinstance(items, list):
1448
+ reader.warn(label, 'questions is not a list')
1449
+ return []
1450
+ file_stale = body.get('possibly_stale') is True
1451
+ rows, skipped = [], 0
1452
+ for question in items:
1453
+ if not isinstance(question, dict) or not isinstance(question.get('id'), str) or not question['id']:
1454
+ skipped += 1
1455
+ continue
1456
+ qid = question['id']
1457
+ stem = f'{prefix}/brief.parked/{qid}' if parked else f'{prefix}/brief/{qid}'
1458
+ if parked:
1459
+ state, entry = None, None
1460
+ elif qid in answers:
1461
+ state, entry = 'answered', answers[qid]
1462
+ elif qid in late:
1463
+ state, entry = 'late', late[qid]
1464
+ else:
1465
+ state, entry = 'open', None
1466
+ row = dict(id=qid, text=_cap_str(reader, question.get('text'), stem + '.text'),
1467
+ why=_cap_str(reader, question.get('why'), stem + '.why'),
1468
+ options=_cap_options(reader, question.get('options'), stem + '.options'),
1469
+ default=_cap_str(reader, question.get('default'), stem + '.default'),
1470
+ must_answer=question.get('must_answer') is True,
1471
+ possibly_stale=file_stale or question.get('possibly_stale') is True)
1472
+ if parked:
1473
+ scope = question.get('scope')
1474
+ group = question.get('group')
1475
+ row['scope'] = scope if isinstance(scope, str) else None
1476
+ row['group'] = group if isinstance(group, str) and group else None
1477
+ # Parked answers live in brief.parked.answers.json, passed in as `answers`.
1478
+ row['answer'] = _cap_str(reader, _entry_text(answers.get(qid)), stem + '.answer')
1479
+ else:
1480
+ row['state'] = state
1481
+ row['answer'] = _cap_str(reader, _entry_text(entry), stem + '.answer')
1482
+ rows.append(row)
1483
+ if skipped:
1484
+ reader.warn(label, f'{skipped} question{"" if skipped == 1 else "s"} skipped')
1485
+ return rows
1486
+
1487
+
1488
+ def _late_rows(reader, prefix, late):
1489
+ """brief.late.json in file order: `{id, text, actor, t}`. `t` is kept only when it is a finite number."""
1490
+ rows = []
1491
+ for qid, entry in late.items():
1492
+ actor = entry.get('actor') if isinstance(entry, dict) else None
1493
+ stamp = entry.get('t') if isinstance(entry, dict) else None
1494
+ rows.append(dict(id=qid, text=_cap_str(reader, _entry_text(entry), f'{prefix}/brief.late/{qid}.text'),
1495
+ actor=actor if isinstance(actor, str) else None,
1496
+ t=stamp if _is_number(stamp) else None))
1497
+ return rows
1498
+
1499
+
1500
+ def _task_brief(reader, ident):
1501
+ """The task's questions, parked questions and late answers, or None when it has none of those files."""
1502
+ prefix = f'tasks/{ident}'
1503
+ paths = {'brief': f'{prefix}/brief.json', 'parked': f'{prefix}/brief.parked.json',
1504
+ 'late': f'{prefix}/brief.late.json'}
1505
+ present = {name: reader.exists(path) for name, path in paths.items()}
1506
+ if not any(present.values()):
1507
+ return None
1508
+ brief = reader.object(paths['brief']) if present['brief'] else None
1509
+ parked = reader.object(paths['parked']) if present['parked'] else None
1510
+ late = _answer_map(reader.object(paths['late']) if present['late'] else None)
1511
+ answers = _answer_map(reader.object(f'{prefix}/brief.answers.json'))
1512
+ # Missing parked answers are no answers. The file is not read when this task has no parked questions,
1513
+ # and a missing file is not tracked, so `updated` does not move.
1514
+ parked_answers = _answer_map(reader.object(f'{prefix}/brief.parked.answers.json')) if present['parked'] else {}
1515
+ return dict(questions=_brief_rows(reader, prefix, brief, answers, late, False),
1516
+ parked=_brief_rows(reader, prefix, parked, parked_answers, {}, True),
1517
+ late=_late_rows(reader, prefix, late))
1518
+
1519
+
1520
+ def _run_brief(level, tasks):
1521
+ """RunDetail.brief: the level, and how many task questions are still open (flagged: open and must_answer).
1522
+
1523
+ Parked questions are not counted: they are wider than this task and do not hold it."""
1524
+ open_n = flagged = 0
1525
+ for task in tasks:
1526
+ brief = task.get('brief')
1527
+ if not brief:
1528
+ continue
1529
+ for question in brief['questions']:
1530
+ if question['state'] != 'open':
1531
+ continue
1532
+ open_n += 1
1533
+ flagged += question['must_answer']
1534
+ return dict(level=level, open=open_n, flagged=flagged)
1535
+
1536
+
1537
+ def _affected(reader, ident):
1538
+ """`tasks/<id>/brief.affected` as `{pid, reason, flag_only}`, or None when the marker is absent or not one.
1539
+
1540
+ `t` stays on disk. `flag_only` is true only when the file says exactly that: a task that had already
1541
+ started when the proposal was applied. A bad object is warned about here, or already by the JSON read.
1542
+ """
1543
+ label = f'tasks/{ident}/brief.affected'
1544
+ body = reader.object(label)
1545
+ if body is None:
1546
+ return None
1547
+ pid, reason = body.get('pid'), body.get('reason')
1548
+ if not isinstance(pid, str) or not pid or len(pid) > 32 or not isinstance(reason, str) or not reason:
1549
+ reader.warn(label, 'not an affected marker')
1550
+ return None
1551
+ return dict(pid=pid, reason=reader.cap(reason, label + '.reason', 500),
1552
+ flag_only=body.get('flag_only') is True)
1553
+
1554
+
1555
+ def _as_str(value):
1556
+ return value if isinstance(value, str) else None
1557
+
1558
+
1559
+ def _proposals(reader):
1560
+ """`<plan>/proposals/<pid>/` in numeric order: the public record, the hash, and the diff.
1561
+
1562
+ The diff is capped like every other text. `truncated` is true when the shown diff is not the file.
1563
+ The hash is not capped: Approve sends the hash the page shows. `answer` and the edit lists stay in
1564
+ the file; the run JSON does not carry them. A directory that is not a proposal id is skipped.
1565
+ """
1566
+ names = []
1567
+ for path in reader.children('proposals'):
1568
+ if not _PID_DIR.fullmatch(path.name):
1569
+ continue
1570
+ try:
1571
+ if not path.is_dir():
1572
+ continue
1573
+ except (OSError, ValueError) as exc:
1574
+ reader.warn(f'proposals/{path.name}', f'cannot stat ({type(exc).__name__})')
1575
+ continue
1576
+ names.append(path.name)
1577
+ names.sort(key=lambda name: int(name[1:]))
1578
+ rows = []
1579
+ for pid in names:
1580
+ prefix = f'proposals/{pid}'
1581
+ body = reader.object(f'{prefix}/proposal.json')
1582
+ if body is None:
1583
+ continue
1584
+ if body.get('pid') != pid:
1585
+ reader.warn(f'{prefix}/proposal.json', 'pid does not match the directory')
1586
+ raw = reader.text(f'{prefix}/diff.patch')
1587
+ if raw is None:
1588
+ diff, cut = '', False
1589
+ else:
1590
+ diff = reader.cap(raw, f'{prefix}/diff')
1591
+ cut = diff != raw
1592
+ raw_hash = reader.text(f'{prefix}/hash')
1593
+ digest = raw_hash.strip() if isinstance(raw_hash, str) else ''
1594
+ rows.append(dict(pid=pid, scope=_as_str(body.get('scope')), group=_as_str(body.get('group')),
1595
+ task=_as_str(body.get('task')), qid=_as_str(body.get('qid')),
1596
+ summary=_cap_str(reader, body.get('summary'), f'{prefix}/summary'),
1597
+ state=_as_str(body.get('state')),
1598
+ reason=_cap_str(reader, body.get('reason'), f'{prefix}/reason'),
1599
+ created=_as_str(body.get('created')), hash=digest or None, diff=diff, truncated=cut))
1600
+ return rows
1601
+
1602
+
1603
+ def _attach_brief(reader, tasks):
1604
+ """Set each task's `brief` and return the run's `{level, open, flagged}`, or None when brief is off.
1605
+
1606
+ Off means the questions are not shown either: a file left from an earlier level stays on disk.
1607
+ Affected markers are attached only while brief is on, and only when the file is a real marker.
1608
+ The key is omitted otherwise, including when brief is off, so that run JSON does not grow a null.
1609
+ """
1610
+ level = _brief_level(reader)
1611
+ if level is None:
1612
+ for task in tasks:
1613
+ task['brief'] = None
1614
+ return None
1615
+ for task in tasks:
1616
+ task['brief'] = _task_brief(reader, task['id'])
1617
+ affected = _affected(reader, task['id'])
1618
+ if affected is not None:
1619
+ task['affected'] = affected
1620
+ return _run_brief(level, tasks)
1621
+
1622
+
1623
+ def _task_detail(reader, task, run_id, waves, branches, max_attempts, origin, request, queues):
855
1624
  """Fill in a plan task; returns every execution it read (its own and its shadows')."""
856
1625
  ident = task['id']
857
1626
  prefix = f'tasks/{ident}'
@@ -862,7 +1631,8 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
862
1631
  task['branch'] = f'forge/{run_id}/{ident}'
863
1632
  except (OSError, ValueError):
864
1633
  pass
865
- task['attempts'], task['attempt'] = _attempt_state(reader, prefix)
1634
+ logged, task['attempt'] = _attempt_view(reader, prefix + '/attempts.tsv', prefix + '/attempt')
1635
+ task['attempts'] = [_public_attempt(row) for row in logged]
866
1636
  task['attempts_total'] = sum(item['status'] != 'INFRA' for item in task['attempts'])
867
1637
  task['escalations'] = _history(reader, prefix + '/escalations.tsv', True)
868
1638
  qa = reader.text(prefix + '/qa.last')
@@ -872,8 +1642,10 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
872
1642
  task['accepted_by'] = reader.text(prefix + '/accepted.by')
873
1643
  task['accepted_attempt'], task['accepted_over'] = _accepted_fields(
874
1644
  reader, prefix + '/accepted.by', task['accepted_by'])
1645
+ texts = {}
875
1646
  for field, filename in [('prompt', 'prompt.md'), ('approach', 'approach.md'), ('retry_findings', 'retry_findings.md')]:
876
- task[field] = reader.cap(reader.text(prefix + '/' + filename), prefix + '/' + field)
1647
+ texts[field] = reader.text(prefix + '/' + filename)
1648
+ task[field] = reader.cap(texts[field], prefix + '/' + field)
877
1649
  # the implementer's question for the user, when the task stopped NEEDS_INPUT
878
1650
  task['needs_input'] = reader.cap(reader.text(prefix + '/needs_input.md'), prefix + '/needs_input')
879
1651
  # the stop records: why an INFRA dispatch stopped, the lateral moves, the review ledger, and a NEEDS_DECISION's question
@@ -893,6 +1665,8 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
893
1665
  item.get('explored') is True for item in task['route'])
894
1666
  execs = _task_execs(reader, task)
895
1667
  task['executions'] = execs
1668
+ task['header'] = _header(reader, task['title'], texts['prompt'], texts['approach'], request, prefix, origin)
1669
+ task['trail'] = _trail(reader, logged, execs, prefix + '/retry_sources.tsv', task['escalations'], queues)
896
1670
  task['now'] = _now(reader, prefix, execs) if task['status'] == 'RUNNING' else None
897
1671
  merged = reader.stat(prefix + '/merged') if task['status'] == 'MERGED' else None
898
1672
  task['merged_at'] = float(merged.st_mtime) if merged is not None else None
@@ -905,6 +1679,8 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
905
1679
  task['swept'] = []
906
1680
  shadows = _shadows(reader, ident, execs)
907
1681
  task['shadow'] = [entry for entry, _, _ in shadows]
1682
+ task['summary'] = _task_summary(reader, prefix)
1683
+ task['summaries_override'] = _mode_or_none(reader.word(prefix + '/summaries'))
908
1684
  # What `forge control show` reads of the task. A change there (a write, or a delete: the dir's mtime) moves `updated`,
909
1685
  # so the page redraws and the Controls panel asks again.
910
1686
  reader.stat(prefix)
@@ -985,8 +1761,9 @@ def _sweep(reader, tasks):
985
1761
  # Read only for their mtimes, so the run's `updated` stamp moves when a control changes.
986
1762
  # control.requests is a directory: its mtime moves when a request is queued or settled.
987
1763
  _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused', 'infra.last',
988
- 'infra_backoff', 'escalate_effort', 'control.requests')
989
- _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next')
1764
+ 'infra_backoff', 'escalate_effort', 'control.requests', 'summaries', 'summaries_model')
1765
+ _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next',
1766
+ 'summaries')
990
1767
 
991
1768
 
992
1769
  _FAIL_FIRST_RESULTS = ('proven', 'passes_without_change', 'inconclusive', 'error')
@@ -1482,23 +2259,29 @@ def _frozen_profile(reader):
1482
2259
  def _solo_detail(reader, source):
1483
2260
  result = _solo_summary(reader, source)
1484
2261
  status = next(iter(result['counts']))
1485
- result['request'] = reader.cap(reader.text('request.md'), 'request')
2262
+ request = reader.text('request.md')
2263
+ result['request'] = reader.cap(request, 'request')
2264
+ result['retro'] = _retro(reader)
2265
+ result['summaries'] = None # generated summaries are for plan tasks only
2266
+ result['brief'] = None # brief mode is a plan's questions, not a solo run's
1486
2267
  result['settings'] = dict.fromkeys(_SOLO_SETTINGS)
1487
2268
  result['settings']['qa_threshold'], result['settings']['qa_threshold_source'] = _threshold(reader)
1488
2269
  result['settings']['profile'] = _frozen_profile(reader)
1489
2270
  result['verification'] = None
1490
2271
  result['attribution'] = _attribution(reader)
1491
2272
  result['waves'] = [['solo']]
1492
- attempts = _history(reader, 'attempts.tsv')
2273
+ logged, attempt = _attempt_view(reader, 'attempts.tsv', None)
2274
+ attempts = [_public_attempt(row) for row in logged]
1493
2275
  qa = reader.text('qa.last')
1494
2276
  execs = _solo_execs(reader, status, attempts)
2277
+ prompt, approach = reader.text('prompt.md'), reader.text('approach.md')
1495
2278
  task = dict(id='solo', title=result['goal'] or 'Solo run', deps=[], difficulty=None, files=[],
1496
2279
  dwarf=_role_spec(reader, 'dwarf'), qa=_role_spec(reader, 'qa'), wave=1, status=status,
1497
- branch=None, attempt=max((item['attempt'] for item in attempts), default=None),
2280
+ branch=None, attempt=attempt,
1498
2281
  attempts=attempts, escalations=[], verdict=_verdict(qa), accepted_by=None,
1499
2282
  accepted=False, accepted_attempt=None, accepted_over=None,
1500
2283
  explored=False, route=[], shadow=[],
1501
- prompt=reader.cap(reader.text('prompt.md'), 'tasks/solo/prompt'), approach=None,
2284
+ prompt=reader.cap(prompt, 'tasks/solo/prompt'), approach=None,
1502
2285
  retry_findings=None, needs_input=None, infra=None, lateral=[], ledger=[], decision=None, decisions=[],
1503
2286
  attempts_total=sum(item['status'] != 'INFRA' for item in attempts), attempt_cap=None,
1504
2287
  qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
@@ -1506,7 +2289,11 @@ def _solo_detail(reader, source):
1506
2289
  executions=execs, merged_at=None, findings=executions.summary_of(qa),
1507
2290
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
1508
2291
  fail_first=_fail_first(reader, 'failfirst.json'), pre_review=None,
1509
- now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[])
2292
+ now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[],
2293
+ summary=None, summaries_override=None, brief=None)
2294
+ task['header'] = _header(reader, task['title'], prompt, approach, request, 'tasks/solo',
2295
+ _github_origin(reader))
2296
+ task['trail'] = _trail(reader, logged, execs, 'retry_sources.tsv', [], _queued_retries(reader).get('solo', ()))
1510
2297
  result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[], adoptions=[],
1511
2298
  deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
1512
2299
  scheduler=None, sweep=None)
@@ -1560,12 +2347,49 @@ def _attribution(reader):
1560
2347
  gate_outcome=_text_or_none(outcome, 40))
1561
2348
 
1562
2349
 
2350
+ # --- retro: the report and the counts of its notes, written when retro mode is on ----------------
2351
+
2352
+ _RETRO_GROUPS = (('user', 'fixable_by', 'user'), ('forge', 'fixable_by', 'forge'), ('unsure', 'fixable_by', 'unsure'),
2353
+ ('verified', 'check', 'verified'), ('claimed', 'check', 'claimed'))
2354
+
2355
+
2356
+ def _retro(reader):
2357
+ """RunDetail.retro: retro.md's text and the counts of retro/notes.jsonl, or null when the run has neither file.
2358
+
2359
+ A note is a line that parses as a JSON object. Other non-blank lines are skipped, with one warning for the
2360
+ file. `notes` counts every note; each other count is the notes whose field has that value."""
2361
+ if not (reader.exists('retro.md') or reader.exists('retro/notes.jsonl')):
2362
+ return None
2363
+ name = 'retro/notes.jsonl'
2364
+ counts = dict.fromkeys(('notes', 'user', 'forge', 'unsure', 'verified', 'claimed', 'blocking'), 0)
2365
+ skipped = 0
2366
+ for line in (reader.text(name) or '').split('\n'):
2367
+ if not line.strip():
2368
+ continue
2369
+ try:
2370
+ note = json.loads(line)
2371
+ except (ValueError, RecursionError):
2372
+ note = None
2373
+ if not isinstance(note, dict):
2374
+ skipped += 1
2375
+ continue
2376
+ counts['notes'] += 1
2377
+ for key, field, value in _RETRO_GROUPS:
2378
+ counts[key] += note.get(field) == value
2379
+ counts['blocking'] += note.get('blocking') is True
2380
+ if skipped:
2381
+ reader.warn(name, f'{skipped} malformed line{"" if skipped == 1 else "s"} skipped')
2382
+ return dict(text=reader.cap(reader.text('retro.md'), 'retro'), **counts)
2383
+
2384
+
1563
2385
  def detail(path, source='plan') -> dict:
1564
2386
  reader = _Read(path)
1565
2387
  if _kind(reader.path) == 'solo':
1566
2388
  return _solo_detail(reader, source)
1567
2389
  result, tasks = _summary(reader, source)
1568
- result['request'] = reader.cap(reader.text('request.md'), 'request')
2390
+ request = reader.text('request.md')
2391
+ result['request'] = reader.cap(request, 'request')
2392
+ result['retro'] = _retro(reader)
1569
2393
  threshold = _threshold(reader)
1570
2394
  result['settings'] = dict(explore=reader.number('explore'), shadow_rate=reader.number('shadow_rate'),
1571
2395
  shadow_qa=_list(reader.text('shadow_qa') or ''), timeout=reader.number('timeout', int),
@@ -1574,13 +2398,16 @@ def detail(path, source='plan') -> dict:
1574
2398
  escalate_after=reader.number('escalate_after', int),
1575
2399
  verify_retries=reader.number('verify_retries', int), final_qa=reader.line('final_qa'),
1576
2400
  profile=_frozen_profile(reader))
2401
+ result['summaries'] = _run_summaries(reader)
1577
2402
  waves, wave_map = _waves(reader)
1578
2403
  result['waves'] = [waves.get(n, []) for n in range(1, max(waves, default=0) + 1)]
1579
2404
  branches = {row[0]: _nullable(row[2]) for _, row in reader.rows('results.tsv', 3)}
1580
2405
  max_attempts = _max_attempts(reader)
2406
+ origin, queues = _github_origin(reader), _queued_retries(reader)
1581
2407
  pool = []
1582
2408
  for task in tasks:
1583
- pool += _task_detail(reader, task, result['run_id'], wave_map, branches, max_attempts)
2409
+ pool += _task_detail(reader, task, result['run_id'], wave_map, branches, max_attempts,
2410
+ origin, request, queues.get(task['id'], ()))
1584
2411
  for name in _RUN_CONTROLS:
1585
2412
  reader.stat(name)
1586
2413
  result['scheduler'] = _scheduler(reader)
@@ -1610,6 +2437,22 @@ def detail(path, source='plan') -> dict:
1610
2437
  result['deferrals'] = [line.strip() for line in (reader.text('deferrals.txt') or '').splitlines() if line.strip()]
1611
2438
  result['findings_available'] = findings.available()
1612
2439
  result['fractal'] = fractal.summary(reader)
2440
+ brief = _attach_brief(reader, tasks)
2441
+ result['brief'] = brief
2442
+ # Absent, not empty, when brief is off: proposals/ is not listed, so the run JSON does not change.
2443
+ if brief is not None:
2444
+ result['proposals'] = _proposals(reader)
2445
+ # No groups.tsv: the run JSON gains nothing. A plan that has one carries `groups` and, on
2446
+ # every task, `group` (its group id, or null when it is in none).
2447
+ if reader.exists('groups.tsv'):
2448
+ listed = groups.groups(reader)
2449
+ result['groups'] = listed
2450
+ owner = {}
2451
+ for item in listed:
2452
+ for member in item['members'] or []:
2453
+ owner.setdefault(member, item['id'])
2454
+ for task in tasks:
2455
+ task['group'] = owner.get(task['id'])
1613
2456
  result.update(tasks=tasks, warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
1614
2457
  return result
1615
2458
 
@@ -1635,6 +2478,14 @@ def _review(kind, item, text):
1635
2478
  verdict=item['verdict'], state=item['state'], findings=findings.listing(text), tests=findings.tests(text))
1636
2479
 
1637
2480
 
2481
+ def group_detail(path, gid, source='plan'):
2482
+ """One group of a plan, with its review, or None when the plan has no such group."""
2483
+ reader = _Read(path)
2484
+ if _kind(reader.path) != 'plan':
2485
+ return None
2486
+ return groups.group(reader, gid)
2487
+
2488
+
1638
2489
  def task_detail(path, task_id, source='plan'):
1639
2490
  """TaskDetail of one task (`solo` for a solo run), or None when there is no such task."""
1640
2491
  reader = _Read(path)
@@ -1694,6 +2545,15 @@ def _execution(reader, name):
1694
2545
  owner, owner_dir = dict(kind='task', id='solo'), ''
1695
2546
  elif parts[0] == 'attempts':
1696
2547
  execs, owner, owner_dir = _run_execs(reader), dict(kind='run', id=None), ''
2548
+ elif parts[0] == 'groups' and len(parts) >= 4 and parts[2] == 'attempts':
2549
+ # A review=group group's QA dispatch lives in groups/<gid>/attempts, and its prompts in the group dir.
2550
+ gid = parts[1]
2551
+ if not groups.GID.fullmatch(gid):
2552
+ return None
2553
+ owner_dir = f'groups/{gid}'
2554
+ execs = executions.scan(reader, owner_dir + '/attempts',
2555
+ reader.word(owner_dir + '/status') == 'REVIEWING', ('qa',))
2556
+ owner = dict(kind='group', id=gid)
1697
2557
  elif parts[0] in ('tasks', 'shadow'):
1698
2558
  task = _plan_task(reader, tasks, parts[1])
1699
2559
  execs = _task_execs(reader, task)
@@ -1743,11 +2603,11 @@ def execution_detail(path, name, source='plan'):
1743
2603
 
1744
2604
 
1745
2605
  def execution_transcript(path, name, source='plan'):
1746
- """ExecutionTranscript of a dwarf or qa execution: its agent's conversation, read from its `.log`; None
1747
- when there is no such execution or it is of another role."""
2606
+ """ExecutionTranscript of a dwarf, qa or script execution, read from its `.log` (`script.log` for the
2607
+ command). None when there is no such execution or it is of another role."""
1748
2608
  reader = _Read(path)
1749
2609
  found = _execution(reader, name)
1750
- if found is None or found[0]['role'] not in ('dwarf', 'qa'):
2610
+ if found is None or found[0]['role'] not in ('dwarf', 'qa', 'script'):
1751
2611
  return None
1752
2612
  item, owner, owner_dir = found
1753
2613
  role, running = item['role'], item['state'] == 'running'
@@ -1765,9 +2625,12 @@ def execution_transcript(path, name, source='plan'):
1765
2625
 
1766
2626
 
1767
2627
  def _agent_log(reader, item, owner_dir):
1768
- """The log of a dwarf or reviewer execution: its copy once it ended, the one being written while it runs."""
2628
+ """The log of a dwarf, reviewer or script execution: its copy once it ended, the one being written while it runs."""
1769
2629
  role = item['role']
1770
- return _log_path(reader, posixpath.join(owner_dir, role + '.log') if item['state'] == 'running' else f'{item.rel}/{role}.log')
2630
+ if item['state'] == 'running':
2631
+ return _log_path(reader, posixpath.join(owner_dir, role + '.log'))
2632
+ # `forge runs compact --logs` gzips the copy (#139); transcripts reads either the same way
2633
+ return _log_path(reader, f'{item.rel}/{role}.log') or _log_path(reader, f'{item.rel}/{role}.log.gz')
1771
2634
 
1772
2635
 
1773
2636
  def _checks_of(reader, item, owner_dir):
@@ -2546,7 +3409,13 @@ class Catalog:
2546
3409
  def runs(self):
2547
3410
  listed, identities = batch(discover(**self.options))
2548
3411
  runs = [_with_repo(summarize(path, source), identities[entry[0]]) for path, source, entry in listed]
2549
- return sorted(runs, key=lambda item: item['updated'] if item['updated'] is not None else float('-inf'), reverse=True)
3412
+ runs = sorted(runs, key=lambda item: item['updated'] if item['updated'] is not None else float('-inf'), reverse=True)
3413
+ _note_followers(runs)
3414
+ return runs
3415
+
3416
+ def keys(self):
3417
+ """The keys of every run the list shows, without summarizing any of them."""
3418
+ return {run_key(path) for path, _source in discover(**self.options)}
2550
3419
 
2551
3420
  def identity(self, key):
2552
3421
  """The identity of the run with this key, resolved in the same batch as the list; None for no such run."""
@@ -2577,12 +3446,17 @@ class Catalog:
2577
3446
  listed, identities = batch(discover(**self.options))
2578
3447
  for path, source, entry in listed:
2579
3448
  if run_key(path) == key:
2580
- return _with_repo(detail(path, source=source), identities[entry[0]])
3449
+ result = _with_repo(detail(path, source=source), identities[entry[0]])
3450
+ result['followed_by'] = _followers(listed, result['path'])
3451
+ return result
2581
3452
  return None
2582
3453
 
2583
3454
  def task(self, key, task_id):
2584
3455
  return self._find(key, task_detail, task_id)
2585
3456
 
3457
+ def group(self, key, gid):
3458
+ return self._find(key, group_detail, gid)
3459
+
2586
3460
  def execution(self, key, name):
2587
3461
  return self._find(key, execution_detail, name)
2588
3462