@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
@@ -27,8 +27,9 @@ One the sweep did not fix is drafted as before.
27
27
 
28
28
  --json lists every finding in `findings` (fp, severity, origin, plan, task, text, `filed`, `review`, `swept`, ...). --offline never
29
29
  runs `gh` (no filed state, publication of commits judged from local refs only). --only FP[,FP] keeps those
30
- fingerprints. --all-runs reads <run> as a repository (or a plan dir naming one) and collects every run in its
31
- registry, the newest plan winning for a finding present in several. A caller filing an explicit selection
30
+ fingerprints. --all-runs reads <run> as a repository (or a plan dir naming one) and collects every run of that
31
+ repository, whichever checkout started it (the main working tree, a linked worktree, one that is removed), the newest
32
+ plan winning for a finding present in several. --to-file keeps only the findings whose record status is `to-file`. A caller filing an explicit selection
32
33
  passes `--max-issues <len(selection)>`; the default is 10.
33
34
 
34
35
  --dismiss FP[,FP] / --undismiss FP[,FP] (repeatable, with an optional --reason TEXT of at most 500 characters) mark
@@ -37,7 +38,14 @@ matches no current finding. A dismissed finding stays in `findings` with `dismis
37
38
  and is left out of the drafts unless --include-dismissed is given. The marks live outside the repository, in
38
39
  `${XDG_STATE_HOME:-~/.local/state}/forge/findings/<repo_key>.json` (an empty or relative XDG_STATE_HOME counts as
39
40
  unset); the store directory and file must not be symlinks, and the file must be a regular one. The repository they
40
- belong to is the one <run> resolves to; --repo does not change it.
41
+ belong to is the one <run> resolves to (its identity, shared by every checkout of it); --repo does not change it.
42
+ The marks are written to the finding record `<identity key>.record.json` (forge_findings.store): --dismiss sets
43
+ status `dismissed`, --undismiss `open`. The old `<checkout key>.json` stores are read, never written. Every finding in
44
+ `findings` carries `record` (its record entry, or null) and `status` (open, to-file, filed, fixed, dismissed,
45
+ duplicate, swept); a finding that is filed, fixed or a duplicate is never drafted, and --apply records `filed`
46
+ with the issue url. A `to-file` record's draft title replaces the generated one and its body follows under Notes.
47
+ A repository with no GitHub origin lists with fingerprints computed from an empty slug (and a warning); --apply
48
+ still needs a slug (--repo).
41
49
 
42
50
  The repository is the run's own, whatever form <run> takes: a file or task dir resolves to its plan dir and that plan's
43
51
  `repo` file, a solo run dir to its own `repo` file, and --all-runs to the repository it names. Listing, filing and
@@ -68,7 +76,6 @@ from __future__ import annotations
68
76
  import argparse
69
77
  import contextlib
70
78
  import errno
71
- import fcntl
72
79
  import hashlib
73
80
  import importlib.util
74
81
  import json
@@ -83,7 +90,11 @@ import time
83
90
  from pathlib import Path
84
91
 
85
92
  sys.path.insert(0, str(Path(__file__).resolve().parent))
86
- from forge_registry import repo_key, runs_registry # noqa: E402
93
+ import forge_posix # noqa: E402
94
+ from forge_registry import repo_key # noqa: E402
95
+ import forge_identity # noqa: E402
96
+ from forge_findings import status as record_status # noqa: E402
97
+ from forge_findings import store as record_store # noqa: E402
87
98
 
88
99
  FINDING_RE = re.compile(r"^\s*[-*]\s*\[(P[0-3])\]\s*\[(CONFIRMED|PLAUSIBLE)\]\s*(\S.*?)\s+[—–]+\s+(.+?)\s*$", re.M)
89
100
  # gh-proman writes `gh-proman:finding`, this command `forge:finding`; the fingerprints match.
@@ -121,6 +132,7 @@ TEXT = {
121
132
  "code": "Code",
122
133
  "unpublished": "(commit not pushed to GitHub yet)",
123
134
  "duplicate_comment": "A forge review finding that looks like this issue, in other words:",
135
+ "notes": "Notes",
124
136
  },
125
137
  "it": {
126
138
  "plausible": "Da verificare: ",
@@ -149,6 +161,7 @@ TEXT = {
149
161
  "code": "Codice",
150
162
  "unpublished": "(commit non ancora pubblicato su GitHub)",
151
163
  "duplicate_comment": "Una segnalazione della review di forge che sembra questa issue, con altre parole:",
164
+ "notes": "Note",
152
165
  },
153
166
  }
154
167
 
@@ -585,19 +598,15 @@ def collect_plan(plan_dir: Path, include_plausible):
585
598
 
586
599
 
587
600
  def collect_all(path: Path, include_plausible):
601
+ """Every run of the repository <path> names: the registered run dirs of all its checkouts (the main working
602
+ tree, linked worktrees, and checkouts that are gone), newest first."""
588
603
  plan_file = path / "repo"
589
604
  repo = Path(read(plan_file)) if plan_file.is_file() else path
590
- registry = runs_registry(repo)
591
- lines = read(registry).splitlines() if registry.is_file() else []
605
+ ident = forge_identity.identity(path)
592
606
  plans, notes = [], []
593
- for line in lines:
594
- line = line.strip()
595
- if not line or line.startswith("#"):
596
- continue
607
+ for line in forge_identity.run_dirs(ident) if ident else []:
597
608
  d = Path(line)
598
- if not d.is_dir():
599
- notes.append(f"{line}: run directory is missing, skipped")
600
- elif not (d / "tasks").is_dir():
609
+ if not (d / "tasks").is_dir():
601
610
  notes.append(f"{line}: no tasks/ directory, skipped")
602
611
  elif d not in plans:
603
612
  plans.append(d)
@@ -685,13 +694,50 @@ def collect(path: Path, include_plausible, all_runs=False):
685
694
  found, [note] if note else []
686
695
 
687
696
 
688
- def run_repository(meta):
689
- """(repo_path, warnings): the run's recorded repository, else the current directory with a warning saying so.
697
+ def enclosing_run_dir(path):
698
+ """The run dir (the dir holding a `repo` file) that <path> is, or sits at most three levels inside; None when
699
+ it is not inside one. A checkout (a dir with `.git`) ends the walk."""
700
+ current = Path(path).resolve()
701
+ if current.is_file():
702
+ current = current.parent
703
+ for _ in range(4):
704
+ if (current / "repo").is_file():
705
+ return current
706
+ if (current / ".git").exists() or current.parent == current:
707
+ return None
708
+ current = current.parent
709
+ return None
710
+
690
711
 
691
- Listing, filing and (un)dismissing all go through here, so they agree on the dismissal store.
712
+ def run_identity(args, meta):
713
+ """The repository identity of the run, resolved once: from the run dir <run> is or sits in (a run whose
714
+ checkout is gone still names its repository; a task or review dir has no `repo` file of its own, so it is the
715
+ plan dir that is asked), else from the recorded checkout, else from the current directory."""
716
+ ident = None
717
+ if meta["repo_path"]:
718
+ run_dir = enclosing_run_dir(args.run)
719
+ ident = forge_identity.identity(run_dir) if run_dir else None
720
+ if ident is None:
721
+ ident = forge_identity.identity(meta["repo_path"])
722
+ if ident is None:
723
+ ident = forge_identity.identity(os.getcwd())
724
+ if ident is None:
725
+ raise Fail(f"{args.run}: cannot tell which repository this run belongs to")
726
+ return ident
727
+
728
+
729
+ def run_repository(meta, ident=None):
730
+ """(repo_path, warnings): the run's recorded checkout, else the current directory with a warning saying so.
731
+
732
+ A recorded checkout that no longer exists (a removed worktree) gives way to the repository's root, with a
733
+ warning. Listing, filing and (un)dismissing all go through here, so they agree on the repository.
692
734
  """
693
735
  if meta["repo_path"]:
694
- return meta["repo_path"], []
736
+ recorded = meta["repo_path"]
737
+ if ident is not None and ident.get("root") and not os.path.isdir(recorded):
738
+ return ident["root"], [f"the recorded checkout {recorded} no longer exists; using the repository "
739
+ f"root {ident['root']}"]
740
+ return recorded, []
695
741
  cwd = os.getcwd()
696
742
  return cwd, [f"run {meta['plan']} records no repository; using the current directory {cwd}"]
697
743
 
@@ -946,7 +992,10 @@ def _read_store(name, noun, shape, valid):
946
992
  if not stat.S_ISREG(os.lstat(path).st_mode):
947
993
  raise Fail(not_regular)
948
994
  # NOFOLLOW again for a swap after the lstat; NONBLOCK so a FIFO cannot hold the open
949
- with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as fh:
995
+ with os.fdopen(
996
+ forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK),
997
+ "rb",
998
+ ) as fh:
950
999
  if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
951
1000
  raise Fail(not_regular)
952
1001
  raw = fh.read(STORE_MAX + 1)
@@ -984,82 +1033,115 @@ def _write_store(name, noun, data):
984
1033
  raise Fail(f"{path}: cannot write the {noun}: {exc.strerror}")
985
1034
 
986
1035
  def load_dismissed(key):
987
- """The repository's dismissals, `{fp: {"at": epoch, "reason": str}}`; empty when it has none yet."""
988
- data = _read_store(f"{key}.json", "dismissal store", "{fingerprint: {at, reason}}",
989
- lambda v: isinstance(v, dict) and isinstance(v.get("reason"), str)
990
- and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool))
991
- return {fp: {"at": v["at"], "reason": v["reason"]} for fp, v in data.items()}
1036
+ """The repository's dismissals under `key`, `{fp: {"at": epoch, "reason": str}}`; empty when it has none yet.
992
1037
 
1038
+ Read through the record store: the record `<key>.record.json` and the old `<key>.json` dismissals, the
1039
+ record winning (a finding reopened there is not dismissed). Read only: nothing writes `<key>.json` any more.
1040
+ """
1041
+ return {fp: {"at": int(v["at"]), "reason": v.get("reason", "")}
1042
+ for fp, v in load_record({"key": key}).items()
1043
+ if v.get("status") == "dismissed" and isinstance(v.get("at"), (int, float))}
993
1044
 
994
- def save_dismissed(key, data):
995
- _write_store(f"{key}.json", "dismissal store", data)
1045
+
1046
+ def _valid_receipt(v):
1047
+ return (isinstance(v, dict) and isinstance(v.get("issue"), str)
1048
+ and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool))
1049
+
1050
+
1051
+ def _comment_receipts(key):
1052
+ data = _read_store(f"{key}.comments.json", "comment-receipt store", "{fingerprint: {issue, at}}", _valid_receipt)
1053
+ return {fp: {"issue": v["issue"], "at": v["at"]} for fp, v in data.items()}
996
1054
 
997
1055
 
998
- def load_comments(key):
1056
+ def load_comments(ident):
999
1057
  """The repository's comment receipts, `{fp: {"issue": url, "at": epoch}}`; empty when it has none yet.
1000
1058
 
1001
1059
  A comment's fingerprint marker is invisible to the issue-body index that guards filing, so this record is
1002
- what keeps one duplicate from being commented on every run. It sits next to the dismissal store.
1060
+ what keeps one duplicate from being commented on every run. They live in `<identity key>.comments.json`; the
1061
+ old `<checkout key>.comments.json` of every checkout is read too (the newest receipt wins) and never written.
1003
1062
  """
1004
- data = _read_store(f"{key}.comments.json", "comment-receipt store", "{fingerprint: {issue, at}}",
1005
- lambda v: isinstance(v, dict) and isinstance(v.get("issue"), str)
1006
- and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool))
1007
- return {fp: {"issue": v["issue"], "at": v["at"]} for fp, v in data.items()}
1063
+ key = ident["key"]
1064
+ merged = {}
1065
+ for checkout in forge_identity.checkouts(ident):
1066
+ try:
1067
+ old_key = repo_key(checkout)
1068
+ except (OSError, ValueError, RuntimeError, UnicodeError):
1069
+ continue
1070
+ if old_key == key:
1071
+ continue
1072
+ try:
1073
+ old = _comment_receipts(old_key)
1074
+ except Fail:
1075
+ continue # an unreadable old store is skipped, as the record store skips old dismissals
1076
+ for fp, receipt in old.items():
1077
+ if fp not in merged or receipt["at"] > merged[fp]["at"]:
1078
+ merged[fp] = receipt
1079
+ merged.update(_comment_receipts(key))
1080
+ return merged
1008
1081
 
1009
1082
 
1010
- def save_comments(key, data):
1011
- _write_store(f"{key}.comments.json", "comment-receipt store", data)
1083
+ def save_comments(ident, data):
1084
+ _write_store(f"{ident['key']}.comments.json", "comment-receipt store", data)
1012
1085
 
1013
1086
 
1014
1087
  @contextlib.contextmanager
1015
- def repo_lock(key, label):
1016
- """Hold the repository's `<key>.lock` (flock, next to the store); busy for LOCK_WAIT seconds raises Busy.
1088
+ def repo_lock(ident, label):
1089
+ """Hold the repository's `<key>.lock` (flock, next to the stores) through the record store; busy for
1090
+ LOCK_WAIT seconds raises Busy. `ident` is the repository identity, or its key.
1017
1091
 
1018
- The lock is its own file, opened in place and never replaced, because the store is: a lock on the store
1092
+ The lock is its own file, opened in place and never replaced, because the stores are: a lock on a store
1019
1093
  file would stay with the old inode after an atomic save.
1020
1094
  """
1021
- path = store_dir(create=True) / f"{key}.lock"
1022
- try:
1023
- fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
1024
- except OSError as exc:
1025
- raise Fail(f"{path}: cannot open the repository lock ({exc.strerror}); it must not be a symlink")
1095
+ if isinstance(ident, str):
1096
+ ident = {"key": ident}
1097
+ waited = record_store.LOCK_WAIT
1098
+ record_store.LOCK_WAIT = LOCK_WAIT
1026
1099
  try:
1027
- if not stat.S_ISREG(os.fstat(fd).st_mode):
1028
- raise Fail(f"{path}: the repository lock must be a regular file")
1029
- deadline = time.monotonic() + LOCK_WAIT
1030
- while True:
1031
- try:
1032
- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1033
- break
1034
- except OSError as exc:
1035
- if exc.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES):
1036
- raise Fail(f"{path}: cannot lock the repository: {exc.strerror}")
1037
- if time.monotonic() >= deadline:
1038
- raise Busy(f"busy: another filing or dismissal for {label} is in progress")
1039
- time.sleep(LOCK_POLL)
1040
- yield
1100
+ with record_store.lock(ident):
1101
+ yield
1102
+ except record_store.Busy:
1103
+ raise Busy(f"busy: another filing or dismissal for {label} is in progress")
1104
+ except (record_store.Corrupt, record_store.Invalid) as exc:
1105
+ raise Fail(str(exc))
1041
1106
  finally:
1042
- os.close(fd) # closing the descriptor releases the flock
1107
+ record_store.LOCK_WAIT = waited
1108
+
1109
+
1110
+ def load_record(ident):
1111
+ """{fp: entry}: the finding record of the repository, old dismissals merged in. Fail when it is unusable."""
1112
+ try:
1113
+ return record_store.load(ident)
1114
+ except (record_store.Corrupt, record_store.Invalid) as exc:
1115
+ raise Fail(str(exc))
1116
+
1117
+
1118
+ def set_record_status(ident, fps, status, **fields):
1119
+ try:
1120
+ return record_store.set_status(ident, fps, status, "issues", locked=True, **fields)
1121
+ except record_store.Busy as exc:
1122
+ raise Busy(str(exc))
1123
+ except (record_store.Corrupt, record_store.Invalid) as exc:
1124
+ raise Fail(str(exc))
1125
+
1126
+
1127
+ NO_REASON = "dismissed with forge issues" # a record's `dismissed` needs a reason; --dismiss without one gets this
1043
1128
 
1044
1129
 
1045
1130
  def dismiss(args):
1046
- """--dismiss / --undismiss: update the repository's store under its lock. No network: <run> is only read to
1047
- find the repository it resolves to."""
1131
+ """--dismiss / --undismiss: write the repository's finding record under its lock. No network: <run> is only
1132
+ read to find the repository it resolves to."""
1048
1133
  meta, _found, _notes = collect(Path(args.run), False, args.all_runs)
1049
- repo_path, warnings = run_repository(meta)
1050
- key = repo_key(repo_path)
1051
- with repo_lock(key, args.repo or github_slug(repo_path) or repo_path):
1052
- data = load_dismissed(key)
1053
- before = json.dumps(data, sort_keys=True)
1054
- now = int(time.time())
1055
- for fp in args.dismiss:
1056
- # dismissing again without a --reason keeps the earlier mark, with its reason and date
1057
- if fp not in data or args.reason is not None:
1058
- data[fp] = {"at": now, "reason": args.reason or ""}
1059
- for fp in args.undismiss:
1060
- data.pop(fp, None)
1061
- if json.dumps(data, sort_keys=True) != before:
1062
- save_dismissed(key, data)
1134
+ ident = run_identity(args, meta)
1135
+ repo_path, warnings = run_repository(meta, ident)
1136
+ with repo_lock(ident, args.repo or github_slug(repo_path) or forge_identity.github_slug(ident) or repo_path):
1137
+ data = load_record(ident)
1138
+ # dismissing again without a --reason keeps the earlier mark, with its reason and date
1139
+ marks = [fp for fp in args.dismiss if (data.get(fp) or {}).get("status") != "dismissed" or args.reason is not None]
1140
+ if marks:
1141
+ set_record_status(ident, marks, "dismissed", reason=args.reason or NO_REASON)
1142
+ lifts = [fp for fp in args.undismiss if (data.get(fp) or {}).get("status") == "dismissed"]
1143
+ if lifts:
1144
+ set_record_status(ident, lifts, "open")
1063
1145
  return {"ok": True, "dismissed": args.dismiss, "undismissed": args.undismiss, "warnings": warnings}
1064
1146
 
1065
1147
 
@@ -1187,11 +1269,11 @@ def comment_body(f, lang):
1187
1269
  f"<!-- forge:finding fp={f['fp']} source=forge:{f['plan']}/{f['task'] or 'final-review'} -->"])
1188
1270
 
1189
1271
 
1190
- def post_comments(key, comments, by_fp, lang):
1272
+ def post_comments(ident, comments, by_fp, lang):
1191
1273
  """Comment on the issue each reworded duplicate restates, and record a receipt for each: the marker in a
1192
1274
  comment is invisible to the issue-body index, so without the receipt the next run would comment again.
1193
1275
  Runs under the repository lock `--apply` holds. A comment that fails is reported and gets no receipt."""
1194
- receipts = load_comments(key)
1276
+ receipts = load_comments(ident)
1195
1277
  done = []
1196
1278
  for c in comments:
1197
1279
  with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as fh:
@@ -1204,7 +1286,7 @@ def post_comments(key, comments, by_fp, lang):
1204
1286
  finally:
1205
1287
  os.unlink(fh.name)
1206
1288
  receipts[c["fp"]] = {"issue": c["issue"], "at": int(time.time())}
1207
- save_comments(key, receipts)
1289
+ save_comments(ident, receipts)
1208
1290
  done.append(dict(c))
1209
1291
  return done
1210
1292
 
@@ -1217,7 +1299,7 @@ def split_fps(values):
1217
1299
  return None if any(not FP_RE.fullmatch(x) for x in fps) else list(dict.fromkeys(fps))
1218
1300
 
1219
1301
 
1220
- def main(argv=None):
1302
+ def build_parser():
1221
1303
  ap = argparse.ArgumentParser(prog="forge issues", description=__doc__.split("\n\n")[0],
1222
1304
  formatter_class=argparse.RawDescriptionHelpFormatter,
1223
1305
  epilog="\n\n".join(__doc__.split("\n\n")[1:]))
@@ -1237,7 +1319,10 @@ def main(argv=None):
1237
1319
  ap.add_argument("--offline", action="store_true", help="never run `gh`: no filed state, local refs only")
1238
1320
  ap.add_argument("--only", action="append", default=[], metavar="FP",
1239
1321
  help="keep only this 12-hex fingerprint; repeatable or comma-separated")
1240
- ap.add_argument("--all-runs", action="store_true", help="collect every run in the repository's run registry")
1322
+ ap.add_argument("--to-file", action="store_true",
1323
+ help="keep only the findings whose record status is to-file (may be combined with --only: both must match)")
1324
+ ap.add_argument("--all-runs", action="store_true",
1325
+ help="collect every run of the repository: its main checkout, linked worktrees and removed ones")
1241
1326
  ap.add_argument("--dismiss", action="append", default=[], metavar="FP",
1242
1327
  help="mark this 12-hex fingerprint as needing no work, then exit; repeatable or comma-separated")
1243
1328
  ap.add_argument("--undismiss", action="append", default=[], metavar="FP",
@@ -1245,6 +1330,11 @@ def main(argv=None):
1245
1330
  ap.add_argument("--reason", help=f"why --dismiss marks them (at most {REASON_MAX} characters)")
1246
1331
  ap.add_argument("--include-dismissed", action="store_true", help="draft dismissed findings too")
1247
1332
  ap.add_argument("--json", action="store_true", help="machine-readable output")
1333
+ return ap
1334
+
1335
+
1336
+ def main(argv=None):
1337
+ ap = build_parser()
1248
1338
  args = ap.parse_args(argv)
1249
1339
  if args.offline and args.apply:
1250
1340
  ap.error("--offline cannot be combined with --apply")
@@ -1287,14 +1377,15 @@ def main(argv=None):
1287
1377
  return 0
1288
1378
 
1289
1379
 
1290
- def finding_entry(f, filed=None, dismissed=None, commented=None):
1380
+ def finding_entry(f, filed=None, dismissed=None, commented=None, record=None):
1291
1381
  entry = {"fp": f["fp"], "severity": f["severity"], "confidence": f["confidence"], "origin": f["origin"],
1292
1382
  "plan": f["plan"], "plan_dir": f["plan_dir"], "task": f["task"], "file": f["file"],
1293
1383
  "summary": (f["text"].splitlines() or [""])[0][:160], "text": f["text"],
1294
1384
  "reviewer": f["reviewer"], "commit": f.get("commit") or "",
1295
1385
  "review": f.get("review"), "swept": f.get("swept"),
1296
1386
  "filed": {"url": filed["url"], "state": filed["state"]} if filed else None,
1297
- "dismissed": dismissed}
1387
+ "dismissed": dismissed, "record": record}
1388
+ entry["status"] = record_status.effective(record, entry, None)
1298
1389
  if commented:
1299
1390
  entry["commented"] = commented # only a finding with a receipt has the key: the rest is as before
1300
1391
  return entry
@@ -1303,24 +1394,47 @@ def finding_entry(f, filed=None, dismissed=None, commented=None):
1303
1394
  def file_findings(args):
1304
1395
  meta, found, notes = collect(Path(args.run), args.include_plausible, args.all_runs)
1305
1396
  mark_swept(found)
1306
- repo_path, warnings = run_repository(meta)
1307
- slug = args.repo or github_slug(repo_path)
1397
+ ident = run_identity(args, meta)
1398
+ repo_path, warnings = run_repository(meta, ident)
1399
+ slug = args.repo or github_slug(repo_path) or forge_identity.github_slug(ident)
1308
1400
  if not slug:
1309
- raise Fail("; ".join(warnings + [f"{repo_path} has no GitHub origin remote; pass --repo owner/repo"]))
1401
+ problem = f"{repo_path} has no GitHub origin remote; pass --repo owner/repo"
1402
+ if args.apply:
1403
+ raise Fail("; ".join(warnings + [problem]))
1404
+ warnings = warnings + [f"{problem}. Listing without a repository name: fingerprints are computed with an "
1405
+ "empty one, so they differ from the ones a named repository gives"]
1310
1406
  if args.min_severity:
1311
1407
  cut = SEVERITIES.index(args.min_severity)
1312
1408
  found = [f for f in found if SEVERITIES.index(f["severity"]) <= cut]
1313
1409
  # Filing is list-then-create, so no other filing or dismissal for this repository may run in between: the
1314
1410
  # lock covers the lookup, the drafts (which ask `gh` whether commits are published) and every create.
1315
- with repo_lock(repo_key(repo_path), slug) if args.apply else contextlib.nullcontext():
1316
- return list_and_file(args, meta, found, notes, repo_path, slug, warnings)
1411
+ with repo_lock(ident, slug or repo_path) if args.apply else contextlib.nullcontext():
1412
+ return list_and_file(args, meta, found, notes, repo_path, slug or "", warnings, ident)
1413
+
1414
+
1415
+ def listing(path, include_plausible=True, include_dismissed=True, online=False, all_runs=True):
1416
+ """The `--json` object of a listing without `--apply`, for callers in this process (forge-findings, forge-ui).
1417
+
1418
+ Offline unless `online`. Raises Fail (Busy included) exactly as `main` would print it.
1419
+ """
1420
+ argv = [] if online else ["--offline"]
1421
+ argv += ["--include-plausible"] if include_plausible else []
1422
+ argv += ["--include-dismissed"] if include_dismissed else []
1423
+ argv += ["--all-runs"] if all_runs else []
1424
+ return file_findings(build_parser().parse_args([*argv, "--json", "--", str(path)]))
1425
+
1426
+
1427
+ def draft_notes(record):
1428
+ """(title, body) a `to-file` record carries for its issue; "" for what it does not."""
1429
+ draft = (record or {}).get("draft") if (record or {}).get("status") == "to-file" else None
1430
+ draft = draft if isinstance(draft, dict) else {}
1431
+ return str(draft.get("title") or ""), str(draft.get("body") or "")
1317
1432
 
1318
1433
 
1319
- def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1320
- offline = args.offline
1321
- store_key = repo_key(repo_path)
1322
- dismissed = load_dismissed(store_key)
1323
- receipts = load_comments(store_key)
1434
+ def list_and_file(args, meta, found, notes, repo_path, slug, warnings, ident):
1435
+ offline = args.offline or not slug # no repository name, nothing to ask GitHub about
1436
+ record = load_record(ident)
1437
+ receipts = load_comments(ident)
1324
1438
  issues = [] if offline else existing_issues(slug)
1325
1439
  filed = {fp: issue for issue in issues for fp in FP_MARK_RE.findall(issue.get("body") or "")}
1326
1440
  only = set(args.only)
@@ -1329,13 +1443,17 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1329
1443
  for f in found:
1330
1444
  f["fp"] = fingerprint(slug, f)
1331
1445
  known.add(f["fp"])
1332
- if f["fp"] in seen or (only and f["fp"] not in only):
1446
+ rec = record.get(f["fp"])
1447
+ if f["fp"] in seen or (only and f["fp"] not in only) \
1448
+ or (args.to_file and (rec or {}).get("status") != "to-file"):
1333
1449
  continue
1334
1450
  seen.add(f["fp"])
1335
1451
  issue = filed.get(f["fp"])
1336
- mark = dismissed.get(f["fp"])
1452
+ mark = {"at": int(rec["at"]), "reason": rec.get("reason", "")} \
1453
+ if rec and rec.get("status") == "dismissed" and isinstance(rec.get("at"), (int, float)) else None
1337
1454
  receipt = receipts.get(f["fp"])
1338
- entries.append(finding_entry(f, issue, mark, receipt))
1455
+ entry = finding_entry(f, issue, mark, receipt, rec)
1456
+ entries.append(entry)
1339
1457
  if issue:
1340
1458
  already.append({"finding": f["raw"], "issue": issue["url"], "state": issue["state"]})
1341
1459
  elif receipt: # commented on an issue as a duplicate: as good as filed
@@ -1343,7 +1461,9 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1343
1461
  already.append({"finding": f["raw"], "issue": receipt["issue"], "state": state})
1344
1462
  elif f.get("swept"):
1345
1463
  continue # fixed in the run by its finding sweep
1346
- elif not mark or args.include_dismissed:
1464
+ elif entry["status"] in ("filed", "fixed", "duplicate"):
1465
+ continue # the record says it has an issue, is fixed, or is another finding's twin
1466
+ elif entry["status"] != "dismissed" or args.include_dismissed:
1347
1467
  todo.append(f)
1348
1468
  notes = notes + [f"--only {fp}: no such open finding" for fp in args.only if fp not in known]
1349
1469
  entries.sort(key=lambda e: SEVERITIES.index(e["severity"]))
@@ -1382,16 +1502,25 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1382
1502
  else:
1383
1503
  prefix = t["plausible"] if origin == "plausible" else ""
1384
1504
  title = f"[{items[0]['severity']}] {prefix}{t['group_title'].format(scope=scope)}"
1505
+ written = [draft_notes(record.get(f["fp"])) for f in items]
1506
+ if len(items) == 1 and written[0][0]:
1507
+ title = written[0][0] # the title a person wrote for it in the record
1508
+ body = body_for(slug, repo_path if meta["repo_path"] else None, items, args.lang, offline)
1509
+ extra = [text for _title, text in written if text]
1510
+ if extra:
1511
+ body = "\n".join([body, "", f"## {t['notes']}", *[escape(text) for text in extra]])
1385
1512
  drafts.append({"title": title, "severity": items[0]["severity"], "origin": items[0]["origin"],
1386
1513
  "findings": [f["raw"] for f in items], "fingerprints": [f["fp"] for f in items],
1387
1514
  "same_title": None if offline else open_titles.get(norm_title(title)),
1388
- "body": body_for(slug, repo_path if meta["repo_path"] else None, items, args.lang, offline)})
1515
+ "body": body})
1389
1516
  if any(f["fp"] in gates for f in items):
1390
1517
  drafts[-1]["gate"] = draft_gate([gates[f["fp"]] for f in items if f["fp"] in gates])
1391
1518
  drafts.sort(key=lambda d: SEVERITIES.index(d["severity"]))
1392
1519
  out = {"repo": slug, "plan": meta["plan"], "notes": notes, "warnings": warnings,
1393
1520
  "summary": {"findings": len(seen), "already_filed": len(already),
1394
1521
  "dismissed": sum(1 for e in entries if e["dismissed"]),
1522
+ **{name: sum(1 for e in entries if e["status"] == status)
1523
+ for name, status in (("fixed", "fixed"), ("duplicate", "duplicate"), ("to_file", "to-file"))},
1395
1524
  "swept": sum(1 for e in entries if e["swept"]), "drafts": len(drafts),
1396
1525
  **{o: sum(1 for f in todo if f["origin"] == o)
1397
1526
  for o in ("tolerated", "accepted", "review", "plausible")}},
@@ -1399,16 +1528,19 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1399
1528
  if comments is not None:
1400
1529
  out["comments"] = comments
1401
1530
  if args.apply:
1402
- out["created"] = create(slug, drafts, args)
1531
+ def record_filed(draft, url):
1532
+ if url.startswith("https://"):
1533
+ set_record_status(ident, draft["fingerprints"], "filed", issue=url)
1534
+ out["created"] = create(slug, drafts, args, record_filed)
1403
1535
  for d in drafts:
1404
1536
  d.pop("body")
1405
1537
  if comments:
1406
1538
  by_fp = {f["fp"]: f for f in found}
1407
- out["commented"] = post_comments(store_key, comments, by_fp, args.lang)
1539
+ out["commented"] = post_comments(ident, comments, by_fp, args.lang)
1408
1540
  return out
1409
1541
 
1410
1542
 
1411
- def create(slug, drafts, args):
1543
+ def create(slug, drafts, args, on_created=None):
1412
1544
  labels = []
1413
1545
  if args.label:
1414
1546
  res = run(["gh", "label", "list", "--repo", slug, "--limit", "500", "--json", "name"], check=False)
@@ -1433,6 +1565,8 @@ def create(slug, drafts, args):
1433
1565
  os.unlink(fh.name)
1434
1566
  url = next((w for w in res.stdout.split() if w.startswith("https://")), res.stdout.strip())
1435
1567
  created.append({"title": d["title"], "url": url})
1568
+ if on_created:
1569
+ on_created(d, url)
1436
1570
  missing = sorted(set(args.label) - set(labels))
1437
1571
  if missing:
1438
1572
  created.append({"note": f"labels not in {slug}, left off: {', '.join(missing)}"})
@@ -1443,7 +1577,7 @@ def print_human(out, applied):
1443
1577
  s = out["summary"]
1444
1578
  dismissed = f", {s['dismissed']} dismissed" if s["dismissed"] else ""
1445
1579
  dismissed += f", {s['swept']} fixed by the run's finding sweep" if s.get("swept") else ""
1446
- print(f"{out['repo']} · run {out['plan']}: {s['findings']} finding(s), {s['already_filed']} already filed{dismissed}, "
1580
+ print(f"{out['repo'] or '(no GitHub remote)'} · run {out['plan']}: {s['findings']} finding(s), {s['already_filed']} already filed{dismissed}, "
1447
1581
  f"{s['drafts']} draft(s) ({s['tolerated']} tolerated, {s['accepted']} accepted, "
1448
1582
  f"{s['review']} review, {s['plausible']} plausible)")
1449
1583
  for warning in out["warnings"]: