@giamme/forge 0.12.0 → 0.13.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 (117) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +31 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +18 -6
  7. package/docs/commands.md +189 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +34 -4
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +81 -19
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +40 -14
  17. package/references/decision-models.md +759 -0
  18. package/references/decompose.md +197 -28
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/references/ui.md +11 -0
  23. package/scripts/forge-artifact.sh +30 -4
  24. package/scripts/forge-config.py +238 -29
  25. package/scripts/forge-contract.py +127 -58
  26. package/scripts/forge-control.py +40 -9
  27. package/scripts/forge-decide.py +6 -0
  28. package/scripts/forge-dispatch.sh +47 -15
  29. package/scripts/forge-fail-first.py +2 -2
  30. package/scripts/forge-gate-addressed.sh +40 -0
  31. package/scripts/forge-gate-message.sh +64 -0
  32. package/scripts/forge-issues.py +368 -36
  33. package/scripts/forge-jev-options.sh +269 -42
  34. package/scripts/forge-lib-attribute.sh +447 -0
  35. package/scripts/forge-lib-gates.sh +32 -0
  36. package/scripts/forge-lib-plans.sh +17 -6
  37. package/scripts/forge-lib-review.sh +24 -19
  38. package/scripts/forge-lib-task.sh +219 -39
  39. package/scripts/forge-lib-verify.sh +45 -8
  40. package/scripts/forge-memory.sh +3 -3
  41. package/scripts/forge-parallel-options.sh +44 -5
  42. package/scripts/forge-parallel.sh +503 -304
  43. package/scripts/forge-plan-check.py +35 -1
  44. package/scripts/forge-pre-review.py +437 -0
  45. package/scripts/forge-prompt.py +25 -5
  46. package/scripts/forge-route.py +2 -2
  47. package/scripts/forge-runtime.py +55 -1
  48. package/scripts/forge-schedule.py +70 -9
  49. package/scripts/forge-shadow.py +2 -2
  50. package/scripts/forge-solo.sh +41 -10
  51. package/scripts/forge-submodules.py +389 -0
  52. package/scripts/forge-sweep.py +542 -0
  53. package/scripts/forge_dataset/cli.py +12 -6
  54. package/scripts/forge_dataset/export.py +55 -45
  55. package/scripts/forge_dataset/forecast.py +4 -1
  56. package/scripts/forge_dataset/harvest.py +33 -5
  57. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  58. package/scripts/forge_decide/__init__.py +141 -0
  59. package/scripts/forge_decide/budget.py +149 -0
  60. package/scripts/forge_decide/cache.py +66 -0
  61. package/scripts/forge_decide/cli.py +953 -0
  62. package/scripts/forge_decide/doctor.py +221 -0
  63. package/scripts/forge_decide/label_addressed.py +75 -0
  64. package/scripts/forge_decide/label_attribution.py +62 -0
  65. package/scripts/forge_decide/label_coverage.py +81 -0
  66. package/scripts/forge_decide/label_message.py +38 -0
  67. package/scripts/forge_decide/label_prompt.py +139 -0
  68. package/scripts/forge_decide/labels.py +328 -0
  69. package/scripts/forge_decide/metrics.py +125 -0
  70. package/scripts/forge_decide/migrate.py +226 -0
  71. package/scripts/forge_decide/providers.py +292 -0
  72. package/scripts/forge_decide/replay.py +350 -0
  73. package/scripts/forge_decide/report.py +382 -0
  74. package/scripts/forge_decide/resolve.py +397 -0
  75. package/scripts/forge_decide/sites.py +377 -0
  76. package/scripts/forge_jev/__init__.py +202 -104
  77. package/scripts/forge_jev/addressed.py +171 -0
  78. package/scripts/forge_jev/attribution.py +198 -0
  79. package/scripts/forge_jev/cli.py +460 -382
  80. package/scripts/forge_jev/client.py +155 -77
  81. package/scripts/forge_jev/coupling.py +19 -87
  82. package/scripts/forge_jev/coverage.py +303 -0
  83. package/scripts/forge_jev/findings.py +219 -0
  84. package/scripts/forge_jev/gates.py +225 -27
  85. package/scripts/forge_jev/memory.py +65 -4
  86. package/scripts/forge_jev/message.py +134 -0
  87. package/scripts/forge_jev/plan_gates.py +294 -0
  88. package/scripts/forge_jev/questions.py +173 -313
  89. package/scripts/forge_jev/verify.py +130 -104
  90. package/ui/README.md +41 -10
  91. package/ui/docs/api.md +212 -44
  92. package/ui/forge_ui/checks.py +331 -0
  93. package/ui/forge_ui/control.py +60 -11
  94. package/ui/forge_ui/export.py +8 -3
  95. package/ui/forge_ui/models.py +1 -0
  96. package/ui/forge_ui/reader.py +436 -26
  97. package/ui/forge_ui/server.py +13 -0
  98. package/ui/forge_ui/static/app.js +15 -8
  99. package/ui/forge_ui/static/checksview.js +449 -0
  100. package/ui/forge_ui/static/controls.js +20 -13
  101. package/ui/forge_ui/static/convo.js +11 -2
  102. package/ui/forge_ui/static/findingsview.js +6 -4
  103. package/ui/forge_ui/static/index.html +1 -0
  104. package/ui/forge_ui/static/panel.js +105 -17
  105. package/ui/forge_ui/static/runmodel.js +40 -2
  106. package/ui/forge_ui/static/scene3d.js +2 -15
  107. package/ui/forge_ui/static/settings.js +336 -41
  108. package/ui/forge_ui/static/style.css +72 -7
  109. package/ui/forge_ui/transcripts.py +225 -54
  110. package/references/jev.md +0 -865
  111. package/scripts/forge_jev/backtest.py +0 -322
  112. package/scripts/forge_jev/corpus.py +0 -156
  113. package/scripts/forge_jev/features.py +0 -24
  114. package/scripts/forge_jev/predict.py +0 -204
  115. package/scripts/forge_jev/review.py +0 -73
  116. package/scripts/forge_jev/routing.py +0 -271
  117. package/scripts/forge_jev/subset.py +0 -123
