@giamme/forge 0.13.0 → 0.14.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 (60) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -0
  5. package/docs/commands.md +121 -7
  6. package/docs/development.md +3 -0
  7. package/docs/forge-ui.md +7 -1
  8. package/docs/reviews.md +2 -0
  9. package/docs/troubleshooting.md +5 -1
  10. package/forge +28 -1
  11. package/package.json +1 -1
  12. package/references/dataset.md +3 -1
  13. package/references/decision-models.md +5 -1
  14. package/references/decompose.md +199 -61
  15. package/references/runtime.md +29 -0
  16. package/references/ui.md +10 -0
  17. package/scripts/forge-compare.py +491 -0
  18. package/scripts/forge-config.py +3 -3
  19. package/scripts/forge-contract.py +34 -8
  20. package/scripts/forge-control.py +105 -13
  21. package/scripts/forge-dispatch.sh +9 -5
  22. package/scripts/forge-jev-options.sh +17 -4
  23. package/scripts/forge-ledger.py +387 -0
  24. package/scripts/forge-lib-plans.sh +16 -2
  25. package/scripts/forge-lib-task.sh +390 -28
  26. package/scripts/forge-parallel-options.sh +20 -4
  27. package/scripts/forge-parallel.sh +118 -12
  28. package/scripts/forge-plan-check.py +68 -3
  29. package/scripts/forge-pr.py +276 -0
  30. package/scripts/forge-route.py +350 -34
  31. package/scripts/forge-runs.py +18 -1
  32. package/scripts/forge-runtime.py +23 -7
  33. package/scripts/forge-schedule.py +303 -46
  34. package/scripts/forge-solo.sh +1 -0
  35. package/scripts/forge-ui-options.sh +25 -0
  36. package/scripts/forge-verify-failed.py +111 -0
  37. package/scripts/forge-watch.py +372 -0
  38. package/scripts/forge_dataset/export.py +87 -41
  39. package/scripts/forge_dataset/harvest.py +3 -1
  40. package/scripts/forge_decide/budget.py +39 -8
  41. package/scripts/forge_decide/doctor.py +49 -0
  42. package/scripts/forge_fractal/cli.py +23 -6
  43. package/scripts/forge_infra.py +274 -0
  44. package/scripts/forge_jev/client.py +13 -9
  45. package/ui/docs/api.md +83 -15
  46. package/ui/forge_ui/control.py +11 -3
  47. package/ui/forge_ui/export.py +6 -2
  48. package/ui/forge_ui/models.py +16 -16
  49. package/ui/forge_ui/reader.py +217 -13
  50. package/ui/forge_ui/repos.py +428 -0
  51. package/ui/forge_ui/static/app.js +24 -5
  52. package/ui/forge_ui/static/checksview.js +20 -7
  53. package/ui/forge_ui/static/cloudmodel.js +8 -5
  54. package/ui/forge_ui/static/controls.js +6 -3
  55. package/ui/forge_ui/static/modelstats.js +12 -8
  56. package/ui/forge_ui/static/panel.js +69 -4
  57. package/ui/forge_ui/static/runmodel.js +55 -10
  58. package/ui/forge_ui/static/scene3d.js +3 -2
  59. package/ui/forge_ui/static/settings.js +147 -29
  60. package/ui/forge_ui/static/style.css +49 -7
@@ -38,7 +38,10 @@ _EXEC = re.compile(r'(?:task|dwarf|qa|solo|verification|parallel)-[0-9a-f]{32}')
38
38
  _TEXT_KEYS = frozenset(('prompt', 'last', 'request', 'log_tail', 'dwarf_tail', 'qa_tail', 'qa_last', 'qa_input',
39
39
  'tasks_summary', 'known_issues', 'texts', 'text', 'planning_last', 'approach', 'retry_findings',
40
40
  'dwarf_input', 'error', 'last_line', 'message', 'excerpt', 'tail', 'lines', 'call', 'split',
41
- 'needs_input'))
41
+ 'needs_input', 'detail'))
42
+ # keys that are private text only under one parent: a person's --reason on each decision (`reason` elsewhere is
43
+ # a short machine word, such as a sweep's dropped-finding reason, and stays)
44
+ _TEXT_KEYS_UNDER = {'decisions': frozenset(('reason',))}
42
45
 
43
46
 
44
47
  def _enc(value):
@@ -109,7 +112,8 @@ class _Snapshot:
109
112
 
110
113
  def clean(self, value, key=None):
111
114
  if isinstance(value, dict):
