@giamme/forge 0.13.0 → 0.13.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.
@@ -490,6 +490,12 @@ def _delete(ctx):
490
490
  return ctx.locked(work)
491
491
 
492
492
 
493
+ def _directory(value):
494
+ """`value` when it is an absolute existing directory with no control characters, else None."""
495
+ ok = isinstance(value, str) and os.path.isabs(value) and _no_control_chars(value) and os.path.isdir(value)
496
+ return value if ok else None
497
+
498
+
493
499
  def _repo_of(path):
494
500
  """The repository the run's own `repo` file names, or None."""
495
501
  try:
@@ -497,17 +503,19 @@ def _repo_of(path):
497
503
  line = handle.readline().strip()
498
504
  except (OSError, UnicodeDecodeError):
499
505
  return None
500
- return line if line and os.path.isabs(line) and _no_control_chars(line) and os.path.isdir(line) else None
506
+ return _directory(line)
501
507
 
502
508
 
503
509
  def _config_run(ctx, key):
504
- """(repo, error answer) for the run key a config request names."""
510
+ """(repo, error answer) for the run key a config request names. The repository is the run's root
511
+ (every worktree of one repository shares its .forge/ config), else the directory its `repo` names."""
505
512
  if not isinstance(key, str) or not re.fullmatch(r'[0-9a-f]{12}', key):
506
513
  return None, _invalid('run must be a 12-hex run key')
507
514
  found = ctx.server.catalog.locate(key)
508
515
  if not found:
509
516
  return None, (404, {'error': 'not found'})
510
- repo = _repo_of(found[0])
517
+ identity = ctx.server.catalog.identity(key)
518
+ repo = _directory(identity and identity['root']) or _repo_of(found[0])
511
519
  if repo is None:
512
520
  return None, (409, {'error': 'refused', 'detail': 'the run names no repository directory'})
513
521
  return repo, None
@@ -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']
@@ -12,7 +12,7 @@ import stat
12
12
  import time
13
13
  import urllib.parse
14
14
 
15
- from forge_ui import checks, diffs, executions, findings, fractal, transcripts
15
+ from forge_ui import checks, diffs, executions, findings, fractal, repos, transcripts
16
16
  from forge_ui.findings import verdict as _verdict
17
17
 
18
18
 
@@ -2243,18 +2243,52 @@ def verification_log(path, lane=None, k=None, first=None, retry=False, source='p
2243
2243
  return _log_tail(stream, info, name) if first is None else _log_range(stream, info, name, first)
2244
2244
 
2245
2245
 
2246
+ def batch(found):
2247
+ """The runs among `found` ((path, source) pairs of discover) as [(path, source, entry)], and
2248
+ {run dir: identity} for them. An entry is (run dir, repo text, kind), what repos.resolve takes.
2249
+
2250
+ One repos.resolve call over the whole batch, so the base-commit step sees every known root; a
2251
+ run resolved on its own could miss its root.
2252
+ """
2253
+ listed = []
2254
+ for path, source in found:
2255
+ kind = _kind(path)
2256
+ if kind:
2257
+ reader = _Read(path)
2258
+ listed.append((path, source, (str(reader.path), reader.line('repo'), kind)))
2259
+ return listed, repos.resolve([entry for _path, _source, entry in listed])
2260
+
2261
+
2262
+ def repo_root(identity, repo):
2263
+ """A run's grouping key: its identity's root, or its repo text when nothing better is known."""
2264
+ return identity['root'] or repo
2265
+
2266
+
2267
+ def _with_repo(result, identity):
2268
+ """A run summary or detail with its repository fields: repo_root (the grouping key), repo_worktree
2269
+ (the checkout it started in, null when that is the root) and repo_branch (null when unknown)."""
2270
+ result.update(repo_root=repo_root(identity, result['repo']), repo_worktree=identity['worktree'],
2271
+ repo_branch=identity['branch'])
2272
+ return result
2273
+
2274
+
2246
2275
  class Catalog:
2247
2276
  def __init__(self, plans=(), roots=(), registry=True, registry_dir=None):
2248
2277
  self.options = dict(plans=tuple(plans), roots=tuple(roots), registry=registry, registry_dir=registry_dir)
2249
2278
 
2250
2279
  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)
