@giamme/forge 0.11.1 → 0.12.1

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 (54) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/SKILL.md +7 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +50 -11
  5. package/docs/commands.md +56 -8
  6. package/docs/decomposed-runs.md +43 -2
  7. package/docs/forge-ui.md +55 -8
  8. package/docs/reviews.md +64 -6
  9. package/package.json +1 -1
  10. package/references/dataset.md +4 -2
  11. package/references/decompose.md +191 -17
  12. package/references/harnesses.md +13 -1
  13. package/references/ui.md +25 -4
  14. package/scripts/forge-contract.py +37 -7
  15. package/scripts/forge-control.py +268 -25
  16. package/scripts/forge-dispatch.sh +90 -3
  17. package/scripts/forge-guard.py +156 -15
  18. package/scripts/forge-issues.py +47 -3
  19. package/scripts/forge-lib-plans.sh +9 -3
  20. package/scripts/forge-lib-review.sh +24 -5
  21. package/scripts/forge-lib-task.sh +53 -5
  22. package/scripts/forge-lib-verify.sh +137 -6
  23. package/scripts/forge-parallel-options.sh +85 -0
  24. package/scripts/forge-parallel.sh +262 -31
  25. package/scripts/forge-ripwire.py +1 -1
  26. package/scripts/forge-route.py +157 -5
  27. package/scripts/forge-runtime.py +49 -1
  28. package/scripts/forge-schedule.py +735 -53
  29. package/scripts/forge-solo.sh +3 -1
  30. package/scripts/forge-sweep.py +542 -0
  31. package/scripts/forge-verify.py +878 -0
  32. package/scripts/forge_dataset/forecast.py +33 -5
  33. package/scripts/forge_dataset/harvest.py +10 -4
  34. package/scripts/forge_verify_reports.py +225 -0
  35. package/ui/README.md +58 -12
  36. package/ui/docs/api.md +277 -28
  37. package/ui/forge_ui/checks.py +331 -0
  38. package/ui/forge_ui/control.py +12 -2
  39. package/ui/forge_ui/export.py +25 -8
  40. package/ui/forge_ui/reader.py +657 -24
  41. package/ui/forge_ui/server.py +29 -0
  42. package/ui/forge_ui/static/app.js +15 -7
  43. package/ui/forge_ui/static/checksview.js +449 -0
  44. package/ui/forge_ui/static/controls.js +217 -33
  45. package/ui/forge_ui/static/convo.js +11 -2
  46. package/ui/forge_ui/static/findingsview.js +6 -4
  47. package/ui/forge_ui/static/gantt.js +14 -9
  48. package/ui/forge_ui/static/index.html +2 -0
  49. package/ui/forge_ui/static/panel.js +44 -1
  50. package/ui/forge_ui/static/runmodel.js +109 -12
  51. package/ui/forge_ui/static/scene3d.js +9 -5
  52. package/ui/forge_ui/static/style.css +113 -0
  53. package/ui/forge_ui/static/verifyview.js +324 -0
  54. package/ui/forge_ui/transcripts.py +225 -54
@@ -9,9 +9,10 @@ from pathlib import Path
9
9
  import posixpath
10
10
  import re
11
11
  import stat
12
+ import time
12
13
  import urllib.parse
13
14
 
14
- from forge_ui import diffs, executions, findings, fractal, transcripts
15
+ from forge_ui import checks, diffs, executions, findings, fractal, transcripts
15
16
  from forge_ui.findings import verdict as _verdict
16
17
 
17
18
 
@@ -544,6 +545,133 @@ def _accepted_fields(reader, name, text):
544
545
  return attempt, status if status in ('FAIL', 'UNKNOWN') else None
545
546
 
546
547
 
548
+ def _log_path(reader, rel):
549
+ """The regular file `rel` of the run dir as a Path, or None; a path that resolves outside the run is never read."""
550
+ try:
551
+ real = Path(os.path.realpath(reader.path / rel))
552
+ if executions.inside(reader.path, str(real)) and stat.S_ISREG(real.stat().st_mode):
553
+ return real
554
+ if real.exists():
555
+ reader.warn(rel, 'outside the run dir or not a regular file')
556
+ except (OSError, ValueError):
557
+ pass
558
+ return None
559
+
560
+
561
+ _CALL_CAP = 400 # characters of the running command in RunDetail
562
+
563
+
564
+ def _now(reader, owner_dir, execs):
565
+ """Task.now: where a running task (or solo run) is. The dwarf or reviewer running in it, with the call it is
566
+ making and when its log last moved; else the task execution's own phase."""
567
+ running = [item for item in execs if item['state'] == 'running' and not item['shadow']]
568
+ agent = next((item for item in reversed(running) if item['role'] in ('dwarf', 'qa')), None)
569
+ item = agent or next((item for item in reversed(running) if item['role'] in executions.CONTAINERS), None)
570
+ if item is None:
571
+ return None
572
+ now = dict(role=item['role'], execution=item['id'], attempt=item['attempt'], phase=item['phase'],
573
+ phase_started=item['phase_started'], started=item['started'], last_output_at=None, call=None)
574
+ if agent is not None:
575
+ rel = posixpath.join(owner_dir, agent['role'] + '.log')
576
+ reader.stat(rel) # the page redraws while the agent writes
577
+ log = _log_path(reader, rel)
578
+ state = transcripts.live(log, (agent['model'] or {}).get('harness')) if log is not None else None
579
+ if state is not None:
580
+ call = state['call']
581
+ if call is not None:
582
+ command = call['command']
583
+ call = dict(call, command=command if not command or len(command) <= _CALL_CAP else command[:_CALL_CAP] + '…',
584
+ check=checks.classify(command) if command else None)
585
+ now.update(last_output_at=state['last_output_at'], call=call)
586
+ return now
587
+
588
+
589
+ def _scheduler(reader):
590
+ """RunDetail.scheduler: whether a scheduler runs this plan now, and, while one does, what holds it: a drain, a
591
+ stop, infrastructure pauses (scheduler-written infra.paused) and the capacity it dispatches up to."""
592
+ pid = (reader.object('scheduler.live') or {}).get('pid') if reader.exists('scheduler.live') else None
593
+ live = False
594
+ if type(pid) is int and pid > 0:
595
+ try:
596
+ os.kill(pid, 0)
597
+ live = True
598
+ except PermissionError:
599
+ live = True
600
+ except (OSError, OverflowError):
601
+ live = False
602
+ result = dict(live=live, drained=False, stopping=None, pauses=[], max_parallel=None)
603
+ if not live:
604
+ return result
605
+ stop = reader.line('stop')
606
+ capacity = reader.number('max_parallel', int)
607
+ result.update(drained=reader.exists('drain'), stopping=stop if stop in ('graceful', 'now') else None,
608
+ max_parallel=capacity if capacity is not None and 1 <= capacity <= 64 else None)
609
+ paused = reader.object('infra.paused') if reader.exists('infra.paused') else None
610
+ for scope in (paused or {}).get('scopes') or []:
611
+ if isinstance(scope, dict):
612
+ result['pauses'].append({key: scope.get(key) for key in
613
+ ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')})
614
+ return result
615
+
616
+
617
+ _STOPPED = ('FAIL', 'BLOCKED', 'INFRA', 'INTERRUPTED', 'TIMEOUT', 'ERROR', 'CONFLICT', 'NOCHANGES', 'INVALIDATED', 'UNKNOWN')
618
+
619
+
620
+ def _escalation_stop(reader, ident):
621
+ """The retry policy stopped this task: {attempts, model, split} from escalation.stop and split.suggested."""
622
+ text = reader.text(f'tasks/{ident}/escalation.stop')
623
+ if text is None:
624
+ return None
625
+ cells = (text.splitlines() or [''])[0].split('\t')
626
+ attempts = int(cells[0]) if cells[0].strip().isdigit() else None
627
+ split = (reader.text(f'tasks/{ident}/split.suggested') or '').strip()
628
+ return dict(kind='escalation', attempts=attempts, model=cells[1].strip() if len(cells) > 1 and cells[1].strip() else None,
629
+ split=reader.cap(split, f'tasks/{ident}/split.suggested', 600) or None)
630
+
631
+
632
+ def _waiting(reader, tasks, scheduler):
633
+ """Task.waiting: why a task that is not running is not, as far as the run dir tells.
634
+
635
+ escalation (the retry policy stopped it, whether or not a scheduler runs); and while one runs: infra (a pause
636
+ holds it), deps (on tasks not merged yet), drained, stopping, overlap (it shares files with a running task),
637
+ slot (the run is at its capacity) or next (nothing holds it: it starts at the scheduler's next turn)."""
638
+ status = {task['id']: task['status'] for task in tasks}
639
+ running = [task for task in tasks if task['status'] == 'RUNNING']
640
+ for task in tasks:
641
+ task['waiting'] = None
642
+ if task['status'] in ('RUNNING', 'MERGED'):
643
+ continue
644
+ stop = _escalation_stop(reader, task['id'])
645
+ if stop is not None:
646
+ task['waiting'] = stop
647
+ continue
648
+ if not scheduler['live'] or task['status'] not in ('PENDING', 'INFRA'):
649
+ continue
650
+ pause = next((p for p in scheduler['pauses'] if p['scope'] == 'all' or task['id'] in (p['tasks'] or [])), None)
651
+ if pause is not None:
652
+ task['waiting'] = dict(pause, kind='infra')
653
+ continue
654
+ if task['status'] != 'PENDING':
655
+ continue
656
+ on = [dep for dep in task['deps'] if status.get(dep) != 'MERGED']
657
+ if on:
658
+ task['waiting'] = dict(kind='deps', on=on, stopped=[dep for dep in on if status.get(dep) in _STOPPED])
659
+ elif scheduler['stopping']:
660
+ task['waiting'] = dict(kind='stopping', mode=scheduler['stopping'])
661
+ elif scheduler['drained']:
662
+ task['waiting'] = dict(kind='drained')
663
+ else:
664
+ mine = [_scope(path) for path in task['files'] if path and path != '-']
665
+ shared = [other['id'] for other in running if _overlap(mine, [_scope(p) for p in other['files'] if p and p != '-'])]
666
+ cap = scheduler['max_parallel']
667
+ if shared:
668
+ task['waiting'] = dict(kind='overlap', on=shared)
669
+ elif cap is not None and len(running) >= cap:
670
+ task['waiting'] = dict(kind='slot', running=len(running), max_parallel=cap)
671
+ else:
672
+ task['waiting'] = dict(kind='next')
673
+
674
+
547
675
  def _task_detail(reader, task, run_id, waves, branches):
548
676
  """Fill in a plan task; returns every execution it read (its own and its shadows')."""
549
677
  ident = task['id']
@@ -586,12 +714,15 @@ def _task_detail(reader, task, run_id, waves, branches):
586
714
  task['clef']['retry_pass'][suffix] = obj
587
715
  execs = _task_execs(reader, task)
588
716
  task['executions'] = execs
717
+ task['now'] = _now(reader, prefix, execs) if task['status'] == 'RUNNING' else None
589
718
  merged = reader.stat(prefix + '/merged') if task['status'] == 'MERGED' else None
590
719
  task['merged_at'] = float(merged.st_mtime) if merged is not None else None
591
720
  task['findings'] = executions.summary_of(qa)
592
721
  task['gate'] = _gate(reader, prefix + '/qa.gate')
593
722
  task['known_issues'] = _nonempty(reader, prefix + '/known_issues.md')
594
723
  task['fail_first'] = _fail_first(reader, prefix + '/failfirst.json')
724
+ task['sweep'] = _sweep_task(reader, prefix, task['status'])
725
+ task['swept'] = []
595
726
  shadows = _shadows(reader, ident, execs)
596
727
  task['shadow'] = [entry for entry, _, _ in shadows]
597
728
  # What `forge control show` reads of the task. A change there (a write, or a delete: the dir's mtime) moves `updated`,
@@ -602,9 +733,79 @@ def _task_detail(reader, task, run_id, waves, branches):
602
733
  return execs + [item for _, items, _ in shadows for item in items]
603
734
 
604
735
 
736
+ # --- the finding sweep (run --sweep): its plan, each fix task's findings and what became of them ------------------
737
+
738
+ _MAX_SWEEP = 200
739
+ _SWEEP_STATES = ('fixed', 'not-fixed', 'unreported')
740
+
741
+
742
+ def _text_or_none(value, size=400):
743
+ return value[:size] if isinstance(value, str) and value else None
744
+
745
+
746
+ def _sweep_task(reader, prefix, status):
747
+ """A fix task's file and findings: each with what its review said (fixed, not-fixed, or unreported when the
748
+ task merged without a line for it), or None while the task has not merged; None for any other task."""
749
+ obj = reader.object(prefix + '/sweep.json')
750
+ if obj is None or not isinstance(obj.get('findings'), list):
751
+ return None
752
+ said = {}
753
+ if status == 'MERGED':
754
+ for item in list((reader.object(prefix + '/sweep.outcome.json') or {}).get('findings') or []):
755
+ if isinstance(item, dict) and item.get('status') in _SWEEP_STATES and isinstance(item.get('id'), str):
756
+ said[item['id']] = (item['status'], _text_or_none(item.get('note')))
757
+ found = []
758
+ for item in obj['findings'][:_MAX_SWEEP]:
759
+ if not isinstance(item, dict) or not isinstance(item.get('id'), str):
760
+ continue
761
+ state, note = said.get(item['id'], ('unreported' if status == 'MERGED' else None, None))
762
+ found.append(dict(id=item['id'], severity=_text_or_none(item.get('severity'), 8),
763
+ confidence=_text_or_none(item.get('confidence'), 16), task=_text_or_none(item.get('task'), 200),
764
+ location=_text_or_none(item.get('location')),
765
+ summary=_text_or_none((item.get('text') or '').split('\n')[0] if isinstance(item.get('text'), str) else None),
766
+ status=state, note=note))
767
+ return dict(file=_text_or_none(obj.get('file')), findings=found)
768
+
769
+
770
+ def _sweep(reader, tasks):
771
+ """RunDetail.sweep: the run's finding sweep, from sweep/plan.json and its fix tasks; None when it was never
772
+ swept. Also fills each source task's `swept`: its findings a fix task took, and what became of them."""
773
+ by_id = {task['id']: task for task in tasks}
774
+ fix = [task for task in tasks if task.get('sweep')]
775
+ for task in fix:
776
+ for item in task['sweep']['findings']:
777
+ source = by_id.get(item['task'])
778
+ if source is not None and len(source['swept']) < _MAX_SWEEP:
779
+ source['swept'].append(dict(item, by=task['id']))
780
+ obj = reader.object('sweep/plan.json')
781
+ if obj is None:
782
+ return None
783
+ found = [item for task in fix for item in task['sweep']['findings']]
784
+ dropped = []
785
+ for item in list(obj.get('dropped') or [])[:_MAX_SWEEP]:
786
+ if not isinstance(item, dict):
787
+ continue
788
+ line = item.get('line') if isinstance(item.get('line'), int) and not isinstance(item.get('line'), bool) else None
789
+ where = _text_or_none(item.get('file'))
790
+ detail = item.get('detail') if isinstance(item.get('detail'), dict) else {}
791
+ dropped.append(dict(task=_text_or_none(item.get('task'), 200), severity=_text_or_none(item.get('severity'), 8),
792
+ location=f'{where}:{line}' if where and line else where,
793
+ summary=_text_or_none((item.get('text') or '').split('\n')[0] if isinstance(item.get('text'), str) else None),
794
+ reason=_text_or_none(item.get('reason'), 40),
795
+ merged_since=[x for x in list(detail.get('merged_since') or []) if isinstance(x, str)][:20]))
796
+ at = obj.get('at')
797
+ return dict(at=float(at) if isinstance(at, (int, float)) and not isinstance(at, bool) else None,
798
+ severity=_text_or_none(obj.get('severity'), 8), plausible=obj.get('plausible') is True,
799
+ tasks=[task['id'] for task in fix], findings=len(found),
800
+ fixed=sum(1 for item in found if item['status'] == 'fixed'), dropped=dropped)
801
+
802
+
605
803
  # The control files (CONTRACT.md) nothing else here reads. `forge control` appends control.log and writes the task's
606
804
  # files without touching the run dir, so they are stat'd for `updated` only.
607
- _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget')
805
+ # Read only for their mtimes, so the run's `updated` stamp moves when a control changes.
806
+ # control.requests is a directory: its mtime moves when a request is queued or settled.
807
+ _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused',
808
+ 'infra_backoff', 'escalate_effort', 'control.requests')
608
809
  _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next')
609
810
 
610
811
 
@@ -797,21 +998,210 @@ def _final_review(reader, item, newest, published):
797
998
 
798
999
 
799
1000
  def _verification_runs(reader):
1001
+ """6 columns from a single command, 8 (adding lane and started) from lanes."""
800
1002
  runs = []
801
1003
  for label, row in reader.rows('verification.runs.tsv', 6):
802
1004
  try:
1005
+ if len(row) not in (6, 8):
1006
+ raise ValueError()
803
1007
  n, duration = int(row[0]), float(row[4])
804
1008
  code = int(row[2]) if row[2].strip() else None
805
- if row[3].strip() not in ('0', '1') or not math.isfinite(duration):
1009
+ started = float(row[7]) if len(row) == 8 else None
1010
+ if row[3].strip() not in ('0', '1') or not math.isfinite(duration) \
1011
+ or (started is not None and not math.isfinite(started)):
806
1012
  raise ValueError()
807
1013
  except (ValueError, OverflowError):
808
1014
  reader.warn(label, 'invalid verification run')
809
1015
  continue
810
1016
  runs.append(dict(n=n, kind=row[1], exit=code, tree_changed=row[3].strip() == '1',
811
- duration_s=duration, log=row[5].strip() or None))
1017
+ duration_s=duration, log=row[5].strip() or None,
1018
+ lane=(row[6].strip() or None) if len(row) == 8 else None, started=started))
812
1019
  return runs
813
1020
 
814
1021
 
1022
+ # --- live verification and lanes -----------------------------------------------------------
1023
+
1024
+ _LANES_MAX = 4 << 20 # verification.lanes.json beyond this is not read
1025
+ _LIVE_TAIL = 65536 # what is read of a single-command log for its step and last line
1026
+ _FAILING_MAX = 200
1027
+ _LAST_LINE_MAX = 300
1028
+ _STEP = re.compile(r'::forge step name=(\S+) state=(start|end)(?: exit=(-?\d+))?')
1029
+ _ANSI = re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]')
1030
+ _LANE_STATES = ('waiting', 'running', 'pass', 'fail', 'flaky', 'known', 'skipped', 'interrupted')
1031
+
1032
+
1033
+ def _finite(value):
1034
+ return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) \
1035
+ and math.isfinite(value) else None
1036
+
1037
+
1038
+ def _str(value):
1039
+ return value if isinstance(value, str) else None
1040
+
1041
+
1042
+ def _last_line(text):
1043
+ for line in reversed((text or '').splitlines()):
1044
+ line = _ANSI.sub('', line).strip()
1045
+ if line:
1046
+ return line[:_LAST_LINE_MAX]
1047
+ return None
1048
+
1049
+
1050
+ def _open_step(text):
1051
+ """The last step marker started and not yet ended in the text, or None."""
1052
+ open_steps = []
1053
+ for line in (text or '').splitlines():
1054
+ match = _STEP.fullmatch(_ANSI.sub('', line).strip())
1055
+ if not match:
1056
+ continue
1057
+ if match.group(2) == 'start':
1058
+ open_steps.append(match.group(1))
1059
+ elif match.group(1) in open_steps:
1060
+ del open_steps[len(open_steps) - 1 - open_steps[::-1].index(match.group(1))]
1061
+ return open_steps[-1] if open_steps else None
1062
+
1063
+
1064
+ def _lanes_doc(reader):
1065
+ """(the lanes document, its stat) or (None, stat): a missing, oversized or invalid file
1066
+ is warned about and never fails the request."""
1067
+ name = 'verification.lanes.json'
1068
+ info = reader.stat(name)
1069
+ if info is None:
1070
+ return None, None
1071
+ if info.st_size > _LANES_MAX:
1072
+ reader.warn(name, 'larger than 4 MB, not read')
1073
+ return None, info
1074
+ doc = reader.object(name)
1075
+ if doc is not None and not isinstance(doc.get('lanes'), list):
1076
+ reader.warn(name, 'no lanes list')
1077
+ doc = None
1078
+ return doc, info
1079
+
1080
+
1081
+ def _items(value):
1082
+ """A JSON list, or nothing in place of anything else."""
1083
+ return value if isinstance(value, list) else []
1084
+
1085
+
1086
+ def _tests(reader, value, field):
1087
+ if not isinstance(value, dict):
1088
+ return None
1089
+ counts = {key: int(value[key]) if isinstance(value.get(key), int) and not isinstance(value.get(key), bool)
1090
+ else 0 for key in ('pass', 'fail', 'skip', 'error')}
1091
+ failing = []
1092
+ for entry in value.get('failing') if isinstance(value.get('failing'), list) else []:
1093
+ if not isinstance(entry, dict) or len(failing) >= _FAILING_MAX:
1094
+ continue
1095
+ line = entry.get('log_line')
1096
+ failing.append(dict(name=reader.cap(_str(entry.get('name')), field + '.name', 500),
1097
+ suite=_str(entry.get('suite')), file=_str(entry.get('file')),
1098
+ message=reader.cap(_str(entry.get('message')), field + '.message', 500),
1099
+ excerpt=reader.cap(_str(entry.get('excerpt')), field + '.excerpt', 2000),
1100
+ known=entry.get('known') is True,
1101
+ log_line=line if isinstance(line, int) and not isinstance(line, bool) and line > 0 else None))
1102
+ return dict(counts, failing=failing,
1103
+ reports=[r for r in _items(value.get('reports')) if isinstance(r, str)][:200],
1104
+ notes=[reader.cap(n, field + '.notes', 500) for n in _items(value.get('notes')) if isinstance(n, str)][:50],
1105
+ truncated=value.get('truncated') is True)
1106
+
1107
+
1108
+ def _lanes(reader, doc, now):
1109
+ lanes = []
1110
+ for index, lane in enumerate(doc['lanes']):
1111
+ if not isinstance(lane, dict) or not _str(lane.get('name')):
1112
+ reader.warn('verification.lanes.json', f'lane {index + 1} is not a lane')
1113
+ continue
1114
+ name = lane['name']
1115
+ started, ended = _finite(lane.get('started')), _finite(lane.get('ended'))
1116
+ state = lane.get('state') if lane.get('state') in _LANE_STATES else _str(lane.get('state'))
1117
+ last_output = _finite(lane.get('last_output_at'))
1118
+ step = lane.get('step') if isinstance(lane.get('step'), dict) else None
1119
+ runs = []
1120
+ for run in lane.get('runs') if isinstance(lane.get('runs'), list) else []:
1121
+ if isinstance(run, dict):
1122
+ runs.append(dict(k=run.get('k') if isinstance(run.get('k'), int) else None, kind=_str(run.get('kind')),
1123
+ started=_finite(run.get('started')), ended=_finite(run.get('ended')),
1124
+ exit=run.get('exit') if isinstance(run.get('exit'), int) else None,
1125
+ log=_str(run.get('log'))))
1126
+ options = lane.get('options') if isinstance(lane.get('options'), dict) else {}
1127
+ lanes.append(dict(
1128
+ name=name, command=reader.cap(_str(lane.get('command')), f'verification.lanes.{name}.command'),
1129
+ group=_str(lane.get('group')), first=lane.get('first') is True,
1130
+ retries=options.get('retries') if isinstance(options.get('retries'), int) else None,
1131
+ options={k: v for k, v in options.items() if isinstance(v, (str, int)) and not isinstance(v, bool)},
1132
+ state=state, exit=lane.get('exit') if isinstance(lane.get('exit'), int) else None,
1133
+ started=started, ended=ended,
1134
+ duration_s=((ended if ended is not None else now) - started) if started is not None else None,
1135
+ runs=runs,
1136
+ step=dict(name=_str(step.get('name')), started=_finite(step.get('started'))) if step else None,
1137
+ last_line=reader.cap(_str(lane.get('last_line')), f'verification.lanes.{name}.last_line', _LAST_LINE_MAX),
1138
+ last_output_at=last_output,
1139
+ idle_s=(now - last_output) if state == 'running' and last_output is not None else None,
1140
+ log=_str(lane.get('log')),
1141
+ tests=_tests(reader, lane.get('tests'), f'verification.lanes.{name}.tests')))
1142
+ return lanes
1143
+
1144
+
1145
+ def _live_single(reader, started, now):
1146
+ """The running command's live state from whichever of its two logs moved last: a rerun
1147
+ writes verification.retry.log."""
1148
+ logs = [(info.st_mtime, name) for name in ('verification.log', 'verification.retry.log')
1149
+ for info in [reader.stat(name)] if info is not None]
1150
+ if not logs:
1151
+ return dict(started=started, step=None, last_line=None, last_output_at=None,
1152
+ idle_s=(now - started) if started is not None else None, log=None)
1153
+ mtime, name = max(logs)
1154
+ text = reader.text(name, _LIVE_TAIL)
1155
+ step = _open_step(text)
1156
+ return dict(started=started, step=dict(name=step, started=None) if step else None,
1157
+ last_line=_last_line(text), last_output_at=float(mtime), idle_s=max(0.0, now - mtime), log=name)
1158
+
1159
+
1160
+ def _live_lanes(lanes, started, now):
1161
+ """The running lane that printed most recently speaks for the verification."""
1162
+ running = [lane for lane in lanes if lane['state'] == 'running']
1163
+ printed = [lane for lane in running if lane['last_output_at'] is not None]
1164
+ lane = max(printed, key=lambda item: item['last_output_at']) if printed else (running[0] if running else None)
1165
+ last = lane['last_output_at'] if lane else None
1166
+ return dict(started=started, step=lane['step'] if lane else None, last_line=lane['last_line'] if lane else None,
1167
+ last_output_at=last, idle_s=max(0.0, now - (last if last is not None else started))
1168
+ if (last is not None or started is not None) else None, log=None)
1169
+
1170
+
1171
+ def _verification(reader, status, verifications):
1172
+ """RunDetail.verification: the result files, plus whether it is running now, in which
1173
+ mode, its live state, its lanes and every failing test."""
1174
+ now = time.time()
1175
+ newest = max(verifications, key=lambda item: (item['started'] is not None, item['started'] or 0.0), default=None)
1176
+ state = None if newest is None else 'running' if newest['state'] == 'running' else 'done'
1177
+ started = newest['started'] if newest is not None else None
1178
+ doc, info = _lanes_doc(reader)
1179
+ lanes_file = info is not None
1180
+ mode = 'lanes' if lanes_file and (started is None or info.st_mtime >= started) else 'single'
1181
+ command = reader.text('verification.command')
1182
+ log_tail = reader.cap(reader.text('verification.log', 65536), 'verification.log_tail', 4000, True)
1183
+ present = any('verification.' + suffix in reader.present_files for suffix in ('status', 'command', 'log'))
1184
+ if not (present or state or lanes_file):
1185
+ return None
1186
+ lanes = _lanes(reader, doc, now) if mode == 'lanes' and doc is not None else None
1187
+ if state == 'running':
1188
+ live = _live_lanes(lanes or [], started, now) if mode == 'lanes' else _live_single(reader, started, now)
1189
+ else:
1190
+ live = None
1191
+ failing = []
1192
+ for lane in lanes or []:
1193
+ for entry in (lane['tests'] or {}).get('failing', []):
1194
+ if len(failing) < _FAILING_MAX:
1195
+ failing.append(dict(entry, lane=lane['name']))
1196
+ runs = _verification_runs(reader)
1197
+ # A lane or a run of the command changed the checkout: later reruns were skipped.
1198
+ mutated = doc.get('mutated') is True if lanes is not None else any(run['tree_changed'] for run in runs)
1199
+ return dict(status='RUNNING' if state == 'running' else status,
1200
+ command=command.strip() if command is not None else None,
1201
+ log_tail=log_tail, runs=runs, commit=reader.line('verification.commit'),
1202
+ state=state, mode=mode, live=live, lanes=lanes, failing=failing, mutated=mutated)
1203
+
1204
+
815
1205
  def _integration(reader, tasks, integrations, reviews, published):
816
1206
  base, accepted = reader.line('integration.base'), reader.line('accepted.integration')
817
1207
  merged = sorted((dict(id=task['id'], at=task['merged_at']) for task in tasks if task['merged_at'] is not None),
@@ -868,9 +1258,11 @@ def _solo_detail(reader, source):
868
1258
  dwarf_tail=reader.cap(reader.text('dwarf.last'), 'tasks/solo/dwarf_tail', 4000, True),
869
1259
  executions=execs, merged_at=None, findings=executions.summary_of(qa),
870
1260
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
871
- fail_first=_fail_first(reader, 'failfirst.json'))
1261
+ fail_first=_fail_first(reader, 'failfirst.json'),
1262
+ now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[])
872
1263
  result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[],
873
- deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader))
1264
+ deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
1265
+ scheduler=None, sweep=None)
874
1266
  result.update(tasks=[task], warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
875
1267
  return result
876
1268
 
@@ -901,14 +1293,6 @@ def detail(path, source='plan') -> dict:
901
1293
  max_parallel=reader.number('max_parallel', int), qa_threshold=reader.line('qa_threshold'),
902
1294
  escalate_after=reader.number('escalate_after', int),
903
1295
  verify_retries=reader.number('verify_retries', int), final_qa=reader.line('final_qa'))
904
- command = reader.text('verification.command')
905
- verification = dict(status=result['verification_status'], command=command.strip() if command is not None else None,
906
- log_tail=reader.cap(reader.text('verification.log', 65536), 'verification.log_tail', 4000, True))
907
- if any('verification.' + suffix in reader.present_files for suffix in ('status', 'command', 'log')):
908
- verification.update(runs=_verification_runs(reader), commit=reader.line('verification.commit'))
909
- result['verification'] = verification
910
- else:
911
- result['verification'] = None
912
1296
  waves, wave_map = _waves(reader)
913
1297
  result['waves'] = [waves.get(n, []) for n in range(1, max(waves, default=0) + 1)]
914
1298
  branches = {row[0]: _nullable(row[2]) for _, row in reader.rows('results.tsv', 3)}
@@ -917,7 +1301,12 @@ def detail(path, source='plan') -> dict:
917
1301
  pool += _task_detail(reader, task, result['run_id'], wave_map, branches)
918
1302
  for name in _RUN_CONTROLS:
919
1303
  reader.stat(name)
1304
+ result['scheduler'] = _scheduler(reader)
1305
+ _waiting(reader, tasks, result['scheduler'])
1306
+ result['sweep'] = _sweep(reader, tasks)
920
1307
  run_execs = _run_execs(reader)
