@giamme/forge 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,542 @@
1
+ #!/usr/bin/env python3
2
+ """The finding sweep (`run --sweep`) and its cheaper first step (`run --sweep-ahead`).
3
+
4
+ A run can end with findings nobody acts on in the run: CONFIRMED findings `--qa-threshold` tolerated
5
+ (`tasks/<id>/known_issues.md`) and, opted in, PLAUSIBLE findings in passed tasks' `qa.last`. Without a
6
+ sweep they reach `forge issues` and are fixed later, if at all. With one, the scheduler calls `plan` once
7
+ every task has merged: the open findings become a few fix tasks, one per file, added to the live run.
8
+
9
+ plan <plan> --severity P0..P3 [--plausible] [--max N]
10
+ Collect the open findings (forge-issues.py's collector), triage them, group them by file, write
11
+ each fix task (tasks.tsv row, prompt.md, sweep.json) and the sweep plan (sweep/plan.json and
12
+ plan.md, also printed to stderr), then print the new task ids, one per line. A plan is swept at
13
+ most once: an existing sweep/plan.json prints nothing.
14
+ ahead <plan> <task> [--role dwarf|qa] [--cap N]
15
+ The prompt step: the open findings in files <task> owns, as a prompt section. Picked once per
16
+ task (tasks/<task>/sweep.ahead.json), so every attempt and its reviewer see the same list.
17
+ settle <plan> <task>
18
+ After a sweep task merged: its reviewer's `S<n>: FIXED` / `S<n>: NOT FIXED` lines, per finding,
19
+ in tasks/<task>/sweep.outcome.json. `forge issues` leaves out the findings marked fixed.
20
+ report <plan>
21
+ What the sweep did, for the run's closing summary; nothing when the plan was never swept.
22
+
23
+ Triage keeps a finding only when it is CONFIRMED and tolerated (or PLAUSIBLE, with --plausible), at
24
+ least as severe as --severity, from a task that is not itself a sweep task (one round: what a sweep
25
+ review finds goes to `forge issues`), not dismissed (`forge issues --dismiss`), located in a file the
26
+ integration branch still has, and still there: when a later merge changed the file and the line the
27
+ reviewer saw is gone from it, the finding is left for `forge issues` rather than "fixed" twice. A
28
+ person's acceptance of a reviewer's FAIL (`accept`) is theirs to triage, so accepted findings are never
29
+ swept. Every finding left out is listed in the plan with its reason.
30
+
31
+ Each fix task gets at most GROUP_CAP findings; --max (default DEFAULT_MAX) caps the tasks, worst
32
+ severity first. Its implementer is the plan's low tier (the first spec of --dwarf-low, else of
33
+ --dwarf), else the implementer of the task the worst finding came from; its reviewer is that task's.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import contextlib
39
+ import fcntl
40
+ import importlib.util
41
+ import json
42
+ import os
43
+ from pathlib import Path
44
+ import posixpath
45
+ import re
46
+ import subprocess
47
+ import sys
48
+ import tempfile
49
+ import time
50
+
51
+ SCRIPTS = Path(__file__).resolve().parent
52
+ SEVERITIES = ('P0', 'P1', 'P2', 'P3')
53
+ DEFAULT_MAX = 5 # fix tasks one sweep may add
54
+ GROUP_CAP = 8 # findings one fix task is given; the rest of its file stays for forge issues
55
+ AHEAD_CAP = 3 # findings the prompt step hands one task
56
+ LOCK_WAIT = 5.0
57
+ # A reviewer's line per finding: `- S2: NOT FIXED — why`. A placeholder (`S<n>`) never matches.
58
+ S_LINE = re.compile(r'^[ \t]*(?:[-*+][ \t]+)?[*_`]*(S\d{1,3})[*_`]*[ \t]*[:—–-][ \t]*[*_`]*(NOT[ \t]+FIXED|FIXED)\b'
59
+ r'[*_`]*[ \t]*[:—–-]?[ \t]*(.*)$', re.I | re.M)
60
+ REASONS = {
61
+ 'below-severity': 'less severe than the sweep threshold',
62
+ 'dismissed': 'dismissed with forge issues --dismiss',
63
+ 'no-location': 'no file in the repository to fix it in',
64
+ 'file-gone': 'its file is no longer on the integration branch',
65
+ 'changed': 'the code it points at changed after the review',
66
+ 'duplicate': 'the same finding was reported again',
67
+ 'group-cap': 'over the %d findings one fix task takes' % GROUP_CAP,
68
+ 'over-max': 'over --sweep-max fix tasks',
69
+ 'no-model': 'no implementer or reviewer to give its fix task',
70
+ }
71
+
72
+ _ISSUES = None
73
+
74
+
75
+ def issues():
76
+ """forge-issues.py, loaded by path: the one owner of finding collection, keys and dismissals."""
77
+ global _ISSUES
78
+ if _ISSUES is None:
79
+ spec = importlib.util.spec_from_file_location('forge_issues', SCRIPTS / 'forge-issues.py')
80
+ _ISSUES = importlib.util.module_from_spec(spec)
81
+ spec.loader.exec_module(_ISSUES)
82
+ return _ISSUES
83
+
84
+
85
+ def read(path: Path) -> str:
86
+ try:
87
+ return path.read_text(encoding='utf-8').strip()
88
+ except (OSError, UnicodeDecodeError):
89
+ return ''
90
+
91
+
92
+ def write_atomic(path: Path, text: str) -> None:
93
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
94
+ try:
95
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
96
+ os.fchmod(handle.fileno(), 0o644)
97
+ handle.write(text)
98
+ os.replace(tmp, path)
99
+ except BaseException:
100
+ with contextlib.suppress(OSError):
101
+ os.unlink(tmp)
102
+ raise
103
+
104
+
105
+ @contextlib.contextmanager
106
+ def control_lock(plan: Path):
107
+ """The plan's control.lock, as `forge control` takes it, around a tasks.tsv rewrite. Busy for
108
+ LOCK_WAIT seconds: proceed without it, as the scheduler does."""
109
+ fd = os.open(str(plan / 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644)
110
+ try:
111
+ deadline = time.monotonic() + LOCK_WAIT
112
+ while True:
113
+ try:
114
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
115
+ break
116
+ except BlockingIOError:
117
+ if time.monotonic() >= deadline:
118
+ break
119
+ time.sleep(0.05)
120
+ yield
121
+ finally:
122
+ os.close(fd)
123
+
124
+
125
+ def rows(plan: Path) -> list:
126
+ return [line.split('\t') for line in read(plan / 'tasks.tsv').splitlines()
127
+ if line and not line.startswith('#') and len(line.split('\t')) == 7]
128
+
129
+
130
+ def is_sweep_task(plan: Path, task: str) -> bool:
131
+ return (plan / 'tasks' / task / 'sweep.json').is_file()
132
+
133
+
134
+ def git(cwd, *args) -> tuple:
135
+ result = subprocess.run(['git', '-C', str(cwd), *args], capture_output=True)
136
+ return result.returncode, result.stdout
137
+
138
+
139
+ def blob(cwd, commit: str, path: str) -> 'str | None':
140
+ """The file at commit, or None when it is not a regular file there."""
141
+ rc, kind = git(cwd, 'cat-file', '-t', commit + ':' + path)
142
+ if rc or kind.strip() != b'blob':
143
+ return None
144
+ rc, data = git(cwd, 'show', commit + ':' + path)
145
+ return None if rc else data.decode('utf-8', 'replace')
146
+
147
+
148
+ def relative(path: str, roots: list) -> 'str | None':
149
+ """A finding's file as a repository path: a path inside one of the run's checkouts loses its
150
+ checkout; anything else absolute, or climbing out of the repository, is no location."""
151
+ path = (path or '').strip().strip('`')
152
+ if path.startswith('/'):
153
+ for root in roots:
154
+ if root and path.startswith(root.rstrip('/') + '/'):
155
+ path = path[len(root.rstrip('/')) + 1:]
156
+ break
157
+ else:
158
+ return None
159
+ path = posixpath.normpath(path)
160
+ # a tab, newline or comma would break tasks.tsv's files column
161
+ if path in ('', '.') or path.startswith('../') or path == '..' or any(c in path for c in '\t\n\r,'):
162
+ return None
163
+ return path
164
+
165
+
166
+ def merged_since(cwd, commit: str, tip: str, path: str) -> list:
167
+ """Tasks whose merge onto the integration branch after commit changed path."""
168
+ rc, out = git(cwd, 'log', '--first-parent', '--format=%s', commit + '..' + tip, '--', path)
169
+ if rc:
170
+ return []
171
+ found = []
172
+ for subject in out.decode('utf-8', 'replace').splitlines():
173
+ m = re.fullmatch(r'forge: merge (\S+)', subject.strip())
174
+ if m and m.group(1) not in found:
175
+ found.append(m.group(1))
176
+ return found[::-1]
177
+
178
+
179
+ def summary(f) -> str:
180
+ return (f['text'].splitlines() or [''])[0][:200]
181
+
182
+
183
+ def location(f, path=None) -> str:
184
+ where = path or f['file']
185
+ return where + (':%d' % f['line'] if f.get('line') else '')
186
+
187
+
188
+ class Context:
189
+ """What triage reads once per plan: the repository, its checkouts, the dismissal marks."""
190
+
191
+ def __init__(self, plan: Path):
192
+ self.plan = plan
193
+ self.repo = read(plan / 'repo')
194
+ wt_root = read(plan / 'wt_root')
195
+ self.integration = os.path.join(wt_root, '_integration') if wt_root else ''
196
+ rc, tip = git(self.integration, 'rev-parse', 'HEAD') if self.integration else (1, b'')
197
+ self.tip = tip.decode().strip() if not rc else ''
198
+ self.roots = [self.integration, self.repo] + [os.path.join(wt_root, r[0]) for r in rows(plan)] if wt_root \
199
+ else [self.repo]
200
+ mod = issues()
201
+ self.slug = mod.github_slug(self.repo) if self.repo else None
202
+ self.dismissed = {}
203
+ if self.slug:
204
+ with contextlib.suppress(Exception):
205
+ self.dismissed = mod.load_dismissed(mod.repo_key(self.repo))
206
+
207
+ def candidates(self, include_plausible: bool) -> list:
208
+ found, _ = issues().collect_plan(self.plan, include_plausible)
209
+ return found
210
+
211
+
212
+ def triage(ctx: Context, found: list, severity: str, plausible: bool) -> tuple:
213
+ """(kept, dropped). kept: findings with `path` (their repository path) and `key`; dropped: the
214
+ candidates left out, each with its `reason` and a `detail` (merged_since for `changed`)."""
215
+ mod = issues()
216
+ origins = ('tolerated', 'plausible') if plausible else ('tolerated',)
217
+ cut = SEVERITIES.index(severity)
218
+ kept, dropped, seen = [], [], {}
219
+ tip_text = {}
220
+ for f in sorted(found, key=lambda f: SEVERITIES.index(f['severity'])):
221
+ if f['origin'] not in origins or not f.get('task') or is_sweep_task(ctx.plan, f['task']):
222
+ continue
223
+ f = dict(f, key=mod.finding_key(f))
224
+
225
+ def drop(reason, **detail):
226
+ dropped.append(dict(f, reason=reason, detail=detail))
227
+
228
+ if SEVERITIES.index(f['severity']) > cut:
229
+ drop('below-severity')
230
+ continue
231
+ if ctx.slug and mod.fingerprint(ctx.slug, f) in ctx.dismissed:
232
+ drop('dismissed')
233
+ continue
234
+ if f['key'] in seen:
235
+ drop('duplicate', of=seen[f['key']])
236
+ continue
237
+ path = relative(f['file'], ctx.roots)
238
+ if path not in tip_text:
239
+ tip_text[path] = blob(ctx.integration, ctx.tip, path) if path and ctx.tip else None
240
+ after = tip_text[path]
241
+ if after is None:
242
+ drop('no-location' if path is None or not f.get('line') else 'file-gone')
243
+ continue
244
+ commit = f.get('commit') or ''
245
+ before = blob(ctx.integration, commit, path) if commit and f.get('line') else None
246
+ if before is not None and before != after and 1 <= f['line'] <= len(before.splitlines()):
247
+ line = before.splitlines()[f['line'] - 1].strip()
248
+ if line and line not in {other.strip() for other in after.splitlines()}:
249
+ drop('changed', merged_since=merged_since(ctx.integration, commit, ctx.tip, path))
250
+ continue
251
+ seen[f['key']] = f['task']
252
+ kept.append(dict(f, path=path))
253
+ return kept, dropped
254
+
255
+
256
+ def groups(kept: list, limit: int) -> tuple:
257
+ """(groups, dropped): one group per file, worst first, each at most GROUP_CAP findings."""
258
+ by_path = {}
259
+ for f in kept:
260
+ by_path.setdefault(f['path'], []).append(f)
261
+ ordered = sorted(by_path.items(), key=lambda item: (min(SEVERITIES.index(f['severity']) for f in item[1]),
262
+ -len(item[1]), item[0]))
263
+ chosen, dropped = [], []
264
+ for path, items in ordered:
265
+ items = sorted(items, key=lambda f: SEVERITIES.index(f['severity']))
266
+ if len(chosen) >= limit:
267
+ dropped += [dict(f, reason='over-max', detail={}) for f in items]
268
+ continue
269
+ chosen.append((path, items[:GROUP_CAP]))
270
+ dropped += [dict(f, reason='group-cap', detail={}) for f in items[GROUP_CAP:]]
271
+ return chosen, dropped
272
+
273
+
274
+ def pools(plan: Path) -> dict:
275
+ try:
276
+ data = json.loads(read(plan / 'fractal-routing.json') or '{}')
277
+ except ValueError:
278
+ return {}
279
+ return data if isinstance(data, dict) else {}
280
+
281
+
282
+ def models(plan: Path, source: 'list | None') -> tuple:
283
+ """(dwarf, qa) for a fix task whose worst finding came from the task with row `source` (None when
284
+ that task is not in tasks.tsv); an empty string where there is no spec to use."""
285
+ def usable(spec):
286
+ return spec if isinstance(spec, str) and spec not in ('', '-', 'UNASSIGNED') else ''
287
+ qa = usable(source[5]) if source else ''
288
+ routing = pools(plan)
289
+ for tier in ('low', 'any'):
290
+ specs = routing.get(tier)
291
+ if isinstance(specs, list) and specs and usable(specs[0]):
292
+ return specs[0], qa
293
+ return (usable(source[4]) if source else ''), qa
294
+
295
+
296
+ def free_ids(taken: set, count: int) -> list:
297
+ ids, n = [], 1
298
+ while len(ids) < count:
299
+ name = 'sweep-%d' % n
300
+ if name not in taken:
301
+ ids.append(name)
302
+ n += 1
303
+ return ids
304
+
305
+
306
+ def finding_line(item: dict) -> str:
307
+ return '- %s [%s][%s] %s — %s (task %s)' % (item['id'], item['severity'], item['confidence'],
308
+ item['location'], item['text'], item['task'])
309
+
310
+
311
+ def prompt_text(run_id: str, path: str, items: list) -> str:
312
+ lines = ['Fix review findings in `%s`' % path, '',
313
+ 'The reviewers of earlier tasks in forge run %s reported these findings and let the work merge' % run_id,
314
+ 'anyway (below the run\'s QA threshold, or only PLAUSIBLE). Fix them now, while the work is fresh.', '']
315
+ lines += [finding_line(item) for item in items]
316
+ lines += ['',
317
+ 'Line numbers are the ones the reviewer saw; later tasks may have moved the code. Fix each finding',
318
+ 'with the smallest change that removes it, and add or adjust a test when it is a behaviour bug and',
319
+ 'the code has tests nearby. Leave a finding that no longer applies, or that you judge wrong, alone',
320
+ 'and say why in your reply. Change nothing else.', '',
321
+ '## Acceptance criteria', '',
322
+ '- Each finding above is fixed, or the reply says why it no longer applies or is wrong.',
323
+ '- No behaviour outside these findings changes.']
324
+ return '\n'.join(lines) + '\n'
325
+
326
+
327
+ def plan_markdown(record: dict) -> str:
328
+ tasks, dropped = record['tasks'], record['dropped']
329
+ scope = '%s and worse, %s' % (record['severity'], 'CONFIRMED and PLAUSIBLE' if record['plausible'] else 'CONFIRMED only')
330
+ n = sum(len(t['findings']) for t in tasks)
331
+ out = ['# Finding sweep: %d fix task(s) for %d finding(s) (%s)' % (len(tasks), n, scope), '']
332
+ if tasks:
333
+ out += ['Each fix task is one implementation and one narrow review: %d dispatches, plus any automatic'
334
+ % record['estimate']['dispatches'], 'retries (--retry-failed). They run on the integration branch at %s.'
335
+ % (record['integration'][:12] or '?'), '']
336
+ for task in tasks:
337
+ out += ['## %s: %s (implementer %s, reviewer %s)' % (task['id'], task['file'], task['dwarf'], task['qa'])]
338
+ out += [finding_line(item) for item in task['findings']] + ['']
339
+ if dropped:
340
+ out += ['## Left for forge issues (%d)' % len(dropped)]
341
+ for item in dropped:
342
+ why = REASONS.get(item['reason'], item['reason'])
343
+ since = item['detail'].get('merged_since') if item['detail'] else None
344
+ if since:
345
+ why += ' (merged since: %s)' % ', '.join(since)
346
+ out.append('- [%s] %s — %s (task %s): %s' % (item['severity'], location(item), summary(item), item['task'], why))
347
+ out.append('')
348
+ if not tasks and not dropped:
349
+ out += ['No open finding to sweep.', '']
350
+ return '\n'.join(out)
351
+
352
+
353
+ def cmd_plan(args) -> int:
354
+ plan = Path(args.plan).resolve()
355
+ sweep_dir = plan / 'sweep'
356
+ if (sweep_dir / 'plan.json').exists():
357
+ return 0 # one sweep per plan
358
+ ctx = Context(plan)
359
+ if not ctx.tip:
360
+ print('forge: sweep: the integration branch cannot be read; nothing swept', file=sys.stderr)
361
+ return 3
362
+ kept, dropped = triage(ctx, ctx.candidates(args.plausible), args.severity, args.plausible)
363
+ chosen, over = groups(kept, args.max)
364
+ dropped += over
365
+ table = rows(plan)
366
+ by_id = {row[0]: row for row in table}
367
+ ids = free_ids(set(by_id) | {p.name for p in (plan / 'tasks').iterdir() if p.is_dir()}, len(chosen))
368
+ run_id = read(plan / 'run_id') or plan.name
369
+ tasks, new_rows = [], []
370
+ for path, items in list(chosen):
371
+ if not all(models(plan, by_id.get(items[0]['task']))):
372
+ chosen.remove((path, items))
373
+ dropped += [dict(f, reason='no-model', detail={}) for f in items]
374
+ for ident, (path, items) in zip(ids, chosen):
375
+ entries = [dict(id='S%d' % n, key=f['key'], severity=f['severity'], confidence=f['confidence'],
376
+ origin=f['origin'], task=f['task'], file=f['file'], line=f.get('line'), path=path,
377
+ location=location(f, path), text=f['text'], raw=f['raw'])
378
+ for n, f in enumerate(items, 1)]
379
+ dwarf, qa = models(plan, by_id.get(items[0]['task']))
380
+ title = 'Fix %d review finding%s in %s' % (len(entries), '' if len(entries) == 1 else 's', path)
381
+ root = plan / 'tasks' / ident
382
+ root.mkdir(parents=True, exist_ok=True)
383
+ write_atomic(root / 'prompt.md', prompt_text(run_id, path, entries))
384
+ write_atomic(root / 'sweep.json', json.dumps(dict(file=path, findings=entries), indent=1) + '\n')
385
+ tasks.append(dict(id=ident, file=path, dwarf=dwarf, qa=qa, title=title, findings=entries))
386
+ new_rows.append('\t'.join([ident, '-', 'low', path, dwarf, qa, title]))
387
+ record = dict(version=1, at=time.time(), severity=args.severity, plausible=args.plausible, max=args.max,
388
+ integration=ctx.tip, tasks=tasks, estimate=dict(dispatches=2 * len(tasks)),
389
+ dropped=[dict(task=f['task'], severity=f['severity'], confidence=f['confidence'], origin=f['origin'],
390
+ file=f['file'], line=f.get('line'), text=f['text'], key=f['key'], reason=f['reason'],
391
+ detail=f['detail'])
392
+ for f in dropped])
393
+ sweep_dir.mkdir(exist_ok=True)
394
+ text = plan_markdown(record)
395
+ write_atomic(sweep_dir / 'plan.md', text)
396
+ # The marker before the rows: a crash in between loses this sweep (its findings still reach forge
397
+ # issues), and never plans a second one over tasks already in tasks.tsv.
398
+ write_atomic(sweep_dir / 'plan.json', json.dumps(record, indent=1) + '\n')
399
+ if new_rows:
400
+ with control_lock(plan):
401
+ current = (plan / 'tasks.tsv').read_text(encoding='utf-8')
402
+ write_atomic(plan / 'tasks.tsv', current + ('' if current.endswith('\n') or not current else '\n')
403
+ + ''.join(row + '\n' for row in new_rows))
404
+ for line in text.rstrip().splitlines():
405
+ print('forge: sweep: ' + line if line else 'forge: sweep:', file=sys.stderr)
406
+ for task in tasks:
407
+ print(task['id'])
408
+ return 0
409
+
410
+
411
+ def owns(scopes: list, path: str) -> bool:
412
+ return any(s == '.' or path == s or path.startswith(s.rstrip('/') + '/') for s in scopes)
413
+
414
+
415
+ def cmd_ahead(args) -> int:
416
+ plan = Path(args.plan).resolve()
417
+ root = plan / 'tasks' / args.task
418
+ record = root / 'sweep.ahead.json'
419
+ if record.is_file():
420
+ try:
421
+ picked = json.loads(read(record) or '[]')
422
+ except ValueError:
423
+ picked = []
424
+ else:
425
+ row = next((r for r in rows(plan) if r[0] == args.task), None)
426
+ if row is None or is_sweep_task(plan, args.task):
427
+ return 0
428
+ scopes = [posixpath.normpath(p) for p in row[3].split(',') if p and p != '-']
429
+ ctx = Context(plan)
430
+ found = [f for f in ctx.candidates(False)
431
+ if f['origin'] == 'tolerated' and f.get('task') not in (None, args.task)
432
+ and (plan / 'tasks' / f['task'] / 'merged').exists() and not is_sweep_task(plan, f['task'])]
433
+ mod, picked, seen = issues(), [], set()
434
+ for f in sorted(found, key=lambda f: SEVERITIES.index(f['severity'])):
435
+ path = relative(f['file'], ctx.roots)
436
+ key = mod.finding_key(f)
437
+ if path is None or not owns(scopes, path) or key in seen:
438
+ continue
439
+ if ctx.slug and mod.fingerprint(ctx.slug, f) in ctx.dismissed:
440
+ continue
441
+ seen.add(key)
442
+ picked.append(dict(key=key, severity=f['severity'], confidence=f['confidence'], task=f['task'],
443
+ location=location(f, path), text=f['text']))
444
+ if len(picked) >= args.cap:
445
+ break
446
+ write_atomic(record, json.dumps(picked, indent=1) + '\n')
447
+ if not picked:
448
+ return 0
449
+ if args.role == 'dwarf':
450
+ out = ['## Open findings on your files', '',
451
+ 'Reviews of tasks merged earlier in this run left these findings open in files this task owns.',
452
+ 'Fix one only if your change already goes through that code; otherwise leave it, and do not widen',
453
+ 'the task for them. Say in your reply which ones you fixed.', '']
454
+ else:
455
+ out = ['Open findings on this task\'s files were passed to the implementer, to fix only if its change',
456
+ 'already went through that code. A fix of one is in scope; leaving one alone is not a finding.']
457
+ out += ['- [%s][%s] %s — %s (task %s)' % (p['severity'], p['confidence'], p['location'], p['text'], p['task'])
458
+ for p in picked]
459
+ print('\n'.join(out) + '\n')
460
+ return 0
461
+
462
+
463
+ def outcome(text: str, findings: list) -> list:
464
+ """Each finding's status from a sweep review: fixed, not-fixed or unreported (the first S line wins)."""
465
+ said = {}
466
+ for m in S_LINE.finditer(text or ''):
467
+ said.setdefault(m.group(1).upper(), ('not-fixed' if m.group(2).upper().startswith('NOT') else 'fixed',
468
+ m.group(3).strip()[:300]))
469
+ return [dict(id=f['id'], key=f['key'], task=f['task'], status=said.get(f['id'], ('unreported', ''))[0],
470
+ note=said.get(f['id'], ('', ''))[1]) for f in findings]
471
+
472
+
473
+ def cmd_settle(args) -> int:
474
+ root = Path(args.plan).resolve() / 'tasks' / args.task
475
+ try:
476
+ findings = json.loads(read(root / 'sweep.json'))['findings']
477
+ except (ValueError, KeyError, TypeError):
478
+ return 0
479
+ result = dict(at=time.time(), findings=outcome(read(root / 'qa.last'), findings))
480
+ write_atomic(root / 'sweep.outcome.json', json.dumps(result, indent=1) + '\n')
481
+ return 0
482
+
483
+
484
+ def task_state(root: Path) -> str:
485
+ if (root / 'merged').exists():
486
+ return 'MERGED'
487
+ return (read(root / 'status').split() or ['PENDING'])[0]
488
+
489
+
490
+ def cmd_report(args) -> int:
491
+ plan = Path(args.plan).resolve()
492
+ try:
493
+ record = json.loads(read(plan / 'sweep' / 'plan.json'))
494
+ except ValueError:
495
+ return 0
496
+ tasks, fixed, total = record.get('tasks') or [], 0, 0
497
+ lines = []
498
+ for task in tasks:
499
+ root = plan / 'tasks' / task['id']
500
+ state = task_state(root)
501
+ done = 0
502
+ if state == 'MERGED':
503
+ try:
504
+ done = sum(1 for f in json.loads(read(root / 'sweep.outcome.json'))['findings'] if f.get('status') == 'fixed')
505
+ except (ValueError, KeyError, TypeError):
506
+ pass
507
+ fixed += done
508
+ total += len(task['findings'])
509
+ lines.append(' %-14s %-9s %d of %d fixed %s' % (task['id'], state, done, len(task['findings']), task['file']))
510
+ left = len(record.get('dropped') or []) + total - fixed
511
+ print('finding sweep (%s and worse): %d fix task(s), %d of %d finding(s) fixed; %d left for forge issues'
512
+ % (record.get('severity'), len(tasks), fixed, total, left))
513
+ print('\n'.join(lines + [' plan: %s' % (plan / 'sweep' / 'plan.md'), '']))
514
+ return 0
515
+
516
+
517
+ def main(argv=None) -> int:
518
+ parser = argparse.ArgumentParser(prog='forge-sweep.py', description=__doc__.split('\n\n')[0])
519
+ sub = parser.add_subparsers(dest='command', required=True)
520
+ p = sub.add_parser('plan')
521
+ p.add_argument('plan')
522
+ p.add_argument('--severity', choices=SEVERITIES, required=True)
523
+ p.add_argument('--plausible', action='store_true')
524
+ p.add_argument('--max', type=int, default=DEFAULT_MAX)
525
+ a = sub.add_parser('ahead')
526
+ a.add_argument('plan')
527
+ a.add_argument('task')
528
+ a.add_argument('--role', choices=('dwarf', 'qa'), default='dwarf')
529
+ a.add_argument('--cap', type=int, default=AHEAD_CAP)
530
+ s = sub.add_parser('settle')
531
+ s.add_argument('plan')
532
+ s.add_argument('task')
533
+ r = sub.add_parser('report')
534
+ r.add_argument('plan')
535
+ args = parser.parse_args(argv)
536
+ if args.command == 'plan' and args.max < 1:
537
+ parser.error('--max must be at least 1')
538
+ return {'plan': cmd_plan, 'ahead': cmd_ahead, 'settle': cmd_settle, 'report': cmd_report}[args.command](args)
539
+
540
+
541
+ if __name__ == '__main__':
542
+ sys.exit(main())
@@ -337,7 +337,10 @@ def budget() -> float:
337
337
  value = float(os.environ.get('FORGE_FORECAST_BUDGET_S') or BUDGET_S)
