@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
@@ -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
@@ -83,7 +91,10 @@ import time
83
91
  from pathlib import Path
84
92
 
85
93
  sys.path.insert(0, str(Path(__file__).resolve().parent))
86
- from forge_registry import repo_key, runs_registry # 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
 
@@ -984,82 +1030,115 @@ def _write_store(name, noun, data):
984
1030
  raise Fail(f"{path}: cannot write the {noun}: {exc.strerror}")
985
1031
 
986
1032
  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()}
1033
+ """The repository's dismissals under `key`, `{fp: {"at": epoch, "reason": str}}`; empty when it has none yet.
992
1034
 
1035
+ Read through the record store: the record `<key>.record.json` and the old `<key>.json` dismissals, the
1036
+ record winning (a finding reopened there is not dismissed). Read only: nothing writes `<key>.json` any more.
1037
+ """
1038
+ return {fp: {"at": int(v["at"]), "reason": v.get("reason", "")}
1039
+ for fp, v in load_record({"key": key}).items()
1040
+ if v.get("status") == "dismissed" and isinstance(v.get("at"), (int, float))}
993
1041
 
994
- def save_dismissed(key, data):
995
- _write_store(f"{key}.json", "dismissal store", data)
1042
+
1043
+ def _valid_receipt(v):
1044
+ return (isinstance(v, dict) and isinstance(v.get("issue"), str)
1045
+ and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool))
1046
+
1047
+
1048
+ def _comment_receipts(key):
1049
+ data = _read_store(f"{key}.comments.json", "comment-receipt store", "{fingerprint: {issue, at}}", _valid_receipt)
1050
+ return {fp: {"issue": v["issue"], "at": v["at"]} for fp, v in data.items()}
996
1051
 
997
1052
 
998
- def load_comments(key):
1053
+ def load_comments(ident):
999
1054
  """The repository's comment receipts, `{fp: {"issue": url, "at": epoch}}`; empty when it has none yet.
1000
1055
 
1001
1056
  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.
1057
+ what keeps one duplicate from being commented on every run. They live in `<identity key>.comments.json`; the
1058
+ old `<checkout key>.comments.json` of every checkout is read too (the newest receipt wins) and never written.
1003
1059
  """
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()}
1060
+ key = ident["key"]
1061
+ merged = {}
1062
+ for checkout in forge_identity.checkouts(ident):
1063
+ try:
1064
+ old_key = repo_key(checkout)
1065
+ except (OSError, ValueError, RuntimeError, UnicodeError):
1066
+ continue
1067
+ if old_key == key:
1068
+ continue
1069
+ try:
1070
+ old = _comment_receipts(old_key)
1071
+ except Fail:
1072
+ continue # an unreadable old store is skipped, as the record store skips old dismissals
1073
+ for fp, receipt in old.items():
1074
+ if fp not in merged or receipt["at"] > merged[fp]["at"]:
1075
+ merged[fp] = receipt
1076
+ merged.update(_comment_receipts(key))
1077
+ return merged
1008
1078
 
1009
1079
 
1010
- def save_comments(key, data):
1011
- _write_store(f"{key}.comments.json", "comment-receipt store", data)
1080
+ def save_comments(ident, data):
1081
+ _write_store(f"{ident['key']}.comments.json", "comment-receipt store", data)
1012
1082
 
1013
1083
 
1014
1084
  @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.
1085
+ def repo_lock(ident, label):
1086
+ """Hold the repository's `<key>.lock` (flock, next to the stores) through the record store; busy for
1087
+ LOCK_WAIT seconds raises Busy. `ident` is the repository identity, or its key.
1017
1088
 
1018
- The lock is its own file, opened in place and never replaced, because the store is: a lock on the store
1089
+ The lock is its own file, opened in place and never replaced, because the stores are: a lock on a store
1019
1090
  file would stay with the old inode after an atomic save.
1020
1091
  """
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")
1092
+ if isinstance(ident, str):
1093
+ ident = {"key": ident}
1094
+ waited = record_store.LOCK_WAIT
1095
+ record_store.LOCK_WAIT = LOCK_WAIT
1026
1096
  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