1308
+ result['verification'] = _verification(reader, result['verification_status'],
1309
+ [item for item in run_execs if item['role'] == 'verification'])
921
1310
  items, integrations = executions.review_dirs(reader)
922
1311
  published = _published(reader)
923
1312
  reviews = []
@@ -1077,16 +1466,7 @@ def execution_transcript(path, name, source='plan'):
1077
1466
  item, owner, owner_dir = found
1078
1467
  role, running = item['role'], item['state'] == 'running'
1079
1468
  # A finished execution's log is its copy; the owner dir's is the one being written, or the next one's.
1080
- rel = posixpath.join(owner_dir, role + '.log') if running else f'{item.rel}/{role}.log'
1081
- log = None
1082
- try:
1083
- real = Path(os.path.realpath(reader.path / rel))
1084
- if executions.inside(reader.path, str(real)) and stat.S_ISREG(real.stat().st_mode):
1085
- log = real
1086
- elif real.exists():
1087
- reader.warn(rel, 'outside the run dir or not a regular file')
1088
- except (OSError, ValueError):
1089
- pass
1469
+ log = _agent_log(reader, item, owner_dir)
1090
1470
  resolved = executions.resolved_of(reader, f'{item.rel}/{role}.resolved')
1091
1471
  if resolved is None and running:
1092
1472
  resolved = executions.parse_resolved(reader.text(posixpath.join(owner_dir, role + '.resolved'))) or None
@@ -1098,6 +1478,141 @@ def execution_transcript(path, name, source='plan'):
1098
1478
  return result
1099
1479
 
1100
1480
 