338
338
  except ValueError:
339
339
  return BUDGET_S
340
- return value if value > 0 else BUDGET_S
340
+ if not value > 0:
341
+ return BUDGET_S
342
+ # Thread.join refuses a timeout past TIMEOUT_MAX (inf, 1e10, ...): that budget means no limit.
343
+ return min(value, threading.TIMEOUT_MAX)
341
344
 
342
345
 
343
346
  def main(args) -> int:
package/ui/README.md CHANGED
@@ -18,6 +18,13 @@ blocks on a plate, with cables between them and lamps that light up as things ha
18
18
  - **Verification as it happens:** the step each lane is in, its last line, the failing tests
19
19
  first (new or known, from the lanes' test reports) with a link into the log at each one, and
20
20
  every lane's output a click away.
21
+ - **Where each task is, and what it checked:** the command a running dwarf or reviewer is
22
+ running and for how long, flagged when its log has been quiet for five minutes; why a task
23
+ that is not running waits (its dependencies, shared files, a full run, a drain, an
24
+ infrastructure pause with its countdown, the retry policy); each attempt's tests, type checks,
25
+ lints and builds with their exits, times and counts, against the commands its acceptance
26
+ criteria name; and one banner for an environment problem (Docker, a sandbox's EPERM, a port in
27
+ use) that several tasks met.
21
28
  - **Click to open.** A task opens to show its attempts, each with its dwarf, its reviewer and
22
29
  any shadow reviews, linked; an escalation is a labelled cable between attempts. The
23
30
  inspector beside the stage shows what launched each step and what came of it: the exact
@@ -172,15 +179,35 @@ keep one meaning everywhere (amber running, green merged or passed, red failed,
172
179
  a lamp: their severity is a shape (P0 spike, P1 diamond, P2 cone, P3 pin).
173
180
  - **Tables:** the task table and the leaderboard's tables sort by any column (click its header:
174
181
  ascending, descending, off), reorder by dragging a header (or Alt+← → on it), and show or hide
175
- columns from *Columns*, which also resets them. Each table remembers its columns.
182
+ columns from *Columns*, which also resets them. Each table remembers its columns. The task
183
+ table's *Now* column says what each running task runs (and for how long), or why one waits.
176
184
 
177
185
  <img src="docs/media/run.png" width="49%" alt="Planned waves: a run's tasks on a 3D plate with dependency cables, finding marks and the finish nodes, between the runs list and the run's inspector."> <img src="docs/media/execution.png" width="49%" alt="Execution: one block per attempt on wall-clock time, failed attempts in red, with the timeline and critical path in the inspector.">
178
- - **Inspector:** for the run, its timeline, critical path, peak concurrency and finish line;
179
- for a task, its models and routing, escalations, timings (busy, model time, overhead,
180
- queue wait after its dependencies merged), attempts and their executions, review findings
181
- with the gate decision, Clef predictions against outcomes, and its prompts; for one
182
- execution, its model, phases, tokens, exact prompt and final message; for the final
183
- review, its verdict, findings, report, prompt and history.
186
+ - **Inspector:** for the run, its timeline, critical path, peak concurrency, what its scheduler
187
+ is doing (dispatching, drained or stopping, how many tasks wait and on what, each pause with its
188
+ countdown) and finish line, with what the finding sweep fixed and left; for a task, *Now* (below), its models and routing, escalations,
189
+ timings (busy, model time, overhead, queue wait after its dependencies merged), attempts and
190
+ their executions with the checks each ran, review findings with the gate decision, what the
191
+ finding sweep did with its findings (or, for a fix task, each finding it took and whether its
192
+ review found it fixed), Clef predictions against outcomes, and its prompts; for one execution, its model, phases, tokens,
193
+ checks, exact prompt and final message; for the final review, its verdict, findings, report,
194
+ prompt and history.
195
+ - **Now and checks:** a running task's *Now* names the agent at work and its attempt, the phase
196
+ and for how long, the command it is running (its first line, and whether it is a test, type
197
+ check, lint or build) and for how long, when its log last moved, and *quiet N min* once that is
198
+ over five minutes; it links to the conversation. A task that is not running says why: the
199
+ tasks it waits on (a stopped one marked), the running task it shares files with, no free slot,
200
+ a drain or stop, an infrastructure pause with its countdown, or the retry policy's stop with
201
+ the split it suggests. Under each attempt's dwarf and reviewer are the checks they ran, from
202
+ their logs: a lamp, the kind, the command (opening the conversation at it), its exit, time and
203
+ counts (passed, failed, skipped; or errors and warnings), and a failed one's last lines; then
204
+ the environment problems its failed commands met, and which of the commands the brief's
205
+ `## Acceptance criteria` names ran, ran another way, or never ran. A codex or grok log carries
206
+ no times, so the times come from the clock forge keeps beside each log (runs from before it
207
+ show none). The run header's *Environment* banner lists a problem (Docker down or out of
208
+ address pools, a missing container, a port in use, the sandbox's EPERM, a refused local
209
+ service, no network, a full disk, a missing command) that the failed commands of more than one
210
+ task met, with those tasks and, folded, each command and the line that showed it.
184
211
  - **Verification (its finish node):** while it runs, how long it has run, the step a lane
