@giamme/forge 0.17.0 → 0.18.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 (76) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +5 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/safety.md +8 -0
  11. package/forge +24 -1
  12. package/package.json +1 -1
  13. package/references/dataset.md +19 -0
  14. package/references/decompose.md +134 -1
  15. package/references/solo.md +2 -1
  16. package/references/ui.md +5 -2
  17. package/scripts/forge-artifact.sh +14 -0
  18. package/scripts/forge-brief.py +132 -0
  19. package/scripts/forge-compare.py +11 -1
  20. package/scripts/forge-config.py +176 -9
  21. package/scripts/forge-contract.py +46 -3
  22. package/scripts/forge-control.py +86 -13
  23. package/scripts/forge-dispatch.sh +14 -10
  24. package/scripts/forge-du.py +167 -0
  25. package/scripts/forge-lib-adopt.sh +1 -0
  26. package/scripts/forge-lib-plans.sh +5 -2
  27. package/scripts/forge-lib-review.sh +29 -1
  28. package/scripts/forge-metrics.sh +7 -3
  29. package/scripts/forge-parallel-options.sh +4 -0
  30. package/scripts/forge-parallel.sh +503 -9
  31. package/scripts/forge-prompt.py +120 -0
  32. package/scripts/forge-retro.py +115 -0
  33. package/scripts/forge-runs-compact.py +443 -0
  34. package/scripts/forge-runs-rm.py +2 -0
  35. package/scripts/forge-runs.py +18 -3
  36. package/scripts/forge-schedule.py +279 -4
  37. package/scripts/forge-shadow.py +7 -1
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-summarize.py +698 -0
  40. package/scripts/forge-ui-options.sh +10 -0
  41. package/scripts/forge_brief/__init__.py +587 -0
  42. package/scripts/forge_brief/answers.py +459 -0
  43. package/scripts/forge_dataset/__init__.py +10 -0
  44. package/scripts/forge_dataset/export.py +18 -4
  45. package/scripts/forge_dataset/facts.py +6 -4
  46. package/scripts/forge_dataset/harvest.py +40 -6
  47. package/scripts/forge_dataset/history.py +5 -3
  48. package/scripts/forge_decide/__init__.py +11 -1
  49. package/scripts/forge_locations.py +366 -0
  50. package/scripts/forge_registry.py +19 -0
  51. package/scripts/forge_retro/__init__.py +417 -0
  52. package/scripts/forge_retro/issues.py +1193 -0
  53. package/scripts/forge_retro/report.py +671 -0
  54. package/scripts/forge_side/__init__.py +477 -0
  55. package/scripts/forge_storage.py +515 -0
  56. package/ui/README.md +68 -8
  57. package/ui/docs/api.md +205 -17
  58. package/ui/forge_ui/control.py +92 -11
  59. package/ui/forge_ui/export.py +24 -5
  60. package/ui/forge_ui/links.py +337 -0
  61. package/ui/forge_ui/models.py +57 -4
  62. package/ui/forge_ui/projects.py +4 -1
  63. package/ui/forge_ui/reader.py +661 -30
  64. package/ui/forge_ui/static/app.js +86 -4
  65. package/ui/forge_ui/static/briefview.js +302 -0
  66. package/ui/forge_ui/static/checksview.js +6 -2
  67. package/ui/forge_ui/static/controls.js +5 -0
  68. package/ui/forge_ui/static/index.html +3 -0
  69. package/ui/forge_ui/static/panel.js +268 -2
  70. package/ui/forge_ui/static/runmodel.js +13 -1
  71. package/ui/forge_ui/static/storageview.js +271 -0
  72. package/ui/forge_ui/static/style.css +99 -3
  73. package/ui/forge_ui/static/worktreesview.js +3 -3
  74. package/ui/forge_ui/storage.py +136 -0
  75. package/ui/forge_ui/transcripts.py +35 -10
  76. 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, links, repos, transcripts
17
18
  from forge_ui.findings import verdict as _verdict
18
19
 
19
20
 
@@ -425,9 +426,43 @@ def summarize(path, source='plan') -> dict:
425
426
  return _summary(reader, source)[0]
426
427
 
427
428
 
429
+ def _attempt_log(reader, name):
430
+ """attempts.tsv rows, oldest first, including the dwarf column the public attempt omits.
431
+
432
+ The public attempt stays `{at, attempt, status, infra}`: callers compare that dict exactly.
433
+ """
434
+ result = []
435
+ for label, row in reader.rows(name, 3):
436
+ try:
437
+ at, attempt = float(row[0]), int(row[1])
438
+ if not math.isfinite(at):
439
+ raise ValueError()
440
+ except (ValueError, OverflowError):
441
+ reader.warn(label, 'invalid epoch or attempt')
442
+ continue
443
+ dwarf = row[4].strip() if len(row) > 4 else ''
444
+ result.append(dict(at=at, attempt=attempt, status=row[2],
445
+ infra=_nullable(row[3]) if len(row) > 3 else None, dwarf=_nullable(dwarf)))
446
+ return result
447
+
448
+
449
+ def _public_attempt(row):
450
+ return dict(at=row['at'], attempt=row['attempt'], status=row['status'], infra=row['infra'])
451
+
452
+
453
+ def _attempt_view(reader, name, number_file):
454
+ rows = _attempt_log(reader, name)
455
+ attempt = reader.number(number_file, int) if number_file else None
456
+ if attempt is None:
457
+ attempt = max((item['attempt'] for item in rows), default=None)
458
+ return rows, attempt
459
+
460
+
428
461
  def _history(reader, name, escalation=False):
462
+ if not escalation:
463
+ return [_public_attempt(row) for row in _attempt_log(reader, name)]
429
464
  result = []