112
- return {k: (None if not self.texts and k in _TEXT_KEYS and isinstance(v, (str, dict, list)) else self.clean(v, k))
115
+ private = _TEXT_KEYS | _TEXT_KEYS_UNDER.get(key, frozenset())
116
+ return {k: (None if not self.texts and k in private and isinstance(v, (str, dict, list)) else self.clean(v, k))
113
117
  for k, v in value.items()}
114
118
  if isinstance(value, list):
115
119
  return [self.clean(v, key) for v in value]
@@ -127,10 +127,10 @@ def _reviews(key, ident, execs, shadows):
127
127
  return rows
128
128
 
129
129
 
130
- def _facts(path, summary):
130
+ def _facts(path, summary, root):
131
131
  rd = reader._Read(path)
132
132
  key = summary['key']
133
- base_row = dict(run=key, repo=summary['repo'], created=summary['created'])
133
+ base_row = dict(run=key, repo=summary['repo'], repo_root=root, created=summary['created'])
134
134
  tasks, reviews = [], []
135
135
  if summary['kind'] == 'solo':
136
136
  execs = reader._solo_execs(rd, reader._solo_status(rd), reader._history(rd, 'attempts.tsv'))
@@ -166,25 +166,28 @@ def _facts(path, summary):
166
166
  spec=spec, verdict=review['verdict'] if review['verdict'] in ('PASS', 'FAIL') else None,
167
167
  findings=review['findings'], duration_s=review['duration_s'],
168
168
  tokens=run['tokens'] if run else None, agreement=None, primary_alias=None))
169
- order = ('run', 'task', 'kind', 'repo', 'difficulty', 'created', 'explored', 'propensity', 'final_status',
170
- 'accepted', 'attempts', 'escalations')
169
+ order = ('run', 'task', 'kind', 'repo', 'repo_root', 'difficulty', 'created', 'explored', 'propensity',
170
+ 'final_status', 'accepted', 'attempts', 'escalations')
171
+ # Reviews have no repo of their own; every row carries the run's grouping key.
172
+ reviews = [dict(row, repo_root=root) for row in reviews]
171
173
  return dict(tasks=[{name: row[name] for name in order} for row in tasks], reviews=reviews,
172
174
  warnings=[f'{key}: {item}' for item in rd.warnings])
173
175
 
174
176
 
175
- def _signature(summary):
177
+ def _signature(summary, root):
178
+ # The grouping key is part of the signature: a root that appears later must reach the cached rows.
176
179
  return (summary['updated'], summary['task_count'], json.dumps(summary['counts'], sort_keys=True),
177
- summary['final_review'])
180
+ summary['final_review'], root)
178
181
 
179
182
 
180
- def _cached(path, summary, now):
183
+ def _cached(path, summary, now, root):
181
184
  real = os.path.realpath(path)
182
- sig = _signature(summary)
185
+ sig = _signature(summary, root)
183
186
  hit = _RUNS.get(real)
184
187
  if hit is not None and hit[0] == sig and not ('RUNNING' in summary['counts'] and now - hit[1] > _RUNNING_S):
185
188
  _RUNS.move_to_end(real)
186
189
  return hit[2]
187
- facts = _facts(path, summary)
190
+ facts = _facts(path, summary, root)
188
191
  _RUNS[real] = (sig, now, facts)
189
192
  _RUNS.move_to_end(real)
190
193
  while len(_RUNS) > _SIZE:
@@ -197,18 +200,15 @@ def collect(found):
197
200
  # One computation at a time: a cold cache reads every run once, not once per request.
198
201
  with _LOCK:
199
202
  now = time.time()
200
- runs = []
201
- for path, source in found:
202
- summary = reader.summarize(path, source)
203
- if reader._kind(path):
204
- runs.append((path, summary))
203
+ listed, identities = reader.batch(found)
204
+ runs = [(path, reader.summarize(path, source), identities[entry[0]]) for path, source, entry in listed]
205
205
  runs.sort(key=lambda item: item[1]['updated'] if item[1]['updated'] is not None else float('-inf'), reverse=True)
206
206
  tasks, reviews, warnings, count, truncated = [], [], [], 0, False
207
- for path, summary in runs:
207
+ for path, summary, identity in runs:
208
208
  if len(tasks) + summary['task_count'] > _MAX_ROWS:
209
209
  truncated = True
210
210
  break
211
- facts = _cached(path, summary, now)
211
+ facts = _cached(path, summary, now, reader.repo_root(identity, summary['repo']))
212
212
  tasks += facts['tasks']
