@giamme/forge 0.12.1 → 0.13.1

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 (111) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +29 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +12 -6
  7. package/docs/commands.md +179 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +14 -4
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +49 -20
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +39 -13
  17. package/references/decision-models.md +763 -0
  18. package/references/decompose.md +166 -29
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/scripts/forge-artifact.sh +30 -4
  23. package/scripts/forge-config.py +238 -29
  24. package/scripts/forge-contract.py +95 -56
  25. package/scripts/forge-control.py +40 -9
  26. package/scripts/forge-decide.py +6 -0
  27. package/scripts/forge-dispatch.sh +38 -16
  28. package/scripts/forge-fail-first.py +2 -2
  29. package/scripts/forge-gate-addressed.sh +40 -0
  30. package/scripts/forge-gate-message.sh +64 -0
  31. package/scripts/forge-issues.py +321 -33
  32. package/scripts/forge-jev-options.sh +269 -42
  33. package/scripts/forge-lib-attribute.sh +447 -0
  34. package/scripts/forge-lib-gates.sh +32 -0
  35. package/scripts/forge-lib-plans.sh +22 -6
  36. package/scripts/forge-lib-review.sh +22 -17
  37. package/scripts/forge-lib-task.sh +217 -38
  38. package/scripts/forge-lib-verify.sh +45 -8
  39. package/scripts/forge-memory.sh +3 -3
  40. package/scripts/forge-parallel-options.sh +18 -5
  41. package/scripts/forge-parallel.sh +457 -303
  42. package/scripts/forge-plan-check.py +35 -1
  43. package/scripts/forge-pre-review.py +437 -0
  44. package/scripts/forge-prompt.py +25 -5
  45. package/scripts/forge-route.py +2 -2
  46. package/scripts/forge-runtime.py +10 -4
  47. package/scripts/forge-schedule.py +21 -5
  48. package/scripts/forge-shadow.py +2 -2
  49. package/scripts/forge-solo.sh +39 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge-ui-options.sh +25 -0
  52. package/scripts/forge_dataset/cli.py +12 -6
  53. package/scripts/forge_dataset/export.py +140 -84
  54. package/scripts/forge_dataset/harvest.py +33 -5
  55. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  56. package/scripts/forge_decide/__init__.py +141 -0
  57. package/scripts/forge_decide/budget.py +180 -0
  58. package/scripts/forge_decide/cache.py +66 -0
  59. package/scripts/forge_decide/cli.py +953 -0
  60. package/scripts/forge_decide/doctor.py +270 -0
  61. package/scripts/forge_decide/label_addressed.py +75 -0
  62. package/scripts/forge_decide/label_attribution.py +62 -0
  63. package/scripts/forge_decide/label_coverage.py +81 -0
  64. package/scripts/forge_decide/label_message.py +38 -0
  65. package/scripts/forge_decide/label_prompt.py +139 -0
  66. package/scripts/forge_decide/labels.py +328 -0
  67. package/scripts/forge_decide/metrics.py +125 -0
  68. package/scripts/forge_decide/migrate.py +226 -0
  69. package/scripts/forge_decide/providers.py +292 -0
  70. package/scripts/forge_decide/replay.py +350 -0
  71. package/scripts/forge_decide/report.py +382 -0
  72. package/scripts/forge_decide/resolve.py +397 -0
  73. package/scripts/forge_decide/sites.py +377 -0
  74. package/scripts/forge_jev/__init__.py +202 -104
  75. package/scripts/forge_jev/addressed.py +171 -0
  76. package/scripts/forge_jev/attribution.py +198 -0
  77. package/scripts/forge_jev/cli.py +460 -382
  78. package/scripts/forge_jev/client.py +155 -77
  79. package/scripts/forge_jev/coupling.py +19 -87
  80. package/scripts/forge_jev/coverage.py +303 -0
  81. package/scripts/forge_jev/findings.py +219 -0
  82. package/scripts/forge_jev/gates.py +225 -27
  83. package/scripts/forge_jev/memory.py +65 -4
  84. package/scripts/forge_jev/message.py +134 -0
  85. package/scripts/forge_jev/plan_gates.py +294 -0
  86. package/scripts/forge_jev/questions.py +173 -313
  87. package/scripts/forge_jev/verify.py +130 -104
  88. package/ui/README.md +2 -2
  89. package/ui/docs/api.md +92 -39
  90. package/ui/forge_ui/control.py +71 -14
  91. package/ui/forge_ui/export.py +2 -1
  92. package/ui/forge_ui/models.py +17 -16
  93. package/ui/forge_ui/reader.py +132 -21
  94. package/ui/forge_ui/repos.py +428 -0
  95. package/ui/forge_ui/static/app.js +24 -5
  96. package/ui/forge_ui/static/cloudmodel.js +8 -5
  97. package/ui/forge_ui/static/controls.js +20 -13
  98. package/ui/forge_ui/static/modelstats.js +12 -8
  99. package/ui/forge_ui/static/panel.js +63 -17
  100. package/ui/forge_ui/static/runmodel.js +48 -7
  101. package/ui/forge_ui/static/scene3d.js +2 -15
  102. package/ui/forge_ui/static/settings.js +481 -68
  103. package/ui/forge_ui/static/style.css +56 -9
  104. package/references/jev.md +0 -865
  105. package/scripts/forge_jev/backtest.py +0 -322
  106. package/scripts/forge_jev/corpus.py +0 -156
  107. package/scripts/forge_jev/features.py +0 -24
  108. package/scripts/forge_jev/predict.py +0 -204
  109. package/scripts/forge_jev/review.py +0 -73
  110. package/scripts/forge_jev/routing.py +0 -271
  111. package/scripts/forge_jev/subset.py +0 -123