430
- for label, row in reader.rows(name, 4 if escalation else 3):
465
+ for label, row in reader.rows(name, 4):
431
466
  try:
432
467
  at, attempt = float(row[0]), int(row[1])
433
468
  if not math.isfinite(at):
@@ -435,23 +470,15 @@ def _history(reader, name, escalation=False):
435
470
  except (ValueError, OverflowError):
436
471
  reader.warn(label, 'invalid epoch or attempt')
437
472
  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)
473
+ # the 5th column says who decided (policy, a human's retry --dwarf, a pin); older rows have 4
474
+ source = row[4].strip() if len(row) > 4 else ''
475
+ result.append(dict(at=at, attempt=attempt, **{'from': row[2], 'to': row[3], 'source': source or 'policy'}))
446
476
  return result
447
477
 
448
478
 
449
479
  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
480
+ rows, attempt = _attempt_view(reader, prefix + '/attempts.tsv', prefix + '/attempt')
481
+ return [_public_attempt(row) for row in rows], attempt
455
482
 
456
483
 
457
484
  def _gate(reader, name):
@@ -808,12 +835,42 @@ def _attempt_cap(max_attempts, decisions):
808
835
  return max_attempts + sum(_grant(item['choice']) for item in decisions)
809
836
 
810
837
 
838
+ def _brief_writer_alive(reader):
839
+ """brief.pid names a running process: the question writer `run` started has not finished."""
840
+ try:
841
+ pid = int((reader.text('brief.pid') or '').split()[0])
842
+ if pid > 0:
843
+ os.kill(pid, 0)
844
+ return True
845
+ except PermissionError:
846
+ return True
847
+ except (OSError, ValueError, IndexError):
848
+ pass
849
+ return False
850
+
851
+
852
+ def _brief_wait(reader, ident):
853
+ """Why a gated plan holds this task, as forge-schedule.py tells it: the ids of its must_answer questions that
854
+ have no entry in brief.answers.json, or `[]` when it has no brief.json yet and the writer still runs.
855
+ None for any other level, or when nothing holds it."""
856
+ if reader.word('brief') != 'gated':
857
+ return None
858
+ brief = reader.object(f'tasks/{ident}/brief.json')
859
+ if brief is None:
860
+ return [] if not reader.exists(f'tasks/{ident}/brief.json') and _brief_writer_alive(reader) else None
861
+ answers = reader.object(f'tasks/{ident}/brief.answers.json') or {}
862
+ asked = [q['id'] for q in brief.get('questions') or [] if isinstance(q, dict) and q.get('must_answer') is True
863
+ and isinstance(q.get('id'), str) and q['id'] and q['id'] not in answers]
864
+ return asked or None
865
+
866
+
811
867
  def _waiting(reader, tasks, scheduler):
812
868
  """Task.waiting: why a task that is not running is not, as far as the run dir tells.
813
869
 
814
870
  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)."""
871
+ holds it), deps (on tasks not merged yet), drained, stopping, brief (a gated plan waits for your answer),
872
+ overlap (it shares files with a running task), slot (the run is at its capacity) or next (nothing holds it:
873
+ it starts at the scheduler's next turn)."""
817
874
  status = {task['id']: task['status'] for task in tasks}
818
875
  running = [task for task in tasks if task['status'] == 'RUNNING']
819
876
  for task in tasks:
@@ -839,6 +896,8 @@ def _waiting(reader, tasks, scheduler):
839
896
  task['waiting'] = dict(kind='stopping', mode=scheduler['stopping'])
840
897
  elif scheduler['drained']:
841
898
  task['waiting'] = dict(kind='drained')
899
+ elif (asked := _brief_wait(reader, task['id'])) is not None:
900
+ task['waiting'] = dict(kind='brief', questions=asked)
842
901
  else:
843
902
  mine = [_scope(path) for path in task['files'] if path and path != '-']
844
903
  shared = [other['id'] for other in running if _overlap(mine, [_scope(p) for p in other['files'] if p and p != '-'])]
@@ -851,7 +910,517 @@ def _waiting(reader, tasks, scheduler):
851
910
  task['waiting'] = dict(kind='next')
852
911
 
853
912
 
854
- def _task_detail(reader, task, run_id, waves, branches, max_attempts):
913
+ # The first paragraph of a task's approach (else its prompt), after the markdown title.
914
+ _GOAL_CAP = 600
915
+ _ATX = re.compile(r'^[ ]{0,3}#{1,6}(?:[ \t]|$)')
916
+ _CRITERIA = re.compile(r'^## Acceptance criteria[ \t]*:?[ \t]*$')
917
+ _FENCE = re.compile(r'^( {0,3})(`{3,}|~{3,})(.*)$')
918
+ # retry_sources.tsv sources. Anything else is warned and skipped; the last known row for an attempt wins.
919
+ _RETRY_SOURCES = frozenset(('review', 'prereview', 'bounce', 'message', 'answer'))
920
+ _DATASET = None
921
+
922
+
923
+ def _open_fence(line):
924
+ match = _FENCE.match(line)
925
+ if match is None:
926
+ return None
927
+ mark, info = match.group(2), match.group(3)
928
+ if mark[0] == '`' and '`' in info:
929
+ return None
930
+ return mark[0], len(mark)
931
+
932
+
933
+ def _close_fence(line, opened):
934
+ match = _FENCE.match(line)
935
+ if match is None:
936
+ return False
937
+ mark, info = match.group(2), match.group(3)
938
+ return mark[0] == opened[0] and len(mark) >= opened[1] and not info.strip()
939
+
940
+
941
+ _IMAGE = re.compile(r'!\[([^\[\]]*)\]\([^)]*\)')
942
+ _LINK = re.compile(r'\[([^\[\]]*)\]\([^)]*\)')
943
+ # A marker inside a word (`2*3*4`) is not emphasis. Underscores are left as written.
944
+ _STRONG = re.compile(r'(?<!\w)\*\*([^*]+)\*\*(?!\w)')
945
+ _EM = re.compile(r'(?<!\w)\*(?!\*)(\S(?:[^*]*?\S)?)\*(?!\w)')
946
+ _STRIKE = re.compile(r'(?<!\w)~~([^~]+)~~(?!\w)')
947
+
948
+
949
+ def _hold_code(text):
950
+ """Replace inline code spans with placeholders. Return `(text, contents)`.
951
+
952
+ Contents keep their characters and lose the backticks. A span that starts and ends
953
+ with a space, and is not all spaces, loses one space on each side.
954
+ """
955
+ pieces, held = [], []
956
+ index, size = 0, len(text)
957
+ while index < size:
958
+ if text[index] != '`':
959
+ pieces.append(text[index])
960
+ index += 1
961
+ continue
962
+ end = index
963
+ while end < size and text[end] == '`':
964
+ end += 1
965
+ length, cursor, close = end - index, end, None
966
+ while cursor < size:
967
+ if text[cursor] != '`':
968
+ cursor += 1
969
+ continue
970
+ run = cursor
971
+ while run < size and text[run] == '`':
972
+ run += 1
973
+ if run - cursor == length:
974
+ close = run
975
+ break
976
+ cursor = run
977
+ if close is None:
978
+ pieces.append(text[index:end])
979
+ index = end
980
+ continue
981
+ interior = text[end:close - length]
982
+ if len(interior) >= 2 and interior[0] == ' ' and interior[-1] == ' ' and interior.strip(' '):
983
+ interior = interior[1:-1]
984
+ held.append(interior)
985
+ pieces.append(f'\ue000{len(held) - 1}\ue000')
986
+ index = close
987
+ return ''.join(pieces), held
988
+
989
+
990
+ def _plain_inline(text):
991
+ """Drop inline markdown. Code-span contents stay literal, and underscores stay."""
992
+ held_text, held = _hold_code(text)
993
+ plain = _IMAGE.sub(r'\1', held_text)
994
+ plain = _LINK.sub(r'\1', plain)
995
+ plain = _STRONG.sub(r'\1', plain)
996
+ plain = _EM.sub(r'\1', plain)
997
+ plain = _STRIKE.sub(r'\1', plain)
998
+ for index, interior in enumerate(held):
999
+ plain = plain.replace(f'\ue000{index}\ue000', interior)
1000
+ return plain
1001
+
1002
+
1003
+ def _goal_text(text):
1004
+ """The first prose paragraph after an optional `# ` title, as plain text, or None."""
1005
+ if not text:
1006
+ return None
1007
+ lines, index = text.splitlines(), 0
1008
+ while index < len(lines) and not lines[index].strip():
1009
+ index += 1
1010
+ if index < len(lines) and lines[index].startswith('# '):
1011
+ index += 1
1012
+ while index < len(lines) and (not lines[index].strip() or _ATX.match(lines[index])):
1013
+ index += 1
1014
+ paragraph = []
1015
+ while index < len(lines) and lines[index].strip() and not _ATX.match(lines[index]):
1016
+ paragraph.append(lines[index].strip())
1017
+ index += 1
1018
+ if not paragraph:
1019
+ return None
1020
+ return re.sub(r'\s+', ' ', _plain_inline('\n'.join(paragraph))).strip() or None
1021
+
1022
+
1023
+ def _criteria_text(text):
1024
+ """prompt.md's `## Acceptance criteria` section, up to the next `## ` heading, or None.
1025
+
1026
+ A fenced `## ` does not end the section, and a `### ` subsection stays inside it.
1027
+ """
1028
+ if not text:
1029
+ return None
1030
+ fence, started, body = None, False, []
1031
+ for line in text.splitlines():
1032
+ if fence is not None:
1033
+ if started:
1034
+ body.append(line)
1035
+ if _close_fence(line, fence):
1036
+ fence = None
1037
+ continue
1038
+ opened = _open_fence(line)
1039
+ if opened is not None:
1040
+ fence = opened
1041
+ if started:
1042
+ body.append(line)
1043
+ continue
1044
+ if not started:
1045
+ started = _CRITERIA.match(line) is not None
1046
+ continue
1047
+ if line.startswith('## '):
1048
+ break
1049
+ body.append(line)
1050
+ if not started:
1051
+ return None
1052
+ return '\n'.join(body).strip() or None
1053
+
1054
+
1055
+ def _forge_dataset():
1056
+ """forge_dataset, loaded from scripts/, or None when it cannot be imported. Cached.
1057
+
1058
+ scripts/ is on the path only while that import runs.
1059
+ """
1060
+ global _DATASET
1061
+ if _DATASET is False:
1062
+ return None
1063
+ if _DATASET is not None:
1064
+ return _DATASET
1065
+ scripts = str(Path(__file__).resolve().parents[2] / 'scripts')
1066
+ inserted = scripts not in sys.path
1067
+ if inserted:
1068
+ sys.path.insert(0, scripts)
1069
+ try:
1070
+ import forge_dataset
1071
+ except Exception:
1072
+ _DATASET = False
1073
+ return None
1074
+ finally:
1075
+ if inserted and scripts in sys.path:
1076
+ sys.path.remove(scripts)
1077
+ _DATASET = forge_dataset
1078
+ return _DATASET
1079
+
1080
+
1081
+ def _github_origin(reader):
1082
+ """The run repo's origin URL, from the plan's `repo` file then `.git/config`. No git, no network.
1083
+
1084
+ A missing config is not a warning: `#N` then has a null url.
1085
+ """
1086
+ repo = reader.line('repo')
1087
+ module = _forge_dataset() if repo else None
1088
+ if module is None:
1089
+ return None
1090
+ try:
1091
+ return module.git_origin(repo)
1092
+ except Exception:
1093
+ return None
1094
+
1095
+
1096
+ def _header(reader, title, prompt, approach, request, field, origin):
1097
+ """`{title, goal, criteria, links}` from the raw prompt, approach and request texts."""
1098
+ goal = _goal_text(approach)
1099
+ if goal is None:
1100
+ goal = _goal_text(prompt)
1101
+ found, seen = [], set()
1102
+ for name, text in (('prompt.md', prompt), ('approach.md', approach), ('request.md', request)):
1103
+ if not text:
1104
+ continue
1105
+ for item in links.extract(text, name, origin):
1106
+ key = (item['kind'], item['number'], item['url'])
1107
+ if key in seen:
1108
+ continue
1109
+ seen.add(key)
1110
+ found.append(item)
1111
+ return dict(title=title, goal=reader.cap(goal, field + '/goal', _GOAL_CAP),
1112
+ criteria=reader.cap(_criteria_text(prompt), field + '/criteria'), links=found)
1113
+
1114
+
1115
+ def _retry_sources(reader, name):
1116
+ """`{attempt: source}` from retry_sources.tsv. The last known source for an attempt wins."""
1117
+ found = {}
1118
+ for label, row in reader.rows(name, 3):
1119
+ try:
1120
+ attempt = int(row[0])
1121
+ except ValueError:
1122
+ reader.warn(label, 'invalid attempt')
1123
+ continue
1124
+ source = row[1].strip()
1125
+ if source not in _RETRY_SOURCES:
1126
+ reader.warn(label, 'unknown retry source')
1127
+ continue
1128
+ found[attempt] = source
1129
+ return found
1130
+
1131
+
1132
+ def _queued_retries(reader):
1133
+ """`{task: [epoch, ...]}` of control.log lines that queued a retry.
1134
+
1135
+ A scheduler settlement carries `outcome` and actor `scheduler`; it is not the queue.
1136
+ A line that is not JSON is skipped, with no warning.
1137
+ """
1138
+ found = {}
1139
+ for line in (reader.text('control.log') or '').splitlines():
1140
+ if not line.strip():
1141
+ continue
1142
+ try:
1143
+ obj = json.loads(line)
1144
+ except (ValueError, RecursionError):
1145
+ continue
1146
+ if not isinstance(obj, dict) or obj.get('action') != 'retry':
1147
+ continue
1148
+ if obj.get('outcome') or obj.get('actor') == 'scheduler':
1149
+ continue
1150
+ task, at = obj.get('task'), obj.get('at')
1151
+ if not isinstance(task, str) or not task:
1152
+ continue
1153
+ if isinstance(at, bool) or not isinstance(at, (int, float)) or not math.isfinite(at):
1154
+ continue
1155
+ found.setdefault(task, []).append(float(at))
1156
+ return found
1157
+
1158
+
1159
+ def _manual_indexes(rows, times):
1160
+ """Row indexes a queued retry explains.
1161
+
1162
+ attempts.tsv is written when the attempt ends, so the queue explains the next attempt:
1163
+ the first row that is not attempt 1 and whose end is at or after the queue, plus later
1164
+ rows of that same attempt number that also end then. An earlier row of the same number,
1165
+ already finished before the queue, is not that retry.
1166
+ """
1167
+ found = set()
1168
+ for moment in times:
1169
+ chosen = None
1170
+ for index, row in enumerate(rows):
1171
+ if row['attempt'] == 1 or row['at'] < moment:
1172
+ continue
1173
+ if chosen is None:
1174
+ chosen = row['attempt']
1175
+ if row['attempt'] == chosen:
1176
+ found.add(index)
1177
+ return found
1178
+
1179
+
1180
+ def _attempt_reason(index, row, rows, sources, escalations, manual):
1181
+ """Why this attempt ran: first, a recorded retry source, an escalation, a queued retry, or unknown."""
1182
+ if row['attempt'] == 1:
1183
+ return 'first'
1184
+ source = sources.get(row['attempt'])
1185
+ if source:
1186
+ return source
1187
+ # escalations.tsv names the attempt that finished, which is the previous one. The signal
1188
+ # is a dwarf change while any escalation is recorded, not that column.
1189
+ previous = rows[index - 1]['dwarf'] if index else None
1190
+ if row['dwarf'] != previous and escalations:
1191
+ return 'escalation'
1192
+ if index in manual:
1193
+ return 'manual'
1194
+ return 'unknown'
1195
+
1196
+
1197
+ def _attempt_review(execs, attempt):
1198
+ """The newest done, non-shadow qa execution of this attempt, or None."""
1199
+ chosen = None
1200
+ for item in execs:
1201
+ if item.get('shadow') or item.get('role') != 'qa' or item.get('state') != 'done':
1202
+ continue
1203
+ if item.get('attempt') != attempt:
1204
+ continue
1205
+ chosen = item
1206
+ return chosen
1207
+
1208
+
1209
+ def _trail(reader, rows, execs, sources_name, escalations, queue_times):
1210
+ """One entry per attempts.tsv row: its review, why it ran, and its execution ids."""
1211
+ sources = _retry_sources(reader, sources_name)
1212
+ manual = _manual_indexes(rows, queue_times)
1213
+ result = []
1214
+ for index, row in enumerate(rows):
1215
+ review = _attempt_review(execs, row['attempt'])
1216
+ summary = None
1217
+ verdict = None
1218
+ if review is not None:
1219
+ verdict = review.get('verdict')
1220
+ found = review.get('findings')
1221
+ summary = dict(found) if found else None
1222
+ result.append(dict(
1223
+ attempt=row['attempt'], dwarf=row['dwarf'], verdict=verdict, findings=summary,
1224
+ worst=summary.get('worst') if summary else None, reason=_attempt_reason(
1225
+ index, row, rows, sources, escalations, manual),
1226
+ executions=[item['id'] for item in execs
1227
+ if item.get('attempt') == row['attempt'] and not item.get('shadow')]))
1228
+ return result
1229
+
1230
+
1231
+ # --- generated task summaries (#133 B): tasks/<id>/summary.json, its error, and the switches -----------------------
1232
+
1233
+ _SUMMARY_SOURCES = ('attempt', 'finding')
1234
+ # The facts a summary is made from, as the reader shows them: one changed after generated_at makes it stale.
1235
+ _SUMMARY_FACTS = ('attempts.tsv', 'status', 'merged', 'qa.last')
1236
+
1237
+
1238
+ def _mode_or_none(value):
1239
+ return value if value in ('on', 'off') else None
1240
+
1241
+
1242
+ def _is_number(value):
1243
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
1244
+
1245
+
1246
+ def _summary_sources(reader, prefix, sources):
1247
+ """The well-formed `{kind, ref}` entries of a summary's sources; any other entry is dropped."""
1248
+ if not isinstance(sources, list):
1249
+ return []
1250
+ return [dict(kind=item['kind'], ref=reader.cap(item['ref'], prefix + '/summary.sources'))
1251
+ for item in sources
1252
+ if isinstance(item, dict) and item.get('kind') in _SUMMARY_SOURCES and isinstance(item.get('ref'), str)]
1253
+
1254
+
1255
+ def _task_summary(reader, prefix):
1256
+ """The task's generated summary, or None when there is no summary.json (or it is not a summary: warned)."""
1257
+ body = reader.object(prefix + '/summary.json')
1258
+ error = reader.text(prefix + '/summary.error')
1259
+ if body is None:
1260
+ return None
1261
+ text, generated = body.get('text'), body.get('generated_at')
1262
+ if not isinstance(text, str) or not _is_number(generated):
1263
+ reader.warn(prefix + '/summary.json', 'not a summary (needs text and generated_at)')
1264
+ return None
1265
+ facts = [reader.stat(f'{prefix}/{name}') for name in _SUMMARY_FACTS]
1266
+ # generated_at is whole seconds: a fact written in the second the summary was made is not after it.
1267
+ stale = any(info is not None and int(info.st_mtime) > generated for info in facts)
1268
+ sentence, model = body.get('sentence'), body.get('model')
1269
+ return dict(text=reader.cap(text, prefix + '/summary.text'),
1270
+ sentence=reader.cap(sentence, prefix + '/summary.sentence') if isinstance(sentence, str) else None,
1271
+ model=model if isinstance(model, str) else None, generated_at=generated,
1272
+ sources=_summary_sources(reader, prefix, body.get('sources')), stale=stale,
1273
+ error=reader.cap(error, prefix + '/summary.error') if error and error.strip() else None)
1274
+
1275
+
1276
+ def _run_summaries(reader):
1277
+ """The run's summary switch from its plan files. `mode` is on only when `summaries` says so (absent is off);
1278
+ `model` is the first line of `summaries_model`, or null."""
1279
+ return dict(mode='on' if reader.word('summaries') == 'on' else 'off', model=reader.line('summaries_model'))
1280
+
1281
+
1282
+ # --- brief mode (#135): tasks/<id>/brief.json, parked questions, answers and late answers ---------
1283
+
1284
+ _BRIEF_LEVELS = ('advisory', 'gated', 'strict')
1285
+
1286
+
1287
+ def _brief_level(reader):
1288
+ """The plan's brief level, or None when brief is off (no `brief` file, `off`, or any other word)."""
1289
+ level = reader.word('brief')
1290
+ return level if level in _BRIEF_LEVELS else None
1291
+
1292
+
1293
+ def _cap_str(reader, value, field):
1294
+ return reader.cap(value, field) if isinstance(value, str) else None
1295
+
1296
+
1297
+ def _cap_options(reader, value, field):
1298
+ if not isinstance(value, list):
1299
+ return []
1300
+ return [reader.cap(item, field) for item in value if isinstance(item, str)]
1301
+
1302
+
1303
+ def _answer_map(data):
1304
+ """`{qid: entry}` from an answers or late object. Anything else is no answers."""
1305
+ if not isinstance(data, dict):
1306
+ return {}
1307
+ return {key: value if isinstance(value, dict) else {}
1308
+ for key, value in data.items() if isinstance(key, str) and key}
1309
+
1310
+
1311
+ def _entry_text(entry):
1312
+ text = entry.get('text') if isinstance(entry, dict) else None
1313
+ return text if isinstance(text, str) else None
1314
+
1315
+
1316
+ def _brief_rows(reader, prefix, body, answers, late, parked):
1317
+ """Questions from a brief.json or brief.parked.json object, in file order.
1318
+
1319
+ An entry that is not an object, or has no string id, is skipped, with one warning for the file.
1320
+ Answers apply to task questions only: `answered` beats `late`, and anything else is `open`.
1321
+ """
1322
+ if not isinstance(body, dict):
1323
+ return []
1324
+ label = f'{prefix}/brief.parked.json' if parked else f'{prefix}/brief.json'
1325
+ items = body.get('questions', [])
1326
+ if not isinstance(items, list):
1327
+ reader.warn(label, 'questions is not a list')
1328
+ return []
1329
+ file_stale = body.get('possibly_stale') is True
1330
+ rows, skipped = [], 0
1331
+ for question in items:
1332
+ if not isinstance(question, dict) or not isinstance(question.get('id'), str) or not question['id']:
1333
+ skipped += 1
1334
+ continue
1335
+ qid = question['id']
1336
+ stem = f'{prefix}/brief.parked/{qid}' if parked else f'{prefix}/brief/{qid}'
1337
+ if parked:
1338
+ state, entry = None, None
1339
+ elif qid in answers:
1340
+ state, entry = 'answered', answers[qid]
1341
+ elif qid in late:
1342
+ state, entry = 'late', late[qid]
1343
+ else:
1344
+ state, entry = 'open', None
1345
+ row = dict(id=qid, text=_cap_str(reader, question.get('text'), stem + '.text'),
1346
+ why=_cap_str(reader, question.get('why'), stem + '.why'),
1347
+ options=_cap_options(reader, question.get('options'), stem + '.options'),
1348
+ default=_cap_str(reader, question.get('default'), stem + '.default'),
1349
+ must_answer=question.get('must_answer') is True,
1350
+ possibly_stale=file_stale or question.get('possibly_stale') is True)
1351
+ if parked:
1352
+ scope = question.get('scope')
1353
+ row['scope'] = scope if isinstance(scope, str) else None
1354
+ else:
1355
+ row['state'] = state
1356
+ row['answer'] = _cap_str(reader, _entry_text(entry), stem + '.answer')
1357
+ rows.append(row)
1358
+ if skipped:
1359
+ reader.warn(label, f'{skipped} question{"" if skipped == 1 else "s"} skipped')
1360
+ return rows
1361
+
1362
+
1363
+ def _late_rows(reader, prefix, late):
1364
+ """brief.late.json in file order: `{id, text, actor, t}`. `t` is kept only when it is a finite number."""
1365
+ rows = []
1366
+ for qid, entry in late.items():
1367
+ actor = entry.get('actor') if isinstance(entry, dict) else None
1368
+ stamp = entry.get('t') if isinstance(entry, dict) else None
1369
+ rows.append(dict(id=qid, text=_cap_str(reader, _entry_text(entry), f'{prefix}/brief.late/{qid}.text'),
1370
+ actor=actor if isinstance(actor, str) else None,
1371
+ t=stamp if _is_number(stamp) else None))
1372
+ return rows
1373
+
1374
+
1375
+ def _task_brief(reader, ident):
1376
+ """The task's questions, parked questions and late answers, or None when it has none of those files."""
1377
+ prefix = f'tasks/{ident}'
1378
+ paths = {'brief': f'{prefix}/brief.json', 'parked': f'{prefix}/brief.parked.json',
1379
+ 'late': f'{prefix}/brief.late.json'}
1380
+ present = {name: reader.exists(path) for name, path in paths.items()}
1381
+ if not any(present.values()):
1382
+ return None
1383
+ brief = reader.object(paths['brief']) if present['brief'] else None
1384
+ parked = reader.object(paths['parked']) if present['parked'] else None
1385
+ late = _answer_map(reader.object(paths['late']) if present['late'] else None)
1386
+ answers = _answer_map(reader.object(f'{prefix}/brief.answers.json'))
1387
+ return dict(questions=_brief_rows(reader, prefix, brief, answers, late, False),
1388
+ parked=_brief_rows(reader, prefix, parked, {}, {}, True),
1389
+ late=_late_rows(reader, prefix, late))
1390
+
1391
+
1392
+ def _run_brief(level, tasks):
1393
+ """RunDetail.brief: the level, and how many task questions are still open (flagged: open and must_answer).
1394
+
1395
+ Parked questions are not counted: they are wider than this task and do not hold it."""
1396
+ open_n = flagged = 0
1397
+ for task in tasks:
1398
+ brief = task.get('brief')
1399
+ if not brief:
1400
+ continue
1401
+ for question in brief['questions']:
1402
+ if question['state'] != 'open':
1403
+ continue
1404
+ open_n += 1
1405
+ flagged += question['must_answer']
1406
+ return dict(level=level, open=open_n, flagged=flagged)
1407
+
1408
+
1409
+ def _attach_brief(reader, tasks):
1410
+ """Set each task's `brief` and return the run's `{level, open, flagged}`, or None when brief is off.
1411
+
1412
+ Off means the questions are not shown either: a file left from an earlier level stays on disk."""
1413
+ level = _brief_level(reader)
1414
+ if level is None:
1415
+ for task in tasks:
1416
+ task['brief'] = None
1417
+ return None
1418
+ for task in tasks:
1419
+ task['brief'] = _task_brief(reader, task['id'])
1420
+ return _run_brief(level, tasks)
1421
+
1422
+
1423
+ def _task_detail(reader, task, run_id, waves, branches, max_attempts, origin, request, queues):
855
1424
  """Fill in a plan task; returns every execution it read (its own and its shadows')."""
856
1425
  ident = task['id']
857
1426
  prefix = f'tasks/{ident}'
@@ -862,7 +1431,8 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
862
1431
  task['branch'] = f'forge/{run_id}/{ident}'
863
1432
  except (OSError, ValueError):
864
1433
  pass
865
- task['attempts'], task['attempt'] = _attempt_state(reader, prefix)
1434
+ logged, task['attempt'] = _attempt_view(reader, prefix + '/attempts.tsv', prefix + '/attempt')
1435
+ task['attempts'] = [_public_attempt(row) for row in logged]
866
1436
  task['attempts_total'] = sum(item['status'] != 'INFRA' for item in task['attempts'])
867
1437
  task['escalations'] = _history(reader, prefix + '/escalations.tsv', True)
868
1438
  qa = reader.text(prefix + '/qa.last')
@@ -872,8 +1442,10 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
872
1442
  task['accepted_by'] = reader.text(prefix + '/accepted.by')
873
1443
  task['accepted_attempt'], task['accepted_over'] = _accepted_fields(
874
1444
  reader, prefix + '/accepted.by', task['accepted_by'])
1445
+ texts = {}
875
1446
  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)
1447
+ texts[field] = reader.text(prefix + '/' + filename)
1448
+ task[field] = reader.cap(texts[field], prefix + '/' + field)
877
1449
  # the implementer's question for the user, when the task stopped NEEDS_INPUT
878
1450
  task['needs_input'] = reader.cap(reader.text(prefix + '/needs_input.md'), prefix + '/needs_input')
879
1451
  # the stop records: why an INFRA dispatch stopped, the lateral moves, the review ledger, and a NEEDS_DECISION's question
@@ -893,6 +1465,8 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
893
1465
  item.get('explored') is True for item in task['route'])
894
1466
  execs = _task_execs(reader, task)
895
1467
  task['executions'] = execs
1468
+ task['header'] = _header(reader, task['title'], texts['prompt'], texts['approach'], request, prefix, origin)
1469
+ task['trail'] = _trail(reader, logged, execs, prefix + '/retry_sources.tsv', task['escalations'], queues)
896
1470
  task['now'] = _now(reader, prefix, execs) if task['status'] == 'RUNNING' else None
897
1471
  merged = reader.stat(prefix + '/merged') if task['status'] == 'MERGED' else None
898
1472
  task['merged_at'] = float(merged.st_mtime) if merged is not None else None
@@ -905,6 +1479,8 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
905
1479
  task['swept'] = []
