@giamme/forge 0.19.0 → 0.20.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.
@@ -13,8 +13,9 @@ Two opt-in behaviours live here, both off by default so a plain `run` is unchang
13
13
 
14
14
  A third, ``--sweep Pn``, also per invocation: once every task has merged, the open review
15
15
  findings at Pn or worse become fix tasks (``forge-parallel.sh _sweep``, forge-sweep.py) that
16
- this run then dispatches like any other, once per plan. A fix task that fails leaves its
17
- findings for ``forge issues`` and does not fail the run.
16
+ this run then dispatches like any other: one round per invocation, each finding swept once (a
17
+ rerun that merged new findings starts the next round; ``forge-sweep.py plan --check`` says whether
18
+ there is one). A fix task that fails leaves its findings for ``forge issues`` and does not fail the run.
18
19
 
19
20
  Both numbers are per invocation, but while the scheduler runs they are mirrored into the
20
21
  plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
@@ -735,6 +736,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
735
736
  fractal = _fractal_plan(plan)
736
737
  drain_told = False # the drained message was printed for this drain
737
738
  sweep_asked = False # this invocation already asked for the finding sweep
739
+ sweep_checked = {} # the answer of this invocation's one `plan --check`
738
740
  brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
739
741
  brief_told = set() # (task, qid or '') whose brief wait was already printed
740
742
  brief_waiting = set() # tasks the last dispatch pass held for a brief answer or the brief writer
@@ -1414,12 +1416,66 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1414
1416
  """A finding sweep's fix task."""
1415
1417
  return (plan / 'tasks' / name / 'sweep.json').is_file()
1416
1418
 
1419
+ def sweep_rounds() -> list:
1420
+ """The sweep rounds this plan has, oldest first: [(number, plan.json path)]."""
1421
+ found = {}
1422
+ if (plan / 'sweep' / 'plan.json').exists():
1423
+ found[1] = plan / 'sweep' / 'plan.json'
1424
+ with contextlib.suppress(OSError):
1425
+ for path in (plan / 'sweep' / 'rounds').iterdir():
1426
+ if path.name.isdigit() and int(path.name) >= 2 and (path / 'plan.json').exists():
1427
+ found[int(path.name)] = path / 'plan.json'
1428
+ return sorted(found.items())
1429
+
1430
+ def sweep_check() -> bool:
1431
+ """Whether `forge-sweep.py plan --check` finds a finding no round swept yet; asked once per
1432
+ invocation. Nothing new is written down for the run summary (sweep/nothing.json). A check that
1433
+ fails (the integration branch cannot be read) is not a reason to plan."""
1434
+ if 'answer' not in sweep_checked:
1435
+ result = subprocess.run([sys.executable, str(Path(__file__).resolve().with_name('forge-sweep.py')), 'plan',
1436
+ str(plan), '--severity', sweep, '--max', str(sweep_max), '--check']
1437
+ + (['--plausible'] if sweep_plausible else []),
1438
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
1439
+ sweep_checked['code'] = result.returncode
1440
+ sweep_checked['answer'] = result.returncode == 0
1441
+ if result.returncode == 1:
1442
+ try:
1443
+ counts = json.loads(result.stdout)
1444
+ note = {'at': time.time(), 'attempted': int(counts['attempted']), 'left': int(counts['left'])}
1445
+ (plan / 'sweep').mkdir(exist_ok=True)
1446
+ fd, tmp = tempfile.mkstemp(dir=str(plan / 'sweep'), prefix='.nothing.json.')
1447
+ with os.fdopen(fd, 'w') as handle:
1448
+ handle.write(json.dumps(note) + '\n')
1449
+ os.replace(tmp, plan / 'sweep' / 'nothing.json')
1450
+ except (ValueError, KeyError, TypeError, OSError) as error:
1451
+ _warn('could not record that the sweep found nothing new: ' + str(error))
1452
+ return sweep_checked['answer']
1453
+
1417
1454
  def sweep_due() -> bool:
1418
- """--sweep was given, every task merged, nothing stops or holds the run, and this plan was
1419
- never swept (sweep/plan.json is the planner's record, and its marker)."""
1420
- return (bool(sweep) and not sweep_asked and not interrupted and not graceful and not paused
1421
- and not drained(plan) and not (plan / 'sweep' / 'plan.json').exists()
1422
- and all(status(name) == 'MERGED' for name in tasks))
1455
+ """--sweep was given and nothing stops or holds the run, every task of the plan merged
1456
+ (a fix task of an earlier round may have stopped), the last round's queued fix tasks are
1457
+ merged or stopped, and `plan --check` finds a finding no round tried. At most one round
1458
+ per invocation."""
1459
+ if (not sweep or sweep_asked or interrupted or graceful or paused or drained(plan)
1460
+ or not all(status(name) == 'MERGED' for name in tasks if not is_fix(name))):
1461
+ return False
1462
+ rounds = sweep_rounds()
1463
+ if rounds:
1464
+ try:
1465
+ last = json.loads((rounds[-1][1]).read_text()).get('tasks') or []
1466
+ except (OSError, ValueError, AttributeError):
1467
+ last = []
1468
+ # A crash between plan.json and the tasks.tsv append leaves the fix task with no row
1469
+ # and no status. status() would say PENDING and hold every later round; that round is lost.
1470
+ if any(status(item['id']) not in ('MERGED', 'FAIL', 'NEEDS_DECISION', 'INFRA')
1471
+ for item in last if isinstance(item, dict) and isinstance(item.get('id'), str)
1472
+ and (item['id'] in tasks or (plan / 'tasks' / item['id'] / 'status').exists())):
1473
+ return False
1474
+ return sweep_check()
1475
+ # Round 1 asks too, so nothing eligible is recorded and not planned. A check that cannot
1476
+ # be answered (the integration branch cannot be read) still starts the round.
1477
+ sweep_check()
1478
+ return sweep_checked.get('code') != 1
1423
1479
 
1424
1480
  def start_sweep() -> int:
1425
1481
  """Plan the finding sweep and queue its fix tasks; how many were queued. Whatever goes
@@ -6,23 +6,31 @@ A run can end with findings nobody acts on in the run: CONFIRMED findings `--qa-
6
6
  sweep they reach `forge issues` and are fixed later, if at all. With one, the scheduler calls `plan` once
7
7
  every task has merged: the open findings become a few fix tasks, one per file, added to the live run.
8
8
 
9
- plan <plan> --severity P0..P3 [--plausible] [--max N]
9
+ plan <plan> --severity P0..P3 [--plausible] [--max N] [--check]
10
10
  Collect the open findings (forge-issues.py's collector), triage them, group them by file, write
11
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.
12
+ plan.md, also printed to stderr), then print the new task ids, one per line. A plan is swept in
13
+ rounds (#152): round 1 is sweep/plan.json, round N >= 2 is sweep/rounds/<N>/plan.json, and a
14
+ finding is swept at most once: one an earlier round attempted, or the record of the repository's
15
+ findings (forge_findings) marks fixed, filed or duplicate, is left out. A later round with nothing
16
+ new writes and prints nothing. --check does the same triage, writes nothing and prints
17
+ {"eligible": E, "attempted": A, "left": L}; it exits 0 when E >= 1, else 1.
14
18
  ahead <plan> <task> [--role dwarf|qa] [--cap N]
15
19
  The prompt step: the open findings in files <task> owns, as a prompt section. Picked once per
16
20
  task (tasks/<task>/sweep.ahead.json), so every attempt and its reviewer see the same list.
17
21
  settle <plan> <task>
18
22
  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.
23
+ in tasks/<task>/sweep.outcome.json. `forge issues` leaves out the findings marked fixed once the
24
+ task has merged, and only then does the record get a `fixed` entry for each (actor sweep, the
25
+ task, the merge commit).
20
26
  report <plan>
21
- What the sweep did, for the run's closing summary; nothing when the plan was never swept.
27
+ What each sweep round did, for the run's closing summary, and the line saying a sweep found nothing
28
+ new (sweep/nothing.json, written by the scheduler); nothing when the plan was never swept.
22
29
 
23
30
  Triage keeps a finding only when it is CONFIRMED and tolerated (or PLAUSIBLE, with --plausible), at
24
31
  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
32
+ review finds goes to `forge issues`), not dismissed (`forge issues --dismiss`) or otherwise settled in the finding record, not attempted by
33
+ an earlier round, located in a file the
26
34
  integration branch still has, and still there: when a later merge changed the file and the line the
27
35
  reviewer saw is gone from it, the finding is left for `forge issues` rather than "fixed" twice. A
28
36
  person's acceptance of a reviewer's FAIL (`accept`, or `adopt --approved`) is theirs to triage, so accepted
@@ -53,11 +61,17 @@ import tempfile
53
61
  import time
54
62
 
55
63
  SCRIPTS = Path(__file__).resolve().parent
64
+ if str(SCRIPTS) not in sys.path:
65
+ sys.path.insert(0, str(SCRIPTS))
56
66
  SEVERITIES = ('P0', 'P1', 'P2', 'P3')
57
67
  DEFAULT_MAX = 5 # fix tasks one sweep may add
58
68
  GROUP_CAP = 8 # findings one fix task is given; the rest of its file stays for forge issues
59
69
  AHEAD_CAP = 3 # findings the prompt step hands one task
60
70
  LOCK_WAIT = 5.0
71
+ try:
72
+ from forge_findings.status import OPEN # the record statuses a finding can still be swept in
73
+ except Exception: # fail-open: the sweep never depends on the record store loading
74
+ OPEN = ('open', 'to-file')
61
75
  # A reviewer's line per finding: `- S2: NOT FIXED — why`. A placeholder (`S<n>`) never matches.
62
76
  S_LINE = re.compile(r'^[ \t]*(?:[-*+][ \t]+)?[*_`]*(S\d{1,3})[*_`]*[ \t]*[:—–-][ \t]*[*_`]*(NOT[ \t]+FIXED|FIXED)\b'
63
77
  r'[*_`]*[ \t]*[:—–-]?[ \t]*(.*)$', re.I | re.M)
@@ -67,6 +81,8 @@ REASONS = {
67
81
  'no-location': 'no file in the repository to fix it in',
68
82
  'file-gone': 'its file is no longer on the integration branch',
69
83
  'changed': 'the code it points at changed after the review',
84
+ 'attempted': 'an earlier sweep round already tried it',
85
+ 'recorded': 'the finding record marks it fixed, filed or a duplicate',
70
86
  'duplicate': 'the same finding was reported again',
71
87
  'group-cap': 'over the %d findings one fix task takes' % GROUP_CAP,
72
88
  'over-max': 'over --sweep-max fix tasks',
@@ -190,8 +206,50 @@ def location(f, path=None) -> str:
190
206
  return where + (':%d' % f['line'] if f.get('line') else '')
191
207
 
192
208
 
209
+ def round_paths(plan: Path) -> dict:
210
+ """{round number: its plan.json}: round 1 is sweep/plan.json, round N >= 2 sweep/rounds/<N>/plan.json."""
211
+ found = {}
212
+ if (plan / 'sweep' / 'plan.json').exists():
213
+ found[1] = plan / 'sweep' / 'plan.json'
214
+ try:
215
+ names = sorted((plan / 'sweep' / 'rounds').iterdir())
216
+ except OSError:
217
+ names = []
218
+ for path in names:
219
+ if path.name.isdigit() and int(path.name) >= 2 and (path / 'plan.json').exists():
220
+ found[int(path.name)] = path / 'plan.json'
221
+ return found
222
+
223
+
224
+ def round_record(path: Path) -> 'dict | None':
225
+ """A round's plan record, None when it is not one."""
226
+ try:
227
+ record = json.loads(read(path))
228
+ except ValueError:
229
+ return None
230
+ return record if isinstance(record, dict) else None
231
+
232
+
233
+ def attempted_keys(plan: Path) -> dict:
234
+ """{finding key: the sweep task that took it} over every sweep task's sweep.json, once a round exists.
235
+ Whatever its outcome: a finding is swept once."""
236
+ found = {}
237
+ if not round_paths(plan):
238
+ return found
239
+ for path in sorted((plan / 'tasks').glob('sweep-*/sweep.json')):
240
+ try:
241
+ entries = json.loads(read(path))['findings']
242
+ except (ValueError, KeyError, TypeError):
243
+ continue
244
+ for entry in entries if isinstance(entries, list) else []:
245
+ if isinstance(entry, dict) and isinstance(entry.get('key'), str):
246
+ found.setdefault(entry['key'], path.parent.name)
247
+ return found
248
+
249
+
193
250
  class Context:
194
- """What triage reads once per plan: the repository, its checkouts, the dismissal marks."""
251
+ """What triage reads once per plan: the repository, its checkouts, the finding record (what became of
252
+ each finding), the findings earlier rounds attempted."""
195
253
 
196
254
  def __init__(self, plan: Path):
197
255
  self.plan = plan
@@ -202,12 +260,26 @@ class Context:
202
260
  self.tip = tip.decode().strip() if not rc else ''
203
261
  self.roots = [self.integration, self.repo] + [os.path.join(wt_root, r[0]) for r in rows(plan)] if wt_root \
204
262
  else [self.repo]
205
- mod = issues()
206
- self.slug = mod.github_slug(self.repo) if self.repo else None
207
- self.dismissed = {}
208
- if self.slug:
209
- with contextlib.suppress(Exception):
210
- self.dismissed = mod.load_dismissed(mod.repo_key(self.repo))
263
+ self.ident, self.slug, self.record = None, '', {}
264
+ if self.repo:
265
+ try:
266
+ import forge_identity
267
+ from forge_findings import store
268
+ self.ident = forge_identity.identity(plan)
269
+ self.slug = forge_identity.github_slug(self.ident) or ''
270
+ self.record = store.load(self.ident) # an unreadable record leaves every finding in
271
+ except Exception:
272
+ self.record = {}
273
+ self.attempted = attempted_keys(plan)
274
+
275
+ def status(self, f) -> str:
276
+ """The record's status for a finding: open when it says nothing or cannot be read."""
277
+ try:
278
+ from forge_findings import fingerprint
279
+ entry = self.record.get(fingerprint(self.slug, f['file'], f['text']))
280
+ return entry['status'] if isinstance(entry, dict) and isinstance(entry.get('status'), str) else 'open'
281
+ except Exception:
282
+ return 'open'
211
283
 
212
284
  def candidates(self, include_plausible: bool) -> list:
213
285
  found, _ = issues().collect_plan(self.plan, include_plausible)
@@ -239,12 +311,22 @@ def triage(ctx: Context, found: list, severity: str, plausible: bool) -> tuple:
239
311
  if SEVERITIES.index(f['severity']) > cut:
240
312
  drop('below-severity')
241
313
  continue
242
- if ctx.slug and mod.fingerprint(ctx.slug, f) in ctx.dismissed:
314
+ recorded = ctx.status(f)
315
+ if recorded == 'dismissed':
243
316
  drop('dismissed')
244
317
  continue
318
+ if recorded not in OPEN:
319
+ drop('recorded', status=recorded)
320
+ continue
321
+ # A repeat is one finding reported again, including one an earlier round attempted.
322
+ # Record that drop so the next report reaches this check instead of counting as attempted again.
245
323
  if f['key'] in seen:
246
324
  drop('duplicate', of=seen[f['key']])
247
325
  continue
326
+ if f['key'] in ctx.attempted:
327
+ drop('attempted', task=ctx.attempted[f['key']])
328
+ seen[f['key']] = f['task']
329
+ continue
248
330
  path = relative(f['file'], ctx.roots)
249
331
  if path not in tip_text:
250
332
  tip_text[path] = blob(ctx.integration, ctx.tip, path) if path and ctx.tip else None
@@ -343,7 +425,8 @@ def plan_markdown(record: dict) -> str:
343
425
  tasks, dropped = record['tasks'], record['dropped']
344
426
  scope = '%s and worse, %s' % (record['severity'], 'CONFIRMED and PLAUSIBLE' if record['plausible'] else 'CONFIRMED only')
345
427
  n = sum(len(t['findings']) for t in tasks)
346
- out = ['# Finding sweep: %d fix task(s) for %d finding(s) (%s)' % (len(tasks), n, scope), '']
428
+ label = 'Finding sweep' if record.get('round', 1) == 1 else 'Finding sweep, round %d' % record['round']
429
+ out = ['# %s: %d fix task(s) for %d finding(s) (%s)' % (label, len(tasks), n, scope), '']
347
430
  if tasks:
348
431
  out += ['Each fix task is one implementation and one narrow review: %d dispatches, plus any automatic'
349
432
  % record['estimate']['dispatches'], 'retries (--retry-failed). They run on the integration branch at %s.'
@@ -365,27 +448,50 @@ def plan_markdown(record: dict) -> str:
365
448
  return '\n'.join(out)
366
449
 
367
450
 
451
+ def eligible_groups(plan: Path, ctx: Context, args) -> tuple:
452
+ """(chosen, dropped, table, by_id): the triage and grouping a sweep round runs, writing nothing."""
453
+ kept, dropped = triage(ctx, ctx.candidates(args.plausible), args.severity, args.plausible)
454
+ chosen, over = groups(kept, args.max)
455
+ dropped += over
456
+ table = rows(plan)
457
+ by_id = {row[0]: row for row in table}
458
+ for path, items in list(chosen):
459
+ if not all(models(plan, by_id.get(items[0]['task']), items[0], table)):
460
+ chosen.remove((path, items))
461
+ dropped += [dict(f, reason='no-model', detail={}) for f in items]
462
+ return chosen, dropped, table, by_id
463
+
464
+
465
+ def cmd_check(args, plan: Path) -> int:
466
+ """plan --check: how many findings a round would sweep, nothing written."""
467
+ ctx = Context(plan)
468
+ if not ctx.tip:
469
+ print('forge: sweep: the integration branch cannot be read; nothing swept', file=sys.stderr)
470
+ return 3
471
+ chosen, dropped, _, _ = eligible_groups(plan, ctx, args)
472
+ eligible = sum(len(items) for _, items in chosen)
473
+ attempted = sum(1 for f in dropped if f['reason'] == 'attempted')
474
+ print(json.dumps(dict(eligible=eligible, attempted=attempted, left=len(dropped) - attempted)))
475
+ return 0 if eligible else 1
476
+
477
+
368
478
  def cmd_plan(args) -> int:
369
479
  plan = Path(args.plan).resolve()
480
+ if args.check:
481
+ return cmd_check(args, plan)
370
482
  sweep_dir = plan / 'sweep'
371
- if (sweep_dir / 'plan.json').exists():
372
- return 0 # one sweep per plan
483
+ rounds = round_paths(plan)
484
+ number = max(rounds, default=0) + 1
373
485
  ctx = Context(plan)
374
486
  if not ctx.tip:
375
487
  print('forge: sweep: the integration branch cannot be read; nothing swept', file=sys.stderr)
376
488
  return 3
377
- kept, dropped = triage(ctx, ctx.candidates(args.plausible), args.severity, args.plausible)
378
- chosen, over = groups(kept, args.max)
379
- dropped += over
380
- table = rows(plan)
381
- by_id = {row[0]: row for row in table}
489
+ chosen, dropped, table, by_id = eligible_groups(plan, ctx, args)
490
+ if number > 1 and not chosen:
491
+ return 0 # a later round with nothing new leaves no trace
382
492
  ids = free_ids(set(by_id) | {p.name for p in (plan / 'tasks').iterdir() if p.is_dir()}, len(chosen))
383
493
  run_id = read(plan / 'run_id') or plan.name
384
494
  tasks, new_rows = [], []
385
- for path, items in list(chosen):
386
- if not all(models(plan, by_id.get(items[0]['task']), items[0], table)):
387
- chosen.remove((path, items))
388
- dropped += [dict(f, reason='no-model', detail={}) for f in items]
389
495
  for ident, (path, items) in zip(ids, chosen):
390
496
  entries = [dict(id='S%d' % n, key=f['key'], severity=f['severity'], confidence=f['confidence'],
391
497
  origin=f['origin'], task=f['task'], file=f['file'], line=f.get('line'), path=path,
@@ -399,18 +505,19 @@ def cmd_plan(args) -> int:
399
505
  write_atomic(root / 'sweep.json', json.dumps(dict(file=path, findings=entries), indent=1) + '\n')
400
506
  tasks.append(dict(id=ident, file=path, dwarf=dwarf, qa=qa, title=title, findings=entries))
401
507
  new_rows.append('\t'.join([ident, '-', 'low', path, dwarf, qa, title]))
402
- record = dict(version=1, at=time.time(), severity=args.severity, plausible=args.plausible, max=args.max,
403
- integration=ctx.tip, tasks=tasks, estimate=dict(dispatches=2 * len(tasks)),
508
+ record = dict(version=1, round=number, at=time.time(), severity=args.severity, plausible=args.plausible,
509
+ max=args.max, integration=ctx.tip, tasks=tasks, estimate=dict(dispatches=2 * len(tasks)),
404
510
  dropped=[dict(task=f['task'], severity=f['severity'], confidence=f['confidence'], origin=f['origin'],
405
511
  file=f['file'], line=f.get('line'), text=f['text'], key=f['key'], reason=f['reason'],
406
512
  detail=f['detail'])
407
513
  for f in dropped])
408
- sweep_dir.mkdir(exist_ok=True)
514
+ target = sweep_dir if number == 1 else sweep_dir / 'rounds' / str(number)
515
+ target.mkdir(parents=True, exist_ok=True)
409
516
  text = plan_markdown(record)
410
- write_atomic(sweep_dir / 'plan.md', text)
411
- # The marker before the rows: a crash in between loses this sweep (its findings still reach forge
517
+ write_atomic(target / 'plan.md', text)
518
+ # The marker before the rows: a crash in between loses this round (its findings still reach forge
412
519
  # issues), and never plans a second one over tasks already in tasks.tsv.
413
- write_atomic(sweep_dir / 'plan.json', json.dumps(record, indent=1) + '\n')
520
+ write_atomic(target / 'plan.json', json.dumps(record, indent=1) + '\n')
414
521
  if new_rows:
415
522
  with control_lock(plan):
416
523
  current = (plan / 'tasks.tsv').read_text(encoding='utf-8')
@@ -451,7 +558,7 @@ def cmd_ahead(args) -> int:
451
558
  key = mod.finding_key(f)
452
559
  if path is None or not owns(scopes, path) or key in seen:
453
560
  continue
454
- if ctx.slug and mod.fingerprint(ctx.slug, f) in ctx.dismissed:
561
+ if ctx.status(f) not in OPEN:
455
562
  continue
456
563
  seen.add(key)
457
564
  picked.append(dict(key=key, severity=f['severity'], confidence=f['confidence'], task=f['task'],
@@ -485,14 +592,47 @@ def outcome(text: str, findings: list) -> list:
485
592
  note=said.get(f['id'], ('', ''))[1]) for f in findings]
486
593
 
487
594
 
595
+ def record_fixed(plan: Path, task: str, findings: list) -> None:
596
+ """A `fixed` record for each finding the sweep review marked fixed, once that sweep task has merged
597
+ (actor sweep, the task, the merge commit). Best effort: whatever goes wrong here is ignored, settle
598
+ never fails because of it. Before `tasks/<task>/merged` exists, write nothing."""
599
+ try:
600
+ # `forge issues` counts a finding swept only after this marker exists; the record follows it.
601
+ if not (plan / 'tasks' / task / 'merged').exists():
602
+ return
603
+ fixed = [f for f in findings if f.get('status') == 'fixed']
604
+ if not fixed:
605
+ return
606
+ ctx = Context(plan)
607
+ if not ctx.ident:
608
+ return
609
+ from forge_findings import fingerprint, store
610
+ try:
611
+ entries = json.loads(read(plan / 'tasks' / task / 'sweep.json'))['findings']
612
+ except (ValueError, KeyError, TypeError):
613
+ return
614
+ by_id = {e['id']: e for e in entries if isinstance(e, dict) and 'id' in e}
615
+ fps = [fingerprint(ctx.slug, by_id[f['id']]['file'], by_id[f['id']]['text']) for f in fixed if f['id'] in by_id]
616
+ fields = dict(reason='sweep ' + task)
617
+ commit = read(plan / 'accepted.integration')
618
+ if store.COMMIT_RE.fullmatch(commit):
619
+ fields['commit'] = commit
620
+ if fps:
621
+ store.set_status(ctx.ident, fps, 'fixed', 'sweep', **fields)
622
+ except Exception:
623
+ pass
624
+
625
+
488
626
  def cmd_settle(args) -> int:
489
- root = Path(args.plan).resolve() / 'tasks' / args.task
627
+ plan = Path(args.plan).resolve()
628
+ root = plan / 'tasks' / args.task
490
629
  try:
491
630
  findings = json.loads(read(root / 'sweep.json'))['findings']
492
631
  except (ValueError, KeyError, TypeError):
493
632
  return 0
494
633
  result = dict(at=time.time(), findings=outcome(read(root / 'qa.last'), findings))
495
634
  write_atomic(root / 'sweep.outcome.json', json.dumps(result, indent=1) + '\n')
635
+ record_fixed(plan, args.task, result['findings'])
496
636
  return 0
497
637
 
498
638
 
@@ -502,12 +642,7 @@ def task_state(root: Path) -> str:
502
642
  return (read(root / 'status').split() or ['PENDING'])[0]
503
643
 
504
644
 
505
- def cmd_report(args) -> int:
506
- plan = Path(args.plan).resolve()
507
- try:
508
- record = json.loads(read(plan / 'sweep' / 'plan.json'))
509
- except ValueError:
510
- return 0
645
+ def report_round(plan: Path, record: dict, path: Path, number: 'int | None') -> None:
511
646
  tasks, fixed, total = record.get('tasks') or [], 0, 0
512
647
  lines = []
513
648
  for task in tasks:
@@ -522,10 +657,29 @@ def cmd_report(args) -> int:
522
657
  fixed += done
523
658
  total += len(task['findings'])
524
659
  lines.append(' %-14s %-9s %d of %d fixed %s' % (task['id'], state, done, len(task['findings']), task['file']))
525
- left = len(record.get('dropped') or []) + total - fixed
526
- print('finding sweep (%s and worse): %d fix task(s), %d of %d finding(s) fixed; %d left for forge issues'
527
- % (record.get('severity'), len(tasks), fixed, total, left))
528
- print('\n'.join(lines + [' plan: %s' % (plan / 'sweep' / 'plan.md'), '']))
660
+ # what an earlier round attempted, or the record settled, is not this round's to leave for forge issues
661
+ left = sum(1 for d in record.get('dropped') or [] if d.get('reason') not in ('attempted', 'recorded')) + total - fixed
662
+ print('finding sweep%s (%s and worse): %d fix task(s), %d of %d finding(s) fixed; %d left for forge issues'
663
+ % (' round %d' % number if number else '', record.get('severity'), len(tasks), fixed, total, left))
664
+ print('\n'.join(lines + [' plan: %s' % path.with_name('plan.md'), '']))
665
+
666
+
667
+ def cmd_report(args) -> int:
668
+ plan = Path(args.plan).resolve()
669
+ paths = round_paths(plan)
670
+ records = {n: round_record(path) for n, path in sorted(paths.items())}
671
+ records = {n: record for n, record in records.items() if record is not None}
672
+ for number, record in records.items():
673
+ report_round(plan, record, paths[number], number if len(records) > 1 else None)
674
+ # Printed after the last round, or alone when round 1's check found nothing (no round was planned).
675
+ last_at = float(records[max(records)].get('at') or 0) if records else 0.0
676
+ try:
677
+ nothing = json.loads(read(plan / 'sweep' / 'nothing.json'))
678
+ if float(nothing['at']) > last_at:
679
+ print('sweep: nothing new to sweep (%d finding(s) already swept or attempted, %d left for forge issues)\n'
680
+ % (int(nothing.get('attempted') or 0), int(nothing.get('left') or 0)))
681
+ except (ValueError, KeyError, TypeError, OSError):
682
+ pass
529
683
  return 0
530
684
 
531
685
 
@@ -537,6 +691,7 @@ def main(argv=None) -> int:
537
691
  p.add_argument('--severity', choices=SEVERITIES, required=True)
538
692
  p.add_argument('--plausible', action='store_true')
539
693
  p.add_argument('--max', type=int, default=DEFAULT_MAX)
694
+ p.add_argument('--check', action='store_true')
540
695
  a = sub.add_parser('ahead')
541
696
  a.add_argument('plan')
542
697
  a.add_argument('task')
@@ -0,0 +1,17 @@
1
+ """Findings: the record store (store.py), default tags (tags.py) and the one status rule (status.py).
2
+
3
+ Standard library only. `fingerprint` is the record key: a finding's identity across runs and checkouts.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import re
9
+
10
+
11
+ def fingerprint(slug, file, text) -> str:
12
+ """12 hex chars naming a finding; byte-identical to `forge-issues.py fingerprint(slug, {"file", "text"})`.
13
+
14
+ `slug` is `owner/repo` (`forge_identity.github_slug(ident) or ""`). Keep the two in step: a test pins them.
15
+ """
16
+ norm = re.sub(r"\s+", " ", text.lower())[:160]
17
+ return hashlib.sha1(f"{slug.lower()}|{file}|{norm}".encode("utf-8")).hexdigest()[:12]