@giamme/forge 0.11.1 → 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.
Files changed (54) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/SKILL.md +7 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +50 -11
  5. package/docs/commands.md +56 -8
  6. package/docs/decomposed-runs.md +43 -2
  7. package/docs/forge-ui.md +55 -8
  8. package/docs/reviews.md +64 -6
  9. package/package.json +1 -1
  10. package/references/dataset.md +4 -2
  11. package/references/decompose.md +191 -17
  12. package/references/harnesses.md +13 -1
  13. package/references/ui.md +25 -4
  14. package/scripts/forge-contract.py +37 -7
  15. package/scripts/forge-control.py +268 -25
  16. package/scripts/forge-dispatch.sh +90 -3
  17. package/scripts/forge-guard.py +156 -15
  18. package/scripts/forge-issues.py +47 -3
  19. package/scripts/forge-lib-plans.sh +9 -3
  20. package/scripts/forge-lib-review.sh +24 -5
  21. package/scripts/forge-lib-task.sh +53 -5
  22. package/scripts/forge-lib-verify.sh +137 -6
  23. package/scripts/forge-parallel-options.sh +85 -0
  24. package/scripts/forge-parallel.sh +262 -31
  25. package/scripts/forge-ripwire.py +1 -1
  26. package/scripts/forge-route.py +157 -5
  27. package/scripts/forge-runtime.py +49 -1
  28. package/scripts/forge-schedule.py +735 -53
  29. package/scripts/forge-solo.sh +3 -1
  30. package/scripts/forge-sweep.py +542 -0
  31. package/scripts/forge-verify.py +878 -0
  32. package/scripts/forge_dataset/forecast.py +33 -5
  33. package/scripts/forge_dataset/harvest.py +10 -4
  34. package/scripts/forge_verify_reports.py +225 -0
  35. package/ui/README.md +58 -12
  36. package/ui/docs/api.md +277 -28
  37. package/ui/forge_ui/checks.py +331 -0
  38. package/ui/forge_ui/control.py +12 -2
  39. package/ui/forge_ui/export.py +25 -8
  40. package/ui/forge_ui/reader.py +657 -24
  41. package/ui/forge_ui/server.py +29 -0
  42. package/ui/forge_ui/static/app.js +15 -7
  43. package/ui/forge_ui/static/checksview.js +449 -0
  44. package/ui/forge_ui/static/controls.js +217 -33
  45. package/ui/forge_ui/static/convo.js +11 -2
  46. package/ui/forge_ui/static/findingsview.js +6 -4
  47. package/ui/forge_ui/static/gantt.js +14 -9
  48. package/ui/forge_ui/static/index.html +2 -0
  49. package/ui/forge_ui/static/panel.js +44 -1
  50. package/ui/forge_ui/static/runmodel.js +109 -12
  51. package/ui/forge_ui/static/scene3d.js +9 -5
  52. package/ui/forge_ui/static/style.css +113 -0
  53. package/ui/forge_ui/static/verifyview.js +324 -0
  54. package/ui/forge_ui/transcripts.py +225 -54
@@ -300,7 +300,9 @@ fi
300
300
  if [ -s "$RUN/failfirst.txt" ]; then cat "$RUN/failfirst.txt"; echo; fi
301
301
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo
302
302
  echo
303
- echo '```diff'; cat "$RUN/changes.diff"; echo '```'
303
+ # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
304
+ # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
305
+ echo '```diff'; git -C "$REPO" diff --binary --irreversible-delete "$START" "$END" -- . ':(exclude).forge'; echo '```'
304
306
  echo; /bin/bash "$MEMORY" note qa
305
307
  echo "Place any learning notes before the final FORGE_VERDICT: PASS or FORGE_VERDICT: FAIL line."
306
308
  } > "$RUN/qa.input"
@@ -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())