@giamme/forge 0.15.0 → 0.17.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 (80) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/VERSION +1 -1
  3. package/docs/artifacts.md +1 -1
  4. package/docs/commands.md +14 -3
  5. package/docs/dataset.md +8 -0
  6. package/docs/forge-ui.md +14 -0
  7. package/docs/memory.md +22 -0
  8. package/docs/reviews.md +22 -1
  9. package/forge +11 -0
  10. package/package.json +1 -1
  11. package/references/dataset.md +129 -7
  12. package/references/decision-models.md +15 -2
  13. package/references/decompose.md +95 -13
  14. package/references/harnesses.md +4 -1
  15. package/references/planning.md +3 -2
  16. package/references/solo.md +5 -1
  17. package/references/ui.md +10 -1
  18. package/scripts/forge-artifact.sh +53 -0
  19. package/scripts/forge-contract.py +107 -9
  20. package/scripts/forge-control.py +0 -2
  21. package/scripts/forge-dispatch.sh +28 -12
  22. package/scripts/forge-fail-first.py +3 -1
  23. package/scripts/forge-guard.py +247 -8
  24. package/scripts/forge-issues.py +16 -3
  25. package/scripts/forge-ledger.py +3 -1
  26. package/scripts/forge-lib-adopt.sh +266 -0
  27. package/scripts/forge-lib-attribute.sh +10 -2
  28. package/scripts/forge-lib-plans.sh +16 -4
  29. package/scripts/forge-lib-review.sh +8 -2
  30. package/scripts/forge-lib-task.sh +19 -5
  31. package/scripts/forge-memory.sh +41 -4
  32. package/scripts/forge-metrics.sh +29 -0
  33. package/scripts/forge-parallel.sh +99 -14
  34. package/scripts/forge-plan-check.py +25 -2
  35. package/scripts/forge-planner.py +20 -6
  36. package/scripts/forge-route.py +16 -2
  37. package/scripts/forge-runs-rm.py +23 -7
  38. package/scripts/forge-runtime.py +25 -2
  39. package/scripts/forge-schedule.py +5 -2
  40. package/scripts/forge-shadow.py +30 -9
  41. package/scripts/forge-solo.sh +6 -0
  42. package/scripts/forge-sweep.py +25 -10
  43. package/scripts/forge_dataset/cli.py +99 -0
  44. package/scripts/forge_dataset/export.py +1 -0
  45. package/scripts/forge_dataset/facts.py +278 -0
  46. package/scripts/forge_dataset/harvest.py +27 -3
  47. package/scripts/forge_dataset/history.py +126 -0
  48. package/scripts/forge_dataset/outcomes.py +206 -58
  49. package/scripts/forge_dataset/pairs.py +174 -0
  50. package/scripts/forge_dataset/risk.py +108 -0
  51. package/scripts/forge_dataset/tiers.py +427 -0
  52. package/scripts/forge_dataset/worktrees.py +95 -0
  53. package/scripts/forge_decide/cli.py +23 -2
  54. package/scripts/forge_decide/labels.py +30 -6
  55. package/scripts/forge_decide/replay.py +10 -4
  56. package/scripts/forge_memory_list.py +153 -0
  57. package/scripts/forge_worktrees.py +88 -0
  58. package/ui/README.md +31 -0
  59. package/ui/docs/api.md +92 -6
  60. package/ui/forge_ui/__init__.py +14 -1
  61. package/ui/forge_ui/__main__.py +1 -1
  62. package/ui/forge_ui/control.py +77 -0
  63. package/ui/forge_ui/export.py +9 -2
  64. package/ui/forge_ui/findings.py +11 -2
  65. package/ui/forge_ui/projects.py +571 -0
  66. package/ui/forge_ui/reader.py +96 -9
  67. package/ui/forge_ui/server.py +8 -0
  68. package/ui/forge_ui/static/app.js +105 -22
  69. package/ui/forge_ui/static/cloudui.js +6 -2
  70. package/ui/forge_ui/static/convo.js +1 -1
  71. package/ui/forge_ui/static/diffview.js +9 -5
  72. package/ui/forge_ui/static/files.js +1 -1
  73. package/ui/forge_ui/static/index.html +5 -1
  74. package/ui/forge_ui/static/panel.js +69 -2
  75. package/ui/forge_ui/static/projectsview.js +372 -0
  76. package/ui/forge_ui/static/settings.js +136 -4
  77. package/ui/forge_ui/static/style.css +94 -3
  78. package/ui/forge_ui/static/uikit.js +94 -1
  79. package/ui/forge_ui/static/worktreesview.js +250 -0
  80. package/ui/forge_ui/worktrees.py +570 -0