906
1480
  shadows = _shadows(reader, ident, execs)
907
1481
  task['shadow'] = [entry for entry, _, _ in shadows]
1482
+ task['summary'] = _task_summary(reader, prefix)
1483
+ task['summaries_override'] = _mode_or_none(reader.word(prefix + '/summaries'))
908
1484
  # What `forge control show` reads of the task. A change there (a write, or a delete: the dir's mtime) moves `updated`,
909
1485
  # so the page redraws and the Controls panel asks again.
910
1486
  reader.stat(prefix)
@@ -985,8 +1561,9 @@ def _sweep(reader, tasks):
985
1561
  # Read only for their mtimes, so the run's `updated` stamp moves when a control changes.
986
1562
  # control.requests is a directory: its mtime moves when a request is queued or settled.
987
1563
  _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')
1564
+ 'infra_backoff', 'escalate_effort', 'control.requests', 'summaries', 'summaries_model')
1565
+ _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next',
1566
+ 'summaries')
990
1567
 
991
1568
 
992
1569
  _FAIL_FIRST_RESULTS = ('proven', 'passes_without_change', 'inconclusive', 'error')
@@ -1482,23 +2059,29 @@ def _frozen_profile(reader):
1482
2059
  def _solo_detail(reader, source):
1483
2060
  result = _solo_summary(reader, source)