@@ -21,7 +21,11 @@ gh-proman computes, and both tools skip a finding either of them already filed,
21
21
  When the gh-proman skill is configured for the repository, prefer `gh-proman findings`: it also
22
22
  adds the issues to the team's project board with a priority. This command is the fallback.
23
23
 
24
- --json lists every finding in `findings` (fp, severity, origin, plan, task, text, `filed`, `review`, ...). --offline never
24
+ A finding a run's finding sweep (`run --sweep`) fixed stays listed, with `swept` = {task, finding} (null
25
+ otherwise), and is never drafted: the sweep task that merged and whose reviewer marked it FIXED is its record.
26
+ One the sweep did not fix is drafted as before.
27
+
28
+ --json lists every finding in `findings` (fp, severity, origin, plan, task, text, `filed`, `review`, `swept`, ...). --offline never
25
29
  runs `gh` (no filed state, publication of commits judged from local refs only). --only FP[,FP] keeps those
26
30
  fingerprints. --all-runs reads <run> as a repository (or a plan dir naming one) and collects every run in its
27
31
  registry, the newest plan winning for a finding present in several. A caller filing an explicit selection
@@ -45,6 +49,18 @@ holds `<repo_key>.lock` (next to the store, `flock`) from the `gh issue list` lo
45
49
  and each --dismiss/--undismiss holds it around its read-modify-write. A busy lock is retried for 10 s. Listing
46
50
  without --apply takes no lock.
47
51
 
52
+ With the `findings` decision-model gate on or in shadow (`forge decide gate findings`; ready per `forge-jev.py status
53
+ --json`), the findings left to file are sent to `forge-jev.py findings`, once per plan with `--run-dir <plan>`, and each
54
+ finding entry and draft carries `gate` = {mode, duplicate_of, concrete, preselect, reason}. A PLAUSIBLE finding that
55
+ reads as a preference (`concrete` below `findings_concrete`) has `preselect` false and the reason; every other finding
56
+ has it true, and CONFIRMED is never deselected. In `on`, a finding that restates an open issue in other words
57
+ (`dup_p` >= `findings_dup`) leaves the drafts for `comments` [{issue, finding, fp}]; --apply posts each with
58
+ `gh issue comment <url> --body-file`, carrying the finding and its `forge:finding` marker, and records a receipt
59
+ `{fp: {issue, at}}` in `<repo_key>.comments.json` next to the dismissal store (written under the same lock). A comment's
60
+ marker is invisible to the issue-body index, so receipts are honoured with the gate on or off: a finding with one is
61
+ never drafted, filed or commented again, and shows `commented` = {issue, at}. Shadow adds the same fields and changes
62
+ nothing; off or not ready adds none and runs no model request.
63
+
48
64
  Exit codes: 0 ok, 2 usage, `gh` or dismissal store error, 3 busy (another filing or dismissal holds the lock).
49
65
  """
50
66
  from __future__ import annotations
@@ -54,6 +70,7 @@ import contextlib
54
70
  import errno
55
71
  import fcntl
56
72
  import hashlib
73
+ import importlib.util
57
74
  import json
58
75
  import math
59
76
  import os
@@ -103,6 +120,7 @@ TEXT = {
103
120
  "closing_plausible": ["The problem is fixed, or refuted with the reasoning in a comment"],
104
121
  "code": "Code",
105
122
  "unpublished": "(commit not pushed to GitHub yet)",
123
+ "duplicate_comment": "A forge review finding that looks like this issue, in other words:",
106
124
  },
107
125
  "it": {
108
126
  "plausible": "Da verificare: ",
@@ -130,6 +148,7 @@ TEXT = {
130
148
  "closing_plausible": ["Il problema è corretto, oppure smentito con motivazione in un commento"],
131
149
  "code": "Codice",
132
150
  "unpublished": "(commit non ancora pubblicato su GitHub)",
151
+ "duplicate_comment": "Una segnalazione della review di forge che sembra questa issue, con altre parole:",
133
152
  },
134
153
  }
135
154
 
@@ -149,8 +168,8 @@ def read(path: Path) -> str:
149
168
  return ""
150
169
 
151
170
 
152
- def run(cmd, cwd=None, stdin=None, check=True):
153
- env = dict(os.environ, LC_ALL="C", GH_PROMPT_DISABLED="1", GH_NO_UPDATE_NOTIFIER="1")
171
+ def run(cmd, cwd=None, stdin=None, check=True, extra_env=None):
172
+ env = dict(os.environ, LC_ALL="C", GH_PROMPT_DISABLED="1", GH_NO_UPDATE_NOTIFIER="1", **(extra_env or {}))
154
173
  try:
155
174
  res = subprocess.run(cmd, cwd=cwd, input=stdin, capture_output=True, text=True, env=env, timeout=120)
156
175
  except FileNotFoundError:
@@ -173,13 +192,71 @@ def parse_findings(text):
173
192
  loc = m.group(3).strip()
174
193
  link = re.fullmatch(r"\[([^\]]+)\]\([^)]*\)", loc)
175
194
  loc = (link.group(1) if link else loc).strip("` ")
176
- lm = re.match(r"(.+?):(\d+)(?:[-:]\d+)?$", loc)
195
+ # `path:12`, `path:12-14`, `path:12:3`; else a path with more after its first line (a list
196
+ # `:442,674`, a range then a note): the path runs to its first `:<digit>`, the line is that number.
197
+ lm = re.match(r"(.+?):(\d+)(?:[-:]\d+)?$", loc) or re.match(r"([^\s,;()]+?):(\d+)(?=[-:,;\s(]|$)", loc)
177
198
  out.append({"severity": m.group(1), "confidence": m.group(2), "file": lm.group(1) if lm else loc,
178
199
  "line": int(lm.group(2)) if lm else None, "text": clean_markdown(m.group(4)),
179
200
  "raw": f"[{m.group(1)}][{m.group(2)}] {loc} — {m.group(4).strip()}"})
180
201
  return out
181
202
 
182
203
 
204
+ _contract = None
205
+
206
+
207
+ def contract():
208
+ """forge-contract.py, loaded by path: its file name is not importable."""
209
+ global _contract
210
+ if _contract is None:
211
+ spec = importlib.util.spec_from_file_location("forge_contract", Path(__file__).resolve().parent / "forge-contract.py")
212
+ _contract = importlib.util.module_from_spec(spec)
213
+ spec.loader.exec_module(_contract)
214
+ return _contract
215
+
216
+
217
+ _LOCATION_RE = re.compile(r"([^\s:`()\[\]]+):(\d+)(?:[-:]\d+)?")
218
+ _BULLET_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s*")
219
+
220
+
221
+ def parse_known(text):
222
+ """Findings of a known_issues.md as the gate's tolerated blocks, in whatever form the reviewer wrote them."""
223
+ out = []
224
+ for block in contract().parse_findings(text or ""):
225
+ if block.status != "CONFIRMED" or block.severity is None:
226
+ continue
227
+ first = block.text.splitlines()[0]
228
+ # Only the block's own first line: a nested bullet under it is another finding, not this one.
229
+ canonical = parse_findings(first)
230
+ if canonical:
231
+ out.append(canonical[0])
232
+ continue
233
+ body = _BULLET_RE.sub("", first, count=1)
234
+ lm = _LOCATION_RE.search(body)
235
+ if lm:
236
+ file, line = lm.group(1).strip("`*"), int(lm.group(2))
237
+ rest = body[lm.end():]
238
+ else:
239
+ file, line = (body.split() or ["?"])[0].strip("`*:"), None
240
+ rest = body[len(body.split()[0]):] if body.split() else ""
241
+ rest = clean_markdown(rest).strip(" \t—–-:`*")
242
+ sev = f"P{block.severity}"
243
+ loc = f"{file}:{line}" if line else file
244
+ out.append({"severity": sev, "confidence": "CONFIRMED", "file": file, "line": line,
245
+ "text": rest or clean_markdown(body), "raw": f"[{sev}][CONFIRMED] {loc} — {rest}"})
246
+ return out
247
+
248
+
249
+ def effective_threshold(task_dir, plan_dir):
250
+ """The blocking threshold a task ran under: its own qa_threshold, else the plan's, else P2; `none` reads P3."""
251
+ for d in (task_dir, plan_dir):
252
+ value = read(d / "qa_threshold").strip().upper() if d else ""
253
+ if value == "NONE":
254
+ return "P3"
255
+ if value in SEVERITIES:
256
+ return value
257
+ return "P2"
258
+
259
+
183
260
  def reviewer_spec(task_dir: Path):
184
261
  kv = dict(line.split("=", 1) for line in read(task_dir / "qa.resolved").splitlines() if "=" in line)
185
262
  return ":".join(x for x in (kv.get("alias"), kv.get("effort"), kv.get("harness")) if x) or "?"
@@ -191,7 +268,8 @@ _REVIEW_KIND = re.compile(r"(final-review|integrate)-([0-9]+)-([0-9]+)\Z")
191
268
  _COMMIT = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z")
192
269
  # accept appends the reviewer's reply under this heading; findings before it were threshold-tolerated.
193
270
  _ACCEPTED_HEADING = re.compile(
194
- r"^## Accepted by a human despite the reviewer's(?:\s+(\S+))?\s+verdict\s*$", re.M)
271
+ r"^## Accepted by a human despite (?:the reviewer's(?:\s+(\S+))?\s+verdict"
272
+ r"|forge's FAIL \(.*\))\s*$", re.M)
195
273
 
196
274
 
197
275
  def _epoch(text):
@@ -391,13 +469,13 @@ def known_findings(text, task_dir, meta):
391
469
  match = _ACCEPTED_HEADING.search(text)
392
470
  before, after = (text[:match.start()], text[match.end():]) if match else (text, "")
393
471
  found = [{**f, **meta, "origin": "tolerated", "review": None}
394
- for f in parse_findings(before) if f["confidence"] == "CONFIRMED"]
472
+ for f in parse_known(before) if f["confidence"] == "CONFIRMED"]
395
473
  if match:
396
474
  file_status, reason = acceptance_of(task_dir)
397
475
  status = file_status or match.group(1) or "UNKNOWN"
398
476
  found += [{**f, **meta, "origin": "accepted", "review": None,
399
477
  "accepted_status": status, "accepted_reason": reason}
400
- for f in parse_findings(after) if f["confidence"] == "CONFIRMED"]
478
+ for f in parse_known(after) if f["confidence"] == "CONFIRMED"]
401
479
  return found
402
480
 
403
481
 
@@ -426,9 +504,10 @@ def task_findings(task_dir: Path, plan_dir, include_plausible, reviewers, review
426
504
  for f in parse_findings(read(task_dir / "qa.last"))
427
505
  if f["confidence"] == "CONFIRMED" or include_plausible]
428
506
  return found, None
429
- if state not in DONE and status not in DONE:
507
+ solo = plan_dir is None and not state and (task_dir / "known_issues.md").is_file()
508
+ if state not in DONE and status not in DONE and not solo:
430
509
  return [], f"{task}: status {state or 'unknown'}, its findings still block it"
431
- threshold = read(task_dir / "qa_threshold") or (read(plan_dir / "qa_threshold") if plan_dir else "") or "?"
510
+ threshold = effective_threshold(task_dir, plan_dir)
432
511
  meta["threshold"] = threshold
433
512
  found = known_findings(read(task_dir / "known_issues.md"), task_dir, meta)
434
513
  if include_plausible:
@@ -545,8 +624,9 @@ def collect(path: Path, include_plausible, all_runs=False):
545
624
  plan_root = parent.parent
546
625
  else:
547
626
  plan_root = parent
548
- is_review = not is_task and not read(parent / "status")
549
- meta = {"task": None if is_review else parent.name, "threshold": "-" if is_review else read(parent / "qa_threshold") or "?",
627
+ solo_known = plan_root == parent and path.name == "known_issues.md"
628
+ is_review = not is_task and not read(parent / "status") and not solo_known
629
+ meta = {"task": None if is_review else parent.name, "threshold": "-" if is_review else effective_threshold(parent, plan_root if plan_root != parent else None),
550
630
  "commit": read(parent / "merged") or read(parent / "reviewed.commit"),
551
631
  "reviewer": reviewer_spec(parent)}
552
632
  meta["plan"], meta["plan_dir"] = (plan_root.name, str(plan_root))
@@ -584,7 +664,7 @@ def collect(path: Path, include_plausible, all_runs=False):
584
664
  if len(cols) >= 6 and not line.startswith("#"):
585
665
  reviewers[cols[0]] = cols[5]
586
666
  found, note = task_findings(path, plan_dir, include_plausible, reviewers,
587
- review=True if path.parent.name != "tasks" and not read(path / "status") else None)
667
+ review=True if plan_dir and path.parent.name != "tasks" and not read(path / "status") else None)
588
668
  for f in found:
589
669
  f["plan"], f["plan_dir"] = (plan_dir or path).name, str(plan_dir or path)
590
670
  # a task or review dir in a plan: the plan's repository; a solo run dir: its own
@@ -611,6 +691,41 @@ def fingerprint(slug, f):
611
691
  return hashlib.sha1(f"{slug.lower()}|{f['file']}|{norm}".encode("utf-8")).hexdigest()[:12]
612
692
 
613
693
 
694
+ def finding_key(f):
695
+ """A finding's fingerprint without the repository, for what is recorded before any slug is known: the
696
+ finding sweep (forge-sweep.py) keys its findings by it."""
697
+ return fingerprint("", f)
698
+
699
+
700
+ def swept(plan_dir):
701
+ """{finding_key: {task, finding}} for the findings a merged sweep task's reviewer marked FIXED."""
702
+ fixed = {}
703
+ tasks = Path(plan_dir) / "tasks"
704
+ if not tasks.is_dir():
705
+ return fixed
706
+ for task_dir in sorted(tasks.iterdir()):
707
+ if not (task_dir / "merged").exists() or not (task_dir / "sweep.outcome.json").is_file():
708
+ continue
709
+ try:
710
+ items = json.loads(read(task_dir / "sweep.outcome.json"))["findings"]
711
+ except (ValueError, KeyError, TypeError):
712
+ continue
713
+ for item in items if isinstance(items, list) else []:
714
+ if isinstance(item, dict) and item.get("status") == "fixed" and isinstance(item.get("key"), str):
715
+ fixed.setdefault(item["key"], {"task": task_dir.name, "finding": item.get("id")})
716
+ return fixed
717
+
718
+
719
+ def mark_swept(found):
720
+ """Set `swept` on each finding a sweep of its own plan fixed (None otherwise)."""
721
+ plans = {}
722
+ for f in found:
723
+ plan_dir = f.get("plan_dir")
724
+ if plan_dir not in plans:
725
+ plans[plan_dir] = swept(plan_dir) if plan_dir else {}
726
+ f["swept"] = plans[plan_dir].get(finding_key(f)) if f.get("task") else None
727
+
728
+
614
729
  def github_slug(repo_path):
615
730
  res = run(["git", "-C", repo_path, "remote", "get-url", "origin"], check=False)
616
731
  m = re.search(r"github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?/?$", res.stdout.strip())
@@ -803,13 +918,17 @@ def store_dir(create):
803
918
  return path
804
919
 
805
920
 
806
- def load_dismissed(key):
807
- """The repository's dismissals, `{fp: {"at": epoch, "reason": str}}`; empty when it has none yet."""
921
+ def _read_store(name, noun, shape, valid):
922
+ """The parsed JSON of `<findings dir>/<name>`, `{}` when it does not exist yet.
923
+
924
+ Read with the checks every store gets: a regular file (no symlink, FIFO or device), no larger than
925
+ STORE_MAX, a JSON object of fingerprints whose values `valid` accepts. `noun` and `shape` word the errors.
926
+ """
808
927
  base = store_dir(create=False)
809
928
  if base is None:
810
929
  return {}
811
- path = base / f"{key}.json"
812
- not_regular = f"{path}: the dismissal store must be a regular file, not a symlink or special file"
930
+ path = base / name
931
+ not_regular = f"{path}: the {noun} must be a regular file, not a symlink or special file"
813
932
  try:
