@giamme/forge 0.18.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.
Files changed (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -356,6 +356,8 @@ git -C "$REPO" diff --binary "$START" "$END" -- . ':(exclude).forge' > "$RUN/cha
356
356
  if [ ! -s "$RUN/changes.diff" ]; then
357
357
  # An exit-0 harness with an empty final message and no changes never really ran.
358
358
  grep -qx 'class=empty' "$RUN/dwarf.infra" 2>/dev/null && die "the dwarf returned nothing (empty output, no changes) — an infrastructure failure, not a refusal; fix the cause and run again (see $RUN/dwarf.infra)" 8
359
+ # Nor did one its CLI cancelled before it changed anything.
360
+ grep -qx 'class=cancelled' "$RUN/dwarf.infra" 2>/dev/null && die "the dwarf was cancelled by its CLI before it changed anything — an infrastructure failure, not a refusal: $(sed -n 's/^detail=//p' "$RUN/dwarf.infra"); fix the cause and run again (see $RUN/dwarf.infra)" 8
359
361
  note "the dwarf produced no changes at all — see $RUN/dwarf.last for what it said"
360
362
  echo NOCHANGES > "$RUN/verdict"
361
363
  exit 5
@@ -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,243 @@
1
+ #!/usr/bin/env python3
2
+ """forge worktrees rm PATH... [--branches] [--dry-run] [--json] [--actor A]
3
+
4
+ Remove worktrees by the rules of forge-ui's Worktrees screen (#147): the statuses come from
5
+ ui/forge_ui/worktrees.py `compute`, the one rule set, never a copy of it.
6
+
7
+ failed / finished `git -C <repo> worktree remove <path>`, without the force flag. With --branches
8
+ a `finished` worktree whose branch is merged also gets the safe branch delete
9
+ (`git branch -d <branch>`, which refuses an unmerged branch).
10
+ unknown + leftover the folder is deleted (shutil.rmtree), after checking again that git does
11
+ not list it as a worktree.
12
+ anything else skipped with a reason: in_use, dirty, locked, needed, missing (run
13
+ `git worktree prune`), foreign, removed, and a path that is no row.
14
+
15
+ Each removal is recorded the way `forge runs rm` records one: a `worktree_removed` dataset event
16
+ (with the actor) and a `gone` entry in forge's location list.
17
+
18
+ --dry-run computes the same actions and changes nothing (`would-remove`).
19
+ --actor is who asked: `cli` (the default) or `ui`.
20
+
21
+ --json prints exactly one object on stdout, on failure too:
22
+ {"ok": bool, "dry_run": bool,
23
+ "rows": [{"path", "action": "remove"|"remove+branch"|"delete-folder"|"none",
24
+ "status": "removed"|"skipped"|"failed"|"would-remove", "reason": str|null}]}
25
+
26
+ Exit codes: 0 no row failed (a skip is not a failure), 4 a row failed, 2 usage.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import importlib.util
32
+ import json
33
+ import os
34
+ import shutil
35
+ import subprocess
36
+ import sys
37
+ from pathlib import Path
38
+ from types import SimpleNamespace
39
+
40
+ SKILL = Path(__file__).resolve().parent.parent
41
+ # `-I` keeps the script's own directory off sys.path, so both are added by hand (as forge-ui.py does).
42
+ sys.path.insert(0, str(SKILL / 'scripts'))
43
+ sys.path.insert(0, str(SKILL / 'ui'))
44
+
45
+ import forge_worktrees # noqa: E402
46
+ from forge_dataset import harvest # noqa: E402
47
+ from forge_ui import reader, worktrees # noqa: E402
48
+
49
+ OK, USAGE, FAILED = 0, 2, 4
50
+ ACTORS = ('cli', 'ui')
51
+ HISTORY_TIMEOUT_S = 120
52
+
53
+ SKIPS = {
54
+ 'in_use': 'its run is active',
55
+ 'dirty': 'it has uncommitted changes',
56
+ 'locked': 'it is locked by git',
57
+ 'needed': 'the integration worktree of a run not integrated yet',
58
+ 'missing': 'its folder is gone: run git worktree prune',
59
+ 'foreign': "not forge's worktree",
60
+ 'removed': 'already removed',
61
+ 'unknown': 'a folder git does not list, and not a leftover: look inside before deleting it',
62
+ }
63
+
64
+
65
+ def load_runs_rm():
66
+ """scripts/forge-runs-rm.py as a module: the recording of a removal is its code, reused."""
67
+ path = SKILL / 'scripts' / 'forge-runs-rm.py'
68
+ spec = importlib.util.spec_from_file_location('forge_runs_rm_for_worktrees', path)
69
+ module = importlib.util.module_from_spec(spec)
70
+ sys.modules[spec.name] = module
71
+ spec.loader.exec_module(module)
72
+ return module
73
+
74
+
75
+ def history():
76
+ """`forge dataset worktrees --json` through this checkout's launcher, or None."""
77
+ try:
78
+ done = subprocess.run([str(SKILL / 'forge'), 'dataset', 'worktrees', '--json'], capture_output=True, text=True,
79
+ stdin=subprocess.DEVNULL, timeout=HISTORY_TIMEOUT_S)
80
+ if done.returncode != 0:
81
+ return None
82
+ found = json.loads(done.stdout)
83
+ except (OSError, ValueError, subprocess.SubprocessError):
84
+ return None
85
+ return found if isinstance(found, dict) else None
86
+
87
+
88
+ def real(path):
89
+ try:
90
+ return os.path.realpath(path)
91
+ except (OSError, ValueError):
92
+ return path
93
+
94
+
95
+ def first_line(text):
96
+ lines = (text or '').strip().splitlines()
97
+ return lines[0] if lines else ''
98
+
99
+
100
+ def plan(path, row, branches):
101
+ """(action, skip reason) for one path: what would be done to it, or why nothing is."""
102
+ if row is None:
103
+ return 'none', 'not a worktree forge knows'
104
+ status = row['status']
105
+ if status in ('failed', 'finished'):
106
+ if not (row.get('git_dir') or row.get('repo')):
107
+ return 'none', 'its repository is not known'
108
+ if branches and status == 'finished' and row.get('merged') and row.get('branch'):
109
+ return 'remove+branch', None
110
+ return 'remove', None
111
+ if status == 'unknown' and row.get('leftover'):
112
+ return 'delete-folder', None
113
+ return 'none', SKIPS.get(status, 'status %s' % status)
114
+
115
+
116
+ def is_registered(repo, path):
117
+ """True when git lists `path` as a worktree of `repo`; True too when git cannot say (never delete then)."""
118
+ code, out = worktrees._git(repo, 'worktree', 'list', '--porcelain', '-z')
119
+ z = True
120
+ if code == 129:
121
+ code, out = worktrees._git(repo, 'worktree', 'list', '--porcelain')
122
+ z = False
123
+ if code != 0:
124
+ return True
125
+ return any(real(wt['path']) == real(path) for wt in forge_worktrees.parse_porcelain(out, z=z))
126
+
127
+
128
+ def record(rm, row, actor):
129
+ """The dataset event and the location-list entry of a removal, as `forge runs rm` writes them."""
130
+ by = 'forge worktrees rm (%s)' % actor
131
+ run_path = row.get('run_path')
132
+ try:
133
+ uid = harvest.run_uid(Path(run_path), create=False) if run_path else None
134
+ except Exception: # noqa: BLE001 -- an identity we cannot read only costs the event its run column
135
+ uid = None
136
+ run = SimpleNamespace(uid=uid, run_id=row.get('run_id'), mode='parallel', path=run_path or row['path'],
137
+ repo=row.get('repo'))
138
+ kind = row.get('kind') or 'task'
139
+ event = rm.event(run, 'worktree_removed', path=row['path'], branch=row.get('branch') or '-', kind=kind,
140
+ repo_path=row.get('repo'), by=by, actor=actor)
141
+ if kind == 'task' and row.get('branch'):
142
+ event['task'] = row['branch'].split('/', 2)[-1]
143
+ elif row.get('task'):
144
+ event['task'] = row['task']
145
+ rm.record([event], repo=row.get('repo'), where='event:worktree_removed')
146
+ rm.forge_locations.gone('worktree', row['path'], by=by)
147
+
148
+
149
+ def act(rm, row, action, actor):
150
+ """Do one planned action. Returns None on success, else the failure text."""
151
+ path = row['path']
152
+ repo = row.get('git_dir') or row.get('repo')
153
+ if action == 'delete-folder':
154
+ if worktrees._layout(path) is None:
155
+ return 'not inside a .forge-worktrees folder'
156
+ if not worktrees._leftover(path):
157
+ return 'it is a worktree again: not deleted'
158
+ if row.get('repo') and is_registered(row['repo'], path):
159
+ return 'git lists it as a worktree: not deleted'
160
+ try:
161
+ shutil.rmtree(path) # never follows a symlink: it refuses one
162
+ except OSError as error:
163
+ return '%s: %s' % (path, error.strerror or error)
164
+ record(rm, row, actor)
165
+ return None
166
+ code, _, err = rm.git(repo, 'worktree', 'remove', path)
167
+ if code != 0:
168
+ return first_line(err) or 'git worktree remove exit %d' % code
169
+ record(rm, row, actor)
170
+ if action == 'remove+branch':
171
+ code, _, err = rm.git(row.get('repo') or repo, 'branch', '-d', row['branch'])
172
+ if code != 0:
173
+ return 'worktree removed, but the branch stays: ' + (first_line(err) or 'git branch -d exit %d' % code)
174
+ return None
175
+
176
+
177
+ def run(args):
178
+ paths = []
179
+ for given in args.paths:
180
+ if real(given) not in {real(p) for p in paths}:
181
+ paths.append(given)
182
+ rows, error = {}, None
183
+ try:
184
+ computed = worktrees.compute(reader.Catalog(), history())
185
+ rows = {real(r['path']): r for r in computed['rows']}
186
+ if not computed['rows'] and any('could not be loaded' in n for n in computed.get('notes') or []):
187
+ error = first_line(computed['notes'][0])
188
+ except Exception as exc: # noqa: BLE001 -- reported per row, still one JSON object
189
+ error = 'could not compute the worktree states: %s' % exc
190
+ out = []
191
+ rm = None
192
+ for given in paths:
193
+ if error:
194
+ out.append(dict(path=given, action='none', status='failed', reason=error))
195
+ continue
196
+ row = rows.get(real(given))
197
+ action, why = plan(given, row, args.branches)
198
+ if action == 'none':
199
+ out.append(dict(path=given, action='none', status='skipped', reason=why))
200
+ elif args.dry_run:
201
+ out.append(dict(path=given, action=action, status='would-remove', reason=None))
202
+ else:
203
+ try:
204
+ rm = rm or load_runs_rm()
205
+ failure = act(rm, row, action, args.actor)
206
+ except Exception as exc: # noqa: BLE001 -- one row's failure never stops the others
207
+ failure = str(exc) or exc.__class__.__name__
208
+ out.append(dict(path=given, action=action, status='failed' if failure else 'removed', reason=failure))
209
+ return dict(ok=not any(r['status'] == 'failed' for r in out), dry_run=bool(args.dry_run), rows=out)
210
+
211
+
212
+ def show(result):
213
+ for r in result['rows']:
214
+ extra = '' if r['action'] == 'none' else ' (%s)' % r['action']
215
+ print('%-12s %s%s%s' % (r['status'], r['path'], extra, ': ' + r['reason'] if r['reason'] else ''))
216
+
217
+
218
+ def parser():
219
+ top = argparse.ArgumentParser(prog='forge worktrees', description='Worktrees forge created, by forge-ui\'s rules.')
220
+ sub = top.add_subparsers(dest='command', required=True, metavar='{rm}')
221
+ rm = sub.add_parser('rm', help='remove worktrees (a dirty, locked or live one is skipped, nothing is forced)',
222
+ description='Remove worktrees by the rules of forge-ui\'s Worktrees screen. Exit 0 when no row '
223
+ 'failed, 4 when one did, 2 for usage.')
224
+ rm.add_argument('paths', nargs='+', metavar='PATH')
225
+ rm.add_argument('--branches', action='store_true', help='also delete the merged branch of a finished worktree (git branch -d)')
226
+ rm.add_argument('--dry-run', action='store_true', help='say what would be removed, change nothing')
227
+ rm.add_argument('--json', action='store_true', help='print one JSON object: ok, dry_run, rows')
228
+ rm.add_argument('--actor', default='cli', choices=ACTORS, help='who asked (recorded with the removal; default cli)')
229
+ return top
230
+
231
+
232
+ def main(argv=None):
233
+ args = parser().parse_args(argv)
234
+ result = run(args)
235
+ if args.json:
236
+ print(json.dumps(result))
237
+ else:
238
+ show(result)
239
+ return OK if result['ok'] else FAILED
240
+
241
+
242
+ if __name__ == '__main__':
243
+ sys.exit(main())