1481
+ def _agent_log(reader, item, owner_dir):
1482
+ """The log of a dwarf or reviewer execution: its copy once it ended, the one being written while it runs."""
1483
+ role = item['role']
1484
+ return _log_path(reader, posixpath.join(owner_dir, role + '.log') if item['state'] == 'running' else f'{item.rel}/{role}.log')
1485
+
1486
+
1487
+ def _checks_of(reader, item, owner_dir):
1488
+ """checks.analyze() of one dwarf or reviewer execution, with what it is and, while it runs, when its log moved."""
1489
+ log = _agent_log(reader, item, owner_dir)
1490
+ model = item['model'] or {}
1491
+ running = item['state'] == 'running'
1492
+ result = transcripts.transcript(log, model.get('harness'), running)
1493
+ found = checks.analyze(result['events'])
1494
+ moved = None
1495
+ if running and log is not None:
1496
+ try:
1497
+ moved = log.stat().st_mtime
1498
+ except OSError:
1499
+ pass
1500
+ found.update(execution=item['id'], role=item['role'], state=item['state'], attempt=item['attempt'],
1501
+ spec=model.get('spec'), harness=model.get('harness'), source=result['source'],
1502
+ truncated=result['truncated'], last_output_at=moved)
1503
+ return found
1504
+
1505
+
1506
+ def _brief_dir(kind, owner):
1507
+ """Where the brief of an execution's owner is, or None for a final review or a shadow."""
1508
+ if owner['kind'] == 'task':
1509
+ return '' if owner['id'] == 'solo' and kind == 'solo' else f"tasks/{owner['id']}"
1510
+ return None
1511
+
1512
+
1513
+ def execution_checks(path, name, source='plan'):
1514
+ """ExecutionChecks: the checks a dwarf or reviewer ran, the call it makes now, the environment problems it met
1515
+ and, for a task's execution, its brief's acceptance-criteria commands against them. None for another role."""
1516
+ reader = _Read(path)
1517
+ found = _execution(reader, name)
1518
+ if found is None or found[0]['role'] not in ('dwarf', 'qa'):
1519
+ return None
1520
+ item, owner, owner_dir = found
1521
+ result = _checks_of(reader, item, owner_dir)
1522
+ brief = _brief_dir(_kind(reader.path), owner)
1523
+ wanted = checks.criteria(reader.text(posixpath.join(brief, 'prompt.md'))) if brief is not None else []
1524
+ result.update(run=run_key(reader.path), owner=owner,
1525
+ criteria=checks.coverage(wanted, [(c['command'], dict(index=c['index'])) for c in result['checks']]),
1526
+ warnings=reader.warnings)
1527
+ return result
1528
+
1529
+
1530
+ def _owners(reader):
1531
+ """(task id, owner dir, executions) of each task of the run (the one `solo` of a solo run), or None."""
1532
+ kind = _kind(reader.path)
1533
+ if kind == 'solo':
1534
+ return [('solo', '', _solo_execs(reader, _solo_status(reader), _history(reader, 'attempts.tsv')))]
1535
+ if kind != 'plan':
1536
+ return None
1537
+ out = []
1538
+ for task in _tasks(reader):
1539
+ task['attempts'], task['attempt'] = _attempt_state(reader, f"tasks/{task['id']}")
1540
+ out.append((task['id'], f"tasks/{task['id']}", _task_execs(reader, task)))
1541
+ return out
1542
+
1543
+
1544
+ def task_checks(path, task_id, source='plan'):
1545
+ """TaskChecks: attempt by attempt, the checks each dwarf and reviewer ran, and which of the commands the task's
1546
+ acceptance criteria name ran, ran another way, or did not run."""
1547
+ reader = _Read(path)
1548
+ owners = _owners(reader)
1549
+ owner = next((item for item in owners or [] if item[0] == task_id), None)
1550
+ if owner is None:
1551
+ return None
1552
+ _, owner_dir, execs = owner
1553
+ wanted = checks.criteria(reader.text(posixpath.join(owner_dir, 'prompt.md')))
1554
+ by_attempt = {}
1555
+ for item in execs:
1556
+ if item['role'] in ('dwarf', 'qa') and not item['shadow']:
1557
+ by_attempt.setdefault(item['attempt'], []).append(_checks_of(reader, item, owner_dir))
1558
+ attempts = []
1559
+ for attempt in sorted(by_attempt, key=lambda value: (value is None, value or 0)):
1560
+ runs = by_attempt[attempt]
1561
+ ran = [(c['command'], dict(execution=r['execution'], role=r['role'], index=c['index'])) for r in runs for c in r['checks']]
1562
+ attempts.append(dict(attempt=attempt, running=any(r['state'] == 'running' for r in runs), executions=runs,
1563
+ criteria=checks.coverage(wanted, ran)))
1564
+ return dict(run=run_key(reader.path), task=task_id, criteria=wanted, attempts=attempts,
1565
+ truncated=reader.truncated, warnings=reader.warnings)
1566
+
1567
+
1568
+ _ENVIRONMENT_HITS = 50 # a problem's hits answered (its tasks are all named)
1569
+ _ENV_CACHE = executions._SigCache(4096)
1570
+
1571
+
1572
+ def _environment_of(reader, item, owner_dir):
1573
+ """The environment problems one execution's failed commands met, cached while its log is unchanged."""
1574
+ log = _agent_log(reader, item, owner_dir)
1575
+ if log is None:
1576
+ return []
1577
+ try:
1578
+ info = log.stat()
1579
+ except OSError:
1580
+ return []
1581
+ clock = log.with_name(log.stem + '.clock')
1582
+ sig = (executions._signature(info), item['state'], transcripts._signature(clock))
1583
+ hit = _ENV_CACHE.get(('environment', str(log)), sig)
1584
+ if hit is None:
1585
+ result = transcripts.transcript(log, (item['model'] or {}).get('harness'), item['state'] == 'running')
1586
+ hit = checks.analyze(result['events'])['environment']
1587
+ _ENV_CACHE.put(('environment', str(log)), sig, hit)
1588
+ return hit
1589
+
1590
+
1591
+ def run_environment(path, source='plan'):
1592
+ """RunEnvironment: each environment problem the run's dwarfs and reviewers met (Docker, a sandbox's EPERM, a
1593
+ port in use, …), with the tasks it hit and where: the commands that failed on it."""
1594
+ reader = _Read(path)
1595
+ owners = _owners(reader)
1596
+ if owners is None:
1597
+ return None
1598
+ found = {}
1599
+ for task_id, owner_dir, execs in owners:
1600
+ for item in execs:
1601
+ if item['role'] not in ('dwarf', 'qa'):
1602
+ continue
1603
+ for hit in _environment_of(reader, item, owner_dir):
1604
+ entry = found.setdefault(hit['problem'], dict(problem=hit['problem'], label=checks.LABELS[hit['problem']],
1605
+ tasks=[], count=0, hits=[]))
1606
+ entry['count'] += 1
1607
+ if task_id not in entry['tasks']:
1608
+ entry['tasks'].append(task_id)
1609
+ if len(entry['hits']) < _ENVIRONMENT_HITS:
1610
+ entry['hits'].append(dict(task=task_id, attempt=item['attempt'], role=item['role'], execution=item['id'],
1611
+ index=hit['index'], command=hit['command'], line=hit['line']))
1612
+ problems = [found[key] for key, _, _ in checks.ENVIRONMENT if key in found]
1613
+ return dict(run=run_key(reader.path), problems=problems, warnings=reader.warnings)
1614
+
1615
+
1101
1616
  def final_review_detail(path, name, source='plan'):
1102
1617
  """FinalReviewDetail of final-review-<e>-<p> or integrate-<e>-<p>, or None."""
1103
1618
  reader = _Read(path)
@@ -1549,6 +2064,112 @@ def fractal_node_diff(path, task_id, node, source='plan'):
1549
2064
  return _fractal(path, task_id, fractal.node_diff, node)
1550
2065
 
1551
2066
 
