@giamme/forge 0.15.0 → 0.16.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 (63) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/VERSION +1 -1
  3. package/docs/artifacts.md +1 -1
  4. package/docs/commands.md +14 -3
  5. package/docs/forge-ui.md +14 -0
  6. package/docs/memory.md +22 -0
  7. package/docs/reviews.md +7 -0
  8. package/forge +11 -0
  9. package/package.json +1 -1
  10. package/references/dataset.md +5 -2
  11. package/references/decompose.md +51 -5
  12. package/references/harnesses.md +4 -1
  13. package/references/solo.md +5 -1
  14. package/references/ui.md +10 -1
  15. package/scripts/forge-artifact.sh +53 -0
  16. package/scripts/forge-contract.py +55 -8
  17. package/scripts/forge-control.py +0 -2
  18. package/scripts/forge-dispatch.sh +28 -12
  19. package/scripts/forge-fail-first.py +3 -1
  20. package/scripts/forge-guard.py +247 -8
  21. package/scripts/forge-issues.py +12 -0
  22. package/scripts/forge-lib-adopt.sh +260 -0
  23. package/scripts/forge-lib-attribute.sh +10 -2
  24. package/scripts/forge-lib-plans.sh +16 -4
  25. package/scripts/forge-lib-review.sh +8 -2
  26. package/scripts/forge-lib-task.sh +19 -5
  27. package/scripts/forge-memory.sh +41 -4
  28. package/scripts/forge-metrics.sh +7 -0
  29. package/scripts/forge-parallel.sh +96 -13
  30. package/scripts/forge-route.py +16 -2
  31. package/scripts/forge-runs-rm.py +23 -7
  32. package/scripts/forge-runtime.py +25 -2
  33. package/scripts/forge-schedule.py +5 -2
  34. package/scripts/forge-shadow.py +2 -0
  35. package/scripts/forge-solo.sh +6 -0
  36. package/scripts/forge_dataset/cli.py +16 -0
  37. package/scripts/forge_dataset/export.py +1 -0
  38. package/scripts/forge_dataset/harvest.py +11 -0
  39. package/scripts/forge_dataset/history.py +126 -0
  40. package/scripts/forge_dataset/worktrees.py +95 -0
  41. package/scripts/forge_memory_list.py +153 -0
  42. package/scripts/forge_worktrees.py +88 -0
  43. package/ui/README.md +31 -0
  44. package/ui/docs/api.md +81 -4
  45. package/ui/forge_ui/__init__.py +14 -1
  46. package/ui/forge_ui/__main__.py +1 -1
  47. package/ui/forge_ui/control.py +77 -0
  48. package/ui/forge_ui/findings.py +7 -0
  49. package/ui/forge_ui/projects.py +571 -0
  50. package/ui/forge_ui/reader.py +27 -7
  51. package/ui/forge_ui/static/app.js +99 -21
  52. package/ui/forge_ui/static/cloudui.js +6 -2
  53. package/ui/forge_ui/static/convo.js +1 -1
  54. package/ui/forge_ui/static/diffview.js +2 -2
  55. package/ui/forge_ui/static/files.js +1 -1
  56. package/ui/forge_ui/static/index.html +5 -1
  57. package/ui/forge_ui/static/panel.js +28 -2
  58. package/ui/forge_ui/static/projectsview.js +372 -0
  59. package/ui/forge_ui/static/settings.js +136 -4
  60. package/ui/forge_ui/static/style.css +93 -3
  61. package/ui/forge_ui/static/uikit.js +94 -1
  62. package/ui/forge_ui/static/worktreesview.js +250 -0
  63. package/ui/forge_ui/worktrees.py +570 -0
