@giamme/forge 0.19.0 → 0.21.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 (72) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +7 -0
  3. package/SKILL.md +3 -0
  4. package/VERSION +1 -1
  5. package/docs/README.md +1 -0
  6. package/docs/commands.md +137 -5
  7. package/docs/development.md +1 -1
  8. package/docs/forge-ui.md +70 -19
  9. package/forge +8 -2
  10. package/package.json +1 -1
  11. package/references/decompose.md +20 -8
  12. package/references/memory.md +30 -5
  13. package/scripts/forge-config.py +10 -9
  14. package/scripts/forge-control.py +51 -35
  15. package/scripts/forge-findings.py +675 -0
  16. package/scripts/forge-group.py +2 -1
  17. package/scripts/forge-guard.py +71 -33
  18. package/scripts/forge-handoff.py +14 -17
  19. package/scripts/forge-issues.py +233 -99
  20. package/scripts/forge-memory.sh +471 -19
  21. package/scripts/forge-parallel.sh +24 -14
  22. package/scripts/forge-planner.py +28 -2
  23. package/scripts/forge-pre-review.py +11 -4
  24. package/scripts/forge-ripwire.py +68 -22
  25. package/scripts/forge-route.py +10 -3
  26. package/scripts/forge-runs-compact.py +3 -2
  27. package/scripts/forge-runs-rm.py +14 -14
  28. package/scripts/forge-runtime.py +36 -19
  29. package/scripts/forge-schedule.py +135 -62
  30. package/scripts/forge-shadow.py +16 -9
  31. package/scripts/forge-summarize.py +7 -3
  32. package/scripts/forge-sweep.py +206 -46
  33. package/scripts/forge-ui.py +8 -13
  34. package/scripts/forge-verify.py +29 -23
  35. package/scripts/forge_brief/__init__.py +1 -1
  36. package/scripts/forge_brief/proposals.py +7 -2
  37. package/scripts/forge_decide/budget.py +6 -1
  38. package/scripts/forge_decide/replay.py +6 -1
  39. package/scripts/forge_findings/__init__.py +17 -0
  40. package/scripts/forge_findings/apply.py +442 -0
  41. package/scripts/forge_findings/status.py +43 -0
  42. package/scripts/forge_findings/store.py +595 -0
  43. package/scripts/forge_findings/tags.py +53 -0
  44. package/scripts/forge_findings/triage.py +594 -0
  45. package/scripts/forge_flock.py +87 -0
  46. package/scripts/forge_fractal/__init__.py +7 -3
  47. package/scripts/forge_fractal/cli.py +7 -2
  48. package/scripts/forge_fractal/execution.py +14 -14
  49. package/scripts/forge_fractal/invocation.py +3 -2
  50. package/scripts/forge_fractal/pipeline.py +2 -1
  51. package/scripts/forge_fractal/selection.py +2 -1
  52. package/scripts/forge_identity.py +328 -0
  53. package/scripts/forge_locations.py +14 -4
  54. package/scripts/forge_memory_list.py +7 -3
  55. package/scripts/forge_posix.py +108 -0
  56. package/scripts/forge_proc.py +399 -0
  57. package/scripts/forge_registry.py +15 -6
  58. package/scripts/forge_retro/__init__.py +8 -2
  59. package/scripts/forge_retro/issues.py +2 -1
  60. package/scripts/forge_side/__init__.py +232 -38
  61. package/scripts/forge_storage.py +11 -1
  62. package/ui/docs/api.md +130 -12
  63. package/ui/forge_ui/control.py +693 -17
  64. package/ui/forge_ui/export.py +1 -1
  65. package/ui/forge_ui/projects.py +209 -22
  66. package/ui/forge_ui/reader.py +18 -17
  67. package/ui/forge_ui/server.py +10 -1
  68. package/ui/forge_ui/static/findingsactions.js +201 -0
  69. package/ui/forge_ui/static/index.html +2 -0
  70. package/ui/forge_ui/static/projectsview.js +600 -45
  71. package/ui/forge_ui/static/style.css +59 -0
  72. package/ui/forge_ui/static/triageview.js +423 -0
@@ -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
@@ -40,7 +48,6 @@ from __future__ import annotations
40
48
 
41
49
  import argparse
42
50
  import contextlib
43
- import fcntl
44
51
  import importlib.util
45
52
  import json
46
53
  import os
@@ -53,11 +60,19 @@ import tempfile
53
60
  import time
54
61
 