@@ -49,6 +49,18 @@ holds `<repo_key>.lock` (next to the store, `flock`) from the `gh issue list` lo
49
49
  and each --dismiss/--undismiss holds it around its read-modify-write. A busy lock is retried for 10 s. Listing
50
50
  without --apply takes no lock.
51
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
+
52
64
  Exit codes: 0 ok, 2 usage, `gh` or dismissal store error, 3 busy (another filing or dismissal holds the lock).
53
65
  """
54
66
  from __future__ import annotations
@@ -58,6 +70,7 @@ import contextlib
58
70
  import errno
59
71
  import fcntl
60
72
  import hashlib
73
+ import importlib.util
61
74
  import json
62
75
  import math
63
76
  import os
@@ -107,6 +120,7 @@ TEXT = {
107
120
  "closing_plausible": ["The problem is fixed, or refuted with the reasoning in a comment"],
108
121
  "code": "Code",
109
122
  "unpublished": "(commit not pushed to GitHub yet)",
123
+ "duplicate_comment": "A forge review finding that looks like this issue, in other words:",
110
124
  },
111
125
  "it": {
112
126
  "plausible": "Da verificare: ",
@@ -134,6 +148,7 @@ TEXT = {
134
148
  "closing_plausible": ["Il problema è corretto, oppure smentito con motivazione in un commento"],
135
149
  "code": "Codice",
136
150
  "unpublished": "(commit non ancora pubblicato su GitHub)",
151
+ "duplicate_comment": "Una segnalazione della review di forge che sembra questa issue, con altre parole:",
137
152
  },
138
153
  }
139
154
 
@@ -153,8 +168,8 @@ def read(path: Path) -> str:
153
168
  return ""
154
169
 
155
170
 
156
- def run(cmd, cwd=None, stdin=None, check=True):
157
- 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 {}))
158
173
  try:
159
174
  res = subprocess.run(cmd, cwd=cwd, input=stdin, capture_output=True, text=True, env=env, timeout=120)
160
175
  except FileNotFoundError:
@@ -177,13 +192,71 @@ def parse_findings(text):
177
192
  loc = m.group(3).strip()
178
193
  link = re.fullmatch(r"\[([^\]]+)\]\([^)]*\)", loc)
179
194
  loc = (link.group(1) if link else loc).strip("` ")
180
- 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)
181
198
  out.append({"severity": m.group(1), "confidence": m.group(2), "file": lm.group(1) if lm else loc,
182
199
  "line": int(lm.group(2)) if lm else None, "text": clean_markdown(m.group(4)),
183
200
  "raw": f"[{m.group(1)}][{m.group(2)}] {loc} — {m.group(4).strip()}"})
184
201
  return out
185
202
 
186
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
+
187
260
  def reviewer_spec(task_dir: Path):
188
261
  kv = dict(line.split("=", 1) for line in read(task_dir / "qa.resolved").splitlines() if "=" in line)
189
262
  return ":".join(x for x in (kv.get("alias"), kv.get("effort"), kv.get("harness")) if x) or "?"
@@ -195,7 +268,8 @@ _REVIEW_KIND = re.compile(r"(final-review|integrate)-([0-9]+)-([0-9]+)\Z")
195
268
  _COMMIT = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z")
196
269
  # accept appends the reviewer's reply under this heading; findings before it were threshold-tolerated.
197
270
  _ACCEPTED_HEADING = re.compile(
198
- 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)
199
273
 
200
274
 
201
275
  def _epoch(text):
@@ -395,13 +469,13 @@ def known_findings(text, task_dir, meta):
395
469
  match = _ACCEPTED_HEADING.search(text)
396
470
  before, after = (text[:match.start()], text[match.end():]) if match else (text, "")
397
471
  found = [{**f, **meta, "origin": "tolerated", "review": None}
398
- for f in parse_findings(before) if f["confidence"] == "CONFIRMED"]
472
+ for f in parse_known(before) if f["confidence"] == "CONFIRMED"]
399
473
  if match:
400
474
  file_status, reason = acceptance_of(task_dir)
401
475
  status = file_status or match.group(1) or "UNKNOWN"
402
476
  found += [{**f, **meta, "origin": "accepted", "review": None,
403
477
  "accepted_status": status, "accepted_reason": reason}
404
- for f in parse_findings(after) if f["confidence"] == "CONFIRMED"]
478
+ for f in parse_known(after) if f["confidence"] == "CONFIRMED"]
405
479
  return found
406
480
 
407
481
 
@@ -430,9 +504,10 @@ def task_findings(task_dir: Path, plan_dir, include_plausible, reviewers, review
430
504
  for f in parse_findings(read(task_dir / "qa.last"))
431
505
  if f["confidence"] == "CONFIRMED" or include_plausible]
432
506
  return found, None
433
- 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:
434
509
  return [], f"{task}: status {state or 'unknown'}, its findings still block it"
435
- 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)
436
511
  meta["threshold"] = threshold
437
512
  found = known_findings(read(task_dir / "known_issues.md"), task_dir, meta)
438
513
  if include_plausible:
@@ -549,8 +624,9 @@ def collect(path: Path, include_plausible, all_runs=False):
549
624
  plan_root = parent.parent
550
625
  else:
551
626
  plan_root = parent
552
- is_review = not is_task and not read(parent / "status")
553
- 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),
554
630
  "commit": read(parent / "merged") or read(parent / "reviewed.commit"),
555
631
  "reviewer": reviewer_spec(parent)}
556
632
  meta["plan"], meta["plan_dir"] = (plan_root.name, str(plan_root))
@@ -588,7 +664,7 @@ def collect(path: Path, include_plausible, all_runs=False):
588
664
  if len(cols) >= 6 and not line.startswith("#"):
589
665
  reviewers[cols[0]] = cols[5]
590
666
  found, note = task_findings(path, plan_dir, include_plausible, reviewers,
591
- 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)
592
668
  for f in found:
593
669
  f["plan"], f["plan_dir"] = (plan_dir or path).name, str(plan_dir or path)
594
670
  # a task or review dir in a plan: the plan's repository; a solo run dir: its own
@@ -842,13 +918,17 @@ def store_dir(create):
842
918
  return path
843
919
 
844
920
 
845
- def load_dismissed(key):
846
- """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
+ """
847
927
  base = store_dir(create=False)
848
928
  if base is None:
849
929
  return {}
850
- path = base / f"{key}.json"
851
- 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"
852
932
  try:
853
933
  if not stat.S_ISREG(os.lstat(path).st_mode):
854
934
  raise Fail(not_regular)
@@ -860,24 +940,22 @@ def load_dismissed(key):
860
940
  except FileNotFoundError:
861
941
  return {}
862
942
  except OSError as exc:
863
- raise Fail(f"{path}: cannot read the dismissal store: {exc.strerror}")
943
+ raise Fail(f"{path}: cannot read the {noun}: {exc.strerror}")
864
944
  try:
865
945
  data = json.loads(raw.decode("utf-8")) if len(raw) <= STORE_MAX else None
866
946
  except ValueError:
867
947
  data = None
868
- if not (isinstance(data, dict) and all(
869
- FP_RE.fullmatch(fp) and isinstance(v, dict) and isinstance(v.get("reason"), str)
870
- and isinstance(v.get("at"), (int, float)) and not isinstance(v["at"], bool) for fp, v in data.items())):
871
- raise Fail(f"{path}: not a dismissal store ({{fingerprint: {{at, reason}}}}); fix or remove it")
872
- 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
873
951
 
874
952
 
875
- def save_dismissed(key, data):
876
- """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."""
877
955
  base = store_dir(create=True)
878
- path = base / f"{key}.json"
956
+ path = base / name
879
957
  try:
880
- 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)
881
959
  try:
882
960
  with os.fdopen(fd, "w", encoding="utf-8") as fh:
883
961
  json.dump(data, fh, indent=2, sort_keys=True, ensure_ascii=False)
@@ -890,7 +968,34 @@ def save_dismissed(key, data):
890
968
  os.unlink(tmp)
891
969
  raise
892
970
  except OSError as exc:
893
- 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)
894
999
 
895
1000
 
896
1001
  @contextlib.contextmanager
@@ -945,6 +1050,152 @@ def dismiss(args):
945
1050
  return {"ok": True, "dismissed": args.dismiss, "undismissed": args.undismiss, "warnings": warnings}
946
1051
 
947
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
+
948
1199
  # ---------------------------------------------------------------------------------------------- main
949
1200
 
950
1201
  def split_fps(values):
@@ -1023,14 +1274,17 @@ def main(argv=None):
1023
1274
  return 0
1024
1275
 
1025
1276
 
1026
- def finding_entry(f, filed=None, dismissed=None):
1027
- 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"],
1028
1279
  "plan": f["plan"], "plan_dir": f["plan_dir"], "task": f["task"], "file": f["file"],
1029
1280
  "summary": (f["text"].splitlines() or [""])[0][:160], "text": f["text"],
1030
1281
  "reviewer": f["reviewer"], "commit": f.get("commit") or "",
1031
1282
  "review": f.get("review"), "swept": f.get("swept"),
1032
1283
  "filed": {"url": filed["url"], "state": filed["state"]} if filed else None,
1033
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
1034
1288
 
1035
1289
 
1036
1290
  def file_findings(args):
@@ -1051,7 +1305,9 @@ def file_findings(args):
1051
1305
 
1052
1306
  def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1053
1307
  offline = args.offline
1054
- 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)
1055
1311
  issues = [] if offline else existing_issues(slug)
1056
1312
  filed = {fp: issue for issue in issues for fp in FP_MARK_RE.findall(issue.get("body") or "")}
1057
1313
  only = set(args.only)
@@ -1065,20 +1321,40 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1065
1321
  seen.add(f["fp"])
1066
1322
  issue = filed.get(f["fp"])
1067
1323
  mark = dismissed.get(f["fp"])
1068
- entries.append(finding_entry(f, issue, mark))
1324
+ receipt = receipts.get(f["fp"])
1325
+ entries.append(finding_entry(f, issue, mark, receipt))
1069
1326
  if issue:
1070
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})
1071
1331
  elif f.get("swept"):
1072
1332
  continue # fixed in the run by its finding sweep
1073
1333
  elif not mark or args.include_dismissed:
1074
1334
  todo.append(f)
1075
1335
  notes = notes + [f"--only {fp}: no such open finding" for fp in args.only if fp not in known]
1076
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}]
1077
1354
  keyed = {}
1078
1355
  for f in todo:
1079
1356
  key = id(f) if args.group == "finding" else (f["plan"], f["origin"], f["task"] if args.group == "task" else "")
1080
1357
  keyed.setdefault(key, []).append(f)
1081
- open_titles = {norm_title(i["title"]): i["url"] for i in issues if i.get("state") == "OPEN"}
1082
1358
  t = TEXT[args.lang]
1083
1359
  drafts = []
1084
1360
  for items in keyed.values():
@@ -1097,6 +1373,8 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1097
1373
  "findings": [f["raw"] for f in items], "fingerprints": [f["fp"] for f in items],
1098
1374
  "same_title": None if offline else open_titles.get(norm_title(title)),
1099
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])
1100
1378
  drafts.sort(key=lambda d: SEVERITIES.index(d["severity"]))
1101
1379
  out = {"repo": slug, "plan": meta["plan"], "notes": notes, "warnings": warnings,
1102
1380
  "summary": {"findings": len(seen), "already_filed": len(already),
@@ -1105,10 +1383,15 @@ def list_and_file(args, meta, found, notes, repo_path, slug, warnings):
1105
1383
  **{o: sum(1 for f in todo if f["origin"] == o)
1106
1384
  for o in ("tolerated", "accepted", "review", "plausible")}},
1107
1385
  "findings": entries, "already_filed": already, "drafts": drafts}
1386
+ if comments is not None:
1387
+ out["comments"] = comments
1108
1388
  if args.apply:
1109
1389
  out["created"] = create(slug, drafts, args)
1110
1390
  for d in drafts:
1111
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)
1112
1395
  return out
1113
1396
 
1114
1397
 
@@ -1157,6 +1440,8 @@ def print_human(out, applied):
1157
1440
  for a in out["already_filed"]:
1158
1441
  print(f" filed {a['issue']} ({a['state'].lower()}): {a['finding'][:100]}")
1159
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']}")
1160
1445
  for c in out["created"]:
1161
1446
  if "note" in c:
1162
1447
  print(f" note {c['note']}")
@@ -1165,12 +1450,15 @@ def print_human(out, applied):
1165
1450
  else:
1166
1451
  print(f" skipped {c['title']}: {c['skipped']}{' ' + c['issue'] if c.get('issue') else ''}")
1167
1452
  return
1453
+ for c in out.get("comments", []):
1454
+ print(f" comment {c['issue']}: {c['finding'][:100]}")
1168
1455
  outdated = {e["fp"] for e in out["findings"] if (e.get("review") or {}).get("outdated") is True}
1169
1456
  for d in out["drafts"]:
1170
1457
  flag = f" (open issue with the same title: {d['same_title']})" if d["same_title"] else ""
1171
1458
  mark = " (outdated review)" if any(fp in outdated for fp in d["fingerprints"]) else ""
1172
- print(f" draft {d['title']}{mark}{flag}")
1173
- 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"):
1174
1462
  print("Nothing created: add --apply to file these.")
1175
1463
 
1176
1464