@@ -0,0 +1,571 @@
1
+ """The Projects screen (#126): one page per repository, with its runs, every finding forge wrote about it and
2
+ every memory forge wrote for it, whichever run or checkout they came from.
3
+
4
+ A project is one repository root, as repos.py resolves it, and its id is the one the run cloud uses
5
+ (cloudmodel.js hashId: FNV-1a over the root's UTF-16 code units), so links between the two views match.
6
+
7
+ Sources, run dirs first:
8
+ runs the catalog's run dirs, grouped by their identity's root
9
+ findings every review of every run dir (each attempt, shadow reviews, final reviews), parsed by forge's
10
+ contract module through findings.py; their state in `forge issues` (dismissed, filed, swept) from
11
+ one offline listing per project; repeats within a task collapsed by `forge issues`' own
12
+ fingerprint (scripts/forge-issues.py, loaded read-only), never matched by guesswork
13
+ memories `forge memory learnings <dir> --json` for the root and each checkout a run started in that still
14
+ exists: the states come from forge-memory.sh itself
15
+ dataset `forge dataset history --json` for runs whose dir is gone and checkouts that are gone; those rows
16
+ say so and link to no run page or diff
17
+
18
+ Finding statuses: open, filed, fixed, swept, dismissed (as on a run's Open findings page) and superseded: a later
19
+ review of the same task (or a later final review) passed. That does not claim the finding was fixed.
20
+
21
+ Cost: nothing here runs on the page's poll. Each tab's endpoint is read when the tab opens; a run's findings
22
+ are cached by its `updated` time, the CLI answers for CACHE_S, and ?refresh=1 reads everything again.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import importlib.machinery
27
+ import importlib.util
28
+ import os
29
+ from pathlib import Path
30
+ import threading
31
+ import time
32
+
33
+ from forge_ui import executions, findings as F, reader, repos
34
+
35
+ ISSUES = Path(__file__).resolve().parents[2] / 'scripts' / 'forge-issues.py'
36
+ CACHE_S = 300
37
+ _SEVERITIES = ('P0', 'P1', 'P2', 'P3')
38
+ _STATE = {}
39
+ _LOCK = threading.Lock()
40
+
41
+
42
+ class _ReadOnlyLoader(importlib.machinery.SourceFileLoader):
43
+ def set_data(self, *args, **kwargs):
44
+ pass
45
+
46
+
47
+ def issues_module():
48
+ """scripts/forge-issues.py for its fingerprint (finding_key over parse_findings), or None."""
49
+ with _LOCK:
50
+ if 'issues' not in _STATE:
51
+ try:
52
+ spec = importlib.util.spec_from_file_location(
53
+ 'forge_issues_for_ui', ISSUES, loader=_ReadOnlyLoader('forge_issues_for_ui', str(ISSUES)))
54
+ module = importlib.util.module_from_spec(spec)
55
+ spec.loader.exec_module(module)
56
+ if not (callable(module.finding_key) and callable(module.parse_findings)):
57
+ raise TypeError('not forge issues')
58
+ _STATE['issues'] = module
59
+ except Exception:
60
+ _STATE['issues'] = None
61
+ return _STATE['issues']
62
+
63
+
64
+ def project_id(root):
65
+ """cloudmodel.js hashId(root): FNV-1a 32-bit over UTF-16 code units, 8 hex digits."""
66
+ h = 0x811c9dc5
67
+ data = str(root).encode('utf-16-le', 'surrogatepass')
68
+ for i in range(0, len(data), 2):
69
+ h ^= data[i] | (data[i + 1] << 8)
70
+ h = (h * 0x01000193) & 0xffffffff
71
+ return '%08x' % h
72
+
73
+
74
+ def fingerprint(first_line):
75
+ """`forge issues`' key for a finding whose first line it can parse, else None (such rows never collapse).
76
+ The canonical `[P1][CONFIRMED] path:line — text` form first, then the other forms forge issues reads from a
77
+ known_issues.md (`parse_known`), so a tolerated finding written another way still finds its entry."""
78
+ module = issues_module()
79
+ if module is None or not first_line:
80
+ return None
81
+ try:
82
+ parsed = module.parse_findings(first_line)
83
+ if not parsed and callable(getattr(module, 'parse_known', None)):
84
+ parsed = module.parse_known(first_line)
85
+ return module.finding_key(parsed[0]) if parsed else None
86
+ except Exception:
87
+ return None
88
+
89
+
90
+ def _isdir(path):
91
+ try:
92
+ return bool(path) and os.path.isabs(path) and os.path.isdir(path)
93
+ except (OSError, ValueError):
94
+ return False
95
+
96
+
97
+ def _first_line(path):
98
+ try:
99
+ with open(path, encoding='utf-8', errors='replace') as stream:
100
+ return stream.readline(4096).strip() or None
101
+ except (OSError, ValueError):
102
+ return None
103
+
104
+
105
+ # ---- runs and projects ---------------------------------------------------------------------------
106
+
107
+ def _catalog_runs(catalog):
108
+ """Run summaries with their repository fields, identity source and dataset uid."""
109
+ listed, identities = reader.batch(reader.discover(**catalog.options))
110
+ out = []
111
+ for path, source, entry in listed:
112
+ identity = identities[entry[0]]
113
+ summary = reader._with_repo(reader.summarize(path, source), identity)
114
+ summary['identity_source'] = identity['source']
115
+ summary['dataset_uid'] = _first_line(os.path.join(str(path), 'dataset.uid'))
116
+ summary['no_memory'] = os.path.exists(os.path.join(str(path), 'no_memory'))
117
+ out.append(summary)
118
+ out.sort(key=lambda r: r['updated'] if r['updated'] is not None else float('-inf'), reverse=True)
119
+ return out
120
+
121
+
122
+ def _names(projects):
123
+ """Two repositories with the same folder name get their parent folder too, as in the cloud."""
124
+ counts = {}
125
+ for p in projects:
126
+ counts[p['name']] = counts.get(p['name'], 0) + 1
127
+ for p in projects:
128
+ if counts[p['name']] > 1:
129
+ parts = [x for x in str(p['root']).split('/') if x]
130
+ p['name'] = '%s (%s)' % (p['name'], parts[-2] if len(parts) > 1 else '/')
131
+
132
+
133
+ def _memory_lines(root):
134
+ try:
135
+ with open(os.path.join(root, '.forge', 'memory.md'), encoding='utf-8', errors='replace') as stream:
136
+ return sum(1 for line in stream if line.startswith('- '))
137
+ except (OSError, ValueError):
138
+ return None
139
+
140
+
141
+ def group(runs):
142
+ """{project id: project} for the catalog's runs."""
143
+ out = {}
144
+ for run in runs:
145
+ root = reader.repo_root(dict(root=run.get('repo_root')), run.get('repo'))
146
+ if not root:
147
+ continue
148
+ pid = project_id(root)
149
+ p = out.setdefault(pid, dict(id=pid, root=root, name=os.path.basename(root.rstrip('/')) or root, runs=[],
150
+ exists=_isdir(root), live=0, last=None, path_only=0))
151
+ p['runs'].append(run)
152
+ if (run.get('counts') or {}).get('RUNNING'):
153
+ p['live'] += 1
154
+ if run.get('updated') is not None and (p['last'] is None or run['updated'] > p['last']):
155
+ p['last'] = run['updated']
156
+ if run.get('identity_source') == 'path':
157
+ p['path_only'] += 1
158
+ _names(list(out.values()))
159
+ return out
160
+
161
+
162
+ def checkouts(project):
163
+ """[{path, exists, branch, runs}] of the checkouts the project's runs started in, the root first."""
164
+ seen = {}
165
+ for run in project['runs']:
166
+ path = run.get('repo_worktree') or project['root']
167
+ c = seen.setdefault(path, dict(path=path, exists=_isdir(path), branch=run.get('repo_branch'), runs=0,
168
+ root=path == project['root']))
169
+ c['runs'] += 1
170
+ c['branch'] = c['branch'] or run.get('repo_branch')
171
+ return sorted(seen.values(), key=lambda c: (not c['root'], c['path']))
172
+
173
+
174
+ # ---- findings --------------------------------------------------------------------------------------
175
+
176
+ def _review_rows(rd, run, owner, reviews, names=None):
177
+ """One occurrence per finding of each review in `reviews` (oldest first), with `superseded` set. `names`
178
+ gives each final review's dir name; a task's reviews have none."""
179
+ out = []
180
+ passes = [(i, r) for i, r in enumerate(reviews) if r['verdict'] == 'PASS' and r['kind'] in ('primary', 'final')]
181
+ for index, review in enumerate(reviews):
182
+ if not review['last']:
183
+ continue
184
+ text = rd.text(review['last'])
185
+ listed = F.listing(text) if text else None
186
+ if not listed:
187
+ continue
188
+ info = rd.stat(review['last'])
189
+ at = float(info.st_mtime) if info is not None else None
190
+ attempt = review['attempt']
191
+
192
+ def later(pass_index, pass_review):
193
+ if review['kind'] == 'shadow':
194
+ return pass_review['attempt'] is not None and attempt is not None and pass_review['attempt'] > attempt
195
+ if attempt is not None and pass_review['attempt'] is not None and review['kind'] == 'primary':
196
+ return pass_review['attempt'] > attempt
197
+ return pass_index > index
198
+ superseded = any(later(i, r) for i, r in passes)
199
+ final_name = names[index] if names else None
200
+ for n, item in enumerate(listed):
201
+ first = (item['text'] or '').split('\n', 1)[0]
202
+ fid = reader._finding_id(review, n)
203
+ if final_name:
204
+ href = '#/runs/%s/final-review/%s/diff/finding/%s' % (run['key'], final_name, fid)
205
+ else:
206
+ href = '#/runs/%s/tasks/%s/diff/finding/%s' % (run['key'], owner, fid)
207
+ out.append(dict(source='run', run=run['key'], run_id=run.get('run_id'), task=None if final_name else owner,
208
+ final_review=final_name, attempt=attempt, kind=review['kind'], reviewer=review['spec'],
209
+ verdict=review['verdict'], at=at, id=fid, severity=item['severity'],
210
+ confidence=item['status'], location=item['location'], summary=item['summary'],
211
+ text=item['text'], fp=fingerprint(first), superseded=superseded, href=href))
212
+ return out
213
+
214
+
215
+ def run_occurrences(run):
216
+ """Every finding of every review of one run dir, oldest review first within each task."""
217
+ rd = reader._Read(run['path'])
218
+ kind = reader._kind(rd.path)
219
+ out = []
220
+ if kind is None:
221
+ return out
222
+ task_ids = ['solo'] if kind == 'solo' else [t['id'] for t in reader._tasks(rd)]
223
+ for task_id in task_ids:
224
+ ctx = reader._diff_task(rd, task_id)
225
+ if ctx:
226
+ out += _review_rows(rd, run, task_id, ctx['reviews'])
227
+ if kind == 'plan':
228
+ items, published = executions.review_dirs(rd)[0], reader._published(rd)
229
+ finals = []
230
+ for index, item in enumerate(items[:reader._MAX_REVIEWS]):
231
+ summary = reader._final_review(rd, item, index == 0, published)[0]
232
+ finals.append((item, reader._diff_review('final', None, None, summary['spec'], summary['verdict'],
233
+ item[3] + '/qa.last', [], summary['execution'])))
234
+ finals.reverse() # oldest first: a later PASS supersedes
235
+ out += _review_rows(rd, run, None, [review for _, review in finals], names=[item[0] for item, _ in finals])
236
+ return out
237
+
238
+
239
+ def _dataset_occurrences(hist, runs_here):
240
+ """Rows from the dataset for runs whose dir is gone: no link, labelled `dataset`."""
241
+ out = []
242
+ by_run = {}
243
+ for review in hist.get('findings') or []:
244
+ if review.get('run') in runs_here:
245
+ by_run.setdefault((review['run'], review.get('task')), []).append(review)
246
+ for (run, task), reviews in by_run.items():
247
+ reviews.sort(key=lambda r: r.get('ts') or 0)
248
+ for index, review in enumerate(reviews):
249
+ superseded = any(r.get('verdict') == 'PASS' and r.get('role') == 'qa' for r in reviews[index + 1:])
250
+ for item in review.get('findings') or []:
251
+ head = item['head']
252
+ module = F._load()
253
+ try:
254
+ match = module._LOCATION.search(head) if module else None
255
+ except Exception:
256
+ match = None
257
+ sev = item.get('severity')
258
+ out.append(dict(source='dataset', run=None, run_id=review.get('run_id'), task=task,
259
+ final_review='final' if review.get('scope') == 'final_review' else None,
260
+ attempt=review.get('attempt'), kind='shadow' if review.get('role') == 'qa_shadow' else
261
+ 'final' if review.get('scope') == 'final_review' else 'primary',
262
+ reviewer=review.get('reviewer'), verdict=review.get('verdict'), at=review.get('ts'),
263
+ id=None, severity='P%d' % sev if isinstance(sev, int) else None,
264
+ confidence=item.get('status'), location=match.group(0) if match else None,
265
+ summary=head.strip()[:240], text=head, fp=fingerprint(head), superseded=superseded,
266
+ href=None))
267
+ return out
268
+
269
+
270
+ def collapse(occurrences):
271
+ """Rows: repeats of one finding within a task (or a run's final reviews) are one row with a count, by
272
+ `forge issues`' fingerprint; a finding it cannot fingerprint is its own row. The newest occurrence leads, a
273
+ primary one before any shadow one: a finding both reviewers reported is not hidden with the shadow reviews."""
274
+ rows, order = {}, []
275
+ for occ in occurrences:
276
+ scope = (occ['source'], occ['run'] or occ['run_id'], occ['task'], bool(occ['final_review']))
277
+ key = scope + (occ['fp'],) if occ['fp'] else ('one', id(occ))
278
+ if key not in rows:
279
+ rows[key] = dict(occ, count=0, occurrences=[])
280
+ order.append(key)
281
+ row = rows[key]
282
+ row['count'] += 1
283
+ row['occurrences'].append(dict(run=occ['run'], run_id=occ['run_id'], task=occ['task'], attempt=occ['attempt'],
284
+ kind=occ['kind'], reviewer=occ['reviewer'], at=occ['at'], href=occ['href']))
285
+ shadow, lead_shadow = occ['kind'] == 'shadow', row['kind'] == 'shadow'
286
+ if (lead_shadow and not shadow) or (shadow == lead_shadow and (occ['at'] or 0) >= (row['at'] or 0)):
287
+ row.update({k: occ[k] for k in occ})
288
+ return [rows[k] for k in order]
289
+
290
+
291
+ def status_of(row, issue):
292
+ """open | filed | fixed | swept | dismissed | superseded, as findingsview.statusOf plus superseded."""
293
+ if issue:
294
+ if issue.get('dismissed'):
295
+ return 'dismissed'
296
+ if issue.get('filed'):
297
+ return 'fixed' if str((issue['filed'] or {}).get('state') or '').upper() == 'CLOSED' else 'filed'
298
+ if issue.get('swept'):
299
+ return 'swept'
300
+ return 'open'
301
+ return 'superseded' if row['superseded'] else 'open'
302
+
303
+
304
+ def _real(path):
305
+ try:
306
+ return os.path.realpath(path) if path else None
307
+ except (OSError, ValueError):
308
+ return None
309
+
310
+
311
+ def issue_index(listing):
312
+ """{(run dir, task, forge issues key): entry} of an offline `forge issues --json --all-runs` listing. The key
313
+ holds the run and the task: the same text found in two runs is two findings, each with its own state."""
314
+ module = issues_module()
315
+ out = {}
316
+ for entry in (listing or {}).get('findings') or []:
317
+ if not isinstance(entry, dict) or not isinstance(entry.get('text'), str):
318
+ continue
319
+ try:
320
+ key = module.finding_key(dict(file=entry.get('file') or '', text=entry['text'])) if module else None
321
+ except Exception:
322
+ key = None
323
+ if key:
324
+ out.setdefault((_real(entry.get('plan_dir')), entry.get('task'), key), entry)
325
+ return out
326
+
327
+
328
+ def issue_for(index, row, run_path):
329
+ """The entry of a row found in a run dir: same run, same task (none for a final review). A solo run's task is
330
+ named after its dir in forge issues and `solo` here: any entry of that run with the key is its own."""
331
+ if not row['fp'] or row['source'] != 'run' or not run_path:
332
+ return None
333
+ where = _real(run_path)
334
+ found = index.get((where, row['task'], row['fp']))
335
+ if found is None and row['task'] == 'solo':
336
+ found = next((e for (w, _t, k), e in index.items() if w == where and k == row['fp']), None)
337
+ return found
338
+
339
+
340
+ # ---- the cached screen -----------------------------------------------------------------------------
341
+
342
+ class Screen:
343
+ """Cached answers for one server: per-run findings by `updated`, the CLI's by CACHE_S."""
344
+
345
+ def __init__(self):
346
+ self.lock = threading.Lock()
347
+ self.runs = {} # run path -> (updated, occurrences)
348
+ self.cli = {} # key -> (time, value)
349
+
350
+ def _cli(self, key, call, refresh, now):
351
+ hit = self.cli.get(key)
352
+ if not refresh and hit is not None and now - hit[0] < CACHE_S:
353
+ return hit[1]
354
+ value = call()
355
+ self.cli[key] = (now, value)
356
+ return value
357
+
358
+ def occurrences(self, run):
359
+ hit = self.runs.get(run['path'])
360
+ if hit is not None and hit[0] == run['updated']:
361
+ return hit[1]
362
+ found = run_occurrences(run)
363
+ self.runs[run['path']] = (run['updated'], found)
364
+ return found
365
+
366
+ def projects(self, catalog):
367
+ return group(_catalog_runs(catalog))
368
+
369
+ def project(self, catalog, pid):
370
+ return self.projects(catalog).get(pid)
371
+
372
+ def listing(self, catalog):
373
+ with self.lock:
374
+ projects = self.projects(catalog)
375
+ out = []
376
+ for p in projects.values():
377
+ # not superseded by a later passing review; dismissals and filed issues show on the Findings tab
378
+ open_findings = sum(1 for row in collapse([o for run in p['runs'] for o in self.occurrences(run)])
379
+ if not row['superseded'])
380
+ out.append(dict(id=p['id'], name=p['name'], root=p['root'], exists=p['exists'], runs=len(p['runs']),
381
+ live=p['live'], last=p['last'], path_only=p['path_only'],
382
+ checkouts=len(checkouts(p)), memory_lines=_memory_lines(p['root']) if p['exists'] else None,
383
+ open_findings=open_findings))
384
+ out.sort(key=lambda p: p['last'] or 0, reverse=True)
385
+ return dict(projects=out)
386
+
387
+ def detail(self, catalog, pid):
388
+ p = self.project(catalog, pid)
389
+ if p is None:
390
+ return None
391
+ return dict(id=p['id'], name=p['name'], root=p['root'], exists=p['exists'], live=p['live'], last=p['last'],
392
+ path_only=p['path_only'], checkouts=checkouts(p), runs=p['runs'],
393
+ memory_off_runs=sum(1 for r in p['runs'] if r.get('no_memory')))
394
+
395
+ def _dataset_runs(self, p, hist, all_projects):
396
+ """Dataset uids of the project's runs whose dir is gone."""
397
+ existing = {r['dataset_uid'] for q in all_projects.values() for r in q['runs'] if r.get('dataset_uid')}
398
+ known_ids = {(r.get('run_id'), r.get('repo')) for r in p['runs']}
399
+ here = {c['path'] for c in checkouts(p)} | {p['root']}
400
+ roots = [q['root'] for q in all_projects.values() if q['exists']]
401
+ out = set()
402
+ for run in (hist or {}).get('runs') or []:
403
+ if run.get('run') in existing or (run.get('run_id'), run.get('repo_path')) in known_ids:
404
+ continue
405
+ path = run.get('repo_path')
406
+ if path in here:
407
+ out.add(run['run'])
408
+ elif path and not _isdir(path) and run.get('base') and p['exists']:
409
+ # the rule repos.py uses for a run whose checkout is gone: its base commit in exactly one known root
410
+ matches = [root for root in roots if _has_commit(root, run['base'])]
411
+ if matches == [p['root']]:
412
+ out.add(run['run'])
413
+ return out
414
+
415
+ def findings(self, catalog, pid, history, issues, refresh=False, now=None):
416
+ now = time.time() if now is None else now
417
+ with self.lock:
418
+ projects = self.projects(catalog)
419
+ p = projects.get(pid)
420
+ if p is None:
421
+ return None
422
+ if refresh:
423
+ self.runs.clear()
424
+ occ = []
425
+ for run in p['runs']:
426
+ occ += self.occurrences(run)
427
+ hist = self._cli('history', history, refresh, now)
428
+ gone = self._dataset_runs(p, hist, projects) if hist else set()
429
+ if hist:
430
+ occ += _dataset_occurrences(hist, gone)
431
+ # forge issues reads every run of the repository (--all-runs) from any one of them, but needs that run's
432
+ # checkout to name its GitHub repository: runs started in the root first, at most three tries.
433
+ tried = sorted(p['runs'], key=lambda r: (r.get('repo_worktree') is not None, r.get('kind') != 'plan'))[:3]
434
+ listing = None
435
+ for run in tried:
436
+ listing = self._cli(('issues', run['path']), lambda: issues(run['path']), refresh, now)
437
+ if listing is not None:
438
+ break
439
+ index = issue_index(listing)
440
+ paths = {run['key']: run['path'] for run in p['runs']}
441
+ rows = collapse(occ)
442
+ for row in rows:
443
+ issue = issue_for(index, row, paths.get(row['run']))
444
+ row['status'] = status_of(row, issue)
445
+ row['fileable'] = issue is not None and row['status'] == 'open' and row['source'] == 'run'
446
+ row['origin'] = issue.get('origin') if issue else None
447
+ rows.sort(key=lambda r: (_SEVERITIES.index(r['severity']) if r['severity'] in _SEVERITIES else 9, -(r['at'] or 0)))
448
+ notes = []
449
+ if hist is None:
450
+ notes.append('the dataset could not be read: findings of runs whose directory is gone are not listed')
451
+ elif not hist.get('enabled'):
452
+ notes.append('the dataset is off (FORGE_DATASET=off): only the run directories that still exist are read')
453
+ if listing is None:
454
+ notes.append('forge issues could not be read: dismissed and filed findings show as open')
455
+ return dict(id=pid, rows=rows, notes=notes, runs=len(p['runs']), dataset_runs=len(gone),
456
+ computed=now, available=F.available())
457
+
458
+ def memories(self, catalog, pid, learnings, history, refresh=False, now=None):
459
+ now = time.time() if now is None else now
460
+ with self.lock:
461
+ projects = self.projects(catalog)
462
+ p = projects.get(pid)
463
+ if p is None:
464
+ return None
465
+ sources = []
466
+ for c in checkouts(p):
467
+ if not c['exists']:
468
+ continue
469
+ stamp = tuple(_mtime(os.path.join(c['path'], '.forge', name)) for name in ('ledger.tsv', 'memory.md'))
470
+ got = self._cli(('memory', c['path'], stamp), lambda: learnings(c['path']), refresh, now)
471
+ sources.append(dict(path=c['path'], root=c['root'], branch=c['branch'], result=got))
472
+ hist = self._cli('history', history, refresh, now)
473
+ merged = _merge_learnings(sources, p, hist, self._dataset_runs(p, hist, projects) if hist else set())
474
+ texts = {s['path']: _memory_text(s['result']) for s in sources if s['result'] and s['result'].get('memory') is not None}
475
+ notes = []
476
+ if hist is None:
477
+ notes.append('the dataset could not be read: learnings of checkouts that are gone are not listed')
478
+ elif not hist.get('enabled'):
479
+ notes.append('the dataset is off (FORGE_DATASET=off): only the checkouts that still exist are read')
480
+ return dict(id=pid, sources=[dict(path=s['path'], root=s['root'], branch=s['branch'],
481
+ ok=s['result'] is not None,
482
+ ledger=bool(s['result'] and s['result'].get('ledger')),
483
+ memory=(s['result'] or {}).get('memory'),
484
+ rebuilt_differs=bool((s['result'] or {}).get('rebuilt_differs')),
485
+ max_lines=(s['result'] or {}).get('max_lines'))
486
+ for s in sources],
487
+ differs=len(set(texts.values())) > 1, learnings=merged, notes=notes,
488
+ memory_off_runs=sum(1 for r in p['runs'] if r.get('no_memory')), runs=len(p['runs']),
489
+ computed=now)
490
+
491
+
492
+ def _mtime(path):
493
+ try:
494
+ return os.stat(path).st_mtime_ns
495
+ except OSError:
496
+ return None
497
+
498
+
499
+ def _memory_text(result):
500
+ return '\n'.join('%s:%s' % (s['category'], line['text']) for s in result['memory'] for line in s['lines'])
501
+
502
+
503
+ def _merge_learnings(sources, project, hist, gone_runs):
504
+ """Every learning once: rows from each checkout's ledger, then the dataset's for checkouts that are gone.
505
+ `states` says what each checkout's forge-memory.sh does with it."""
506
+ merged, order = {}, []
507
+ for s in sources:
508
+ for item in (s['result'] or {}).get('learnings') or []:
509
+ key = (item['category'], item['key'])
510
+ if key not in merged:
511
+ merged[key] = dict(category=item['category'], key=item['key'], text=item['text'], count=item['count'],
512
+ states={}, rows=[], seen=set(), last=item['last'])
513
+ order.append(key)
514
+ m = merged[key]
515
+ m['states'][s['path']] = item['state']
516
+ if item['last'] >= m['last']:
517
+ m['last'], m['text'] = item['last'], item['text']
518
+ for row in item['rows']:
519
+ ident = (row['ts'], row['run_id'], row['task'], row['role'], row['text'])
520
+ if ident in m['seen']:
521
+ for r in m['rows']:
522
+ if (r['ts'], r['run_id'], r['task'], r['role'], r['text']) == ident and s['path'] not in r['from']:
523
+ r['from'].append(s['path'])
524
+ continue
525
+ m['seen'].add(ident)
526
+ m['rows'].append(dict(row, source='ledger', **{'from': [s['path']]}))
527
+ norm = _norm_key
528
+ for item in (hist or {}).get('learnings') or []:
529
+ if item.get('run') not in gone_runs or item.get('category') not in ('verify', 'trap', 'finding'):
530
+ continue
531
+ key = (item['category'], norm(item['text']))
532
+ ts = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(item['ts'])) if isinstance(item.get('ts'), (int, float)) else None
533
+ if key not in merged:
534
+ merged[key] = dict(category=item['category'], key=key[1], text=item['text'], count=0, states={}, rows=[],
535
+ seen=set(), last=ts or '')
536
+ order.append(key)
537
+ m = merged[key]
538
+ ident = (ts, item.get('run_id'), item.get('task'), item.get('role'), item['text'])
539
+ if ident not in m['seen']:
540
+ m['seen'].add(ident)
541
+ m['rows'].append(dict(ts=ts, run_id=item.get('run_id'), task=item.get('task'), role=item.get('role'),
542
+ model=item.get('model'), verdict=None, text=item['text'], injectable=True,
543
+ source='dataset', **{'from': ['dataset']}))
544
+ out = []
545
+ for key in order:
546
+ m = merged.pop(key)
547
+ m.pop('seen')
548
+ m['dataset_only'] = not m['states']
549
+ out.append(m)
550
+ out.sort(key=lambda m: m['last'] or '', reverse=True)
551
+ return out
552
+
553
+
554
+ def _norm_key(text):
555
+ """forge-memory.sh's norm_key of a fact without its [anchor], for dataset learnings that have no ledger key."""
556
+ import re
557
+ body = re.sub(r'\s*\[[^][]+\]\s*$', '', text)
558
+ return re.sub(r'[^a-z0-9]+', ' ', body.lower()).strip()
559
+
560
+
561
+ def _has_commit(root, sha):
562
+ done = repos._run_git(root, 'cat-file', '-e', sha + '^{commit}')
563
+ return done is not None and done.returncode == 0
564
+
565
+
566
+ def screen(server):
567
+ with _LOCK:
568
+ found = getattr(server, 'project_screen', None)
569
+ if found is None:
570
+ found = server.project_screen = Screen()
571
+ return found
@@ -769,14 +769,30 @@ def _max_attempts(reader):
769
769
 
770
770
 
771
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)
772
+ """The N of a retry=N choice (`retry=N dwarf=<spec>` too), however many digits it has; 0 for any other choice."""
773
+ match = re.match(r'retry=([0-9]+)(?: |$)', choice)
774
774
  try:
775
775
  return int(match.group(1)) if match else 0
776
776
  except ValueError: # more digits than Python reads as an int: a reader must not raise over one bad row
777
777
  return 0
778
778
 
779
779
 
780
+ def _adoptions(reader):
781
+ """One row per range `adopt` brought in (adoptions.tsv: epoch, base, tip, verdict, approved, spec, review, reason)."""
782
+ result = []
783
+ for label, row in reader.rows('adoptions.tsv', 8):
784
+ try:
785
+ at = float(row[0])
786
+ if not math.isfinite(at):
787
+ raise ValueError()
788
+ except (ValueError, OverflowError):
789
+ reader.warn(label, 'invalid epoch')
790
+ continue
791
+ result.append(dict(at=at, base=row[1], tip=row[2], verdict=row[3], approved=row[4] == '1', spec=_nullable(row[5]),
792
+ review=_nullable(row[6]), reason=_nullable('\t'.join(row[7:]))))
793
+ return result
794
+
795
+
780
796
  def _attempt_cap(max_attempts, decisions):