55
62
  SCRIPTS = Path(__file__).resolve().parent
63
+ if str(SCRIPTS) not in sys.path:
64
+ sys.path.insert(0, str(SCRIPTS))
65
+ import forge_flock as fcntl # noqa: E402
66
+ import forge_posix # noqa: E402
56
67
  SEVERITIES = ('P0', 'P1', 'P2', 'P3')
57
68
  DEFAULT_MAX = 5 # fix tasks one sweep may add
58
69
  GROUP_CAP = 8 # findings one fix task is given; the rest of its file stays for forge issues
59
70
  AHEAD_CAP = 3 # findings the prompt step hands one task
60
71
  LOCK_WAIT = 5.0
72
+ try:
73
+ from forge_findings.status import OPEN # the record statuses a finding can still be swept in
74
+ except Exception: # fail-open: the sweep never depends on the record store loading
75
+ OPEN = ('open', 'to-file')
61
76
  # A reviewer's line per finding: `- S2: NOT FIXED — why`. A placeholder (`S<n>`) never matches.
62
77
  S_LINE = re.compile(r'^[ \t]*(?:[-*+][ \t]+)?[*_`]*(S\d{1,3})[*_`]*[ \t]*[:—–-][ \t]*[*_`]*(NOT[ \t]+FIXED|FIXED)\b'
63
78
  r'[*_`]*[ \t]*[:—–-]?[ \t]*(.*)$', re.I | re.M)
@@ -67,6 +82,8 @@ REASONS = {
67
82
  'no-location': 'no file in the repository to fix it in',
68
83
  'file-gone': 'its file is no longer on the integration branch',
69
84
  'changed': 'the code it points at changed after the review',
85
+ 'attempted': 'an earlier sweep round already tried it',
86
+ 'recorded': 'the finding record marks it fixed, filed or a duplicate',
70
87
  'duplicate': 'the same finding was reported again',
71
88
  'group-cap': 'over the %d findings one fix task takes' % GROUP_CAP,
72
89
  'over-max': 'over --sweep-max fix tasks',
@@ -111,7 +128,11 @@ def write_atomic(path: Path, text: str) -> None:
111
128
  def control_lock(plan: Path):
112
129
  """The plan's control.lock, as `forge control` takes it, around a tasks.tsv rewrite. Busy for
113
130
  LOCK_WAIT seconds: proceed without it, as the scheduler does."""
114
- fd = os.open(str(plan / 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644)
131
+ fd = forge_posix.open_nofollow(
132
+ str(plan / 'control.lock'),
133
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW,
134
+ 0o644,
135
+ )
115
136
  try:
116
137
  deadline = time.monotonic() + LOCK_WAIT
117
138
  while True:
@@ -190,8 +211,50 @@ def location(f, path=None) -> str:
190
211
  return where + (':%d' % f['line'] if f.get('line') else '')
191
212
 
192
213
 
214
+ def round_paths(plan: Path) -> dict:
215
+ """{round number: its plan.json}: round 1 is sweep/plan.json, round N >= 2 sweep/rounds/<N>/plan.json."""
216
+ found = {}
217
+ if (plan / 'sweep' / 'plan.json').exists():
218
+ found[1] = plan / 'sweep' / 'plan.json'
219
+ try:
220
+ names = sorted((plan / 'sweep' / 'rounds').iterdir())
221
+ except OSError:
222
+ names = []
223
+ for path in names:
224
+ if path.name.isdigit() and int(path.name) >= 2 and (path / 'plan.json').exists():
225
+ found[int(path.name)] = path / 'plan.json'
226
+ return found
227
+
228
+
229
+ def round_record(path: Path) -> 'dict | None':
230
+ """A round's plan record, None when it is not one."""
231
+ try:
232
+ record = json.loads(read(path))
233
+ except ValueError:
234
+ return None
235
+ return record if isinstance(record, dict) else None
236
+
237
+
238
+ def attempted_keys(plan: Path) -> dict:
239
+ """{finding key: the sweep task that took it} over every sweep task's sweep.json, once a round exists.
240
+ Whatever its outcome: a finding is swept once."""
241
+ found = {}
242
+ if not round_paths(plan):
243
+ return found
244
+ for path in sorted((plan / 'tasks').glob('sweep-*/sweep.json')):
245
+ try:
246
+ entries = json.loads(read(path))['findings']
247
+ except (ValueError, KeyError, TypeError):
248
+ continue
249
+ for entry in entries if isinstance(entries, list) else []:
250
+ if isinstance(entry, dict) and isinstance(entry.get('key'), str):
251
+ found.setdefault(entry['key'], path.parent.name)
252
+ return found
253
+
254
+
193
255
  class Context:
194
- """What triage reads once per plan: the repository, its checkouts, the dismissal marks."""
256
+ """What triage reads once per plan: the repository, its checkouts, the finding record (what became of
257
+ each finding), the findings earlier rounds attempted."""
195
258
 
196
259
  def __init__(self, plan: Path):
197
260
  self.plan = plan
@@ -202,12 +265,26 @@ class Context:
202
265
  self.tip = tip.decode().strip() if not rc else ''
203
266
  self.roots = [self.integration, self.repo] + [os.path.join(wt_root, r[0]) for r in rows(plan)] if wt_root \
204
267
  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))