213
213
  reviews += facts['reviews']
214
214
  warnings += facts['warnings']
@@ -2,6 +2,7 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import hashlib
5
+ import importlib.util
5
6
  import json
6
7
  import math
7
8
  import os
@@ -12,7 +13,7 @@ import stat
12
13
  import time
13
14
  import urllib.parse
14
15
 
15
- from forge_ui import checks, diffs, executions, findings, fractal, transcripts
16
+ from forge_ui import checks, diffs, executions, findings, fractal, repos, transcripts
16
17
  from forge_ui.findings import verdict as _verdict
17
18
 
18
19
 
@@ -609,12 +610,22 @@ def _scheduler(reader):
609
610
  paused = reader.object('infra.paused') if reader.exists('infra.paused') else None
610
611
  for scope in (paused or {}).get('scopes') or []:
611
612
  if isinstance(scope, dict):
612
- result['pauses'].append({key: scope.get(key) for key in
613
- ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')})
613
+ pause = {key: scope.get(key) for key in
614
+ ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')}
615
+ # the keys forge added later: an older scope has none, so they read as false and null
616
+ hint, reset_at = scope.get('hint'), scope.get('reset_at')
617
+ numeric = isinstance(reset_at, (int, float)) and not isinstance(reset_at, bool)
618
+ pause.update(needs_you=scope.get('needs_you') is True, hint=hint if isinstance(hint, str) else None,
619
+ reset_at=reset_at if numeric else None)
620
+ result['pauses'].append(pause)
614
621
  return result
615
622
 
616
623
 
624
+ # Not NEEDS_INPUT or NEEDS_DECISION: those wait for the user, so a task that depends on one waits rather than stops.
617
625
  _STOPPED = ('FAIL', 'BLOCKED', 'INFRA', 'INTERRUPTED', 'TIMEOUT', 'ERROR', 'CONFLICT', 'NOCHANGES', 'INVALIDATED', 'UNKNOWN')
626
+ _DETAIL_CAP = 400 # characters of an infra stop's detail, a short text
627
+ _ATTEMPT_CAP = 8 # a plan without a max_attempts file
628
+ _LEDGER_KEEP = 50 # the newest ledger rows a task keeps
618
629
 
619
630
 
620
631
  def _escalation_stop(reader, ident):
@@ -629,6 +640,150 @@ def _escalation_stop(reader, ident):
629
640
  split=reader.cap(split, f'tasks/{ident}/split.suggested', 600) or None)
630
641
 
631
642
 
643
+ def _number_or_none(value):
644
+ """A key=value number (reset_at, retry_after): None when missing, empty or not finite."""
645
+ try:
646
+ result = float(value)
647
+ except (TypeError, ValueError):
648
+ return None
649
+ return result if math.isfinite(result) else None
650
+
651
+
652
+ _INFRA_TABLE = Path(__file__).resolve().parents[2] / 'scripts' / 'forge_infra.py'
653
+ _INFRA_STATE = {}
654
+
655
+
656
+ def _forge_infra():
657
+ """forge's table of infrastructure causes (scripts/forge_infra.py), loaded once and read-only; None when it
658
+ cannot be, which leaves needs_you false and hint null."""
659
+ if 'module' not in _INFRA_STATE:
660
+ try:
661
+ spec = importlib.util.spec_from_file_location(
662
+ 'forge_infra_for_ui', _INFRA_TABLE, loader=findings._ReadOnlyLoader('forge_infra_for_ui', str(_INFRA_TABLE)))
663
+ module = importlib.util.module_from_spec(spec)
664
+ spec.loader.exec_module(module)
665
+ _INFRA_STATE['module'] = module if callable(getattr(module, 'stop_of', None)) else None
666
+ except Exception:
667
+ _INFRA_STATE['module'] = None
668
+ return _INFRA_STATE['module']
669
+
670
+
671
+ def _infra(reader, prefix, status, ident):
672
+ """task['infra']: the stop record of an INFRA task (infra.txt, key=value lines); None for any other status.
673
+ needs_you and hint are forge's own answer (forge_infra.stop_of): the pause that names the task, live
674
+ (infra.paused) or the one the run ended with (infra.last), else what the cause asks for with no peer."""
675
+ if status != 'INFRA':
676
+ return None
677
+ fields = executions.parse_resolved(reader.text(prefix + '/infra.txt'))
678
+ record = dict(cause=fields.get('class') or None, stage=fields.get('stage') or None,
679
+ harness=fields.get('harness') or None, model=fields.get('model') or None,
680
+ reset_at=_number_or_none(fields.get('reset_at')), retry_after=_number_or_none(fields.get('retry_after')),
681
+ detail=reader.cap(fields.get('detail') or None, prefix + '/infra_detail', _DETAIL_CAP),
682
+ needs_you=False, hint=None)
683
+ module = _forge_infra()
684
+ if module is not None:
685
+ try:
686
+ scopes = module.parse_pauses(reader.text('infra.paused')) or module.parse_pauses(reader.text('infra.last'))
687
+ judged = module.stop_of(ident, fields, scopes, time.time())
688
+ record.update(needs_you=judged.get('needs_you') is True,
689
+ hint=judged.get('hint') if isinstance(judged.get('hint'), str) else None)
690
+ except Exception:
691
+ pass
692
+ return record
693
+
694
+
695
+ def _lateral(reader, name):
696
+ """task['lateral']: the moves of a stopped dispatch to another model of its tier (lateral.tsv), read as escalations are."""
697
+ result = []
698
+ for label, row in reader.rows(name, 6):
699
+ try:
700
+ at, attempt = float(row[0]), int(row[1])
701
+ if not math.isfinite(at):
702
+ raise ValueError()
703
+ except (ValueError, OverflowError):
704
+ reader.warn(label, 'invalid epoch or attempt')
705
+ continue
706
+ result.append(dict(at=at, attempt=attempt, role=row[2], cause=row[5], **{'from': row[3], 'to': row[4]}))
707
+ return result
708
+
709
+
710
+ def _ledger(reader, name):
711
+ """task['ledger']: one row per review (ledger.tsv), the newest _LEDGER_KEEP. `-` is None; the counts are ints."""
712
+ result = []
713
+ for label, row in reader.rows(name, 11):
714
+ try:
715
+ at, attempt = float(row[0]), int(row[1])
716
+ if not math.isfinite(at):
717
+ raise ValueError()
718
+ confirmed, new, carried, diff_bytes = (int(cell) for cell in row[6:10])
719
+ delta = _nullable(row[10])
720
+ delta = None if delta is None else int(delta)
721
+ except (ValueError, OverflowError):
722
+ reader.warn(label, 'invalid epoch, attempt or count')
723
+ continue
724
+ result.append(dict(at=at, attempt=attempt, review=row[2], verdict=row[3], gate=_nullable(row[4]),
725
+ worst=_nullable(row[5]), confirmed=confirmed, new=new, carried=carried,
726
+ diff_bytes=diff_bytes, delta_bytes=delta))
727
+ if len(result) > _LEDGER_KEEP:
728
+ reader.truncated.append(name)
729
+ del result[:-_LEDGER_KEEP]
730
+ return result
731
+
732
+
733
+ def _decision(reader, prefix, status):
734
+ """task['decision'] of a NEEDS_DECISION task: `reasons` from decision.md's first line, `text` the markdown after it."""
735
+ if status != 'NEEDS_DECISION':
736
+ return None
737
+ text = reader.text(prefix + '/decision.md')
738
+ first, _, rest = (text or '').partition('\n')
739
+ match = re.fullmatch(r'\s*reasons:(.*)', first)
740
+ if text is not None and match is None:
741
+ reader.warn(prefix + '/decision.md', 'no reasons line')
742
+ body = rest if match else text
743
+ return dict(reasons=_list(match.group(1)) if match else [],
744
+ text=None if body is None else reader.cap(body, prefix + '/decision'))
745
+
746
+
747
+ def _decisions(reader, name):
748
+ """task['decisions']: one human decision per row of decisions.tsv (epoch, attempt, choice, reason)."""
749
+ result = []
750
+ for label, row in reader.rows(name, 3):
751
+ try:
752
+ at, attempt = float(row[0]), int(row[1])
753
+ if not math.isfinite(at):
754
+ raise ValueError()
755
+ except (ValueError, OverflowError):
756
+ reader.warn(label, 'invalid epoch or attempt')
757
+ continue
758
+ result.append(dict(at=at, attempt=attempt, choice=row[2], reason=_nullable('\t'.join(row[3:]))))
759
+ return result
760
+
761
+
762
+ def _max_attempts(reader):
763
+ """The plan's max_attempts: a whole number, 0 for no cap; 8 without the file or when it is not a whole number."""
764
+ value = reader.number('max_attempts', int)
765
+ if value is not None and value < 0:
766
+ reader.warn('max_attempts', 'negative')
767
+ value = None
768
+ return _ATTEMPT_CAP if value is None else value
769
+
770
+
771
+ def _grant(choice):
772
+ """The N of a retry=N choice, however many digits it has; 0 for any other choice."""
773
+ match = re.fullmatch(r'retry=([0-9]+)', choice)
774
+ try:
775
+ return int(match.group(1)) if match else 0
776
+ except ValueError: # more digits than Python reads as an int: a reader must not raise over one bad row
777
+ return 0
778
+
779
+
780
+ def _attempt_cap(max_attempts, decisions):
781
+ """A task's attempt cap: max_attempts plus the N of each retry=N decision. None when max_attempts is 0 (no cap)."""
782
+ if max_attempts == 0:
783
+ return None
784
+ return max_attempts + sum(_grant(item['choice']) for item in decisions)
785
+
786
+
632
787
  def _waiting(reader, tasks, scheduler):
633
788
  """Task.waiting: why a task that is not running is not, as far as the run dir tells.
634
789
 
@@ -672,7 +827,7 @@ def _waiting(reader, tasks, scheduler):
672
827
  task['waiting'] = dict(kind='next')
673
828
 
674
829
 
675
- def _task_detail(reader, task, run_id, waves, branches):
830
+ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
676
831
  """Fill in a plan task; returns every execution it read (its own and its shadows')."""
677
832
  ident = task['id']
678
833
  prefix = f'tasks/{ident}'
@@ -684,6 +839,7 @@ def _task_detail(reader, task, run_id, waves, branches):
684
839
  except (OSError, ValueError):
685
840
  pass
686
841
  task['attempts'], task['attempt'] = _attempt_state(reader, prefix)
842
+ task['attempts_total'] = sum(item['status'] != 'INFRA' for item in task['attempts'])
687
843
  task['escalations'] = _history(reader, prefix + '/escalations.tsv', True)
688
844
  qa = reader.text(prefix + '/qa.last')
689
845
  task['verdict'] = _verdict(qa)
@@ -696,6 +852,13 @@ def _task_detail(reader, task, run_id, waves, branches):
696
852
  task[field] = reader.cap(reader.text(prefix + '/' + filename), prefix + '/' + field)
697
853
  # the implementer's question for the user, when the task stopped NEEDS_INPUT
698
854
  task['needs_input'] = reader.cap(reader.text(prefix + '/needs_input.md'), prefix + '/needs_input')
855
+ # the stop records: why an INFRA dispatch stopped, the lateral moves, the review ledger, and a NEEDS_DECISION's question
856
+ task['infra'] = _infra(reader, prefix, task['status'], task['id'])
857
+ task['lateral'] = _lateral(reader, prefix + '/lateral.tsv')
858
+ task['ledger'] = _ledger(reader, prefix + '/ledger.tsv')
859
+ task['decision'] = _decision(reader, prefix, task['status'])
860
+ task['decisions'] = _decisions(reader, prefix + '/decisions.tsv')
861
+ task['attempt_cap'] = _attempt_cap(max_attempts, task['decisions'])
699
862
  task['route'] = []
700
863
  for n, line in enumerate((reader.text(prefix + '/route.jsonl') or '').splitlines(), 1):
701
864
  if line.strip():
@@ -797,7 +960,7 @@ def _sweep(reader, tasks):
797
960
  # files without touching the run dir, so they are stat'd for `updated` only.
798
961
  # Read only for their mtimes, so the run's `updated` stamp moves when a control changes.
799
962
  # control.requests is a directory: its mtime moves when a request is queued or settled.
800
- _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused',
963
+ _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused', 'infra.last',
801
964
  'infra_backoff', 'escalate_effort', 'control.requests')
802
965
  _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next')
803
966
 
@@ -1293,7 +1456,9 @@ def _solo_detail(reader, source):
1293
1456
  accepted=False, accepted_attempt=None, accepted_over=None,
1294
1457
  explored=False, route=[], shadow=[],
1295
1458
  prompt=reader.cap(reader.text('prompt.md'), 'tasks/solo/prompt'), approach=None,
1296
- retry_findings=None, needs_input=None, qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
1459
+ retry_findings=None, needs_input=None, infra=None, lateral=[], ledger=[], decision=None, decisions=[],
1460
+ attempts_total=sum(item['status'] != 'INFRA' for item in attempts), attempt_cap=None,
1461
+ qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
1297
1462
  dwarf_tail=reader.cap(reader.text('dwarf.last'), 'tasks/solo/dwarf_tail', 4000, True),
1298
1463
  executions=execs, merged_at=None, findings=executions.summary_of(qa),
1299
1464
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
@@ -1368,9 +1533,10 @@ def detail(path, source='plan') -> dict:
1368
1533
  waves, wave_map = _waves(reader)
1369
1534
  result['waves'] = [waves.get(n, []) for n in range(1, max(waves, default=0) + 1)]
1370
1535
  branches = {row[0]: _nullable(row[2]) for _, row in reader.rows('results.tsv', 3)}
1536
+ max_attempts = _max_attempts(reader)
1371
1537
  pool = []
1372
1538
  for task in tasks:
1373
- pool += _task_detail(reader, task, result['run_id'], wave_map, branches)
1539
+ pool += _task_detail(reader, task, result['run_id'], wave_map, branches, max_attempts)
1374
1540
  for name in _RUN_CONTROLS:
1375
1541
  reader.stat(name)
1376
1542
  result['scheduler'] = _scheduler(reader)
@@ -2243,18 +2409,52 @@ def verification_log(path, lane=None, k=None, first=None, retry=False, source='p
2243
2409
  return _log_tail(stream, info, name) if first is None else _log_range(stream, info, name, first)
2244
2410
 
2245
2411
 
2412
+ def batch(found):
2413
+ """The runs among `found` ((path, source) pairs of discover) as [(path, source, entry)], and
2414
+ {run dir: identity} for them. An entry is (run dir, repo text, kind), what repos.resolve takes.
2415
+
2416
+ One repos.resolve call over the whole batch, so the base-commit step sees every known root; a
2417
+ run resolved on its own could miss its root.
2418
+ """
2419
+ listed = []
2420
+ for path, source in found:
2421
+ kind = _kind(path)
2422
+ if kind:
2423
+ reader = _Read(path)
2424
+ listed.append((path, source, (str(reader.path), reader.line('repo'), kind)))
2425
+ return listed, repos.resolve([entry for _path, _source, entry in listed])
2426
+
2427
+
2428
+ def repo_root(identity, repo):
2429
+ """A run's grouping key: its identity's root, or its repo text when nothing better is known."""
2430
+ return identity['root'] or repo
2431
+
2432
+
2433
+ def _with_repo(result, identity):
2434
+ """A run summary or detail with its repository fields: repo_root (the grouping key), repo_worktree
2435
+ (the checkout it started in, null when that is the root) and repo_branch (null when unknown)."""
2436
+ result.update(repo_root=repo_root(identity, result['repo']), repo_worktree=identity['worktree'],
2437
+ repo_branch=identity['branch'])
2438
+ return result
2439
+
2440
+
2246
2441
  class Catalog:
2247
2442
  def __init__(self, plans=(), roots=(), registry=True, registry_dir=None):
2248
2443
  self.options = dict(plans=tuple(plans), roots=tuple(roots), registry=registry, registry_dir=registry_dir)
2249
2444
 
2250
2445
  def runs(self):
2251
- runs = []
2252
- for path, source in discover(**self.options):
2253
- result = summarize(path, source)
2254
- if _kind(path):
2255
- runs.append(result)
2446
+ listed, identities = batch(discover(**self.options))
2447
+ runs = [_with_repo(summarize(path, source), identities[entry[0]]) for path, source, entry in listed]
2256
2448
  return sorted(runs, key=lambda item: item['updated'] if item['updated'] is not None else float('-inf'), reverse=True)
2257
2449
 
2450
+ def identity(self, key):
2451
+ """The identity of the run with this key, resolved in the same batch as the list; None for no such run."""
2452
+ listed, identities = batch(discover(**self.options))
2453
+ for path, _source, entry in listed:
2454
+ if run_key(path) == key:
2455
+ return identities[entry[0]]
2456
+ return None
2457
+
2258
2458
  def _find(self, key, read, *args):
2259
2459
  for path, source in discover(**self.options):
2260
2460
  if run_key(path) == key:
@@ -2273,7 +2473,11 @@ class Catalog:
2273
2473
  return None
2274
2474
 
2275
2475
  def get(self, key):
2276
- return self._find(key, detail)
2476
+ listed, identities = batch(discover(**self.options))
2477
+ for path, source, entry in listed:
2478
+ if run_key(path) == key:
2479
+ return _with_repo(detail(path, source=source), identities[entry[0]])
2480
+ return None
2277
2481
 
2278
2482
  def task(self, key, task_id):
2279
2483
  return self._find(key, task_detail, task_id)