@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
@@ -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
@@ -106,7 +106,7 @@ window.ForgeApp = (() => {
106
106
  function link(text, key, sel) { const a = el('a', text); a.href = hashFor(key, sel); return a; }
107
107
 
108
108
  const statuses = new Set(['merged', 'pass', 'running', 'pending', 'fail', 'error', 'infra',
109
- 'timeout', 'unknown', 'invalidated', 'blocked', 'interrupted', 'nochanges', 'conflict', 'accepted', 'outdated', 'needs_input']);
109
+ 'timeout', 'unknown', 'invalidated', 'blocked', 'interrupted', 'nochanges', 'conflict', 'accepted', 'outdated', 'needs_input', 'needs_decision']);
110
110
  function chip(value, cls) {
111
111
  const status = String(cls || value || 'unknown').toLowerCase();
112
112
  return el('span', value || '—', 'chip st-' + (statuses.has(status) ? status : 'unknown'));
@@ -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');
@@ -759,7 +778,7 @@ window.ForgeApp = (() => {
759
778
  { id: 'title', label: 'Title', value: t => t.title },
760
779
  { id: 'difficulty', label: 'Difficulty', value: t => DIFF_RANK[t.difficulty] ?? null, cell: t => display(t.difficulty) },
761
780
  { id: 'wave', label: 'Wave', value: t => Number.isFinite(Number(t.wave)) && t.wave !== null && t.wave !== '' ? Number(t.wave) : null, cell: t => display(t.wave) },
762
- { id: 'status', label: 'Status', value: t => RM.taskStatus(t), cell: t => chip(RM.taskStatus(t)) },
781
+ { id: 'status', label: 'Status', value: t => RM.taskStatus(t), cell: t => chip(RM.statusText(t), RM.taskStatus(t)) },
763
782
  ...(window.ForgeChecks ? [{ id: 'now', label: 'Now', title: 'What a running task is doing, or why one that is not running waits',
764
783
  value: t => window.ForgeChecks.nowRank(t), cell: t => window.ForgeChecks.cell(t, now(), { hash: s => hashFor(run.key, s) }) }] : []),
765
784
  { id: 'dwarf', label: 'Dwarf', value: t => t.dwarf, cell: t => window.ForgeIcons.modelPlate(t.dwarf) },
@@ -19,6 +19,7 @@
19
19
  })(typeof self !== 'undefined' ? self : this, function (root) {
20
20
  'use strict';
21
21
 
22
+ const RM = typeof module === 'object' && module.exports ? require('./runmodel.js') : root.ForgeRunModel;
22
23
  const QUIET_WARN_S = 300; // a log quiet past this is flagged, as the verification view flags its own
23
24
  const ENV_EVERY_S = 15; // a running run's environment problems are read again at most this often
24
25
  const list = v => Array.isArray(v) ? v : [];
@@ -68,8 +69,9 @@
68
69
  if (scope.startsWith('harness:')) return `harness ${w.harness || scope.slice(8)}`;
69
70
  return scope || 'its model';
70
71
  }
71
- // Why a task waits: {kind, text, tasks: [{id, stopped}], until, exhausted, split}, or null
72
- function waitingModel(w) {
72
+ // Why a task waits: {kind, text, tasks: [{id, stopped}], until, exhausted, split}, or null. A pause also has
73
+ // reset (its reset time, from now) and needs (`needs you: <hint>` when the user must act), each null when unknown.
74
+ function waitingModel(w, now) {
73
75
  if (!w || typeof w !== 'object') return null;
74
76
  const ids = v => list(v).map(String);
75
77
  const out = { kind: w.kind, tasks: [], until: null, exhausted: false, split: null };
@@ -83,8 +85,11 @@
83
85
  if (w.kind === 'stopping') return { ...out, text: w.mode === 'now' ? 'the run is stopping now' : 'the run stops once its running tasks end' };
84
86
  if (w.kind === 'next') return { ...out, text: "starts at the scheduler's next turn" };
85
87
  if (w.kind === 'infra') {
86
- return { ...out, text: `paused: ${scopeText(w)}${w.class ? ' · ' + String(w.class).replace(/_/g, ' ') : ''}`,
87
- until: w.exhausted === true ? null : num(w.until), exhausted: w.exhausted === true };
88
+ const cause = RM.causeLabel(w.class);
89
+ const needs = w.needs_you === true ? (typeof w.hint === 'string' && w.hint ? `needs you: ${w.hint}` : 'needs you') : null;
90
+ return { ...out, text: `paused: ${scopeText(w)}${cause ? ' · ' + cause : ''}`,
91
+ until: w.exhausted === true ? null : num(w.until), exhausted: w.exhausted === true,
92
+ reset: RM.resetText(w.reset_at, now), needs };
88
93
  }
89
94
  if (w.kind === 'escalation') {
90
95
  return { ...out, text: `stopped by the retry policy${num(w.attempts) !== null ? ` after ${plural(w.attempts, 'attempt')}` : ''}${w.model ? ' on ' + w.model : ''}`,
@@ -196,6 +201,11 @@
196
201
  if (t.stopped) parent.append(el('span', ' (stopped)', 'warn'));
197
202
  });
198
203
  }
204
+ // a pause's reset time after its line, then `needs you: <hint>` on a line of its own in the warn style
205
+ function pauseNotes(parent, w) {
206
+ if (w.reset) parent.append(document.createTextNode(' · ' + w.reset));
207
+ if (w.needs) parent.append(el('span', w.needs, 'warn pause-needs'));
208
+ }
199
209
  // Brings the times under `root` up to `now` (epoch seconds) between redraws.
200
210
  function tick(rootNode, now) {
201
211
  if (!rootNode || !rootNode.querySelectorAll || num(now) === null) return;
@@ -216,19 +226,20 @@
216
226
  box.append(quietNode(m.quietSince, now));
217
227
  return box;
218
228
  }
219
- const w = waitingModel(task && task.waiting);
229
+ const w = waitingModel(task && task.waiting, now);
220
230
  if (!w) { box.append(el('span', '—', 'muted')); return box; }
221
231
  box.classList.add('now-waiting');
222
232
  box.append(el('span', w.text + (w.tasks.length ? ' ' : ''), 'now-why'));
223
233
  taskLinks(box, ctx, w.tasks);
224
234
  if (w.until !== null) box.append(untilNode(w.until, now));
235
+ pauseNotes(box, w);
225
236
  if (w.exhausted) box.append(el('span', 'waits used up', 'warn'));
226
237
  return box;
227
238
  }
228
239
 
229
240
  // The task inspector's Now section: what it does, or why it waits
230
241
  function nowSection(host, ctx, task) {
231
- const m = nowModel(task), w = m ? null : waitingModel(task.waiting);
242
+ const m = nowModel(task), w = m ? null : waitingModel(task.waiting, ctx.now);
232
243
  if (!m && !w) return;
233
244
  const s = section(host, 'Now', 'now-section');
234
245
  const box = el('div', undefined, 'vfy-live now-live');
@@ -267,6 +278,7 @@
267
278
  p.append(el('span', w.text + (w.tasks.length ? ' ' : '')));
268
279
  taskLinks(p, ctx, w.tasks);
269
280
  if (w.until !== null) p.append(document.createTextNode(' · '), untilNode(w.until, ctx.now));
281
+ pauseNotes(p, w);
270
282
  if (w.exhausted) p.append(el('span', ' · its waits are used up', 'warn'));
271
283
  box.append(p);
272
284
  if (w.split) {
@@ -390,9 +402,10 @@
390
402
  const dl = el('dl', undefined, 'fields');
391
403
  for (const [label, value] of rows) { dl.append(el('dt', label), el('dd', value)); }
392
404
  for (const p of list(run.scheduler.pauses)) {
393
- const w = waitingModel({ ...p, kind: 'infra' });
405
+ const w = waitingModel({ ...p, kind: 'infra' }, now);
394
406
  const dd = el('dd', w.text);
395
407
  if (w.until !== null) dd.append(document.createTextNode(' · '), untilNode(w.until, now));
408
+ pauseNotes(dd, w);
396
409
  if (w.exhausted) dd.append(el('span', ' · its waits are used up', 'warn'));
397
410
  dl.append(el('dt', 'Paused'), dd);
398
411
  }
@@ -25,7 +25,7 @@
25
25
  };
26
26
  const DIFFS = ['low', 'medium', 'high'];
27
27
 
28
- // FNV-1a: a short stable id for a project (its repo path)
28
+ // FNV-1a: a short stable id for a project (its repository root)
29
29
  function hashId(s) {
30
30
  let h = 0x811c9dc5;
31
31
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
@@ -35,11 +35,13 @@
35
35
  const startOf = r => num(r.created) ?? num(r.updated) ?? 0;
36
36
 
37
37
  /* ---------- projects and per-run facts ---------- */
38
+ // a run's project is its repository root (RM.repoKey), so a run started from a worktree joins its repository's project
39
+ const projectId = r => hashId(RM.repoKey(r) || '?');
38
40
  function projects(runs) {
39
41
  const by = new Map();
40
42
  for (const r of list(runs)) {
41
- const repo = r.repo || '?', id = hashId(repo);
42
- if (!by.has(id)) by.set(id, { id, repo: r.repo || null, name: RM.basename(r.repo), keys: [], first: Infinity, last: -Infinity, count: 0 });
43
+ const id = projectId(r), key = RM.repoKey(r);
44
+ if (!by.has(id)) by.set(id, { id, repo: key, name: RM.basename(key), keys: [], first: Infinity, last: -Infinity, count: 0 });
43
45
  const p = by.get(id), t = startOf(r);
44
46
  p.keys.push(r.key); p.count++; p.first = Math.min(p.first, t); p.last = Math.max(p.last, num(r.updated) ?? t);
45
47
  }
@@ -61,7 +63,7 @@
61
63
  if (state === 'live' && num(now) !== null && num(run.updated) !== null && now - run.updated > 7200) state = 'stale';
62
64
  const n = Math.max(1, num(run.task_count) || tasks.length || 1);
63
65
  const aliases = specs => new Set(list(specs).map(RM.alias).filter(Boolean));
64
- return { key: run.key, run, project: hashId(run.repo || '?'), n, bucket: bucket(n), diff, dominant, state, t: startOf(run),
66
+ return { key: run.key, run, project: projectId(run), checkout: hashId(run.repo || '?'), n, bucket: bucket(n), diff, dominant, state, t: startOf(run),
65
67
  dwarf: aliases(run.dwarf_models || run.models), qa: aliases(run.qa_models || []), all: aliases(run.models),
66
68
  review: RM.runReviewStatus(run) || null, verification: run.verification_status || null, decompose: run.decompose_level || null, kind: run.kind };
67
69
  }
@@ -89,7 +91,8 @@
89
91
  const hay = [r.goal, r.repo, r.run_id, r.path, ...list(r.models), ...list(r.task_statuses).flatMap(t => [t.id, t.title])];
90
92
  if (!hay.some(v => String(v || '').toLowerCase().includes(text))) return false;
91
93
  }
92
- if (f.projects.length && !f.projects.includes(fact.project)) return false;
94
+ // a saved project may be the checkout a run started in (a worktree, before it joined its root): the run still matches it
95
+ if (f.projects.length && !f.projects.includes(fact.project) && !f.projects.includes(fact.checkout)) return false;
93
96
  if (f.states.length && !f.states.includes(fact.state)) return false;
94
97
  if (f.kinds.length && !f.kinds.includes(fact.kind)) return false;
95
98
  if (f.difficulty.levels.length) {
@@ -32,7 +32,10 @@
32
32
  };
33
33
  const BACKOFF_FORMS = 'exp:<base>[,<cap>], linear:<start>,<step>[,<cap>] or list:<a>,<b>,… (seconds)';
34
34
  // A task status after which "Retry now" applies (or the policy stopped it).
35
- const RETRYABLE = ['FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED']; // scripts/forge-schedule.py RETRYABLE; NEEDS_INPUT is in neither list
35
+ const RETRYABLE = ['FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED']; // scripts/forge-schedule.py RETRYABLE
36
+ // A task waiting for the user is not retried from forge-ui. NEEDS_INPUT needs an answer (retry --answer);
37
+ // NEEDS_DECISION is resumed with the CLI commands the decision text lists.
38
+ const WAITING = new Set(['NEEDS_INPUT', 'NEEDS_DECISION']);
36
39
 
37
40
  const obj = v => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
38
41
  const num = v => typeof v === 'number' && Number.isFinite(v) ? v : null;
@@ -216,10 +219,10 @@
216
219
  }
217
220
  const requestText = st => st.state === 'refused' ? `refused${st.reason ? ': ' + st.reason : ''}` : st.state;
218
221
  // Whether "Retry now" shows for a task: live only, after it ended without passing or once the policy stopped it.
219
- // Never for a task waiting for an answer: forge refuses a retry without one (retry --answer).
222
+ // Never while it waits for the user: an answer is retry --answer, a decision is the CLI commands in the decision text.
220
223
  const canRetry = (controls, id) => {
221
224
  const c = obj(controls), v = taskValues(c, id);
222
- return c.live === true && v.known && v.status !== 'MERGED' && v.status !== 'NEEDS_INPUT' && (RETRYABLE.includes(v.status) || v.stop);
225
+ return c.live === true && v.known && v.status !== 'MERGED' && !WAITING.has(v.status) && (RETRYABLE.includes(v.status) || v.stop);
223
226
  };
224
227
  // A task's controls with the effective value of each: an override wins, else the run's value is inherited.
225
228
  function taskValues(controls, id) {