814
933
  if not stat.S_ISREG(os.lstat(path).st_mode):
815
934
  raise Fail(not_regular)
@@ -821,24 +940,22 @@ def load_dismissed(key):
821
940
  except FileNotFoundError:
822
941
  return {}
823
942
  except OSError as exc:
824
- raise Fail(f"{path}: cannot read the dismissal store: {exc.strerror}")
943
+ raise Fail(f"{path}: cannot read the {noun}: {exc.strerror}")
825
944
  try:
826
945
  data = json.loads(raw.decode("utf-8")) if len(raw) <= STORE_MAX else None
827
946
  except ValueError:
828
947
  data = None
829
- if not (isinstance(data, dict) and all(
830
- FP_RE.fullmatch(fp) and isinstance(v, dict) and isinstance(v.get("reason"), str)
831
- and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool) for fp, v in data.items())):
832
- raise Fail(f"{path}: not a dismissal store ({{fingerprint: {{at, reason}}}}); fix or remove it")
833
- return {fp: {"at": v["at"], "reason": v["reason"]} for fp, v in data.items()}
948
+ if not (isinstance(data, dict) and all(FP_RE.fullmatch(fp) and valid(v) for fp, v in data.items())):
949
+ raise Fail(f"{path}: not a {noun} ({shape}); fix or remove it")
950
+ return data
834
951
 
835
952
 
836
- def save_dismissed(key, data):
837
- """Replace the store atomically: a temp file in the same directory, fsynced, then renamed over it."""
953
+ def _write_store(name, noun, data):
954
+ """Replace `<findings dir>/<name>` atomically: a temp file in the same directory, fsynced, then renamed over it."""
838
955
  base = store_dir(create=True)
839
- path = base / f"{key}.json"
956
+ path = base / name
840
957
  try:
841
- fd, tmp = tempfile.mkstemp(prefix=f".{key}.", suffix=".tmp", dir=base)
958
+ fd, tmp = tempfile.mkstemp(prefix=f".{name.removesuffix('.json')}.", suffix=".tmp", dir=base)
842
959
  try:
843
960
  with os.fdopen(fd, "w", encoding="utf-8") as fh:
844
961
  json.dump(data, fh, indent=2, sort_keys=True, ensure_ascii=False)
@@ -851,7 +968,34 @@ def save_dismissed(key, data):
851
968
  os.unlink(tmp)
852
969
  raise
853
970
  except OSError as exc:
854
- raise Fail(f"{path}: cannot write the dismissal store: {exc.strerror}")
971
+ raise Fail(f"{path}: cannot write the {noun}: {exc.strerror}")
972
+
973
+ def load_dismissed(key):
974
+ """The repository's dismissals, `{fp: {"at": epoch, "reason": str}}`; empty when it has none yet."""
975
+ data = _read_store(f"{key}.json", "dismissal store", "{fingerprint: {at, reason}}",
976
+ lambda v: isinstance(v, dict) and isinstance(v.get("reason"), str)
977
+ and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool))
978
+ return {fp: {"at": v["at"], "reason": v["reason"]} for fp, v in data.items()}
979
+
980
+
981
+ def save_dismissed(key, data):
982
+ _write_store(f"{key}.json", "dismissal store", data)
983
+
984
+
985
+ def load_comments(key):
986
+ """The repository's comment receipts, `{fp: {"issue": url, "at": epoch}}`; empty when it has none yet.
987
+
988
+ A comment's fingerprint marker is invisible to the issue-body index that guards filing, so this record is
989
+ what keeps one duplicate from being commented on every run. It sits next to the dismissal store.
990
+ """
991
+ data = _read_store(f"{key}.comments.json", "comment-receipt store", "{fingerprint: {issue, at}}",
992
+ lambda v: isinstance(v, dict) and isinstance(v.get("issue"), str)
993
+ and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool))
994
+ return {fp: {"issue": v["issue"], "at": v["at"]} for fp, v in data.items()}
995
+
996
+
997
+ def save_comments(key, data):
998
+ _write_store(f"{key}.comments.json", "comment-receipt store", data)
855
999
 
856
1000
 
857
1001
  @contextlib.contextmanager
@@ -906,6 +1050,152 @@ def dismiss(args):
906
1050
  return {"ok": True, "dismissed": args.dismiss, "undismissed": args.undismiss, "warnings": warnings}
907
1051
 
908
1052
 