268
+ self.ident, self.slug, self.record = None, '', {}
269
+ if self.repo:
270
+ try:
271
+ import forge_identity
272
+ from forge_findings import store
273
+ self.ident = forge_identity.identity(plan)
274
+ self.slug = forge_identity.github_slug(self.ident) or ''
275
+ self.record = store.load(self.ident) # an unreadable record leaves every finding in
276
+ except Exception:
277
+ self.record = {}
278
+ self.attempted = attempted_keys(plan)
279
+
280
+ def status(self, f) -> str:
281
+ """The record's status for a finding: open when it says nothing or cannot be read."""
282
+ try:
283
+ from forge_findings import fingerprint
284
+ entry = self.record.get(fingerprint(self.slug, f['file'], f['text']))
285
+ return entry['status'] if isinstance(entry, dict) and isinstance(entry.get('status'), str) else 'open'
286
+ except Exception:
287
+ return 'open'
211
288
 
212
289
  def candidates(self, include_plausible: bool) -> list:
213
290
  found, _ = issues().collect_plan(self.plan, include_plausible)
@@ -239,12 +316,22 @@ def triage(ctx: Context, found: list, severity: str, plausible: bool) -> tuple:
239
316
  if SEVERITIES.index(f['severity']) > cut:
240
317
  drop('below-severity')
241
318
  continue
242
- if ctx.slug and mod.fingerprint(ctx.slug, f) in ctx.dismissed:
319
+ recorded = ctx.status(f)
320
+ if recorded == 'dismissed':
243
321
  drop('dismissed')
244
322
  continue
323
+ if recorded not in OPEN:
324
+ drop('recorded', status=recorded)
325
+ continue
326
+ # A repeat is one finding reported again, including one an earlier round attempted.
327
+ # Record that drop so the next report reaches this check instead of counting as attempted again.
245
328
  if f['key'] in seen:
246
329
  drop('duplicate', of=seen[f['key']])
247
330
  continue
331
+ if f['key'] in ctx.attempted:
332
+ drop('attempted', task=ctx.attempted[f['key']])
333
+ seen[f['key']] = f['task']
334
+ continue
248
335
  path = relative(f['file'], ctx.roots)
249
336
  if path not in tip_text:
250
337
  tip_text[path] = blob(ctx.integration, ctx.tip, path) if path and ctx.tip else None
@@ -343,7 +430,8 @@ def plan_markdown(record: dict) -> str:
343
430
  tasks, dropped = record['tasks'], record['dropped']
344
431
  scope = '%s and worse, %s' % (record['severity'], 'CONFIRMED and PLAUSIBLE' if record['plausible'] else 'CONFIRMED only')
345
432
  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), '']
433
+ label = 'Finding sweep' if record.get('round', 1) == 1 else 'Finding sweep, round %d' % record['round']
434
+ out = ['# %s: %d fix task(s) for %d finding(s) (%s)' % (label, len(tasks), n, scope), '']
347
435
  if tasks:
348
436
  out += ['Each fix task is one implementation and one narrow review: %d dispatches, plus any automatic'
349
437
  % record['estimate']['dispatches'], 'retries (--retry-failed). They run on the integration branch at %s.'
@@ -365,27 +453,50 @@ def plan_markdown(record: dict) -> str:
365
453
  return '\n'.join(out)
366
454
 
367
455
 
456
+ def eligible_groups(plan: Path, ctx: Context, args) -> tuple:
457
+ """(chosen, dropped, table, by_id): the triage and grouping a sweep round runs, writing nothing."""
458
+ kept, dropped = triage(ctx, ctx.candidates(args.plausible), args.severity, args.plausible)
459
+ chosen, over = groups(kept, args.max)
460
+ dropped += over
461
+ table = rows(plan)
462
+ by_id = {row[0]: row for row in table}
463
+ for path, items in list(chosen):
464
+ if not all(models(plan, by_id.get(items[0]['task']), items[0], table)):
465
+ chosen.remove((path, items))
466
+ dropped += [dict(f, reason='no-model', detail={}) for f in items]
467
+ return chosen, dropped, table, by_id
468
+
469
+
470
+ def cmd_check(args, plan: Path) -> int:
471
+ """plan --check: how many findings a round would sweep, nothing written."""
472
+ ctx = Context(plan)
473
+ if not ctx.tip:
474
+ print('forge: sweep: the integration branch cannot be read; nothing swept', file=sys.stderr)
475
+ return 3
476
+ chosen, dropped, _, _ = eligible_groups(plan, ctx, args)
477
+ eligible = sum(len(items) for _, items in chosen)
478
+ attempted = sum(1 for f in dropped if f['reason'] == 'attempted')
479
+ print(json.dumps(dict(eligible=eligible, attempted=attempted, left=len(dropped) - attempted)))
480
+ return 0 if eligible else 1
481
+
482
+
368
483
  def cmd_plan(args) -> int:
369
484
  plan = Path(args.plan).resolve()
485
+ if args.check:
486
+ return cmd_check(args, plan)
370
487
  sweep_dir = plan / 'sweep'
371
- if (sweep_dir / 'plan.json').exists():
372
- return 0 # one sweep per plan
488
+ rounds = round_paths(plan)
489
+ number = max(rounds, default=0) + 1
373
490
  ctx = Context(plan)
374
491
  if not ctx.tip:
375
492
  print('forge: sweep: the integration branch cannot be read; nothing swept', file=sys.stderr)
376
493
  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}
494
+ chosen, dropped, table, by_id = eligible_groups(plan, ctx, args)
495
+ if number > 1 and not chosen:
496
+ return 0 # a later round with nothing new leaves no trace
382
497
  ids = free_ids(set(by_id) | {p.name for p in (plan / 'tasks').iterdir() if p.is_dir()}, len(chosen))
383
498
  run_id = read(plan / 'run_id') or plan.name
384
499
  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
500
  for ident, (path, items) in zip(ids, chosen):
390
501
  entries = [dict(id='S%d' % n, key=f['key'], severity=f['severity'], confidence=f['confidence'],
391
502
  origin=f['origin'], task=f['task'], file=f['file'], line=f.get('line'), path=path,
@@ -399,18 +510,19 @@ def cmd_plan(args) -> int:
399
510
  write_atomic(root / 'sweep.json', json.dumps(dict(file=path, findings=entries), indent=1) + '\n')
400
511
  tasks.append(dict(id=ident, file=path, dwarf=dwarf, qa=qa, title=title, findings=entries))
401
512
  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)),
513
+ record = dict(version=1, round=number, at=time.time(), severity=args.severity, plausible=args.plausible,
514
+ max=args.max, integration=ctx.tip, tasks=tasks, estimate=dict(dispatches=2 * len(tasks)),
404
515
  dropped=[dict(task=f['task'], severity=f['severity'], confidence=f['confidence'], origin=f['origin'],
405
516
  file=f['file'], line=f.get('line'), text=f['text'], key=f['key'], reason=f['reason'],
406
517
  detail=f['detail'])
407
518
  for f in dropped])
408
- sweep_dir.mkdir(exist_ok=True)
519
+ target = sweep_dir if number == 1 else sweep_dir / 'rounds' / str(number)
520
+ target.mkdir(parents=True, exist_ok=True)
409
521
  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
522
+ write_atomic(target / 'plan.md', text)
523
+ # The marker before the rows: a crash in between loses this round (its findings still reach forge
412
524
  # 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')
525
+ write_atomic(target / 'plan.json', json.dumps(record, indent=1) + '\n')
414
526
  if new_rows:
415
527
  with control_lock(plan):
416
528
  current = (plan / 'tasks.tsv').read_text(encoding='utf-8')
@@ -451,7 +563,7 @@ def cmd_ahead(args) -> int:
451
563
  key = mod.finding_key(f)
452
564
  if path is None or not owns(scopes, path) or key in seen:
453
565
  continue
454
- if ctx.slug and mod.fingerprint(ctx.slug, f) in ctx.dismissed:
566
+ if ctx.status(f) not in OPEN:
455
567
  continue
456
568
  seen.add(key)
457
569
  picked.append(dict(key=key, severity=f['severity'], confidence=f['confidence'], task=f['task'],
@@ -485,14 +597,47 @@ def outcome(text: str, findings: list) -> list:
485
597
  note=said.get(f['id'], ('', ''))[1]) for f in findings]
486
598
 
487
599
 
600
+ def record_fixed(plan: Path, task: str, findings: list) -> None:
601
+ """A `fixed` record for each finding the sweep review marked fixed, once that sweep task has merged
602
+ (actor sweep, the task, the merge commit). Best effort: whatever goes wrong here is ignored, settle
603
+ never fails because of it. Before `tasks/<task>/merged` exists, write nothing."""
604
+ try:
605
+ # `forge issues` counts a finding swept only after this marker exists; the record follows it.
606
+ if not (plan / 'tasks' / task / 'merged').exists():
607
+ return
608
+ fixed = [f for f in findings if f.get('status') == 'fixed']
609
+ if not fixed:
610
+ return
611
+ ctx = Context(plan)
612
+ if not ctx.ident:
613
+ return
614
+ from forge_findings import fingerprint, store
615
+ try:
616
+ entries = json.loads(read(plan / 'tasks' / task / 'sweep.json'))['findings']
617
+ except (ValueError, KeyError, TypeError):
618
+ return
619
+ by_id = {e['id']: e for e in entries if isinstance(e, dict) and 'id' in e}
620
+ fps = [fingerprint(ctx.slug, by_id[f['id']]['file'], by_id[f['id']]['text']) for f in fixed if f['id'] in by_id]
621
+ fields = dict(reason='sweep ' + task)
622
+ commit = read(plan / 'accepted.integration')
623
+ if store.COMMIT_RE.fullmatch(commit):
624
+ fields['commit'] = commit
625
+ if fps:
626
+ store.set_status(ctx.ident, fps, 'fixed', 'sweep', **fields)
627
+ except Exception:
628
+ pass
629
+
630
+
488
631
  def cmd_settle(args) -> int:
489
- root = Path(args.plan).resolve() / 'tasks' / args.task
632
+ plan = Path(args.plan).resolve()
633
+ root = plan / 'tasks' / args.task
490
634
  try:
491
635
  findings = json.loads(read(root / 'sweep.json'))['findings']
492
636
  except (ValueError, KeyError, TypeError):
493
637
  return 0
494
638
  result = dict(at=time.time(), findings=outcome(read(root / 'qa.last'), findings))
495
639
  write_atomic(root / 'sweep.outcome.json', json.dumps(result, indent=1) + '\n')
640
+ record_fixed(plan, args.task, result['findings'])
496
641
  return 0
497
642
 
498
643
 
@@ -502,12 +647,7 @@ def task_state(root: Path) -> str:
502
647
  return (read(root / 'status').split() or ['PENDING'])[0]
503
648
 
504
649
 
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
650
+ def report_round(plan: Path, record: dict, path: Path, number: 'int | None') -> None:
511
651
  tasks, fixed, total = record.get('tasks') or [], 0, 0
512
652
  lines = []
513
653
  for task in tasks:
@@ -522,10 +662,29 @@ def cmd_report(args) -> int:
522
662
  fixed += done
523
663
  total += len(task['findings'])
524
664
  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'), '']))
665
+ # what an earlier round attempted, or the record settled, is not this round's to leave for forge issues
666
+ left = sum(1 for d in record.get('dropped') or [] if d.get('reason') not in ('attempted', 'recorded')) + total - fixed
667
+ print('finding sweep%s (%s and worse): %d fix task(s), %d of %d finding(s) fixed; %d left for forge issues'
668
+ % (' round %d' % number if number else '', record.get('severity'), len(tasks), fixed, total, left))
669
+ print('\n'.join(lines + [' plan: %s' % path.with_name('plan.md'), '']))
670
+
671
+
672
+ def cmd_report(args) -> int:
673
+ plan = Path(args.plan).resolve()
674
+ paths = round_paths(plan)
675
+ records = {n: round_record(path) for n, path in sorted(paths.items())}
676
+ records = {n: record for n, record in records.items() if record is not None}
677
+ for number, record in records.items():
678
+ report_round(plan, record, paths[number], number if len(records) > 1 else None)
679
+ # Printed after the last round, or alone when round 1's check found nothing (no round was planned).
680
+ last_at = float(records[max(records)].get('at') or 0) if records else 0.0
681
+ try:
682
+ nothing = json.loads(read(plan / 'sweep' / 'nothing.json'))
683
+ if float(nothing['at']) > last_at:
684
+ print('sweep: nothing new to sweep (%d finding(s) already swept or attempted, %d left for forge issues)\n'
685
+ % (int(nothing.get('attempted') or 0), int(nothing.get('left') or 0)))
686
+ except (ValueError, KeyError, TypeError, OSError):
687
+ pass
529
688
  return 0
530
689
 
531
690
 
@@ -537,6 +696,7 @@ def main(argv=None) -> int:
537
696
  p.add_argument('--severity', choices=SEVERITIES, required=True)
538
697
  p.add_argument('--plausible', action='store_true')
539
698
  p.add_argument('--max', type=int, default=DEFAULT_MAX)
699
+ p.add_argument('--check', action='store_true')
540
700
  a = sub.add_parser('ahead')
541
701
  a.add_argument('plan')
542
702
  a.add_argument('task')
@@ -17,7 +17,6 @@ from __future__ import annotations
17
17
 
18
18
  import argparse
19
19
  import errno
20
- import fcntl
21
20
  import http.client
22
21
  import json
23
22
  import os
@@ -36,6 +35,9 @@ SKILL = Path(__file__).resolve().parent.parent
36
35
  # `-I` keeps the script's own directory off sys.path, so both are added by hand.
37
36
  sys.path.insert(0, str(SKILL / 'scripts'))
38
37
  sys.path.insert(0, str(SKILL / 'ui'))
38
+ import forge_flock as fcntl # noqa: E402
39
+ import forge_posix # noqa: E402
40
+ import forge_proc # noqa: E402
39
41
 
40
42
  HOST = '127.0.0.1'
41
43
  LISTENING = re.compile(r'^forge-ui on http://127\.0\.0\.1:(\d+)/', re.M)
@@ -71,15 +73,7 @@ def _env_int(name, default):
71
73
 
72
74
 
73
75
  def pid_alive(pid) -> bool:
74
- if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 1:
75
- return False
76
- try:
77
- os.kill(pid, 0)
78
- except (ProcessLookupError, OverflowError): # OverflowError: no process can have that pid
79
- return False
80
- except PermissionError:
81
- return True
82
- return True
76
+ return forge_proc.pid_alive(pid, min_pid=2)
83
77
 
84
78
 
85
79
  def wait_dead(pid, seconds) -> bool:
@@ -114,7 +108,7 @@ def open_regular(path, flags):
114
108
 
115
109
  O_NONBLOCK: a FIFO or device planted at one of our paths must fail, never block.
116
110
  """
117
- fd = os.open(path, flags | os.O_NONBLOCK | os.O_CLOEXEC, 0o644)
111
+ fd = os.open(path, flags | forge_posix.O_NONBLOCK | forge_posix.O_CLOEXEC, 0o644)
118
112
  if not stat.S_ISREG(os.fstat(fd).st_mode):
119
113
  os.close(fd)
120
114
  raise OSError(errno.EINVAL, 'not a regular file', str(path))
@@ -216,7 +210,7 @@ def _spawn(state, port, registry, idle, read_only=False, cli_env=None):
216
210
  command.append('--read-only')
217
211
  with os.fdopen(open_regular(log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 'w') as out:
218
212
  proc = subprocess.Popen(command, cwd=str(state), stdin=subprocess.DEVNULL, stdout=out, stderr=out,
219
- start_new_session=True, close_fds=True, env=env)
213
+ close_fds=True, env=env, **forge_proc.popen_group_kwargs(detached=True))
220
214
  deadline = time.monotonic() + START_WAIT_S
221
215
  while time.monotonic() < deadline:
222
216
  try:
@@ -263,7 +257,8 @@ def launch_browser(url):
263
257
  command = [sys.executable, '-I', str(Path(__file__).resolve()), '_browse', url]
264
258
  try:
265
259
  proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
266
- stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True)
260
+ stderr=subprocess.DEVNULL, close_fds=True,
261
+ **forge_proc.popen_group_kwargs(detached=True))
267
262
  proc.wait(BROWSER_WAIT_S)
268
263
  except subprocess.TimeoutExpired:
269
264
  pass # still starting its browser: leave it
@@ -53,6 +53,12 @@ import sys
53
53
  import tempfile
54
54
  import time
55
55
 
56
+ _SCRIPTS = str(Path(__file__).resolve().parent)
57
+ if _SCRIPTS not in sys.path:
58
+ sys.path.insert(0, _SCRIPTS)
59
+ import forge_posix # noqa: E402
60
+ import forge_proc # noqa: E402
61
+
56
62
  sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
57
63
  import forge_verify_reports as reports # noqa: E402 next to this script
58
64
 
@@ -204,7 +210,7 @@ def run_stoppable(argv: list[str], stopped=None, **kwargs) -> tuple[int, bytes,
204
210
  """Run a command in its own process group and wait for it, stopping the group (TERM, then
205
211
  KILL after KILL_AFTER seconds) and raising Stopped as soon as ``stopped()`` is true."""
206
212
  proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
207
- stderr=subprocess.PIPE, start_new_session=True, **kwargs)
213
+ stderr=subprocess.PIPE, **forge_proc.popen_group_kwargs(), **kwargs)
208
214
  while True:
209
215
  try:
210
216
  out, err = proc.communicate(timeout=TICK)
@@ -212,11 +218,8 @@ def run_stoppable(argv: list[str], stopped=None, **kwargs) -> tuple[int, bytes,
212
218
  except subprocess.TimeoutExpired:
213
219
  if stopped is None or not stopped():
214
220
  continue
215
- for sig, wait in ((signal.SIGTERM, KILL_AFTER), (signal.SIGKILL, KILL_AFTER)):
216
- try:
217
- os.killpg(proc.pid, sig)
218
- except (ProcessLookupError, PermissionError):
219
- pass
221
+ for force, wait in ((False, KILL_AFTER), (True, KILL_AFTER)):
222
+ forge_proc.kill_tree(proc.pid, force=force)
220
223
  try:
221
224
  proc.communicate(timeout=wait)
222
225
  break
@@ -264,7 +267,7 @@ def fingerprint(checkout: str, command: str | None, stopped=None) -> str:
264
267
  """The checkout's fingerprint; Stopped when ``stopped()`` turns true meanwhile."""