@@ -40,8 +40,9 @@ _TEXT_KEYS = frozenset(('prompt', 'last', 'request', 'log_tail', 'dwarf_tail', '
40
40
  'dwarf_input', 'error', 'last_line', 'message', 'excerpt', 'tail', 'lines', 'call', 'split',
41
41
  'needs_input', 'detail'))
42
42
  # keys that are private text only under one parent: a person's --reason on each decision (`reason` elsewhere is
43
- # a short machine word, such as a sweep's dropped-finding reason, and stays)
44
- _TEXT_KEYS_UNDER = {'decisions': frozenset(('reason',))}
43
+ # a short machine word, such as a sweep's dropped-finding reason, and stays); the --reason of each adoption too
44
+ _TEXT_KEYS_UNDER = {'decisions': frozenset(('reason',)), 'adoptions': frozenset(('reason',)),
45
+ 'adoption': frozenset(('reason',))}
45
46
 
46
47
 
47
48
  def _enc(value):
@@ -172,6 +173,10 @@ def build(catalog, key, texts=False, paths=False, now=None):
172
173
  reviews = [r.get('name') for r in (run.get('final_reviews') or []) if isinstance(r, dict) and r.get('name')]
173
174
  for name in reviews:
174
175
  snap.add(f'{base}/final-reviews/{_enc(name)}')
176
+ adopted = [a['review'] for a in (run.get('adoptions') or []) if isinstance(a, dict) and isinstance(a.get('review'), str)
177
+ and re.fullmatch(r'adopt-[0-9]+-[0-9]+', a['review'])]
178
+ for name in adopted:
179
+ snap.add(f'{base}/adoptions/{_enc(name)}')
175
180
  snap.add(f'{base}/files')
176
181
  snap.add(f'{base}/findings')
177
182
  fractal = run.get('fractal') or {}
@@ -193,6 +198,8 @@ def build(catalog, key, texts=False, paths=False, now=None):
193
198
  snap.add(url, cap=DIFF_CAP)
194
199
  for name in reviews:
195
200
  snap.add(f'{base}/final-reviews/{_enc(name)}/diff', cap=DIFF_CAP)
201
+ for name in adopted:
202
+ snap.add(f'{base}/adoptions/{_enc(name)}/diff', cap=DIFF_CAP)
196
203
  # what each dwarf and reviewer said and ran: its conversation is all text, and so are the commands it ran
197
204
  for name in names:
198
205
  if name.startswith(('dwarf-', 'qa-')):
@@ -104,18 +104,27 @@ def listing(text, limit=200):
104
104
  return None
105
105
  result = []
106
106
  for status, severity, line, block in found[:limit]:
107
- first = block.split('\n', 1)[0]
107
+ first, facts = block.split('\n', 1)[0], None
108
108
  try:
109
109
  match = module._LOCATION.search(first)
110
+ # #119: the facts suffix is shown apart, never as part of the summary
111
+ first, facts = module.split_facts(first)[0], module.facts(block)
110
112
  except Exception:
111
113
  match = None
112
114
  result.append(dict(severity=None if severity is None else 'P%d' % severity, status=status,
113
115
  location=match.group(0) if match else None, line=line,
114
- summary=first.strip()[:_SUMMARY_MAX],
116
+ summary=first.strip()[:_SUMMARY_MAX], facts=facts,
115
117
  text=block if len(block) <= _TEXT_MAX else block[:_TEXT_MAX] + '…'))
116
118
  return result
117
119
 
118
120
 
121
+ def tests(text):
122
+ """What the reply says about its tests (forge-contract.py's tests_report), or None."""
123
+ module = _load()
124
+ report = getattr(module, 'tests_report', None)
125
+ return report(text[:_MAX_CHARS]) if report and text else None
126
+
127
+
119
128
  def parse_gate(text):
120
129
  """A qa.gate line: threshold, decision, worst, n_confirmed, n_unlabelled, n_below; None if malformed."""
121
130
  line = next((item for item in (text or '').splitlines() if item.strip()), None)
@@ -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