185
212
  announced (`::forge step name=… state=start`) and for how long, the last line it printed, a
186
213
  warning after five minutes with no output, and the live output of the lane that printed last
@@ -223,7 +250,7 @@ keep one meaning everywhere (amber running, green merged or passed, red failed,
223
250
  from a finding's mark on the stage (`/finding/<id>` scrolls to that finding and focuses it).
224
251
 
225
252
  <img src="docs/media/diff.png" width="760" alt="The diff a reviewer read, with a P1 finding under the line that compares token digests and a P2 finding under the revoke function.">
226
- - **Conversations (`…/tasks/<id>/executions/<dwarf-or-qa>/conversation`, `…/executions/<id>/conversation`):**
253
+ - **Conversations (`…/tasks/<id>/executions/<dwarf-or-qa>/conversation[/event/<n>]`, `…/executions/<id>/conversation`):**
227
254
  what one dwarf or reviewer said and did, read from its agent CLI's `<role>.log`, in the diff's
228
255
  place: its messages, its thinking folded, each command with its exit and output, each edit with
229
256
  its patch and a link to the file in the diff its review read, other tool calls, and the final
@@ -232,7 +259,8 @@ keep one meaning everywhere (amber running, green merged or passed, red failed,
232
259
  *Follow* keeps the newest event in view. codex, grok, claude, openclaude and opencode logs are
233
260
  read event by event; when a claude run logged only its final answer, the conversation comes from
234
261
  Claude's own session file for that run, if it is still on this machine; any other log is shown
235
- as it is. Open it from an attempt's dwarf or reviewer in the inspector.
262
+ as it is. Open it from an attempt's dwarf or reviewer in the inspector, or at one command from a
263
+ check or an environment problem (`/event/<n>` opens it there and stops following the end).
236
264
 
237
265
  <img src="docs/media/conversation.png" width="760" alt="A dwarf's conversation: its thinking, the files it wrote, a test run that failed with exit 1 and the run that passed after the fix.">
238
266
  - **Fractal child tasks:** when a run used Fractal, a task's inspector shows the tree it was split
@@ -322,6 +350,9 @@ turns all of it off: no token is issued, every change is a 405, and the controls
322
350
  - `forge_ui/static/diffview.js`: the diff viewer, with findings pinned to their lines.
323
351
  - `forge_ui/static/convo.js`, `forge_ui/transcripts.py`: an execution's conversation, and the
324
352
  reader of each agent CLI's log format behind it.
353
+ - `forge_ui/static/checksview.js`, `forge_ui/checks.py`: where each task stands and the checks its
354
+ agents ran (the Now column and section, each attempt's checks, the environment banner), and
355
+ the reading of checks, counts, acceptance criteria and environment problems from a transcript.
325
356
  - `forge_ui/static/files.js`: the files heatmap (`matrix()` is pure and node-tested).
326
357
  - `forge_ui/export.py`: a run as one HTML file (the page's scripts and styles inlined, the API
327
358
  responses it reads, the 3D stage's modules as one module text, a hash-based policy).