265
268
  if not command:
266
269
  return default_fingerprint(checkout, stopped)
267
- rc, out, err = run_stoppable(['/bin/bash', '-c', command], stopped, cwd=checkout)
270
+ rc, out, err = run_stoppable(forge_proc.bash_cmd('-c', command), stopped, cwd=checkout)
268
271
  if rc != 0:
269
272
  raise RuntimeError(f'fingerprint command exited {rc}: {_text(err)}')
270
273
  return _text(out)
@@ -430,12 +433,16 @@ class Verification:
430
433
  try:
431
434
  if os.path.islink(log):
432
435
  os.unlink(log) # the log name is ours: never written through a link left in --out
433
- fd = os.open(log, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o666)
436
+ fd = forge_posix.open_nofollow(
437
+ log,
438
+ os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW,
439
+ 0o666,
440
+ )
434
441
  with os.fdopen(fd, 'ab') as fh:
435
442
  offset = fh.tell()
436
- proc = subprocess.Popen(['/bin/bash', '-c', lane['command']], cwd=self.checkout,
443
+ proc = subprocess.Popen(forge_proc.bash_cmd('-c', lane['command']), cwd=self.checkout,
437
444
  stdin=subprocess.DEVNULL, stdout=fh,
438
- stderr=subprocess.STDOUT, start_new_session=True)
445
+ stderr=subprocess.STDOUT, **forge_proc.popen_group_kwargs())
439
446
  except (OSError, ValueError) as exc: # ValueError: an embedded NUL in the command
440
447
  with open(log, 'ab') as fh:
441
448
  fh.write(f'forge-verify: cannot start lane: {exc}\n'.encode())
@@ -462,7 +469,7 @@ class Verification:
462
469
  lane = self.by_name[name]
463
470
  rc = live.proc.poll()
464
471
  if rc is None: # still there after the KILL: a process stuck in the kernel
465
- rc = -signal.SIGKILL
472
+ rc = -forge_proc.SIGKILL
466
473
  self._pump({name: live}) # what is left to read, capped; an interrupt still gets through
467
474
  live.close()
468
475
  self._end(lane, lane['runs'][-1], rc if rc >= 0 else 128 - rc, interrupted)
@@ -644,7 +651,7 @@ class Verification:
644
651
  if live.exists() and not kept.exists():
645
652
  shutil.copyfile(live, kept)
646
653
  if truncate:
647
- os.close(os.open(live, os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW))
654
+ os.close(forge_posix.open_nofollow(live, os.O_WRONLY | os.O_TRUNC | forge_posix.O_NOFOLLOW))
648
655
  except OSError as exc:
649
656
  print(f'forge-verify: cannot keep {kept.name}: {exc}', file=sys.stderr)
650
657
 
@@ -670,7 +677,7 @@ class Verification:
670
677
  time.sleep(TICK)
671
678
  for pgid in groups:
672
679
  if self._group_alive(pgid):
673
- self._signal(pgid, signal.SIGKILL)
680
+ self._signal(pgid, forge_proc.SIGKILL)
674
681
  deadline = time.monotonic() + 3 * KILL_AFTER # SIGKILL cannot be caught; do not hang on D state
675
682
  while time.monotonic() < deadline and any(self._group_alive(g) for g in groups):
676
683
  time.sleep(TICK)
@@ -685,26 +692,25 @@ class Verification:
685
692
  if not self._group_alive(pgid) or now >= give_up:
686
693
  continue
687
694
  if now >= deadline:
688
- self._signal(pgid, signal.SIGKILL)
695
+ self._signal(pgid, forge_proc.SIGKILL)
689
696
  keep.append((pgid, deadline, group, give_up))
690
697
  self.lingering = keep
691
698
 
692
699
  @staticmethod
693
700
  def _signal(pgid: int, sig: int) -> None:
694
- try:
695
- os.killpg(pgid, sig)
696
- except (ProcessLookupError, PermissionError):
697
- pass
701
+ forge_proc.kill_tree(pgid, force=(sig == forge_proc.SIGKILL))
698
702
 
699
703
  def _group_alive(self, pgid: int) -> bool:
700
704
  for live in self.running.values():
701
705
  if live.proc.pid == pgid:
702
706
  live.proc.poll() # reap a leader that exited, or it stays a zombie of the group
703
- try:
704
- os.killpg(pgid, 0)
705
- except (ProcessLookupError, PermissionError):
706
- return False
707
- return True
707
+ if not forge_proc.IS_WINDOWS:
708
+ try:
709
+ os.killpg(pgid, 0)
710
+ except (ProcessLookupError, PermissionError):
711
+ return False
712
+ return True
713
+ return forge_proc.group_alive(pgid)
708
714
 
709
715
  # the whole verification ------------------------------------------------------------
710
716
 
@@ -34,7 +34,6 @@ from __future__ import annotations
34
34
 
35
35
  import concurrent.futures
36
36
  import contextlib
37
- import fcntl
38
37
  import json
39
38
  import os
40
39
  from pathlib import Path
@@ -48,6 +47,7 @@ SCRIPTS = Path(__file__).resolve().parent.parent
48
47
  if str(SCRIPTS) not in sys.path:
49
48
  sys.path.insert(0, str(SCRIPTS))
50
49
 
50
+ import forge_flock as fcntl # noqa: E402
51
51
  import forge_groups # noqa: E402
52
52
  import forge_side # noqa: E402
53
53
 
@@ -79,7 +79,6 @@ import argparse
79
79
  import contextlib
80
80
  import difflib
81
81
  import io
82
- import fcntl
83
82
  import hashlib
84
83
  import json
85
84
  import os
@@ -87,10 +86,16 @@ from pathlib import Path
87
86
  import re
88
87
  import shlex
89
88
  import subprocess
89
+ import sys
90
90
  import tempfile
91
91
  import calendar
92
92
  import time
93
93
 
94
+ _SCRIPTS = str(Path(__file__).resolve().parents[1])
95
+ if _SCRIPTS not in sys.path:
96
+ sys.path.insert(0, _SCRIPTS)
97
+ import forge_flock as fcntl # noqa: E402
98
+ import forge_proc # noqa: E402
94
99
  import forge_brief
95
100
  import forge_brief.answers as answers
96
101
  import forge_groups
@@ -858,7 +863,7 @@ def _recompute_waves(plan) -> str | None:
858
863
  return None # an unplanned plan gains nothing, and waves.tsv is what marks one as planned
859
864
  script = Path(forge_brief.SCRIPTS) / 'forge-parallel.sh'
860
865
  try:
861
- done = subprocess.run(['/bin/bash', str(script), '_waves', str(plan)], stdin=subprocess.DEVNULL,
866
+ done = subprocess.run(forge_proc.bash_cmd(script, '_waves', str(plan)), stdin=subprocess.DEVNULL,
862
867
  capture_output=True, text=True, timeout=120)
863
868
  except (OSError, subprocess.SubprocessError) as error:
864
869
  return 'waves.tsv was not refreshed: %s' % error