2280
+ listed, identities = batch(discover(**self.options))
2281
+ runs = [_with_repo(summarize(path, source), identities[entry[0]]) for path, source, entry in listed]
2256
2282
  return sorted(runs, key=lambda item: item['updated'] if item['updated'] is not None else float('-inf'), reverse=True)
2257
2283
 
2284
+ def identity(self, key):
2285
+ """The identity of the run with this key, resolved in the same batch as the list; None for no such run."""
2286
+ listed, identities = batch(discover(**self.options))
2287
+ for path, _source, entry in listed:
2288
+ if run_key(path) == key:
2289
+ return identities[entry[0]]
2290
+ return None
2291
+
2258
2292
  def _find(self, key, read, *args):
2259
2293
  for path, source in discover(**self.options):
2260
2294
  if run_key(path) == key:
@@ -2273,7 +2307,11 @@ class Catalog:
2273
2307
  return None
2274
2308
 
2275
2309
  def get(self, key):
2276
- return self._find(key, detail)
2310
+ listed, identities = batch(discover(**self.options))
2311
+ for path, source, entry in listed:
2312
+ if run_key(path) == key:
2313
+ return _with_repo(detail(path, source=source), identities[entry[0]])
2314
+ return None
2277
2315
 
2278
2316
  def task(self, key, task_id):
2279
2317
  return self._find(key, task_detail, task_id)
