tempergraph 0.7.1__py3-none-any.whl

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 (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. tempergraph_pytest_plugin.py +64 -0
@@ -0,0 +1,1047 @@
1
+ """Filing findings to the repository that owns the fault (SIL-B2, B3, B6, B7, SIL-B18, SIL-B19, SIL-B20, SIL-B35,
2
+ ISS-B7 to B10, ISS-B12).
3
+
4
+ Publishing code: it reads findings (metadata) and the context the loop child built from the run log's ids, enums
5
+ and numbers (`issue_context`), and never imports or opens the evidence file. An issue's title and body are built
6
+ from cause codes, counts, ids, versions and the cause's fixed remedy text; no request text.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import hashlib
13
+ import json
14
+ import re
15
+ from collections.abc import Iterable, Mapping, Sequence
16
+ from dataclasses import dataclass, field
17
+ from datetime import UTC, datetime, timedelta
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from tempergraph.improve import bindings, causes, params, prebinding
22
+ from tempergraph.improve.codehost import LOOP_LABEL, CodeHost, CodeHostError
23
+
24
+ ENGINE_REPOSITORY = "dbr0vskyi/tempergraph" # engine and executor findings (SIL-B11)
25
+ DEFAULT_LABELS = [LOOP_LABEL, "needs-triage"] # ISS-B1: the engine's own `issue_labels`
26
+ COUNT_CAUSES = frozenset({"answer_overrode", "upstream_confirmed", "retry_passed_unchanged", "retry_same_failure"})
27
+ THREAD_COUNT_CAUSE = "resume_no_progress" # FFD-B8: files on a count of 2 in the thread
28
+
29
+
30
+ def marker(fp: str) -> str:
31
+ return f"tempergraph:fp={fp}"
32
+
33
+
34
+ def _marker_line(fp: str) -> str:
35
+ return f"<!-- {marker(fp)} -->"
36
+
37
+
38
+ def cause_key(f: Mapping[str, Any]) -> str:
39
+ """ISS-B7: the finding's side, workflow and cause, without the unit: one issue holds a cause at every unit."""
40
+ return hashlib.sha256(f"{f.get('side')}|{f.get('workflow')}|{f.get('cause')}".encode()).hexdigest()[:16]
41
+
42
+
43
+ def _cause_line(key: str) -> str:
44
+ return f"<!-- tempergraph:cause={key} -->"
45
+
46
+
47
+ @dataclass(kw_only=True)
48
+ class Candidate:
49
+ """A finding the loop's judge has seen: its lens, confidence, attribution and calibration."""
50
+
51
+ finding: Mapping[str, Any]
52
+ lens: str = "friction" # friction | outcome
53
+ confidence: float | None = None
54
+ attributed: bool = False # the judge attributed the fault to this side
55
+ calibrated: bool = False # the outcome judge has a calibration score for this gate
56
+ request_digest: str | None = None
57
+ issue_labels: Sequence[str] | None = None # the workflow's `improvement.issue_labels` (ISS-B1)
58
+ review_categories: frozenset[str] = frozenset() # the review catalog's category codes, so a body names only those
59
+ records: Sequence[Mapping[str, Any]] = () # the run log's records, read for ISS-B8 to ISS-B10 through issue_context
60
+ mode: str | None = None # the workflow's improvement mode (ISS-B8)
61
+ judge_executor: str | None = None # the loop's judge executor (ISS-B8)
62
+ earlier_answers: Sequence[bool] = () # the attributed flags already recorded for the fingerprint in the window
63
+ facts: Mapping[str, str] = field(default_factory=dict) # what answered the finding's pause (SIL-B37), ids and enums
64
+ threads_final: int | None = None # FFD-B14: the workflow's threads that reached a final exit; None counts as none
65
+
66
+
67
+ @dataclass(kw_only=True)
68
+ class Decision:
69
+ action: str # file | record
70
+ reason: str
71
+ candidate: Candidate
72
+ repo: str | None = None
73
+ counts: dict[str, int] = field(default_factory=dict) # the pattern figures an issue body shows
74
+ counted: Mapping[str, int | float] = field(default_factory=dict) # runs, requests, machines of a judged friction fault
75
+
76
+
77
+ def repository(finding: Mapping[str, Any], issue_repository: str) -> str | None:
78
+ side = str(finding.get("side") or "")
79
+ if side == "host":
80
+ return None # host findings are recorded only
81
+ if side == "engine" or side.startswith("executor:"):
82
+ return ENGINE_REPOSITORY
83
+ if finding.get("child"): # SWF-B9: a finding about a child's unit files to the child's own repository, never the parent's
84
+ return str(finding.get("issue_repository") or "") or None
85
+ return issue_repository or None
86
+
87
+
88
+ def _pattern(c: Candidate, history: Iterable[Mapping[str, Any]], now: datetime | None) -> tuple[dict[str, int], bool]:
89
+ """SIL-B3: the runs, distinct requests and machines that record the candidate's fingerprint inside the window,
90
+ and whether they meet the pattern rule. Both lenses count here (SIL-B18). Only history lines of class `fault`
91
+ count (SIL-B46)."""
92
+ f = c.finding
93
+ now = now or datetime.now(UTC)
94
+ since = (now - timedelta(days=int(params.value("pattern_rule.window_days")))).isoformat()
95
+ same = [h for h in history if h.get("fingerprint") == f.get("fingerprint") and h.get("class") == "fault"
96
+ and str(h.get("at") or "") >= since and h.get("recovered") is not True] # FFD-B15
97
+ runs = {str(h.get("thread")) for h in same} | {str(f.get("thread"))}
98
+ first: dict[str, str] = {} # SIL-B3: a thread counts its request once, by the first digest it recorded
99
+ for h in sorted(same, key=lambda h: str(h.get("at") or "")):
100
+ t = str(h.get("thread"))
101
+ if h.get("request_digest") and t not in first:
102
+ first[t] = str(h["request_digest"])
103
+ if c.request_digest:
104
+ first[str(f.get("thread"))] = c.request_digest # the exit's run counts by its own digest
105
+ reqs = set(first.values())
106
+ counts = {"runs": len(runs), "requests": len(reqs),
107
+ "machines": len({str(h.get("machine")) for h in same} | {str(f.get("machine"))})}
108
+ met = len(runs) >= params.value("pattern_rule.min_runs") and len(reqs) >= params.value(
109
+ "pattern_rule.min_distinct_requests")
110
+ return counts, met
111
+
112
+
113
+ def recorded_answers(root: Path, workflow: str, now: datetime | None = None,
114
+ exclude: Path | None = None) -> dict[str, list[bool]]:
115
+ """SIL-B18, SIL-B36: the `attributed` flags of the `loop_judged` answers of the workflow's runs in the state
116
+ root, per fingerprint, inside `pattern_rule.window_days` by the record's time, oldest first. `exclude` is a loop
117
+ log left out: the loop child leaves out its own thread's, whose one answer for a fingerprint `decide` adds itself
118
+ (SIL-B49, FFD-B1)."""
119
+ now = now or datetime.now(UTC)
120
+ since = now - timedelta(days=int(params.value("pattern_rule.window_days")))
121
+ rows: list[tuple[datetime, str, bool]] = []
122
+ for path in sorted((root / "runs" / workflow).glob("*/loop.jsonl")):
123
+ if exclude is not None and path == exclude:
124
+ continue
125
+ try:
126
+ lines = path.read_text(encoding="utf-8").splitlines()
127
+ except OSError:
128
+ continue
129
+ for ln in lines:
130
+ try:
131
+ rec = json.loads(ln)
132
+ if rec.get("kind") != "loop_judged":
133
+ continue
134
+ at = datetime.fromisoformat(str(rec.get("ts")).replace("Z", "+00:00"))
135
+ at = at if at.tzinfo else at.replace(tzinfo=UTC)
136
+ if at < since:
137
+ continue
138
+ for a in rec.get("answers") or []:
139
+ rows.append((at, str(a["fingerprint"]), bool(a["attributed"])))
140
+ except (ValueError, TypeError, KeyError, AttributeError):
141
+ continue
142
+ out: dict[str, list[bool]] = {}
143
+ for _, fp, flag in sorted(rows, key=lambda r: r[0]):
144
+ out.setdefault(fp, []).append(flag)
145
+ return out
146
+
147
+
148
+ def final_threads(root: Path, workflow: str, own_task: str, now: datetime | None = None) -> int:
149
+ """FFD-B14: the workflow's threads that reached a final exit inside `pattern_rule.window_days`, each once, by a
150
+ `loop_summary` record in its loop log; a thread whose every segment started as a trial, a scenario or an eval is
151
+ left out, and the exit's own thread is added."""
152
+ from tempergraph.improve.promotion import EXCLUDED_ORIGINS
153
+
154
+ now = now or datetime.now(UTC)
155
+ since = now - timedelta(days=int(params.value("pattern_rule.window_days")))
156
+ threads: set[str] = set()
157
+ for path in sorted((root / "runs" / workflow).glob("*/loop.jsonl")):
158
+ try:
159
+ lines = path.read_text(encoding="utf-8").splitlines()
160
+ except OSError:
161
+ continue
162
+ inside = False
163
+ for ln in lines:
164
+ try:
165
+ rec = json.loads(ln)
166
+ if rec.get("kind") != "loop_summary":
167
+ continue
168
+ at = datetime.fromisoformat(str(rec.get("ts")).replace("Z", "+00:00"))
169
+ at = at if at.tzinfo else at.replace(tzinfo=UTC)
170
+ inside = inside or at >= since
171
+ except (ValueError, TypeError, AttributeError):
172
+ continue
173
+ if not inside:
174
+ continue
175
+ origins: list[Any] = []
176
+ try:
177
+ run_lines = (path.parent / "run.jsonl").read_text(encoding="utf-8").splitlines()
178
+ except OSError:
179
+ run_lines = []
180
+ for ln in run_lines:
181
+ try:
182
+ rec = json.loads(ln)
183
+ if rec.get("kind") == "run_started":
184
+ origins.append(rec.get("origin"))
185
+ except (ValueError, TypeError, AttributeError):
186
+ continue
187
+ if origins and all(o in EXCLUDED_ORIGINS for o in origins):
188
+ continue
189
+ threads.add(path.parent.name)
190
+ threads.add(own_task)
191
+ return len(threads)
192
+
193
+
194
+ def decide(c: Candidate, history: Iterable[Mapping[str, Any]], issue_repository: str,
195
+ now: datetime | None = None) -> Decision:
196
+ """Whether a candidate files, or is only recorded, and why (SIL-B12 to SIL-B16, B3, B7). A friction finding
197
+ files only when its judge attributed it and either its confidence is at or above the floor or its fingerprint
198
+ meets the pattern rule on a majority of the recorded answers (SIL-B18); one that does not file carries one of
199
+ `not_judged` (SIL-B35), `not_attributed`, `few_answers` or `below_count`."""
200
+ f = c.finding
201
+ repo = repository(f, issue_repository)
202
+ if f.get("class") != "fault":
203
+ return Decision(action="record", reason=str(f.get("class")), candidate=c)
204
+ if repo is None:
205
+ return Decision(action="record", reason="host" if f.get("side") == "host" else "no_repository", candidate=c)
206
+ escape = str(f.get("cause") or "").split(":", 1)[0] == "outcome_escape" # SIL-B34: the pattern rule alone
207
+ if c.lens == "outcome" and not c.calibrated and not escape:
208
+ return Decision(action="record", reason="uncalibrated", candidate=c) # SIL-B7
209
+ base = str(f.get("cause") or "").split(":", 1)[0]
210
+ if c.lens == "friction" and base in COUNT_CAUSES: # FFD-B7: the pattern rule alone, whatever the judge answered
211
+ counts, met = _pattern(c, history, now)
212
+ if met:
213
+ return Decision(action="file", reason="pattern_met", candidate=c, repo=repo, counts=counts, counted=counts)
214
+ return Decision(action="record", reason="below_count", candidate=c, counted=counts)
215
+ if c.lens == "friction" and base == THREAD_COUNT_CAUSE: # FFD-B8: the thread's own count
216
+ n = int(f.get("count") or 0) + sum(
217
+ int(h.get("count") or 0) for h in history if h.get("fingerprint") == f.get("fingerprint")
218
+ and h.get("thread") == f.get("thread"))
219
+ if n >= 2:
220
+ return Decision(action="file", reason="fault", candidate=c, repo=repo, counted={"count": n})
221
+ return Decision(action="record", reason="below_count", candidate=c, counted={"count": n})
222
+ if c.lens == "friction":
223
+ if c.confidence is None:
224
+ return Decision(action="record", reason="not_judged", candidate=c) # SIL-B35
225
+ counts, met = _pattern(c, history, now)
226
+ if not c.attributed:
227
+ return Decision(action="record", reason="not_attributed", candidate=c, counted=counts)
228
+ answers = [*c.earlier_answers, True]
229
+ majority = len(answers) >= 2 and 2 * sum(answers) > len(answers) # SIL-B18: more than half, two or more
230
+ if causes.cause_of(base).rate: # FFD-B10 to FFD-B13, FFD-B16: the count files only under a share of threads
231
+ threads = c.threads_final or 0
232
+ share = counts["runs"] / threads if threads else 0.0
233
+ counted: dict[str, int | float] = {**counts, "threads_with": counts["runs"], "threads_final": threads,
234
+ "share": share}
235
+ recovered = f.get("recovered") is True
236
+ enough = threads >= params.value("base_rate.min_threads")
237
+ if met and majority and not recovered and enough and share < params.value("base_rate.max_share"):
238
+ return Decision(action="file", reason="pattern_met", candidate=c, repo=repo, counts=counts,
239
+ counted=counted)
240
+ if c.confidence >= params.value("friction.file_confidence"):
241
+ return Decision(action="file", reason="fault", candidate=c, repo=repo, counted=counted)
242
+ if met and majority:
243
+ reason = "recovered" if recovered else "base_rate_unknown" if not enough else "base_rate"
244
+ return Decision(action="record", reason=reason, candidate=c, counted=counted)
245
+ reason = "few_answers" if met and len(answers) == 1 else "not_attributed" if met else "below_count"
246
+ return Decision(action="record", reason=reason, candidate=c, counted=counted)
247
+ if met and majority: # the count files at any confidence
248
+ return Decision(action="file", reason="pattern_met", candidate=c, repo=repo, counts=counts,
249
+ counted=counts)
250
+ if c.confidence >= params.value("friction.file_confidence"):
251
+ return Decision(action="file", reason="fault", candidate=c, repo=repo, counted=counts)
252
+ if met:
253
+ reason = "few_answers" if len(answers) == 1 else "not_attributed"
254
+ return Decision(action="record", reason=reason, candidate=c, counted=counts)
255
+ return Decision(action="record", reason="below_count", candidate=c, counted=counts)
256
+ if c.lens == "outcome" and f.get("side") == "workflow": # SIL-B3; one clear engine fault is enough
257
+ counts, met = _pattern(c, history, now)
258
+ if not met:
259
+ return Decision(action="record", reason="pattern_not_met", candidate=c, repo=repo,
260
+ counts={**counts, "scope_local": 1})
261
+ return Decision(action="file", reason="pattern_met", candidate=c, repo=repo, counts=counts)
262
+ return Decision(action="file", reason="fault", candidate=c, repo=repo)
263
+
264
+
265
+ def title(f: Mapping[str, Any]) -> str:
266
+ """ISS-B7: the cause, not the unit: the issue holds the cause at every unit, listed in its body."""
267
+ return f"[loop] {f.get('workflow')}: {f.get('cause')}"[:200]
268
+
269
+
270
+ def _unit(f: Mapping[str, Any]) -> str:
271
+ return f"{f['child']}/{f.get('unit') or '-'}" if f.get("child") else str(f.get("unit") or "-")
272
+
273
+
274
+ def _context(ds: Sequence[Decision]) -> dict[str, Any]:
275
+ from tempergraph.improve import issue_context
276
+
277
+ c = ds[0].candidate
278
+ return issue_context.build(c.records, [d.candidate.finding for d in ds], mode=c.mode,
279
+ judge_executor=c.judge_executor,
280
+ segment_started=str(c.finding.get("segment_started") or "") or None, facts=c.facts)
281
+
282
+
283
+ def _fmt(v: Any) -> str:
284
+ if isinstance(v, list):
285
+ return ", ".join(f"`{x}`" for x in v)
286
+ if isinstance(v, dict):
287
+ return ", ".join(f"`{k}` {x}" for k, x in v.items())
288
+ return f"`{v}`"
289
+
290
+
291
+ ENV_NAMES = (("engine_version", "Engine version (run)"), ("loop_engine_version", "Engine version (loop)"),
292
+ ("workflow_version", "Workflow version"), ("parent_version", "Parent workflow version"), ("executors", "Executor"), ("executor_cli", "Executor CLI"),
293
+ ("models", "Models"), ("aliases", "Model aliases"), ("efforts", "Effort"),
294
+ ("judge_executor", "Loop judge executor"), ("improvement_mode", "Improvement mode"),
295
+ ("python", "Python"), ("os", "OS"), ("arch", "Architecture"))
296
+ RUN_NAMES = (("thread", "Run"), ("started", "Segment started (UTC)"), ("exit_code", "Exit code"),
297
+ ("exit_reason", "Exit reason"), ("facts", "What answered the pause"), ("run_cost_usd", "Run cost so far (USD)"),
298
+ ("unit_cost_usd", "Cost of these units' sessions (USD)"), ("attempts", "Attempts per unit"),
299
+ ("request_digest", "Request digest"), ("rerun_of", "Rerun of"), ("machine", "Machine id"))
300
+
301
+
302
+ def _env_rows(ctx: Mapping[str, Any], f: Mapping[str, Any]) -> list[str]:
303
+ env = dict(ctx.get("environment") or {})
304
+ if f.get("workflow_version"): # the finding's own workflow: a sub-workflow child's version, not its parent's
305
+ if f.get("child") and env.get("workflow_version") not in (None, f["workflow_version"]):
306
+ env["parent_version"] = env["workflow_version"]
307
+ env["workflow_version"] = f["workflow_version"]
308
+ if f.get("executor_version"):
309
+ env["executor_cli"] = sorted({*(env.get("executor_cli") or []), str(f["executor_version"])})
310
+ return [f"- {name}: {_fmt(env[k])}" for k, name in ENV_NAMES if env.get(k) not in (None, "", [])]
311
+
312
+
313
+ def _run_rows(ctx: Mapping[str, Any]) -> list[str]:
314
+ run = ctx.get("run") or {}
315
+ return [f"- {name}: {_fmt(run[k])}" for k, name in RUN_NAMES if run.get(k) not in (None, "", {}, [])]
316
+
317
+
318
+ def _steps(ds: Sequence[Decision]) -> list[str]:
319
+ """ISS-B8: what a person runs, on the machine that made the run, to see and repeat it."""
320
+ f = ds[0].candidate.finding
321
+ thread = str(f.get("thread") or "")
322
+ wf = str(f.get("parent") or f.get("workflow") or "")
323
+ unit = str(f.get("unit") or "")
324
+ rows = ["On the machine that ran it (machine id above), in the repository the run worked in:", "",
325
+ f"1. `tempergraph status {thread} --detail" + (f" --unit {unit}`" if unit else "`") + ": the run and the unit.",
326
+ f"2. `tempergraph logs {thread} --kind run`: the run log the excerpt below comes from; "
327
+ "`--kind raw --session <session_key>` shows one session's own output.",
328
+ f"3. `tempergraph rerun {wf} {thread} --from {unit or 'start'} --check`, then without `--check`: the same "
329
+ "request again from this unit."]
330
+ rows += ["", "The request, outputs and session logs stay on that machine (under the run's folder in the "
331
+ "repository's `.tempergraph` state root); this issue holds ids, enums, numbers and versions only."]
332
+ return rows
333
+
334
+
335
+ def _log_rows(ctx: Mapping[str, Any]) -> list[str]:
336
+ lines = list(ctx.get("log") or [])
337
+ if not lines:
338
+ return ["No run-log records of these units were found when the loop ran."]
339
+ head = [f"{ctx['log_left_out']} earlier records left out."] if ctx.get("log_left_out") else []
340
+ return [*head, "```text", *lines, "```"]
341
+
342
+
343
+ def _summary(ds: Sequence[Decision], regression_of: int | None) -> list[str]:
344
+ d = ds[0]
345
+ f = d.candidate.finding
346
+ units = list(dict.fromkeys(_unit(x.candidate.finding) for x in ds))
347
+ summary = [f"**Cause** `{f.get('cause')}` ({f.get('class')}, side `{f.get('side')}`), lens {d.candidate.lens}.",
348
+ f"**Workflow** `{f.get('workflow')}`; " + ("unit " if len(units) == 1 else "units ")
349
+ + ", ".join(f"`{u}`" for u in units) + "."]
350
+ for x in ds:
351
+ category = str(x.candidate.finding.get("review") or "").removeprefix("review:")
352
+ if category and category in x.candidate.review_categories: # SRV-B7: the category code only, never a note
353
+ summary.append(f"A session review kept `review:{category}` on unit `{_unit(x.candidate.finding)}` "
354
+ "in this run.")
355
+ if f.get("child") and f.get("parent"): # SWF-B9
356
+ summary.append(f"**Parent** `{f.get('parent')}` ran this workflow as its sub-workflow unit `{f.get('child')}`.")
357
+ if regression_of is not None:
358
+ summary.append(f"Possible regression of #{int(regression_of)}: that issue was closed as completed and this "
359
+ "cause came back. A person decides.")
360
+ return summary
361
+
362
+
363
+ def _figures(ds: Sequence[Decision]) -> list[str]:
364
+ rows = []
365
+ for x in ds:
366
+ f = x.candidate.finding
367
+ row = f"- `{_unit(f)}`: count {f.get('count')}, fingerprint `{f.get('fingerprint')}`"
368
+ if x.counts:
369
+ row += "; pattern " + ", ".join(f"{k} {v}" for k, v in sorted(x.counts.items()))
370
+ rows.append(row + ".")
371
+ return rows
372
+
373
+
374
+ _ANSWERED_ID = re.compile(r"^[A-Za-z0-9_.:@+\-]{1,64}$") # ISS-B10: an id, enum or number, never free text
375
+
376
+
377
+ def _counts(v: Any) -> str:
378
+ if not isinstance(v, Mapping):
379
+ return ""
380
+ return ", ".join(f"`{k}` {n}" for k, n in sorted(v.items(), key=lambda kv: str(kv[0]))
381
+ if (_ANSWERED_ID.match(str(k)) or k == "not given") and isinstance(n, int | float) and not isinstance(n, bool))
382
+
383
+
384
+ def _answered(ds: Sequence[Decision]) -> list[str]:
385
+ """ISS-B19: one line for each unit of what was answered: ids, enums and numbers only."""
386
+ rows = []
387
+ for x in ds:
388
+ f = x.candidate.finding
389
+ parts = []
390
+ for label, key in (("decisions", "decisions"), ("reasons", "reasons"), ("criteria", "criteria")):
391
+ text = _counts(f.get(key))
392
+ if text:
393
+ parts.append(f"{label} {text}")
394
+ for label, key in (("items", "items"), ("median wait (s)", "wait_s_median")):
395
+ v = f.get(key)
396
+ if isinstance(v, int | float) and not isinstance(v, bool):
397
+ parts.append(f"{label} {v}")
398
+ from_unit = f.get("from_unit")
399
+ if isinstance(from_unit, str) and _ANSWERED_ID.match(from_unit):
400
+ parts.append(f"from unit `{from_unit}`")
401
+ if x.counts:
402
+ parts.append("runs " + str(x.counts.get("runs", 0)))
403
+ rows.append(f"- `{_unit(f)}`: " + ("; ".join(parts) or "nothing recorded") + ".")
404
+ return rows
405
+
406
+
407
+ def body(d: Decision | Sequence[Decision], regression_of: int | None = None, related: Sequence[int] = ()) -> str:
408
+ """ISS-B2: the hidden lines, then Summary, Environment, Run, Steps to reproduce, Run log, Evidence, Fingerprint
409
+ and Suggested remedy; ISS-B4: a closed issue the finding may be a regression of is named in the Summary; ISS-B7:
410
+ one body for every unit of the cause in this filing."""
411
+ ds = [d] if isinstance(d, Decision) else list(d)
412
+ f = ds[0].candidate.finding
413
+ ctx = _context(ds)
414
+ fps = list(dict.fromkeys(str(x.candidate.finding.get("fingerprint")) for x in ds))
415
+ hidden = [_marker_line(fps[0]), _cause_line(cause_key(f)), *(_marker_line(fp) for fp in fps[1:])]
416
+ rows = [*hidden, "", "## Summary", *_summary(ds, regression_of), "",
417
+ *([*prebinding.related_section(related), ""] if related else []), # PBD-B7: numbers only
418
+ "## Environment", *_env_rows(ctx, f), "",
419
+ "## Run", *(_run_rows(ctx) or ["- No run record was found when the loop ran."]), "",
420
+ "## Steps to reproduce", *_steps(ds), "", "## Run log", *_log_rows(ctx), "", "## Evidence",
421
+ *_figures(ds), "",
422
+ *(["## What was answered", *_answered(ds), ""]
423
+ if str(f.get("cause") or "").split(":", 1)[0] in {*COUNT_CAUSES, THREAD_COUNT_CAUSE} else []),
424
+ "## Fingerprint", *(f"`{fp}`" for fp in fps), f"Cause key `{cause_key(f)}`.", "",
425
+ "## Suggested remedy", f"{f.get('remedy')}", "",
426
+ "An issue is evidence, not an order: a person decides (SIL-B8)."]
427
+ return "\n".join(rows)
428
+
429
+
430
+ def comment_body(ds: Sequence[Decision]) -> str:
431
+ """SIL-B2, ISS-B7: a "seen again" comment with the same context as a new issue (ISS-B8 to ISS-B10)."""
432
+ f = ds[0].candidate.finding
433
+ ctx = _context(ds)
434
+ units = ", ".join(f"`{_unit(x.candidate.finding)}`" for x in ds)
435
+ fps = list(dict.fromkeys(str(x.candidate.finding.get("fingerprint")) for x in ds))
436
+ rows = [*(_marker_line(fp) for fp in fps), "",
437
+ f"**Seen again**: `{f.get('cause')}` at {units}.", "", "## Environment", *_env_rows(ctx, f), "",
438
+ "## Run", *(_run_rows(ctx) or ["- No run record was found when the loop ran."]), "",
439
+ "## Steps to reproduce", *_steps(ds), "", "## Run log", *_log_rows(ctx), "", "## Evidence",
440
+ *_figures(ds)]
441
+ return "\n".join(rows)
442
+
443
+
444
+ def _names(value: Any) -> list[str] | None:
445
+ """A declared label list, or none when it is not a non-empty list of names (ISS-B1)."""
446
+ if isinstance(value, list | tuple) and value and all(isinstance(v, str) and v.strip() for v in value):
447
+ return [v.strip() for v in value]
448
+ return None
449
+
450
+
451
+ def _labels(f: Mapping[str, Any], declared: Any = None) -> list[str]:
452
+ """ISS-B1: the list of `issue_labels` (the workflow's for its own workflow-side finding, the child's for a
453
+ child's, else the default), `tempergraph-loop` when it omits it, and the side label."""
454
+ side = str(f.get("side") or "")
455
+ base: list[str] | None = None
456
+ if side == "workflow":
457
+ base = _names(f.get("issue_labels")) if f.get("child") else _names(declared)
458
+ out: list[str] = []
459
+ for name in [*(base or DEFAULT_LABELS), LOOP_LABEL, side if side.startswith("executor:") else f"side:{side}"]:
460
+ if name not in out:
461
+ out.append(name)
462
+ return out
463
+
464
+
465
+ @dataclass(kw_only=True)
466
+ class Outbox:
467
+ """Payloads a code host did not take, redelivered by the next filing (SIL-B19, SIL-B20)."""
468
+
469
+ path: Path
470
+
471
+ @classmethod
472
+ def at(cls, root: Path) -> Outbox:
473
+ return cls(path=root / "filing-outbox.jsonl") # LOS-B7, LOS-B8, LOS-B9
474
+
475
+ def add(self, payload: Mapping[str, Any]) -> None:
476
+ """ISS-B18: the entry keeps the time it was first queued; an entry put back keeps the one it holds."""
477
+ entry = dict(payload)
478
+ if not entry.get("queued_at"):
479
+ entry["queued_at"] = datetime.now(UTC).isoformat(timespec="seconds")
480
+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
481
+ with open(self.path, "a", encoding="utf-8") as fh:
482
+ fh.write(json.dumps(entry) + "\n")
483
+
484
+ def take(self) -> list[dict[str, Any]]:
485
+ try:
486
+ lines = self.path.read_text(encoding="utf-8").splitlines()
487
+ except OSError:
488
+ return []
489
+ self.path.unlink(missing_ok=True)
490
+ return [json.loads(ln) for ln in lines if ln.strip()]
491
+
492
+ def entries(self) -> list[dict[str, Any]]:
493
+ """CLI-B21: the payloads in file order; none when the file is absent, an unreadable line is skipped, and
494
+ nothing is written or removed."""
495
+ try:
496
+ lines = self.path.read_text(encoding="utf-8").splitlines()
497
+ except OSError:
498
+ return []
499
+ out: list[dict[str, Any]] = []
500
+ for ln in lines:
501
+ try:
502
+ got = json.loads(ln)
503
+ except ValueError:
504
+ continue
505
+ if isinstance(got, dict):
506
+ out.append(got)
507
+ return out
508
+
509
+ def remove(self, fingerprint: str | None = None) -> int:
510
+ """CLI-B22: remove every entry (no fingerprint) or those of `fingerprint`; returns the number removed."""
511
+ try:
512
+ lines = [ln for ln in self.path.read_text(encoding="utf-8").splitlines() if ln.strip()]
513
+ except OSError:
514
+ return 0
515
+ if fingerprint is None:
516
+ self.path.unlink(missing_ok=True)
517
+ return len(lines)
518
+ keep: list[str] = []
519
+ for ln in lines:
520
+ try:
521
+ got = json.loads(ln)
522
+ except ValueError:
523
+ got = None
524
+ if isinstance(got, dict) and got.get("fingerprint") == fingerprint:
525
+ continue
526
+ keep.append(ln)
527
+ if len(keep) != len(lines):
528
+ self.path.write_text("".join(ln + "\n" for ln in keep), encoding="utf-8")
529
+ return len(lines) - len(keep)
530
+
531
+
532
+ def _deliver(host: CodeHost, p: Mapping[str, Any]) -> str:
533
+ if p["op"] == "comment":
534
+ return host.comment(p["repo"], int(p["number"]), p["body"])
535
+ if p["op"] == "reopen": # PRP-B29: a regression's reopen the host could not take
536
+ host.reopen(p["repo"], int(p["number"]))
537
+ return ""
538
+ return host.create(p["repo"], p["title"], p["body"], list(p.get("labels") or []))
539
+
540
+
541
+ def _closed_at(issue: Mapping[str, Any]) -> datetime:
542
+ try:
543
+ at = datetime.fromisoformat(str(issue.get("closed_at") or "").replace("Z", "+00:00"))
544
+ except ValueError:
545
+ return datetime.min.replace(tzinfo=UTC) # an unreadable time sorts oldest and never mutes
546
+ return at if at.tzinfo else at.replace(tzinfo=UTC)
547
+
548
+
549
+ def _holds(issue: Mapping[str, Any], lines: Sequence[str]) -> bool:
550
+ got = str(issue.get("body") or "").splitlines()
551
+ return any(ln in got for ln in lines)
552
+
553
+
554
+ def _read(host: CodeHost, repo: str, state: str) -> tuple[list[dict[str, Any]] | None, bool]:
555
+ """ISS-B9: the repository's loop issues in `state`, read with one retry; the flag says the read failed twice."""
556
+ for attempt in (1, 2):
557
+ try:
558
+ return list(host.loop_issues(repo, state)), False
559
+ except CodeHostError:
560
+ if attempt == 2:
561
+ return None, True
562
+ return None, True
563
+
564
+
565
+ def _created_on(issue: Mapping[str, Any], day: Any) -> bool:
566
+ try:
567
+ at = datetime.fromisoformat(str(issue.get("created_at") or "").replace("Z", "+00:00"))
568
+ except ValueError:
569
+ return False # no or an unreadable creation time never counts
570
+ return (at if at.tzinfo else at.replace(tzinfo=UTC)).astimezone(UTC).date() == day
571
+
572
+
573
+ def _day_count(opened: Sequence[Mapping[str, Any]], closed: Sequence[Mapping[str, Any]], now: datetime) -> int:
574
+ """ICAP-B4: the loop issues of both lists created on the UTC day of `now`."""
575
+ day = now.astimezone(UTC).date()
576
+ return sum(1 for i in [*opened, *closed] if _created_on(i, day))
577
+
578
+
579
+ Listed = dict[tuple[str, str], tuple[list[dict[str, Any]] | None, bool]]
580
+
581
+
582
+ def _count_today(host: CodeHost, repo: str, listed: Listed, now: datetime) -> int | None:
583
+ """ICAP-B3, ICAP-B7: the repository's day count from the open and closed lists (read once each, cached in
584
+ `listed`); None when either list failed twice. An open list that failed is not followed by a closed read."""
585
+ if (repo, "open") not in listed:
586
+ listed[(repo, "open")] = _read(host, repo, "open")
587
+ opened, failed = listed[(repo, "open")]
588
+ if failed:
589
+ return None
590
+ if (repo, "closed") not in listed:
591
+ listed[(repo, "closed")] = _read(host, repo, "closed")
592
+ closed, cfailed = listed[(repo, "closed")]
593
+ if cfailed:
594
+ return None
595
+ return _day_count(opened or [], closed or [], now)
596
+
597
+
598
+ def _today(host: CodeHost, repo: str, listed: Listed, now: datetime, counts: dict[str, int]) -> int | None:
599
+ """ICAP-B3: the repository's day count for this call. It is read once from the lists and kept in `counts`, raised
600
+ by one for each create the call sends; a list read again later (after a reopen) already holds this call's creates,
601
+ so the count is never taken from it a second time. None when the count cannot be read."""
602
+ if repo not in counts:
603
+ counted = _count_today(host, repo, listed, now)
604
+ if counted is None:
605
+ return None
606
+ counts[repo] = counted
607
+ return counts[repo]
608
+
609
+
610
+ def _keep_for_cap(p: Mapping[str, Any], outbox: Outbox, results: list[dict[str, Any]], issue_cap: int,
611
+ day_count: int | None, fingerprint: Any) -> None:
612
+ """ICAP-B5, ICAP-B6: the create goes to the outbox with its first queue time and the mark; one `capped` result."""
613
+ outbox.add({**p, "capped": True})
614
+ results.append({"op": "capped", "repo": p.get("repo"), "fingerprint": fingerprint, "title": p.get("title"),
615
+ "issue_cap": issue_cap,
616
+ **({"day_count": day_count} if day_count is not None else {"note": "count_unreadable"})})
617
+
618
+
619
+ def _match_open(issues: Sequence[Mapping[str, Any]], fps: Sequence[str], key: str) -> Mapping[str, Any] | None:
620
+ """SIL-B2, ISS-B7: the oldest open issue holding one of the fingerprints' lines, else one holding the cause
621
+ key's line."""
622
+ order = sorted(issues, key=lambda i: int(i.get("number") or 0))
623
+ by_fp = [i for i in order if _holds(i, [_marker_line(fp) for fp in fps])]
624
+ if by_fp:
625
+ return by_fp[0]
626
+ return next((i for i in order if _holds(i, [_cause_line(key)])), None)
627
+
628
+
629
+ def comments_by_day(root: Path, workflow: str | None, now: datetime | None = None) -> dict[tuple[str, int], int]:
630
+ """ISS-B13, BND-B3: the `issue_commented` records of the workflow's runs in the state root (of every workflow
631
+ when `workflow` is None) dated on `now`'s UTC day, counted per (repo, issue number). An unreadable file or line
632
+ is skipped."""
633
+ day = (now or datetime.now(UTC)).astimezone(UTC).date()
634
+ out: dict[tuple[str, int], int] = {}
635
+ pattern = "*/*/loop.jsonl" if workflow is None else f"{workflow}/*/loop.jsonl"
636
+ for path in sorted((root / "runs").glob(pattern)):
637
+ try:
638
+ lines = path.read_text(encoding="utf-8").splitlines()
639
+ except OSError:
640
+ continue
641
+ for ln in lines:
642
+ try:
643
+ rec = json.loads(ln)
644
+ if rec.get("kind") != "issue_commented":
645
+ continue
646
+ at = datetime.fromisoformat(str(rec.get("ts")).replace("Z", "+00:00"))
647
+ at = at if at.tzinfo else at.replace(tzinfo=UTC)
648
+ if at.astimezone(UTC).date() != day:
649
+ continue
650
+ key = (str(rec["repo"]), int(rec["number"]))
651
+ out[key] = out.get(key, 0) + 1
652
+ except (ValueError, TypeError, KeyError, AttributeError):
653
+ continue
654
+ return out
655
+
656
+
657
+ def _expired(p: Mapping[str, Any], now: datetime) -> bool:
658
+ """ISS-B18: first queued more than `outbox.max_age_days` before `now`; no or an unreadable time never expires."""
659
+ try:
660
+ at = datetime.fromisoformat(str(p.get("queued_at")).replace("Z", "+00:00"))
661
+ except ValueError:
662
+ return False
663
+ at = at if at.tzinfo else at.replace(tzinfo=UTC)
664
+ return now - at > timedelta(days=float(params.value("outbox.max_age_days")))
665
+
666
+
667
+ def _queue_order(p: Mapping[str, Any]) -> tuple[int, datetime]:
668
+ """ICAP-B8: the order waiting entries are decided in: by first queue time, an entry with none or an unreadable
669
+ time after every entry with one (a stable sort keeps file order among equals)."""
670
+ try:
671
+ at = datetime.fromisoformat(str(p.get("queued_at")).replace("Z", "+00:00"))
672
+ except ValueError:
673
+ return 1, datetime.min.replace(tzinfo=UTC)
674
+ return 0, at if at.tzinfo else at.replace(tzinfo=UTC)
675
+
676
+
677
+ def _comment_bound(p: dict[str, Any], got: bindings.Binding, source: int, host: CodeHost, outbox: Outbox,
678
+ results: list[dict[str, Any]], comments_today: Mapping[tuple[str, int], int] | None,
679
+ sent_now: dict[tuple[str, int], int]) -> None:
680
+ """BND-B11: a waiting create of a bound cause is one comment on the open target within the day bound (BND-B3);
681
+ its opening sentence is built from the payload, or from its title and `Seen again` line when it lacks the fields."""
682
+ repo = str(p.get("repo"))
683
+ fp = p.get("fingerprint")
684
+ ident = (repo, int(got.number or 0))
685
+ if (comments_today or {}).get(ident, 0) + sent_now.get(ident, 0) >= int(
686
+ params.value("seen_again.max_per_issue_per_day")):
687
+ results.append({"op": "comment_capped", "number": ident[1], "repo": repo, "fingerprint": fp})
688
+ return
689
+ comment = str(p.get("comment") or "")
690
+ m = re.match(r"\[loop\] (.*?): (.*)$", str(p.get("title") or ""))
691
+ workflow = str(p.get("workflow") or (m.group(1) if m else ""))
692
+ cause = str(p.get("cause") or (m.group(2) if m else ""))
693
+ units = p.get("units")
694
+ if not isinstance(units, list):
695
+ seen = re.search(r"\*\*Seen again\*\*: .*? at (.*)\.$", comment, re.MULTILINE)
696
+ units = re.findall(r"`([^`]+)`", seen.group(1)) if seen else []
697
+ sentence = bindings.opening_sentence(workflow, cause, [str(u) for u in units], source)
698
+ c = {"op": "comment", "repo": repo, "number": ident[1], "fingerprint": fp,
699
+ "body": sentence + "\n" + (comment or "**Seen again**"), "queued_at": p.get("queued_at")}
700
+ try:
701
+ url = _deliver(host, c)
702
+ except CodeHostError:
703
+ outbox.add(_unmarked(p)) # ICAP-B10: a refused send is not a cap keep
704
+ return
705
+ sent_now[ident] = sent_now.get(ident, 0) + 1
706
+ results.append({"op": "commented", "url": url, "fingerprint": fp, "repo": repo, "number": ident[1]})
707
+
708
+
709
+ def _unmarked(p: Mapping[str, Any]) -> dict[str, Any]:
710
+ """ICAP-B10: the entry as it goes back when its latest attempt was not kept for the cap."""
711
+ return {k: v for k, v in p.items() if k != "capped"}
712
+
713
+
714
+ def _redeliver(p: dict[str, Any], host: CodeHost, outbox: Outbox, results: list[dict[str, Any]], now: datetime,
715
+ comments_today: Mapping[tuple[str, int], int] | None,
716
+ listed: dict[tuple[str, str], tuple[list[dict[str, Any]] | None, bool]],
717
+ sent_now: dict[tuple[str, int], int], issue_cap: int = 3, counts: dict[str, int] | None = None) -> None:
718
+ """ISS-B16 to ISS-B18: one waiting entry, checked before it is sent: dropped when expired; a create becomes a
719
+ comment on the open issue holding its fingerprint or cause line (within the day's bound), is dropped when its
720
+ cause is muted, else is sent as queued while the day's count is under the cap (ICAP-B3) and kept otherwise. A
721
+ refused entry goes back with its queue time."""
722
+ counts = counts if counts is not None else {}
723
+ repo = str(p.get("repo"))
724
+ if _expired(p, now):
725
+ who = {"fingerprint": p.get("fingerprint")} if p.get("op") == "create" else {"number": p.get("number")}
726
+ results.append({"op": "outbox_dropped", "reason": "expired", "entry_kind": p.get("op"), "repo": repo, **who})
727
+ return
728
+ if p.get("op") == "create":
729
+ lines = [ln for ln in str(p.get("body") or "").splitlines()
730
+ if ln.startswith(("<!-- tempergraph:fp=", "<!-- tempergraph:cause=")) and ln.endswith("-->")]
731
+ if (repo, "open") not in listed:
732
+ listed[(repo, "open")] = _read(host, repo, "open")
733
+ opened, failed = listed[(repo, "open")]
734
+ if not failed and lines:
735
+ match = next((i for i in sorted(opened or [], key=lambda i: int(i.get("number") or 0))
736
+ if _holds(i, lines)), None)
737
+ if match is not None:
738
+ ident = (repo, int(match["number"]))
739
+ fp = p.get("fingerprint")
740
+ if (comments_today or {}).get(ident, 0) + sent_now.get(ident, 0) >= int(
741
+ params.value("seen_again.max_per_issue_per_day")):
742
+ results.append({"op": "comment_capped", "number": ident[1], "repo": repo, "fingerprint": fp})
743
+ return
744
+ text = str(p.get("comment") or "\n".join([*lines, "", "**Seen again**"]))
745
+ c = {"op": "comment", "repo": repo, "number": ident[1], "fingerprint": fp, "body": text,
746
+ "queued_at": p.get("queued_at")}
747
+ try:
748
+ url = _deliver(host, c)
749
+ except CodeHostError:
750
+ outbox.add(_unmarked(p))
751
+ return
752
+ sent_now[ident] = sent_now.get(ident, 0) + 1
753
+ results.append({"op": "commented", "url": url, "fingerprint": fp, "repo": repo, "number": ident[1]})
754
+ return
755
+ if (repo, "closed") not in listed:
756
+ listed[(repo, "closed")] = _read(host, repo, "closed")
757
+ closed, cfailed = listed[(repo, "closed")]
758
+ mine = [i for i in closed or [] if _holds(i, lines)]
759
+ last = max(mine, key=_closed_at) if mine and not cfailed else None
760
+ key = next((ln[len("<!-- tempergraph:cause="):-len(" -->")] for ln in lines
761
+ if ln.startswith("<!-- tempergraph:cause=")), "")
762
+ if (last is not None and key and str(last.get("state_reason") or "") == "duplicate"
763
+ and isinstance(last.get("number"), int)): # BND-B11: a bound cause's waiting create
764
+ got = bindings.learn(host, repo, key, last, outbox.path.parent, now)
765
+ if got.state == "unreadable":
766
+ outbox.add(_unmarked(p)) # back with its queue time; it expires by ISS-B18
767
+ return
768
+ if got.state == "bound":
769
+ if got.learned:
770
+ results.append({"op": "bound", "cause_key": key, "repo": repo, "source": int(last["number"]),
771
+ "target": int(got.number or 0)})
772
+ if str(got.issue.get("state") or "") == "open":
773
+ _comment_bound(p, got, int(last["number"]), host, outbox, results, comments_today, sent_now)
774
+ return
775
+ last = got.issue # BND-B5: the closed target decides as a closed loop issue does
776
+ if (last is not None and str(last.get("state_reason") or "") in ("not_planned", "duplicate")
777
+ and now - _closed_at(last) < timedelta(days=float(params.value("mute.days")))):
778
+ results.append({"op": "outbox_dropped", "reason": "muted", "fingerprint": p.get("fingerprint")})
779
+ return
780
+ today = _today(host, repo, listed, now, counts) # ICAP-B3, ICAP-B7: a create is sent only under the cap
781
+ if today is None or today >= issue_cap:
782
+ _keep_for_cap(p, outbox, results, issue_cap, today, p.get("fingerprint"))
783
+ return
784
+ try:
785
+ url = _deliver(host, p)
786
+ except CodeHostError:
787
+ outbox.add({k: v for k, v in p.items() if k != "capped"})
788
+ return
789
+ if p.get("op") == "create":
790
+ counts[repo] = counts.get(repo, 0) + 1
791
+ _refresh(listed, repo, p, url)
792
+ results.append({"op": "redelivered", "url": url, "fingerprint": p.get("fingerprint")})
793
+
794
+
795
+ def _refresh(listed: dict[tuple[str, str], tuple[list[dict[str, Any]] | None, bool]], repo: str, p: Mapping[str, Any],
796
+ url: str) -> None:
797
+ """ISS-B9, SIL-B2, ISS-B7: the lists read before a second send must hold what it changed, so a finding or a second
798
+ waiting create of the same cause in the same call finds the issue it opened. A new issue joins the cached open
799
+ list with its body; a reopen drops both lists, to be read again when needed."""
800
+ if p.get("op") == "reopen":
801
+ listed.pop((repo, "open"), None)
802
+ listed.pop((repo, "closed"), None)
803
+ return
804
+ if p.get("op") != "create" or (repo, "open") not in listed:
805
+ return
806
+ opened, failed = listed[(repo, "open")]
807
+ m = re.search(r"/issues/(\d+)/?$", str(url))
808
+ if failed or opened is None or m is None:
809
+ listed.pop((repo, "open"), None) # read again by the grouping
810
+ return
811
+ listed[(repo, "open")] = ([*opened, {"number": int(m.group(1)), "url": url, "body": str(p.get("body") or ""),
812
+ "state_reason": ""}], False)
813
+
814
+
815
+ def _dry_group(host: CodeHost, repo: str, key: str, ds: Sequence[Decision], fps: Sequence[str],
816
+ listed: dict[tuple[str, str], tuple[list[dict[str, Any]] | None, bool]], issue_cap: int = 3,
817
+ now: datetime | None = None, counts: dict[str, int] | None = None) -> list[dict[str, Any]]:
818
+ """PBD-B9, PBD-B10, ICAP-B11: a dry run reads the open loop issues, the other open issues and the comments it
819
+ needs, and the closed loop issues only to count a group that would open an issue (a cause that a filing would
820
+ mute is not counted), and writes nothing: `would_bind`
821
+ for a cause with exactly one candidate (no create), else `would_file` for each finding, with the note when a read
822
+ failed twice; a create over the cap, or one whose count cannot be read, adds `capped` `true` (and the note
823
+ `count_unreadable`)."""
824
+ f = ds[0].candidate.finding
825
+ note: str | None = None
826
+ counts = counts if counts is not None else {}
827
+ matched = False
828
+ if (repo, "open") not in listed:
829
+ listed[(repo, "open")] = _read(host, repo, "open")
830
+ opened, failed = listed[(repo, "open")]
831
+ if failed:
832
+ note = "search_failed"
833
+ elif _match_open(opened or [], fps, key) is not None:
834
+ matched = True # a comment, not a create: the cap does not bound it
835
+ else:
836
+ if (repo, "others") not in listed:
837
+ listed[(repo, "others")] = prebinding.read_open(host, repo)
838
+ others, ofailed = listed[(repo, "others")]
839
+ if ofailed:
840
+ note = "prebind_search_failed"
841
+ elif others:
842
+ def read_comments(n: int) -> Any:
843
+ return host.issue_comments(repo, n) # type: ignore[attr-defined]
844
+
845
+ found = prebinding.candidates(others, f, read_comments)
846
+ if found.failed:
847
+ note = "prebind_search_failed"
848
+ elif len(found.issues) == 1 and found.rule is not None:
849
+ return [{"op": "would_bind", "cause_key": key, "repo": repo, "number": int(found.issues[0]["number"]),
850
+ "rule": found.rule}]
851
+ capped = False
852
+ if not matched: # ICAP-B11: the group is one create, counted once
853
+ at = now or datetime.now(UTC)
854
+ today = _today(host, repo, listed, at, counts)
855
+ closed, cfailed = listed.get((repo, "closed"), (None, True))
856
+ mine = [] if cfailed else [i for i in closed or []
857
+ if _holds(i, [*(_marker_line(fp) for fp in fps), _cause_line(key)])]
858
+ last = max(mine, key=_closed_at) if mine else None
859
+ if (last is not None and str(last.get("state_reason") or "") in ("not_planned", "duplicate")
860
+ and at - _closed_at(last) < timedelta(days=float(params.value("mute.days")))):
861
+ pass # ISS-B3: a filing would mute this cause and send no create, so it takes no place under the cap
862
+ elif today is None or today >= issue_cap:
863
+ capped = True
864
+ if today is None:
865
+ note = f"{note} count_unreadable" if note else "count_unreadable"
866
+ else:
867
+ counts[repo] = today + 1
868
+ return [{"op": "would_file", "repo": repo, "title": title(x.candidate.finding),
869
+ "fingerprint": str(x.candidate.finding.get("fingerprint")), "reason": x.reason,
870
+ **({"capped": True} if capped else {}), **({"note": note} if note else {})} for x in ds]
871
+
872
+
873
+ def file(decisions: Sequence[Decision], host: CodeHost, outbox: Outbox, *, dry_run: bool = False,
874
+ now: datetime | None = None, comments_today: Mapping[tuple[str, int], int] | None = None,
875
+ issue_cap: int = 3, home: Path | None = None) -> list[dict[str, Any]]:
876
+ """ICAP-B12: a filing works under one lock for each repository it may create in, kept in the engine's home
877
+ folder (`home`, default the engine's home) and taken in repository order before any read, so the count and the
878
+ creates of a repository are one step and filings on other repositories do not wait. A lock not got within its
879
+ wait leaves that repository's lists unread: its count cannot be read and each create is kept (ICAP-B7). A dry
880
+ run takes no lock. See `_file` for the rest."""
881
+ if dry_run:
882
+ return _file(decisions, host, outbox, {}, dry_run=True, now=now, comments_today=comments_today,
883
+ issue_cap=issue_cap)
884
+ from tempergraph.durability import lock
885
+ from tempergraph.store.layout import home_path
886
+
887
+ folder = (home or home_path()) / "locks" / "loop-issue-cap"
888
+ repos = sorted({d.repo for d in decisions if d.action == "file" and d.repo}
889
+ | {str(e.get("repo")) for e in outbox.entries() if e.get("op") == "create" and e.get("repo")})
890
+ listed: Listed = {}
891
+ with contextlib.ExitStack() as stack:
892
+ for repo in repos:
893
+ try:
894
+ stack.enter_context(lock.exclusive(folder / (re.sub(r"[^A-Za-z0-9._-]", "-", repo) + ".lock")))
895
+ except (lock.LockHeld, OSError):
896
+ listed[(repo, "open")] = (None, True) # the count cannot be read
897
+ return _file(decisions, host, outbox, listed, dry_run=False, now=now, comments_today=comments_today,
898
+ issue_cap=issue_cap)
899
+
900
+
901
+ def _file(decisions: Sequence[Decision], host: CodeHost, outbox: Outbox, listed: Listed, *, dry_run: bool = False,
902
+ now: datetime | None = None, comments_today: Mapping[tuple[str, int], int] | None = None,
903
+ issue_cap: int = 3) -> list[dict[str, Any]]:
904
+ """SIL-B2, ISS-B7: the findings of one cause key go to one issue: a comment on the open issue that holds one of
905
+ their fingerprints or the cause key, else (ISS-B3 to ISS-B6: not planned or duplicate mutes, completed links a
906
+ possible regression) one new issue for all of them; ISS-B13: a comment over `seen_again.max_per_issue_per_day`
907
+ (with `comments_today`, the comments each (repo, number) got on `now`'s UTC day) is not sent and leaves one
908
+ `comment_capped` result; ISS-B9: issues are read from the label list, once per repository and state; a dry run
909
+ reads the open loop issues, the other open issues and the comments of candidates, and the closed list to count
910
+ the creates it shows against the cap, and writes nothing (SIL-B6, PBD-B9, ICAP-B11). ICAP-B3 to ICAP-B7: a create is sent only while the repository's day count (the
911
+ loop issues of the open and closed lists created on `now`'s UTC day, raised by this call's creates) is under
912
+ `issue_cap`; otherwise, or when the count cannot be read, it goes to the outbox marked `capped` and leaves one
913
+ `capped` result."""
914
+ results: list[dict[str, Any]] = []
915
+ now = now or datetime.now(UTC)
916
+ sent_now: dict[tuple[str, int], int] = {} # the comments this call has sent, by (repo, issue number)
917
+ counts: dict[str, int] = {} # the day's count of each repository, read once and raised by each create sent
918
+ if not dry_run:
919
+ for p in sorted(outbox.take(), key=_queue_order): # ICAP-B8: oldest queue time first, none last, before new creates
920
+ _redeliver(p, host, outbox, results, now, comments_today, listed, sent_now, issue_cap, counts)
921
+ groups: dict[tuple[str, str], list[Decision]] = {}
922
+ for d in decisions:
923
+ f = d.candidate.finding
924
+ fp = str(f.get("fingerprint"))
925
+ if d.action != "file" or d.repo is None:
926
+ results.append({"op": "recorded", "reason": d.reason, "fingerprint": fp})
927
+ continue
928
+ groups.setdefault((d.repo, cause_key(f)), []).append(d)
929
+ for (repo, key), ds in groups.items():
930
+ fps = list(dict.fromkeys(str(x.candidate.finding.get("fingerprint")) for x in ds))
931
+ if dry_run: # PBD-B9, PBD-B10: the same reads, no write
932
+ results += _dry_group(host, repo, key, ds, fps, listed, issue_cap, now, counts)
933
+ continue
934
+ note = None
935
+ if (repo, "open") not in listed:
936
+ listed[(repo, "open")] = _read(host, repo, "open")
937
+ opened, failed = listed[(repo, "open")]
938
+ if failed:
939
+ note = "search_failed" # retried once, then files anyway and says why
940
+ match = _match_open(opened or [], fps, key)
941
+ regression: int | None = None
942
+ source: int | None = None # the closed loop issue whose close as a duplicate sends the comment to `match`
943
+ has_target = False # BND-B1: a binding to a target wins over a pre-bind
944
+ if match is None and not failed: # an open issue always wins; only then do closed ones count
945
+ if (repo, "closed") not in listed:
946
+ listed[(repo, "closed")] = _read(host, repo, "closed")
947
+ closed, cfailed = listed[(repo, "closed")]
948
+ mine = [i for i in closed or [] if _holds(i, [*(_marker_line(fp) for fp in fps), _cause_line(key)])]
949
+ last = max(mine, key=_closed_at) if mine else None
950
+ if cfailed:
951
+ note = "closed_search_failed" # files with no link and no mute (ISS-B6)
952
+ elif last is not None:
953
+ reason = str(last.get("state_reason") or "")
954
+ days = float(params.value("mute.days"))
955
+ if reason == "duplicate" and isinstance(last.get("number"), int): # BND-B1 to BND-B7
956
+ got = bindings.learn(host, repo, key, last, outbox.path.parent, now)
957
+ if got.state == "unreadable": # BND-B6: no issue, no comment
958
+ results.append({"op": "binding_unreadable", "cause_key": key, "repo": repo})
959
+ continue
960
+ if got.given_up: # BND-B16: decided as if no target were named
961
+ note = f"{note} binding_given_up" if note else "binding_given_up"
962
+ if got.state == "bound":
963
+ has_target = True
964
+ if got.learned:
965
+ results.append({"op": "bound", "cause_key": key, "repo": repo, "source": int(last["number"]),
966
+ "target": int(got.number or 0)})
967
+ if str(got.issue.get("state") or "") == "open":
968
+ match, source = got.issue, int(last["number"])
969
+ else: # BND-B5: the closed target decides as a closed loop issue does; no chain is followed
970
+ last, reason = got.issue, str(got.issue.get("state_reason") or "")
971
+ if match is None:
972
+ if reason in ("not_planned", "duplicate") and now - _closed_at(last) < timedelta(days=days):
973
+ results += [{"op": "muted", "url": last.get("url"), "fingerprint": fp,
974
+ **({"note": note} if note else {})} for fp in fps] # ISS-B3
975
+ continue
976
+ if reason == "completed" and last.get("number") is not None:
977
+ regression = int(last["number"]) # ISS-B4
978
+ f = ds[0].candidate.finding
979
+ prebound: tuple[int, str] | None = None
980
+ related: list[int] = []
981
+ if match is None and not failed and not has_target: # PBD-B4, PBD-B7, PBD-B8: look for a person's open issue
982
+ if (repo, "others") not in listed:
983
+ listed[(repo, "others")] = prebinding.read_open(host, repo)
984
+ others, ofailed = listed[(repo, "others")]
985
+ if ofailed:
986
+ note = f"{note} prebind_search_failed" if note else "prebind_search_failed"
987
+ elif others:
988
+ reader: Any = host
989
+
990
+ def read_comments(n: int, r: str = repo, h: Any = reader) -> Any:
991
+ return h.issue_comments(r, n)
992
+
993
+ found = prebinding.candidates(others, f, read_comments)
994
+ if found.failed:
995
+ note = f"{note} prebind_search_failed" if note else "prebind_search_failed"
996
+ elif len(found.issues) == 1 and found.rule is not None:
997
+ prebound = (int(found.issues[0]["number"]), found.rule)
998
+ match = found.issues[0]
999
+ else:
1000
+ related = found.numbers
1001
+ if prebound is not None: # PBD-B5: one record, written also when the comment is capped or queued
1002
+ results.append({"op": "prebound", "cause_key": key, "repo": repo, "number": prebound[0],
1003
+ "rule": prebound[1]})
1004
+ if match is not None: # ISS-B13: at most the bound of "seen again" comments to one issue in one UTC day
1005
+ ident = (repo, int(match["number"]))
1006
+ if (comments_today or {}).get(ident, 0) + sent_now.get(ident, 0) >= int(
1007
+ params.value("seen_again.max_per_issue_per_day")):
1008
+ results.append({"op": "comment_capped", "number": ident[1], "repo": repo, "fingerprint": fps[0]})
1009
+ continue
1010
+ if match is not None:
1011
+ text = comment_body(ds)
1012
+ if source is not None: # BND-B4: a comment on a target says where it comes from
1013
+ text = bindings.opening_sentence(str(f.get("workflow")), str(f.get("cause")),
1014
+ list(dict.fromkeys(_unit(x.candidate.finding) for x in ds)),
1015
+ source) + "\n" + text
1016
+ elif prebound is not None: # PBD-B4: the opening sentence names workflow, cause and units
1017
+ text = prebinding.opening_sentence(str(f.get("workflow")), str(f.get("cause")),
1018
+ list(dict.fromkeys(_unit(x.candidate.finding) for x in ds))
1019
+ ) + "\n" + text
1020
+ p = {"op": "comment", "repo": repo, "number": int(match["number"]), "fingerprint": fps[0], "body": text}
1021
+ else:
1022
+ p = {"op": "create", "repo": repo, "title": title(f), "body": body(ds, regression, related),
1023
+ "labels": _labels(f, ds[0].candidate.issue_labels), "fingerprint": fps[0],
1024
+ "comment": comment_body(ds), # ISS-B16: a later send as a comment carries the same context
1025
+ "workflow": str(f.get("workflow")), "cause": str(f.get("cause")), # BND-B11: ids for the opening sentence
1026
+ "units": list(dict.fromkeys(_unit(x.candidate.finding) for x in ds))}
1027
+ if p["op"] == "create": # ICAP-B3 to ICAP-B7: a create goes only while the day's count is under the cap
1028
+ today = _today(host, repo, listed, now, counts)
1029
+ if today is None or today >= issue_cap:
1030
+ _keep_for_cap(p, outbox, results, issue_cap, today, fps[0])
1031
+ continue
1032
+ try:
1033
+ url = _deliver(host, p)
1034
+ except CodeHostError:
1035
+ outbox.add(p)
1036
+ results += [{"op": "queued", "fingerprint": fp} for fp in fps]
1037
+ continue
1038
+ op = "commented" if p["op"] == "comment" else "filed"
1039
+ if op == "commented":
1040
+ sent_now[(repo, int(p["number"]))] = sent_now.get((repo, int(p["number"])), 0) + 1
1041
+ else:
1042
+ counts[repo] = counts.get(repo, 0) + 1
1043
+ where = {"repo": repo, **({"number": int(p["number"])} if op == "commented" else {})} # FFD-B5
1044
+ results.append({"op": op, "url": url, "fingerprint": fps[0], **where, **({"related": related} if op == "filed" else {}),
1045
+ **({"note": note} if note else {})})
1046
+ results += [{"op": "grouped", "url": url, "fingerprint": fp, "with": fps[0]} for fp in fps[1:]]
1047
+ return results