1484
2061
  status = next(iter(result['counts']))
1485
- result['request'] = reader.cap(reader.text('request.md'), 'request')
2062
+ request = reader.text('request.md')
2063
+ result['request'] = reader.cap(request, 'request')
2064
+ result['retro'] = _retro(reader)
2065
+ result['summaries'] = None # generated summaries are for plan tasks only
2066
+ result['brief'] = None # brief mode is a plan's questions, not a solo run's
1486
2067
  result['settings'] = dict.fromkeys(_SOLO_SETTINGS)
1487
2068
  result['settings']['qa_threshold'], result['settings']['qa_threshold_source'] = _threshold(reader)
1488
2069
  result['settings']['profile'] = _frozen_profile(reader)
1489
2070
  result['verification'] = None
1490
2071
  result['attribution'] = _attribution(reader)
1491
2072
  result['waves'] = [['solo']]
1492
- attempts = _history(reader, 'attempts.tsv')
2073
+ logged, attempt = _attempt_view(reader, 'attempts.tsv', None)
2074
+ attempts = [_public_attempt(row) for row in logged]
1493
2075
  qa = reader.text('qa.last')
1494
2076
  execs = _solo_execs(reader, status, attempts)
2077
+ prompt, approach = reader.text('prompt.md'), reader.text('approach.md')
1495
2078
  task = dict(id='solo', title=result['goal'] or 'Solo run', deps=[], difficulty=None, files=[],
1496
2079
  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),