@@ -0,0 +1,428 @@
1
+ """Resolve which repository each forge run belongs to, for new and old runs.
2
+
3
+ forge-ui used to group runs by the literal text of each run's ``repo`` file, which is the checkout
4
+ the run started in. A run started from a git worktree therefore looked like one more repository,
5
+ and once the worktree was removed its path could never be resolved again. This module turns a run
6
+ into an identity instead. It is read-only: it never writes a run dir or a repository.
7
+
8
+ Public interface::
9
+
10
+ Run = (path, repo, kind)
11
+ path the run dir
12
+ repo the text of its ``repo`` file, or None
13
+ kind 'plan' or 'solo'
14
+
15
+ resolve(runs) -> {path: Identity}
16
+ Resolves a batch of runs, for example every run the catalog lists. Each Identity is a dict
17
+ {root, worktree, branch, source}:
18
+ root the repository's main working tree and the grouping key; never None when the
19
+ run has a ``repo`` text (None only when it has none)
20
+ worktree the physical checkout when it differs from root, else None
21
+ branch the branch checked out when the run was created, else None (unknown)
22
+ source how it was found: 'identity', 'live', 'base-commit' or 'path'
23
+
24
+ The order for each run:
25
+
26
+ 1. ``repo.identity`` in the run dir (one JSON object written by forge: root, worktree, branch).
27
+ Used when ``root`` is an absolute path; ``worktree`` and ``branch`` are taken when strings.
28
+ ``root`` is not checked for existence: the identity was right when it was written.
29
+ 2. The ``repo`` path still exists and is a git checkout: root is the first entry of
30
+ ``git worktree list --porcelain``. worktree is the linked checkout holding ``repo`` (None
31
+ when that is root itself); branch is unknown. Source 'live'.
32
+ 3. The ``repo`` path is gone: the run's base commit (``integration.base`` or else the first
33
+ readable ``tasks/*/base_ref`` for a plan, ``dwarf.head.before`` for a solo run) is looked for in
34
+ the known roots, the roots steps 1 and 2 found in this batch that still exist. Exactly one
35
+ match: root is that one and worktree is the ``repo`` text. Source 'base-commit'.
36
+ 4. Otherwise today's behaviour: root is the ``repo`` text. Source 'path'. A run is never grouped
37
+ under a repository it might not belong to.
38
+
39
+ Cost: every git call is an argument list with ``-C <absolute existing dir>``, stdin closed and a
40
+ short timeout; a failure or timeout means "not found". Within one ``resolve`` call ``git worktree
41
+ list`` runs at most once per distinct repo path and ``cat-file`` at most once per (root, sha).
42
+ Results from steps 2 and 3 are cached for the life of the process by run dir (the repository of a
43
+ run never changes); a step 4 result is cached with the known roots it was checked against and is
44
+ resolved again only when that set changes or its repo path appears or vanishes. Step 1 needs no
45
+ git and is not cached.
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import os
51
+ import re
52
+ import stat
53
+ import subprocess
54
+ import threading
55
+
56
+
57
+ _GIT_TIMEOUT = 5
58
+ # repo.identity is a few hundred bytes; anything bigger is not ours.
59
+ _MAX_IDENTITY_BYTES = 64 * 1024
60
+ # A commit id is one short line.
61
+ _MAX_LINE_BYTES = 4096
62
+ _SHA = re.compile(r'(?:[0-9a-f]{40}|[0-9a-f]{64})')
63
+
64
+ # (path, repo) -> identity, for runs resolved by step 2 or 3.
65
+ _RESOLVED: dict = {}
66
+ # (path, repo) -> (frozenset of known roots, repo was a directory, identity), for runs that fell
67
+ # through to step 4.
68
+ _FALLTHROUGH: dict = {}
69
+ _LOCK = threading.Lock()
70
+
71
+
72
+ def _identity(root, worktree=None, branch=None, source='path'):
73
+ return {'root': root, 'worktree': worktree, 'branch': branch, 'source': source}
74
+
75
+
76
+ def _read_file(path, limit):
77
+ """Up to ``limit`` bytes of a regular file as text, or None (missing, unreadable, not a file).
78
+
79
+ One byte more than the limit is read so an oversized file is told apart from one that fits:
80
+ that returns None as well.
81
+ """
82
+ fd = None
83
+ try:
84
+ # O_NONBLOCK: opening a fifo someone left in a run dir must not hang the reader.
85
+ fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NONBLOCK', 0))
86
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
87
+ return None
88
+ data = b''
89
+ while len(data) <= limit:
90
+ chunk = os.read(fd, limit + 1 - len(data))
91
+ if not chunk:
92
+ break
93
+ data += chunk
94
+ except (OSError, ValueError):
95
+ return None
96
+ finally:
97
+ if fd is not None:
98
+ os.close(fd)
99
+ if len(data) > limit:
100
+ return None
101
+ return data.decode('utf-8', 'replace')
102
+
103
+
104
+ def _read_line(path):
105
+ text = _read_file(path, _MAX_LINE_BYTES)
106
+ if text is None:
107
+ return None
108
+ lines = text.strip().splitlines()
109
+ return lines[0].strip() if lines else None
110
+
111
+
112
+ def _is_dir(path) -> bool:
113
+ try:
114
+ return os.path.isabs(path) and os.path.isdir(path)
115
+ except (OSError, ValueError):
116
+ return False
117
+
118
+
119
+ def _real(path):
120
+ try:
121
+ return os.path.realpath(path)
122
+ except (OSError, ValueError):
123
+ return path
124
+
125
+
126
+ def _run_git(cwd, *args):
127
+ """CompletedProcess of ``git -C cwd <args>``, or None when git could not run or timed out.
128
+
129
+ ``cwd`` is an absolute existing directory. No shell, stdin closed, output captured.
130
+ """
131
+ try:
132
+ return subprocess.run(
133
+ ['git', '-C', cwd, *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
134
+ stderr=subprocess.DEVNULL, timeout=_GIT_TIMEOUT, check=False,
135
+ env=dict(os.environ, GIT_TERMINAL_PROMPT='0'))
136
+ except (OSError, ValueError, subprocess.SubprocessError):
137
+ return None
138
+
139
+
140
+ # ---- step 1: repo.identity ---------------------------------------------------------------------
141
+
142
+ def _from_identity_file(run_dir):
143
+ text = _read_file(os.path.join(run_dir, 'repo.identity'), _MAX_IDENTITY_BYTES)
144
+ if text is None:
145
+ return None
146
+ try:
147
+ data = json.loads(text)
148
+ except (ValueError, RecursionError):
149
+ return None
150
+ if not isinstance(data, dict):
151
+ return None
152
+ root = data.get('root')
153
+ if not isinstance(root, str) or '\0' in root or not os.path.isabs(root):
154
+ return None
155
+ worktree, branch = data.get('worktree'), data.get('branch')
156
+ return _identity(root, worktree if isinstance(worktree, str) else None,
157
+ branch if isinstance(branch, str) else None, 'identity')
158
+
159
+
160
+ # ---- step 2: the repo path is a live checkout --------------------------------------------------
161
+
162
+ def _checkout_identity(repo):
163
+ """``(ran, identity)`` for the checkout ``repo``: identity is None when ``repo`` is no checkout
164
+ or its listing could not be read safely; ran is False when git did not run or timed out.
165
+
166
+ ``-z`` keeps a path that contains a newline in one piece. A git too old for it (exit 129)
167
+ falls back to ``_legacy_identity``.
168
+ """
169
+ done = _run_git(repo, 'worktree', 'list', '--porcelain', '-z')
170
+ if done is None:
171
+ return False, None
172
+ if done.returncode == 129:
173
+ return _legacy_identity(repo)
174
+ if done.returncode != 0:
175
+ return True, None
176
+ return True, _live_identity(repo, _porcelain_z_paths(done.stdout) or [])
177
+
178
+
179
+ def _porcelain_z_paths(out):
180
+ """The worktree paths of ``git worktree list --porcelain -z`` output, in order, or None unless
181
+ the whole output is well formed.
182
+
183
+ Every field ends with a NUL and every record with one more (an empty field). A record starts
184
+ with ``worktree <absolute path>``; the fields after it are not read but may not be empty.
185
+ """
186
+ if not isinstance(out, bytes) or not out.endswith(b'\0'):
187
+ return None
188
+ fields = out[:-1].split(b'\0')
189
+ paths = []
190
+ at_start = True
191
+ for field in fields:
192
+ if at_start:
193
+ if not field.startswith(b'worktree '):
194
+ return None
195
+ path = os.fsdecode(field[len(b'worktree '):])
196
+ if not os.path.isabs(path):
197
+ return None
198
+ paths.append(path)
199
+ at_start = False
200
+ elif not field:
201
+ at_start = True
202
+ # The last field must have closed a record.
203
+ return paths if at_start and paths else None
204
+
205
+
206
+ def _rev_parse_path(repo, option):
207
+ """``(ran, path)`` for a ``git rev-parse`` option that prints one path, made absolute.
208
+
209
+ One value per call, so a newline inside the path cannot split it: only git's final newline
210
+ is dropped.
211
+ """
212
+ done = _run_git(repo, 'rev-parse', option)
213
+ if done is None:
214
+ return False, None
215
+ out = done.stdout.decode('utf-8', 'replace')
216
+ if done.returncode != 0 or not out.endswith('\n') or out == '\n':
217
+ return True, None
218
+ return True, os.path.join(repo, out[:-1])
219
+
220
+
221
+ def _git_dir_of(root):
222
+ """The git dir of the working tree ``root`` (its ``.git`` directory or the one a ``.git``
223
+ file names), or None."""
224
+ if not _is_dir(root):
225
+ return None
226
+ dot = os.path.join(root, '.git')
227
+ if os.path.isdir(dot):
228
+ return dot
229
+ text = _read_file(dot, _MAX_LINE_BYTES)
230
+ if text is None or not text.startswith('gitdir: '):
231
+ return None
232
+ lines = text[len('gitdir: '):].splitlines()
233
+ return os.path.join(root, lines[0]) if lines and lines[0] else None
234
+
235
+
236
+ def _legacy_identity(repo):
237
+ """``(ran, identity)`` from line-separated porcelain output, for a git without ``-z``.
238
+
239
+ Without ``-z`` a path containing a newline is split over several lines, and its fragments can
240
+ look like porcelain fields or whole entries, including a path that names another repository.
241
+ No reading of the lines can tell, so the shape is not trusted at all: the first line's path is
242
+ taken as the main working tree only when its git dir is the common dir of ``repo``'s
243
+ repository. The checkout holding ``repo`` comes from ``--show-toplevel``, which prints one path.
244
+ """
245
+ done = _run_git(repo, 'worktree', 'list', '--porcelain')
246
+ if done is None:
247
+ return False, None
248
+ if done.returncode != 0:
249
+ return True, None
250
+ first = done.stdout.decode('utf-8', 'replace').split('\n', 1)[0]
251
+ root = first[len('worktree '):] if first.startswith('worktree ') else ''
252
+ if not os.path.isabs(root):
253
+ return True, None
254
+ root_git_dir = _git_dir_of(root)
255
+ if root_git_dir is None:
256
+ return True, None
257
+ ran, common = _rev_parse_path(repo, '--git-common-dir')
258
+ if common is None or _real(common) != _real(root_git_dir):
259
+ return ran, None
260
+ ran, top = _rev_parse_path(repo, '--show-toplevel')
261
+ if not ran:
262
+ return False, None
263
+ # No toplevel (repo is inside a git dir): the verified root alone is listed.
264
+ return True, _live_identity(repo, [root] + ([top] if top else []))
265
+
266
+
267
+ def _live_identity(repo, entries):
268
+ """Identity from the worktree list of ``repo``; None when it listed nothing usable."""
269
+ if not entries:
270
+ return None
271
+ root = entries[0]
272
+ here, real_root = _real(repo), _real(root)
273
+ holder = None
274
+ for entry in entries:
275
+ real = _real(entry)
276
+ if (here == real or here.startswith(real.rstrip(os.sep) + os.sep)) and (
277
+ holder is None or len(real) > len(holder[1])):
278
+ holder = (entry, real)
279
+ if holder is None:
280
+ worktree = None if here == real_root else here
281
+ else:
282
+ worktree = None if holder[1] == real_root else holder[0]
283
+ return _identity(root, worktree, None, 'live')
284
+
285
+
286
+ # ---- step 3: the base commit is in exactly one known root --------------------------------------
287
+
288
+ def _base_commit(run_dir, kind):
289
+ """The run's base commit as lower-case hex, or None when unknown or not a commit id."""
290
+ if kind == 'plan':
291
+ line = _read_line(os.path.join(run_dir, 'integration.base'))
292
+ if not line:
293
+ try:
294
+ with os.scandir(os.path.join(run_dir, 'tasks')) as entries:
295
+ names = sorted(entry.name for entry in entries)
296
+ except (OSError, ValueError):
297
+ names = []
298
+ for name in names:
299
+ line = _read_line(os.path.join(run_dir, 'tasks', name, 'base_ref'))
300
+ if line:
301
+ break
302
+ elif kind == 'solo':
303
+ line = _read_line(os.path.join(run_dir, 'dwarf.head.before'))
304
+ else:
305
+ line = None
306
+ line = (line or '').lower()
307
+ # Only a full hex id ever reaches git: nothing that could be read as an option or a ref.
308
+ return line if _SHA.fullmatch(line) else None
309
+
310
+
311
+ def _distinct_roots(roots):
312
+ """Known roots without duplicates that are only different spellings of one directory."""
313
+ seen = {}
314
+ for root in sorted(roots):
315
+ seen.setdefault(_real(root), root)
316
+ return list(seen.values())
317
+
318
+
319
+ def _by_base_commit(sha, roots, has_commit):
320
+ matches = [root for root in _distinct_roots(roots) if has_commit(root, sha)]
321
+ return matches[0] if len(matches) == 1 else None
322
+
323
+
324
+ # ---- the batch ---------------------------------------------------------------------------------
325
+
326
+ def resolve(runs):
327
+ """{run dir: Identity} for every ``(path, repo, kind)`` in ``runs``; see the module docstring."""
328
+ runs = list(runs)
329
+ result = {}
330
+ checkouts = {}
331
+ commit_checks = {}
332
+
333
+ def checkout(repo):
334
+ if repo not in checkouts:
335
+ checkouts[repo] = _checkout_identity(repo)
336
+ found = checkouts[repo][1]
337
+ return dict(found) if found is not None else None
338
+
339
+ def has_commit(root, sha):
340
+ key = (root, sha)
341
+ if key not in commit_checks:
342
+ done = _run_git(root, 'cat-file', '-e', sha + '^{commit}')
343
+ commit_checks[key] = done is not None and done.returncode == 0
344
+ return commit_checks[key]
345
+
346
+ known_roots = set()
347
+
348
+ def found_by(given, found):
349
+ result[given] = found
350
+ if found['source'] != 'base-commit' and _is_dir(found['root']):
351
+ known_roots.add(found['root'])
352
+
353
+ def live_step(path, repo):
354
+ found = checkout(repo)
355
+ if found is not None:
356
+ with _LOCK:
357
+ _RESOLVED[(path, repo)] = dict(found)
358
+ return found
359
+
360
+ pending = []
361
+ # Runs with a step 4 answer from an earlier call, held back until the known roots are final.
362
+ waiting = []
363
+ # Steps 1 and 2 for the whole batch first: step 3 needs every root they found.
364
+ for given, repo, kind in runs:
365
+ path = os.fspath(given)
366
+ repo = repo if isinstance(repo, str) and repo.strip() else None
367
+ if repo is None:
368
+ result[given] = _identity(None)
369
+ continue
370
+ found = _from_identity_file(path)
371
+ if found is None:
372
+ with _LOCK:
373
+ found = _RESOLVED.get((path, repo))
374
+ cached = _FALLTHROUGH.get((path, repo))
375
+ if found is not None:
376
+ found = dict(found)
377
+ elif cached is not None:
378
+ waiting.append((given, path, repo, kind, _is_dir(repo), cached))
379
+ continue
380
+ elif _is_dir(repo):
381
+ found = live_step(path, repo)
382
+ if found is None:
383
+ pending.append((given, path, repo, kind))
384
+ continue
385
+ found_by(given, found)
386
+
387
+ # A step 4 answer holds while the repo path has neither appeared nor vanished and the known
388
+ # roots are the ones it was checked against. A stale one goes through step 2 again, which can
389
+ # add a root and so make another one stale: repeat until the known roots stop changing.
390
+ while True:
391
+ roots_key = frozenset(known_roots)
392
+ still = []
393
+ for item in waiting:
394
+ given, path, repo, kind, live, cached = item
395
+ if cached[0] == roots_key and cached[1] == live:
396
+ still.append(item)
397
+ continue
398
+ found = live_step(path, repo) if live else None
399
+ if found is None:
400
+ pending.append((given, path, repo, kind))
401
+ else:
402
+ found_by(given, found)
403
+ waiting = still
404
+ if frozenset(known_roots) == roots_key:
405
+ break
406
+ for given, _path, _repo, _kind, _live, cached in waiting:
407
+ result[given] = dict(cached[2])
408
+
409
+ roots_key = frozenset(known_roots)
410
+ for given, path, repo, kind in pending:
411
+ key = (path, repo)
412
+ live = _is_dir(repo)
413
+ found = None
414
+ if not live:
415
+ sha = _base_commit(path, kind)
416
+ root = _by_base_commit(sha, known_roots, has_commit) if sha else None
417
+ if root is not None:
418
+ found = _identity(root, repo, None, 'base-commit')
419
+ with _LOCK:
420
+ _RESOLVED[key] = dict(found)
421
+ if found is None:
422
+ found = _identity(repo)
423
+ # A live repo whose git call timed out is retried next time rather than remembered.
424
+ if not (live and not checkouts.get(repo, (True, None))[0]):
425
+ with _LOCK:
426
+ _FALLTHROUGH[key] = (roots_key, live, dict(found))
427
+ result[given] = found
428
+ return result
@@ -207,9 +207,26 @@ window.ForgeApp = (() => {
207
207
  function filteredRuns() {
208
208
  const runs = state.runs.filter(run => RM.matchRun(run, state.mapFilter, wall())), byTime = (a, b) => (b.updated || 0) - (a.updated || 0);
209
209
  if (state.runSort === 'state') return runs.sort((a, b) => STATE_ORDER[RM.runState(a)] - STATE_ORDER[RM.runState(b)] || byTime(a, b));
210
- if (state.runSort === 'repo') return runs.sort((a, b) => RM.basename(a.repo).localeCompare(RM.basename(b.repo)) || byTime(a, b));
210
+ if (state.runSort === 'repo') return runs.sort((a, b) => RM.compareRepo(a, b) || byTime(a, b));
211
211
  return runs.sort(byTime);
212
212
  }
213
+ // The repository's name, and — when the run started in a worktree — that checkout as secondary text.
214
+ // The worktree is "leaf (branch)": the leaf truncates first, the branch keeps its place. The title is the full path
215
+ // and, on a second line, the full branch, since the branch can be truncated on screen.
216
+ // No worktree: the name span alone, as before.
217
+ function appendRepo(parent, run) {
218
+ const label = RM.repoLabel(run);
219
+ const name = el('span', label.name, 'repo');
220
+ if (!label.worktree) { parent.append(name); return; }
221
+ const line = el('span', undefined, 'repo-line');
222
+ const wt = el('span', undefined, 'muted repo-wt');
223
+ const branch = typeof run.repo_branch === 'string' ? run.repo_branch.trim() : '';
224
+ wt.title = run.repo_worktree + (branch ? `\nbranch ${branch}` : '');
225
+ const at = branch ? label.worktree.length - branch.length - 3 : label.worktree.length; // " (" and ")" around the branch
226
+ wt.append(el('span', label.worktree.slice(0, at), 'repo-leaf'), el('span', label.worktree.slice(at), 'repo-branch'));
227
+ line.append(name, document.createTextNode(' · '), wt);
228
+ parent.append(line);
229
+ }
213
230
  function renderList() {
214
231
  const runs = filteredRuns();
215
232
  $('run-count').textContent = `${runs.length}/${state.runs.length}`;
@@ -238,7 +255,8 @@ window.ForgeApp = (() => {
238
255
  const updated = el('span', relative(run.updated).replace(/^updated /, ''), 'updated');
239
256
  if (run.updated != null) { updated.dataset.epoch = run.updated; updated.dataset.short = ''; }
240
257
  updated.title = time(run.updated);
241
- sub.append(el('span', RM.basename(run.repo), 'repo'), el('span', run.run_id, 'mono'), updated);
258
+ appendRepo(sub, run);
259
+ sub.append(el('span', run.run_id, 'mono'), updated);
242
260
  item.append(lamp, goal, sub);
243
261
  if (solo) item.append(el('span', 'solo', 'tag'));
244
262
  const counts = el('div', undefined, 'chips');
@@ -729,7 +747,8 @@ window.ForgeApp = (() => {
729
747
  const lamp = el('i', undefined, 'lamp st-' + LAMP[RM.runState(run)]);
730
748
  const title = el('h2', String(run.goal || 'Untitled run').split('\n')[0]); title.title = run.goal || '';
731
749
  const where = el('span', undefined, 'run-where'); where.title = `${run.repo || ''}\n${run.run_id || ''}`;
732
- where.append(el('span', RM.basename(run.repo), 'repo'), document.createTextNode(' '), el('span', run.run_id, 'mono'));
750
+ appendRepo(where, run);
751
+ where.append(el('span', run.run_id, 'mono'));
733
752
  if (solo) where.append(document.createTextNode(' · solo run'));
734
753
  // the describer: each state's count, the wall time so far, and how long since anything moved
735
754
  const desc = el('span', undefined, 'describer');