2067
+ # --- verification logs by path ---------------------------------------------------------------
2068
+
2069
+ LANE_NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}')
2070
+ LOG_TAIL = 65536 # the tail a log endpoint serves
2071
+ LOG_SCAN_MAX = 64 << 20 # what is read to number lines or reach a line range
2072
+ LOG_LINES = 400 # lines in one range
2073
+ LOG_LINE_MAX = 4000 # characters kept of one line in a range
2074
+
2075
+
2076
+ def _log_name(lane, k, retry=False):
2077
+ if retry:
2078
+ return 'verification.retry.log'
2079
+ if lane is None:
2080
+ return 'verification.log'
2081
+ return f'verification.lane.{lane}.log' if k is None else f'verification.lane.{lane}.run-{k}.log'
2082
+
2083
+
2084
+ def _open_log(path, name):
2085
+ """The open log and its stat, or None: a missing file, a symlink, anything not regular."""
2086
+ try:
2087
+ fd = os.open(os.path.join(os.path.realpath(path), name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
2088
+ except OSError:
2089
+ return None
2090
+ try:
2091
+ info = os.fstat(fd)
2092
+ if stat.S_ISREG(info.st_mode):
2093
+ return os.fdopen(fd, 'rb'), info
2094
+ except OSError:
2095
+ pass
2096
+ os.close(fd)
2097
+ return None
2098
+
2099
+
2100
+ def _newlines(stream, end):
2101
+ """How many newlines the first `end` bytes hold, or None past LOG_SCAN_MAX."""
2102
+ if end > LOG_SCAN_MAX:
2103
+ return None
2104
+ stream.seek(0)
2105
+ count = 0
2106
+ while end > 0:
2107
+ chunk = stream.read(min(1 << 20, end))
2108
+ if not chunk:
2109
+ break
2110
+ count += chunk.count(b'\n')
2111
+ end -= len(chunk)
2112
+ return count
2113
+
2114
+
2115
+ def _log_tail(stream, info, name):
2116
+ offset = max(0, info.st_size - LOG_TAIL)
2117
+ stream.seek(offset)
2118
+ raw = stream.read(LOG_TAIL)
2119
+ if offset:
2120
+ # Start on a line: drop the line the cut went through, or at least a split character.
2121
+ cut = raw.find(b'\n')
2122
+ skip = cut + 1 if cut >= 0 else 0
2123
+ if cut < 0:
2124
+ while skip < min(3, len(raw)) and raw[skip] & 0xC0 == 0x80:
2125
+ skip += 1
2126
+ raw, offset = raw[skip:], offset + skip
2127
+ before = _newlines(stream, offset)
2128
+ return dict(name=name, size=info.st_size, mtime=float(info.st_mtime), tail=raw.decode('utf-8', 'replace'),
2129
+ tail_first_line=None if before is None else before + 1, truncated=offset > 0)
2130
+
2131
+
2132
+ def _log_range(stream, info, name, first):
2133
+ """LOG_LINES lines from line `first`: (lines, whether more follow or a line or the read was cut)."""
2134
+ lines, number, read, cut = [], 1, 0, False
2135
+ while read < LOG_SCAN_MAX:
2136
+ part = stream.readline(LOG_LINE_MAX * 4)
2137
+ if not part:
2138
+ return dict(name=name, size=info.st_size, first_line=first, lines=lines, truncated=cut)
2139
+ read += len(part)
2140
+ line, long = part, False
2141
+ while not part.endswith(b'\n') and len(part) == LOG_LINE_MAX * 4 and read < LOG_SCAN_MAX:
2142
+ part, long = stream.readline(LOG_LINE_MAX * 4), True
2143
+ read += len(part)
2144
+ if number >= first:
2145
+ if len(lines) == LOG_LINES:
2146
+ return dict(name=name, size=info.st_size, first_line=first, lines=lines, truncated=True)
2147
+ text = line.rstrip(b'\n').rstrip(b'\r').decode('utf-8', 'replace')
2148
+ if long or len(text) > LOG_LINE_MAX:
2149
+ text, cut = text[:LOG_LINE_MAX].rstrip('\ufffd') + '…', True
2150
+ lines.append(text)
2151
+ number += 1
2152
+ return dict(name=name, size=info.st_size, first_line=first, lines=lines, truncated=True)
2153
+
2154
+
2155
+ def verification_log(path, lane=None, k=None, first=None, retry=False, source='plan'):
2156
+ """The run's own verification log (with `retry`, its rerun's), a lane's or one run of a lane's:
2157
+ its last 64 KB from a line start, with that line's number, or LOG_LINES lines from line `first`.
2158
+ None (a 404) for a solo run, a name no lane can have, and a log that is missing, a symlink or
2159
+ not a regular file."""
2160
+ if _kind(path) != 'plan' or (lane is not None and not LANE_NAME.fullmatch(lane)):
2161
+ return None
2162
+ if (k is not None and (lane is None or k < 1)) or (first is not None and first < 1) or (retry and lane is not None):
2163
+ return None
2164
+ name = _log_name(lane, k, retry)
2165
+ opened = _open_log(path, name)
2166
+ if opened is None:
2167
+ return None
2168
+ stream, info = opened
2169
+ with stream:
2170
+ return _log_tail(stream, info, name) if first is None else _log_range(stream, info, name, first)
2171
+
2172
+
1552
2173
  class Catalog:
1553
2174
  def __init__(self, plans=(), roots=(), registry=True, registry_dir=None):
1554
2175
  self.options = dict(plans=tuple(plans), roots=tuple(roots), registry=registry, registry_dir=registry_dir)
@@ -1599,6 +2220,15 @@ class Catalog:
1599
2220
  def transcript(self, key, name):
1600
2221
  return self._find(key, execution_transcript, name)
1601
2222
 
2223
+ def execution_checks(self, key, name):
2224
+ return self._find(key, execution_checks, name)
2225
+
2226
+ def task_checks(self, key, task_id):
2227
+ return self._find(key, task_checks, task_id)
2228
+
2229
+ def environment(self, key):
2230
+ return self._find(key, run_environment)
2231
+
1602
2232
  def final_review_diff(self, key, name):
1603
2233
  return self._find(key, final_review_diff, name)
1604
2234
 
@@ -1617,6 +2247,9 @@ class Catalog:
1617
2247
  def fractal_node_diff(self, key, task_id, node):
1618
2248
  return self._find(key, fractal_node_diff, task_id, node)
1619
2249
 
2250
+ def verification_log(self, key, lane=None, k=None, first=None, retry=False):
2251
+ return self._find(key, verification_log, lane, k, first, retry)
2252
+
1620
2253
  def models(self):
1621
2254
  from forge_ui import models # it reads runs through this module
1622
2255
  return models.collect(discover(**self.options))