781
797
  """A task's attempt cap: max_attempts plus the N of each retry=N decision. None when max_attempts is 0 (no cap)."""
782
798
  if max_attempts == 0:
@@ -1483,7 +1499,7 @@ def _solo_detail(reader, source):
1483
1499
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
1484
1500
  fail_first=_fail_first(reader, 'failfirst.json'), pre_review=None,
1485
1501
  now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[])
1486
- result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[],
1502
+ result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[], adoptions=[],
1487
1503
  deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
1488
1504
  scheduler=None, sweep=None)
1489
1505
  result.update(tasks=[task], warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
@@ -1582,6 +1598,7 @@ def detail(path, source='plan') -> dict:
1582
1598
  _stamp_review(summary, accepted, merges)
1583
1599
  result['final_review'] = reviews[0] if reviews else None
1584
1600
  result['final_reviews'] = reviews
1601
+ result['adoptions'] = _adoptions(reader)
1585
1602
  result['deferrals'] = [line.strip() for line in (reader.text('deferrals.txt') or '').splitlines() if line.strip()]
1586
1603
  result['findings_available'] = findings.available()
1587
1604
  result['fractal'] = fractal.summary(reader)
@@ -1607,7 +1624,7 @@ def _plan_task(reader, tasks, task_id):
1607
1624
 
1608
1625
  def _review(kind, item, text):
1609
1626
  return dict(kind=kind, execution=item['id'], attempt=item['attempt'], spec=(item['model'] or {}).get('spec'),
1610
- verdict=item['verdict'], state=item['state'], findings=findings.listing(text))
1627
+ verdict=item['verdict'], state=item['state'], findings=findings.listing(text), tests=findings.tests(text))
1611
1628
 