1053
+ # ---------------------------------------------------------------------------------------------- findings gate
1054
+
1055
+ GATE_SITE = "jev-findings"
1056
+ GATE_CANDIDATES = 5 # open issues with the most words in common with a finding, besides its same-title one
1057
+ GATE_DEFAULTS = {"findings_dup": 0.85, "findings_concrete": 0.50}
1058
+ _CONTENT_WORD_RE = re.compile(r"[a-z]{4,}")
1059
+
1060
+
1061
+ def content_words(text):
1062
+ return set(_CONTENT_WORD_RE.findall((text or "").lower()))
1063
+
1064
+
1065
+ def number(value):
1066
+ """`value` when it is a finite number that is not a bool, else None."""
1067
+ ok = isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
1068
+ return float(value) if ok else None
1069
+
1070
+
1071
+ def gate_env(cwd):
1072
+ """FORGE_DECIDE_REPO for the gate subprocesses: the repository's top level, as forge_decide_env exports it.
1073
+
1074
+ `status` has no --repo, so without it the repo level of the configuration (.forge/decide.json, the repo profile)
1075
+ would not apply to the readiness this script reads, while the verb, given --repo, would apply it.
1076
+ """
1077
+ res = run(["git", "rev-parse", "--show-toplevel"], cwd=cwd, check=False)
1078
+ top = res.stdout.strip() if res.returncode == 0 else ""
1079
+ return {"FORGE_DECIDE_REPO": top or os.path.realpath(cwd)}
1080
+
1081
+
1082
+ def findings_gate(cwd):
1083
+ """(mode, {threshold: value}) when the findings gate is shadow or on and can be asked, else None.
1084
+
1085
+ Readiness is `forge-jev.py status --json` -> gates.findings.ready, the way the shell reads it, so the run
1086
+ flags, the kill switch, the privacy floor and a missing key all count. A gate that cannot answer behaves as
1087
+ off: any failure here is None, and nothing about filing changes.
1088
+ """
1089
+ here = Path(__file__).resolve().parent
1090
+ try:
1091
+ env = gate_env(cwd)
1092
+ res = run([sys.executable, str(here / "forge-jev.py"), "status", "--json"], cwd=cwd, check=False, extra_env=env)
1093
+ found = json.loads(res.stdout)["gates"]["findings"] if res.returncode == 0 else None
1094
+ if not (isinstance(found, dict) and found.get("ready") is True and found.get("mode") in ("shadow", "on")):
1095
+ return None
1096
+ limits = dict(GATE_DEFAULTS)
1097
+ try:
1098
+ from forge_jev import threshold, use_repo
1099
+ use_repo(env["FORGE_DECIDE_REPO"])
1100
+ limits = {name: threshold(name, site=GATE_SITE) for name in GATE_DEFAULTS}
1101
+ except Exception: # a threshold that cannot be read keeps its default
1102
+ pass
1103
+ return found["mode"], limits
1104
+ except (Fail, OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
1105
+ return None
1106
+
1107
+
1108
+ def ask_findings(cwd, todo, open_issues, open_titles, lang):
1109
+ """{fp: {duplicate_of, dup_p, concrete}} from `forge-jev.py findings`, one subprocess per plan.
1110
+
1111
+ Each finding is compared with the open issue that has its title, if one does, and with the open issues
1112
+ sharing the most content words with it. A plan whose call fails (no answer, bad output) adds nothing.
1113
+ """
1114
+ here = Path(__file__).resolve().parent
1115
+ words = {i["number"]: content_words(f"{i.get('title')} {i.get('body')}") for i in open_issues}
1116
+ by_url = {i["url"]: i for i in open_issues}
1117
+ plans = {}
1118
+ for f in todo:
1119
+ plans.setdefault(f["plan_dir"], []).append(f)
1120
+ answers, env = {}, gate_env(cwd)
1121
+ for plan_dir, items in plans.items():
1122
+ candidates, entries = {}, []
1123
+ for f in items:
1124
+ chosen = []
1125
+ titled = by_url.get(open_titles.get(norm_title(title_for(f, lang))))
1126
+ if titled:
1127
+ chosen.append(titled)
1128
+ mine = content_words(f["text"])
1129
+ ranked = sorted(((len(mine & words[i["number"]]), i["number"], i) for i in open_issues if i is not titled),
1130
+ key=lambda r: (-r[0], r[1]))
1131
+ chosen += [i for shared, _n, i in ranked if shared][:GATE_CANDIDATES]
1132
+ for i in chosen:
1133
+ candidates.setdefault(str(i["number"]), {"id": str(i["number"]), "title": i.get("title") or "",
1134
+ "body": i.get("body") or ""})
1135
+ entries.append({"fp": f["fp"], "plan": f["plan"], "severity": f["severity"], "status": f["confidence"],
1136
+ "location": f"{f['file']}:{f['line']}" if f["line"] else f["file"], "text": f["text"],
1137
+ "candidates": [str(i["number"]) for i in chosen]})
1138
+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") as fh:
1139
+ json.dump({"findings": entries, "candidates": list(candidates.values())}, fh)
1140
+ try:
1141
+ res = run([sys.executable, str(here / "forge-jev.py"), "findings", "--repo", cwd, "--input", fh.name,
1142
+ "--run-dir", plan_dir], cwd=cwd, check=False, extra_env=env)
1143
+ rows = json.loads(res.stdout) if res.returncode == 0 else []
1144
+ except (ValueError, Fail, OSError, subprocess.SubprocessError):
1145
+ rows = []
1146
+ finally:
1147
+ os.unlink(fh.name)
1148
+ for row in rows if isinstance(rows, list) else []:
1149
+ if isinstance(row, dict) and isinstance(row.get("fp"), str):
1150
+ answers[row["fp"]] = row
1151
+ return answers
1152
+
1153
+
1154
+ def gate_fields(f, row, mode, limits, urls):
1155
+ """The `gate` object of one finding from its answer row, as the module docstring of the verb defines it."""
1156
+ dup_p, concrete = number(row.get("dup_p")), number(row.get("concrete"))
1157
+ duplicate = urls.get(str(row.get("duplicate_of"))) if dup_p is not None and dup_p >= limits["findings_dup"] else None
1158
+ deselect = f["confidence"] == "PLAUSIBLE" and concrete is not None and concrete < limits["findings_concrete"]
1159
+ return {"mode": mode, "duplicate_of": duplicate, "concrete": concrete, "preselect": not deselect,
1160
+ "reason": f"reads as a preference, not a defect (p={concrete:.2f})" if deselect else None}
1161
+
1162
+
1163
+ def draft_gate(fields):
1164
+ """The gate object of a draft that groups several findings: pre-selected when any of them is."""
1165
+ kept = [g for g in fields if g["preselect"]]
1166
+ levels = [g["concrete"] for g in fields if g["concrete"] is not None]
1167
+ return {"mode": fields[0]["mode"], "duplicate_of": next((g["duplicate_of"] for g in fields if g["duplicate_of"]), None),
1168
+ "concrete": min(levels) if levels else None, "preselect": bool(kept),
1169
+ "reason": None if kept else fields[0]["reason"]}
1170
+
1171
+
1172
+ def comment_body(f, lang):
1173
+ return "\n".join([TEXT[lang]["duplicate_comment"], "", f"> {escape(f['raw'])}", "",
1174
+ f"<!-- forge:finding fp={f['fp']} source=forge:{f['plan']}/{f['task'] or 'final-review'} -->"])
1175
+
1176
+
1177
+ def post_comments(key, comments, by_fp, lang):
1178
+ """Comment on the issue each reworded duplicate restates, and record a receipt for each: the marker in a
1179
+ comment is invisible to the issue-body index, so without the receipt the next run would comment again.
1180
+ Runs under the repository lock `--apply` holds. A comment that fails is reported and gets no receipt."""
1181
+ receipts = load_comments(key)
1182
+ done = []
1183
+ for c in comments:
1184
+ with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as fh:
1185
+ fh.write(comment_body(by_fp[c["fp"]], lang))
1186
+ try:
1187
+ run(["gh", "issue", "comment", c["issue"], "--body-file", fh.name])
1188
+ except Fail as exc:
1189
+ done.append({**c, "error": str(exc)})
1190
+ continue
1191
+ finally:
1192
+ os.unlink(fh.name)
1193
+ receipts[c["fp"]] = {"issue": c["issue"], "at": int(time.time())}
1194
+ save_comments(key, receipts)
1195
+ done.append(dict(c))
1196
+ return done
1197
+
1198
+
909
1199
  # ---------------------------------------------------------------------------------------------- main
910
1200
 
911
1201
  def split_fps(values):
@@ -984,18 +1274,22 @@ def main(argv=None):
984
1274
  return 0
985
1275
 
986
1276
 
987
- def finding_entry(f, filed=None, dismissed=None):
988
- return {"fp": f["fp"], "severity": f["severity"], "confidence": f["confidence"], "origin": f["origin"],
1277
+ def finding_entry(f, filed=None, dismissed=None, commented=None):
1278
+ entry = {"fp": f["fp"], "severity": f["severity"], "confidence": f["confidence"], "origin": f["origin"],
989
1279
  "plan": f["plan"], "plan_dir": f["plan_dir"], "task": f["task"], "file": f["file"],
990
1280
  "summary": (f["text"].splitlines() or [""])[0][:160], "text": f["text"],
991
1281
  "reviewer": f["reviewer"], "commit": f.get("commit") or "",
992
- "review": f.get("review"),
1282
+ "review": f.get("review"), "swept": f.get("swept"),
993
1283
  "filed": {"url": filed["url"], "state": filed["state"]} if filed else None,
994
1284
  "dismissed": dismissed}
1285
+ if commented:
1286
+ entry["commented"] = commented # only a finding with a receipt has the key: the rest is as before
1287
+ return entry
995
1288
 
996
1289
 
997
1290
  def file_findings(args):
998
1291
  meta, found, notes = collect(Path(args.run), args.include_plausible, args.all_runs)
1292
+ mark_swept(found)
999
1293
  repo_path, warnings = run_repository(meta)
1000
1294
  slug = args.repo or github_slug(repo_path)
1001
1295
  if not slug:
@@ -1011,7 +1305,9 @@ def file_findings(args):
1011
1305
 
1012
1306
  def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1013
1307
  offline = args.offline
1014
- dismissed = load_dismissed(repo_key(repo_path))
1308
+ store_key = repo_key(repo_path)
1309
+ dismissed = load_dismissed(store_key)
1310
+ receipts = load_comments(store_key)
1015
1311
  issues = [] if offline else existing_issues(slug)
1016
1312
  filed = {fp: issue for issue in issues for fp in FP_MARK_RE.findall(issue.get("body") or "")}
1017
1313
  only = set(args.only)
@@ -1025,18 +1321,40 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1025
1321
  seen.add(f["fp"])
1026
1322
  issue = filed.get(f["fp"])
1027
1323
  mark = dismissed.get(f["fp"])
1028
- entries.append(finding_entry(f, issue, mark))
1324
+ receipt = receipts.get(f["fp"])
1325
+ entries.append(finding_entry(f, issue, mark, receipt))
1029
1326
  if issue:
1030
1327
  already.append({"finding": f["raw"], "issue": issue["url"], "state": issue["state"]})
1328
+ elif receipt: # commented on an issue as a duplicate: as good as filed
1329
+ state = next((i["state"] for i in issues if i["url"] == receipt["issue"]), "UNKNOWN")
1330
+ already.append({"finding": f["raw"], "issue": receipt["issue"], "state": state})
1331
+ elif f.get("swept"):
1332
+ continue # fixed in the run by its finding sweep
1031
1333
  elif not mark or args.include_dismissed:
1032
1334
  todo.append(f)
1033
1335
  notes = notes + [f"--only {fp}: no such open finding" for fp in args.only if fp not in known]
1034
1336
  entries.sort(key=lambda e: SEVERITIES.index(e["severity"]))
1337
+ open_issues = [i for i in issues if i.get("state") == "OPEN"]
1338
+ open_titles = {norm_title(i["title"]): i["url"] for i in open_issues}
1339
+ gates, comments = {}, None
1340
+ ready = findings_gate(repo_path) if todo else None
1341
+ if ready:
1342
+ mode, limits = ready
1343
+ urls = {str(i["number"]): i["url"] for i in open_issues}
1344
+ answers = ask_findings(repo_path, todo, open_issues, open_titles, args.lang)
1345
+ gates = {f["fp"]: gate_fields(f, answers[f["fp"]], mode, limits, urls) for f in todo if f["fp"] in answers}
1346
+ for entry in entries:
1347
+ if entry["fp"] in gates:
1348
+ entry["gate"] = gates[entry["fp"]]
1349
+ comments = [] if gates else None
1350
+ if mode == "on" and gates:
1351
+ comments = [{"issue": gates[f["fp"]]["duplicate_of"], "finding": f["raw"], "fp": f["fp"]}
1352
+ for f in todo if f["fp"] in gates and gates[f["fp"]]["duplicate_of"]]
1353
+ todo = [f for f in todo if f["fp"] not in {c["fp"] for c in comments}]
1035
1354
  keyed = {}
1036
1355
  for f in todo:
1037
1356
  key = id(f) if args.group == "finding" else (f["plan"], f["origin"], f["task"] if args.group == "task" else "")
1038
1357
  keyed.setdefault(key, []).append(f)
1039
- open_titles = {norm_title(i["title"]): i["url"] for i in issues if i.get("state") == "OPEN"}
1040
1358
  t = TEXT[args.lang]
1041
1359
  drafts = []
1042
1360
  for items in keyed.values():
@@ -1055,17 +1373,25 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1055
1373
  "findings": [f["raw"] for f in items], "fingerprints": [f["fp"] for f in items],
1056
1374
  "same_title": None if offline else open_titles.get(norm_title(title)),
1057
1375
  "body": body_for(slug, repo_path if meta["repo_path"] else None, items, args.lang, offline)})
1376
+ if any(f["fp"] in gates for f in items):
1377
+ drafts[-1]["gate"] = draft_gate([gates[f["fp"]] for f in items if f["fp"] in gates])
1058
1378
  drafts.sort(key=lambda d: SEVERITIES.index(d["severity"]))
1059
1379
  out = {"repo": slug, "plan": meta["plan"], "notes": notes, "warnings": warnings,
1060
1380
  "summary": {"findings": len(seen), "already_filed": len(already),
1061
- "dismissed": sum(1 for e in entries if e["dismissed"]), "drafts": len(drafts),
1381
+ "dismissed": sum(1 for e in entries if e["dismissed"]),
1382
+ "swept": sum(1 for e in entries if e["swept"]), "drafts": len(drafts),
1062
1383
  **{o: sum(1 for f in todo if f["origin"] == o)
1063
1384
  for o in ("tolerated", "accepted", "review", "plausible")}},
1064
1385
  "findings": entries, "already_filed": already, "drafts": drafts}
1386
+ if comments is not None:
1387
+ out["comments"] = comments
1065
1388
  if args.apply:
1066
1389
  out["created"] = create(slug, drafts, args)
1067
1390
  for d in drafts:
1068
1391
  d.pop("body")
1392
+ if comments:
1393
+ by_fp = {f["fp"]: f for f in found}
1394
+ out["commented"] = post_comments(store_key, comments, by_fp, args.lang)
1069
1395
  return out
1070
1396
 
1071
1397
 
@@ -1103,6 +1429,7 @@ def create(slug, drafts, args):
1103
1429
  def print_human(out, applied):
1104
1430
  s = out["summary"]
1105
1431
  dismissed = f", {s['dismissed']} dismissed" if s["dismissed"] else ""
1432
+ dismissed += f", {s['swept']} fixed by the run's finding sweep" if s.get("swept") else ""
1106
1433
  print(f"{out['repo']} · run {out['plan']}: {s['findings']} finding(s), {s['already_filed']} already filed{dismissed}, "
1107
1434
  f"{s['drafts']} draft(s) ({s['tolerated']} tolerated, {s['accepted']} accepted, "
1108
1435
  f"{s['review']} review, {s['plausible']} plausible)")
@@ -1113,6 +1440,8 @@ def print_human(out, applied):
1113
1440
  for a in out["already_filed"]:
1114
1441
  print(f" filed {a['issue']} ({a['state'].lower()}): {a['finding'][:100]}")
1115
1442
  if applied:
1443
+ for c in out.get("commented", []):
1444
+ print(f" comment failed {c['issue']}: {c['error']}" if "error" in c else f" commented {c['issue']}")
1116
1445
  for c in out["created"]:
1117
1446
  if "note" in c:
1118
1447
  print(f" note {c['note']}")
@@ -1121,12 +1450,15 @@ def print_human(out, applied):
1121
1450
  else:
1122
1451
  print(f" skipped {c['title']}: {c['skipped']}{' ' + c['issue'] if c.get('issue') else ''}")
1123
1452
  return
1453
+ for c in out.get("comments", []):
1454
+ print(f" comment {c['issue']}: {c['finding'][:100]}")
1124
1455
  outdated = {e["fp"] for e in out["findings"] if (e.get("review") or {}).get("outdated") is True}
1125
1456
  for d in out["drafts"]:
1126
1457
  flag = f" (open issue with the same title: {d['same_title']})" if d["same_title"] else ""
1127
1458
  mark = " (outdated review)" if any(fp in outdated for fp in d["fingerprints"]) else ""
1128
- print(f" draft {d['title']}{mark}{flag}")
1129
- if out["drafts"]:
1459
+ skip = f" (not pre-selected: {d['gate']['reason']})" if d.get("gate") and not d["gate"]["preselect"] else ""
1460
+ print(f" draft {d['title']}{mark}{flag}{skip}")
1461
+ if out["drafts"] or out.get("comments"):
1130
1462
  print("Nothing created: add --apply to file these.")
1131
1463
 
1132
1464