1097
+ with record_store.lock(ident):
1098
+ yield
1099
+ except record_store.Busy:
1100
+ raise Busy(f"busy: another filing or dismissal for {label} is in progress")
1101
+ except (record_store.Corrupt, record_store.Invalid) as exc:
1102
+ raise Fail(str(exc))
1041
1103
  finally:
1042
- os.close(fd) # closing the descriptor releases the flock
1104
+ record_store.LOCK_WAIT = waited
1105
+
1106
+
1107
+ def load_record(ident):
1108
+ """{fp: entry}: the finding record of the repository, old dismissals merged in. Fail when it is unusable."""
1109
+ try:
1110
+ return record_store.load(ident)
1111
+ except (record_store.Corrupt, record_store.Invalid) as exc:
1112
+ raise Fail(str(exc))
1113
+
1114
+
1115
+ def set_record_status(ident, fps, status, **fields):
1116
+ try:
1117
+ return record_store.set_status(ident, fps, status, "issues", locked=True, **fields)
1118
+ except record_store.Busy as exc:
1119
+ raise Busy(str(exc))
1120
+ except (record_store.Corrupt, record_store.Invalid) as exc:
1121
+ raise Fail(str(exc))
1122
+
1123
+
1124
+ NO_REASON = "dismissed with forge issues" # a record's `dismissed` needs a reason; --dismiss without one gets this
1043
1125
 
1044
1126
 
1045
1127
  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."""
1128
+ """--dismiss / --undismiss: write the repository's finding record under its lock. No network: <run> is only
1129
+ read to find the repository it resolves to."""
1048
1130
  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)
1131
+ ident = run_identity(args, meta)
1132
+ repo_path, warnings = run_repository(meta, ident)
1133
+ with repo_lock(ident, args.repo or github_slug(repo_path) or forge_identity.github_slug(ident) or repo_path):
1134
+ data = load_record(ident)
1135
+ # dismissing again without a --reason keeps the earlier mark, with its reason and date
1136
+ marks = [fp for fp in args.dismiss if (data.get(fp) or {}).get("status") != "dismissed" or args.reason is not None]
1137
+ if marks:
1138
+ set_record_status(ident, marks, "dismissed", reason=args.reason or NO_REASON)
1139
+ lifts = [fp for fp in args.undismiss if (data.get(fp) or {}).get("status") == "dismissed"]
1140
+ if lifts:
1141
+ set_record_status(ident, lifts, "open")
1063
1142
  return {"ok": True, "dismissed": args.dismiss, "undismissed": args.undismiss, "warnings": warnings}
1064
1143
 
1065
1144
 
@@ -1187,11 +1266,11 @@ def comment_body(f, lang):
1187
1266
  f"<!-- forge:finding fp={f['fp']} source=forge:{f['plan']}/{f['task'] or 'final-review'} -->"])
1188
1267
 
1189
1268
 
1190
- def post_comments(key, comments, by_fp, lang):
1269
+ def post_comments(ident, comments, by_fp, lang):
1191
1270
  """Comment on the issue each reworded duplicate restates, and record a receipt for each: the marker in a
1192
1271
  comment is invisible to the issue-body index, so without the receipt the next run would comment again.