1612
1629
 
1613
1630
  def task_detail(path, task_id, source='plan'):
@@ -1642,12 +1659,14 @@ def task_detail(path, task_id, source='plan'):
1642
1659
  # The reply in the task dir is normally the copy of the last review; only an unmatched one is listed.
1643
1660
  if live is not None and live not in seen:
1644
1661
  reviews.append(dict(kind='primary', execution=None, attempt=attempt, spec=spec, verdict=_verdict(live),
1645
- state='done', findings=findings.listing(live)))
1662
+ state='done', findings=findings.listing(live), tests=findings.tests(live)))
1646
1663
  for entry, items, sub in shadows:
1647
1664
  run = items[-1] if items else None
1665
+ shadow_text = reader.text(sub + '/qa.last')
1648
1666
  reviews.append(dict(kind='shadow', execution=entry['execution'], attempt=entry['attempt'],
1649
1667
  spec=entry['spec'] if isinstance(entry['spec'], str) else None, verdict=entry['verdict'],
1650
- state=run['state'] if run else None, findings=findings.listing(reader.text(sub + '/qa.last'))))
1668
+ state=run['state'] if run else None, findings=findings.listing(shadow_text),
1669
+ tests=findings.tests(shadow_text)))
1651
1670
  return dict(run=run_key(reader.path), id=task_id, texts=texts, gate=_gate(reader, base + 'qa.gate'),
1652
1671
  reviews=reviews, truncated=reader.truncated, warnings=reader.warnings)
1653
1672
 
@@ -1890,7 +1909,8 @@ def final_review_detail(path, name, source='plan'):
1890
1909
  qa_input=reader.excerpt(rel + '/qa.input', 40000, 20000, 'qa_input'),
1891
1910
  qa_last=reader.clip(qa_last, 20000, 8000, 'qa_last'),
1892
1911
  known_issues=reader.excerpt(rel + '/known_issues.md', 20000, 8000, 'known_issues'),
1893
- findings=findings.listing(qa_last), truncated=reader.truncated, warnings=reader.warnings)
1912
+ findings=findings.listing(qa_last), tests=findings.tests(qa_last),
1913
+ truncated=reader.truncated, warnings=reader.warnings)
1894
1914
  return result
1895
1915
 
1896
1916