2080
+ branch=None, attempt=attempt,
1498
2081
  attempts=attempts, escalations=[], verdict=_verdict(qa), accepted_by=None,
1499
2082
  accepted=False, accepted_attempt=None, accepted_over=None,
1500
2083
  explored=False, route=[], shadow=[],
1501
- prompt=reader.cap(reader.text('prompt.md'), 'tasks/solo/prompt'), approach=None,
2084
+ prompt=reader.cap(prompt, 'tasks/solo/prompt'), approach=None,
1502
2085
  retry_findings=None, needs_input=None, infra=None, lateral=[], ledger=[], decision=None, decisions=[],
1503
2086
  attempts_total=sum(item['status'] != 'INFRA' for item in attempts), attempt_cap=None,
1504
2087
  qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
@@ -1506,7 +2089,11 @@ def _solo_detail(reader, source):
1506
2089
  executions=execs, merged_at=None, findings=executions.summary_of(qa),
1507
2090
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
1508
2091
  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=[])
2092
+ now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[],
2093
+ summary=None, summaries_override=None, brief=None)
2094
+ task['header'] = _header(reader, task['title'], prompt, approach, request, 'tasks/solo',
2095
+ _github_origin(reader))
2096
+ task['trail'] = _trail(reader, logged, execs, 'retry_sources.tsv', [], _queued_retries(reader).get('solo', ()))
1510
2097
  result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[], adoptions=[],
1511
2098
  deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
1512
2099
  scheduler=None, sweep=None)
@@ -1560,12 +2147,49 @@ def _attribution(reader):
1560
2147
  gate_outcome=_text_or_none(outcome, 40))
1561
2148
 
1562
2149
 
2150
+ # --- retro: the report and the counts of its notes, written when retro mode is on ----------------
2151
+
2152
+ _RETRO_GROUPS = (('user', 'fixable_by', 'user'), ('forge', 'fixable_by', 'forge'), ('unsure', 'fixable_by', 'unsure'),
2153
+ ('verified', 'check', 'verified'), ('claimed', 'check', 'claimed'))
2154
+
2155
+
2156
+ def _retro(reader):
2157
+ """RunDetail.retro: retro.md's text and the counts of retro/notes.jsonl, or null when the run has neither file.
2158
+
2159
+ A note is a line that parses as a JSON object. Other non-blank lines are skipped, with one warning for the
2160
+ file. `notes` counts every note; each other count is the notes whose field has that value."""
2161
+ if not (reader.exists('retro.md') or reader.exists('retro/notes.jsonl')):
2162
+ return None
2163
+ name = 'retro/notes.jsonl'
2164
+ counts = dict.fromkeys(('notes', 'user', 'forge', 'unsure', 'verified', 'claimed', 'blocking'), 0)
2165
+ skipped = 0
2166
+ for line in (reader.text(name) or '').split('\n'):
2167
+ if not line.strip():
2168
+ continue
2169
+ try:
2170
+ note = json.loads(line)
2171
+ except (ValueError, RecursionError):
2172
+ note = None
2173
+ if not isinstance(note, dict):
2174
+ skipped += 1
2175
+ continue
2176
+ counts['notes'] += 1
2177
+ for key, field, value in _RETRO_GROUPS:
2178
+ counts[key] += note.get(field) == value
2179
+ counts['blocking'] += note.get('blocking') is True
2180
+ if skipped:
2181
+ reader.warn(name, f'{skipped} malformed line{"" if skipped == 1 else "s"} skipped')
2182
+ return dict(text=reader.cap(reader.text('retro.md'), 'retro'), **counts)
2183
+
2184
+
1563
2185
  def detail(path, source='plan') -> dict:
1564
2186
  reader = _Read(path)
1565
2187
  if _kind(reader.path) == 'solo':
1566
2188
  return _solo_detail(reader, source)
1567
2189
  result, tasks = _summary(reader, source)
1568
- result['request'] = reader.cap(reader.text('request.md'), 'request')
2190
+ request = reader.text('request.md')
2191
+ result['request'] = reader.cap(request, 'request')
2192
+ result['retro'] = _retro(reader)
1569
2193
  threshold = _threshold(reader)
1570
2194
  result['settings'] = dict(explore=reader.number('explore'), shadow_rate=reader.number('shadow_rate'),
1571
2195
  shadow_qa=_list(reader.text('shadow_qa') or ''), timeout=reader.number('timeout', int),
@@ -1574,13 +2198,16 @@ def detail(path, source='plan') -> dict:
1574
2198
  escalate_after=reader.number('escalate_after', int),
1575
2199
  verify_retries=reader.number('verify_retries', int), final_qa=reader.line('final_qa'),
1576
2200
  profile=_frozen_profile(reader))
2201
+ result['summaries'] = _run_summaries(reader)
1577
2202
  waves, wave_map = _waves(reader)
1578
2203
  result['waves'] = [waves.get(n, []) for n in range(1, max(waves, default=0) + 1)]
1579
2204
  branches = {row[0]: _nullable(row[2]) for _, row in reader.rows('results.tsv', 3)}
1580
2205
  max_attempts = _max_attempts(reader)
2206
+ origin, queues = _github_origin(reader), _queued_retries(reader)
1581
2207
  pool = []
1582
2208
  for task in tasks:
1583
- pool += _task_detail(reader, task, result['run_id'], wave_map, branches, max_attempts)
2209
+ pool += _task_detail(reader, task, result['run_id'], wave_map, branches, max_attempts,
2210
+ origin, request, queues.get(task['id'], ()))
1584
2211
  for name in _RUN_CONTROLS:
1585
2212
  reader.stat(name)
1586
2213
  result['scheduler'] = _scheduler(reader)
@@ -1610,6 +2237,7 @@ def detail(path, source='plan') -> dict:
1610
2237
  result['deferrals'] = [line.strip() for line in (reader.text('deferrals.txt') or '').splitlines() if line.strip()]
1611
2238
  result['findings_available'] = findings.available()
1612
2239
  result['fractal'] = fractal.summary(reader)
2240
+ result['brief'] = _attach_brief(reader, tasks)
1613
2241
  result.update(tasks=tasks, warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
1614
2242
  return result
1615
2243
 
@@ -1767,7 +2395,10 @@ def execution_transcript(path, name, source='plan'):
1767
2395
  def _agent_log(reader, item, owner_dir):
1768
2396
  """The log of a dwarf or reviewer execution: its copy once it ended, the one being written while it runs."""
1769
2397
  role = item['role']
1770
- return _log_path(reader, posixpath.join(owner_dir, role + '.log') if item['state'] == 'running' else f'{item.rel}/{role}.log')
2398
+ if item['state'] == 'running':
2399
+ return _log_path(reader, posixpath.join(owner_dir, role + '.log'))
2400
+ # `forge runs compact --logs` gzips the copy (#139); transcripts reads either the same way
2401
+ return _log_path(reader, f'{item.rel}/{role}.log') or _log_path(reader, f'{item.rel}/{role}.log.gz')
1771
2402
 
1772
2403
 
1773
2404
  def _checks_of(reader, item, owner_dir):