1193
1272
  Runs under the repository lock `--apply` holds. A comment that fails is reported and gets no receipt."""
1194
- receipts = load_comments(key)
1273
+ receipts = load_comments(ident)
1195
1274
  done = []
1196
1275
  for c in comments:
1197
1276
  with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as fh:
@@ -1204,7 +1283,7 @@ def post_comments(key, comments, by_fp, lang):
1204
1283
  finally:
1205
1284
  os.unlink(fh.name)
1206
1285
  receipts[c["fp"]] = {"issue": c["issue"], "at": int(time.time())}
1207
- save_comments(key, receipts)
1286
+ save_comments(ident, receipts)
1208
1287
  done.append(dict(c))
1209
1288
  return done
1210
1289
 
@@ -1217,7 +1296,7 @@ def split_fps(values):
1217
1296
  return None if any(not FP_RE.fullmatch(x) for x in fps) else list(dict.fromkeys(fps))
1218
1297
 
1219
1298
 
1220
- def main(argv=None):
1299
+ def build_parser():
1221
1300
  ap = argparse.ArgumentParser(prog="forge issues", description=__doc__.split("\n\n")[0],
1222
1301
  formatter_class=argparse.RawDescriptionHelpFormatter,
1223
1302
  epilog="\n\n".join(__doc__.split("\n\n")[1:]))
@@ -1237,7 +1316,10 @@ def main(argv=None):
1237
1316
  ap.add_argument("--offline", action="store_true", help="never run `gh`: no filed state, local refs only")
1238
1317
  ap.add_argument("--only", action="append", default=[], metavar="FP",
1239
1318
  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")
1319
+ ap.add_argument("--to-file", action="store_true",
1320
+ help="keep only the findings whose record status is to-file (may be combined with --only: both must match)")
1321
+ ap.add_argument("--all-runs", action="store_true",
1322
+ help="collect every run of the repository: its main checkout, linked worktrees and removed ones")
1241
1323
  ap.add_argument("--dismiss", action="append", default=[], metavar="FP",
1242
1324
  help="mark this 12-hex fingerprint as needing no work, then exit; repeatable or comma-separated")
1243
1325
  ap.add_argument("--undismiss", action="append", default=[], metavar="FP",
@@ -1245,6 +1327,11 @@ def main(argv=None):
1245
1327
  ap.add_argument("--reason", help=f"why --dismiss marks them (at most {REASON_MAX} characters)")
1246
1328
  ap.add_argument("--include-dismissed", action="store_true", help="draft dismissed findings too")
1247
1329
  ap.add_argument("--json", action="store_true", help="machine-readable output")
1330
+ return ap
1331
+
1332
+
1333
+ def main(argv=None):
1334
+ ap = build_parser()
1248
1335
  args = ap.parse_args(argv)
1249
1336
  if args.offline and args.apply:
1250
1337
  ap.error("--offline cannot be combined with --apply")
@@ -1287,14 +1374,15 @@ def main(argv=None):
1287
1374
  return 0
1288
1375
 
1289
1376
 
1290
- def finding_entry(f, filed=None, dismissed=None, commented=None):
1377
+ def finding_entry(f, filed=None, dismissed=None, commented=None, record=None):
1291
1378
  entry = {"fp": f["fp"], "severity": f["severity"], "confidence": f["confidence"], "origin": f["origin"],
1292
1379
  "plan": f["plan"], "plan_dir": f["plan_dir"], "task": f["task"], "file": f["file"],
1293
1380
  "summary": (f["text"].splitlines() or [""])[0][:160], "text": f["text"],
1294
1381
  "reviewer": f["reviewer"], "commit": f.get("commit") or "",
1295
1382
  "review": f.get("review"), "swept": f.get("swept"),
1296
1383
  "filed": {"url": filed["url"], "state": filed["state"]} if filed else None,
1297
- "dismissed": dismissed}
1384
+ "dismissed": dismissed, "record": record}
1385
+ entry["status"] = record_status.effective(record, entry, None)
1298
1386
  if commented:
1299
1387
  entry["commented"] = commented # only a finding with a receipt has the key: the rest is as before
1300
1388
  return entry
@@ -1303,24 +1391,47 @@ def finding_entry(f, filed=None, dismissed=None, commented=None):
1303
1391
  def file_findings(args):
1304
1392
  meta, found, notes = collect(Path(args.run), args.include_plausible, args.all_runs)
1305
1393
  mark_swept(found)
1306
- repo_path, warnings = run_repository(meta)
1307
- slug = args.repo or github_slug(repo_path)
1394
+ ident = run_identity(args, meta)
1395
+ repo_path, warnings = run_repository(meta, ident)
1396
+ slug = args.repo or github_slug(repo_path) or forge_identity.github_slug(ident)
1308
1397
  if not slug:
1309
- raise Fail("; ".join(warnings + [f"{repo_path} has no GitHub origin remote; pass --repo owner/repo"]))
1398
+ problem = f"{repo_path} has no GitHub origin remote; pass --repo owner/repo"
1399
+ if args.apply:
1400
+ raise Fail("; ".join(warnings + [problem]))
1401
+ warnings = warnings + [f"{problem}. Listing without a repository name: fingerprints are computed with an "
1402
+ "empty one, so they differ from the ones a named repository gives"]
1310
1403
  if args.min_severity:
1311
1404
  cut = SEVERITIES.index(args.min_severity)
1312
1405
  found = [f for f in found if SEVERITIES.index(f["severity"]) <= cut]
1313
1406
  # Filing is list-then-create, so no other filing or dismissal for this repository may run in between: the
1314
1407
  # 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)
1408
+ with repo_lock(ident, slug or repo_path) if args.apply else contextlib.nullcontext():
1409
+ return list_and_file(args, meta, found, notes, repo_path, slug or "", warnings, ident)
1410
+
1411
+
1412
+ def listing(path, include_plausible=True, include_dismissed=True, online=False, all_runs=True):
1413
+ """The `--json` object of a listing without `--apply`, for callers in this process (forge-findings, forge-ui).
1414
+
1415
+ Offline unless `online`. Raises Fail (Busy included) exactly as `main` would print it.
1416
+ """
1417
+ argv = [] if online else ["--offline"]
1418
+ argv += ["--include-plausible"] if include_plausible else []
1419
+ argv += ["--include-dismissed"] if include_dismissed else []
1420
+ argv += ["--all-runs"] if all_runs else []
1421
+ return file_findings(build_parser().parse_args([*argv, "--json", "--", str(path)]))
1422
+
1423
+
1424
+ def draft_notes(record):
1425
+ """(title, body) a `to-file` record carries for its issue; "" for what it does not."""
1426
+ draft = (record or {}).get("draft") if (record or {}).get("status") == "to-file" else None
1427
+ draft = draft if isinstance(draft, dict) else {}
1428
+ return str(draft.get("title") or ""), str(draft.get("body") or "")
1317
1429
 
1318
1430
 
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)
1431
+ def list_and_file(args, meta, found, notes, repo_path, slug, warnings, ident):
1432
+ offline = args.offline or not slug # no repository name, nothing to ask GitHub about
1433
+ record = load_record(ident)
1434
+ receipts = load_comments(ident)
1324
1435
  issues = [] if offline else existing_issues(slug)
1325
1436
  filed = {fp: issue for issue in issues for fp in FP_MARK_RE.findall(issue.get("body") or "")}
1326
1437
  only = set(args.only)
@@ -1329,13 +1440,17 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1329
1440
  for f in found:
1330
1441
  f["fp"] = fingerprint(slug, f)
1331
1442
  known.add(f["fp"])
1332
- if f["fp"] in seen or (only and f["fp"] not in only):
1443
+ rec = record.get(f["fp"])
1444
+ if f["fp"] in seen or (only and f["fp"] not in only) \
1445
+ or (args.to_file and (rec or {}).get("status") != "to-file"):
1333
1446
  continue
1334
1447
  seen.add(f["fp"])
1335
1448
  issue = filed.get(f["fp"])
1336
- mark = dismissed.get(f["fp"])
1449
+ mark = {"at": int(rec["at"]), "reason": rec.get("reason", "")} \
1450
+ if rec and rec.get("status") == "dismissed" and isinstance(rec.get("at"), (int, float)) else None
1337
1451
  receipt = receipts.get(f["fp"])
1338
- entries.append(finding_entry(f, issue, mark, receipt))
1452
+ entry = finding_entry(f, issue, mark, receipt, rec)
1453
+ entries.append(entry)
1339
1454
  if issue:
1340
1455
  already.append({"finding": f["raw"], "issue": issue["url"], "state": issue["state"]})
1341
1456
  elif receipt: # commented on an issue as a duplicate: as good as filed
@@ -1343,7 +1458,9 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1343
1458
  already.append({"finding": f["raw"], "issue": receipt["issue"], "state": state})
1344
1459
  elif f.get("swept"):
1345
1460
  continue # fixed in the run by its finding sweep
1346
- elif not mark or args.include_dismissed:
1461
+ elif entry["status"] in ("filed", "fixed", "duplicate"):
1462
+ continue # the record says it has an issue, is fixed, or is another finding's twin
1463
+ elif entry["status"] != "dismissed" or args.include_dismissed:
1347
1464
  todo.append(f)
1348
1465
  notes = notes + [f"--only {fp}: no such open finding" for fp in args.only if fp not in known]
1349
1466
  entries.sort(key=lambda e: SEVERITIES.index(e["severity"]))
@@ -1382,16 +1499,25 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1382
1499
  else:
1383
1500
  prefix = t["plausible"] if origin == "plausible" else ""
1384
1501
  title = f"[{items[0]['severity']}] {prefix}{t['group_title'].format(scope=scope)}"
1502
+ written = [draft_notes(record.get(f["fp"])) for f in items]
1503
+ if len(items) == 1 and written[0][0]:
1504
+ title = written[0][0] # the title a person wrote for it in the record
1505
+ body = body_for(slug, repo_path if meta["repo_path"] else None, items, args.lang, offline)
1506
+ extra = [text for _title, text in written if text]
1507
+ if extra:
1508
+ body = "\n".join([body, "", f"## {t['notes']}", *[escape(text) for text in extra]])
1385
1509
  drafts.append({"title": title, "severity": items[0]["severity"], "origin": items[0]["origin"],
1386
1510
  "findings": [f["raw"] for f in items], "fingerprints": [f["fp"] for f in items],
1387
1511
  "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)})
1512
+ "body": body})
1389
1513
  if any(f["fp"] in gates for f in items):
1390
1514
  drafts[-1]["gate"] = draft_gate([gates[f["fp"]] for f in items if f["fp"] in gates])
1391
1515
  drafts.sort(key=lambda d: SEVERITIES.index(d["severity"]))
1392
1516
  out = {"repo": slug, "plan": meta["plan"], "notes": notes, "warnings": warnings,
1393
1517
  "summary": {"findings": len(seen), "already_filed": len(already),
1394
1518
  "dismissed": sum(1 for e in entries if e["dismissed"]),
1519
+ **{name: sum(1 for e in entries if e["status"] == status)
1520
+ for name, status in (("fixed", "fixed"), ("duplicate", "duplicate"), ("to_file", "to-file"))},
1395
1521
  "swept": sum(1 for e in entries if e["swept"]), "drafts": len(drafts),
1396
1522
  **{o: sum(1 for f in todo if f["origin"] == o)
1397
1523
  for o in ("tolerated", "accepted", "review", "plausible")}},
@@ -1399,16 +1525,19 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1399
1525
  if comments is not None:
1400
1526
  out["comments"] = comments
1401
1527
  if args.apply:
1402
- out["created"] = create(slug, drafts, args)
1528
+ def record_filed(draft, url):
1529
+ if url.startswith("https://"):
1530
+ set_record_status(ident, draft["fingerprints"], "filed", issue=url)
1531
+ out["created"] = create(slug, drafts, args, record_filed)
1403
1532
  for d in drafts:
1404
1533
  d.pop("body")
1405
1534
  if comments:
1406
1535
  by_fp = {f["fp"]: f for f in found}
1407
- out["commented"] = post_comments(store_key, comments, by_fp, args.lang)
1536
+ out["commented"] = post_comments(ident, comments, by_fp, args.lang)
1408
1537
  return out
1409
1538
 
1410
1539
 
1411
- def create(slug, drafts, args):
1540
+ def create(slug, drafts, args, on_created=None):
1412
1541
  labels = []
1413
1542
  if args.label:
1414
1543
  res = run(["gh", "label", "list", "--repo", slug, "--limit", "500", "--json", "name"], check=False)
@@ -1433,6 +1562,8 @@ def create(slug, drafts, args):
1433
1562
  os.unlink(fh.name)
1434
1563
  url = next((w for w in res.stdout.split() if w.startswith("https://")), res.stdout.strip())
1435
1564
  created.append({"title": d["title"], "url": url})
1565
+ if on_created:
1566
+ on_created(d, url)
1436
1567
  missing = sorted(set(args.label) - set(labels))
1437
1568
  if missing:
1438
1569
  created.append({"note": f"labels not in {slug}, left off: {', '.join(missing)}"})
@@ -1443,7 +1574,7 @@ def print_human(out, applied):
1443
1574
  s = out["summary"]
1444
1575
  dismissed = f", {s['dismissed']} dismissed" if s["dismissed"] else ""
1445
1576
  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}, "
1577
+ print(f"{out['repo'] or '(no GitHub remote)'} · run {out['plan']}: {s['findings']} finding(s), {s['already_filed']} already filed{dismissed}, "
1447
1578
  f"{s['drafts']} draft(s) ({s['tolerated']} tolerated, {s['accepted']} accepted, "
1448
1579
  f"{s['review']} review, {s['plausible']} plausible)")
1449
1580
  for warning in out["warnings"]: