pythia-knowledge 1.0.0__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 (64) hide show
  1. pythia/__init__.py +3 -0
  2. pythia/cli.py +246 -0
  3. pythia/connectors/__init__.py +0 -0
  4. pythia/connectors/claude_code.py +467 -0
  5. pythia/connectors/common.py +99 -0
  6. pythia/connectors/confluence.py +803 -0
  7. pythia/connectors/github.py +444 -0
  8. pythia/connectors/incident_io.py +365 -0
  9. pythia/connectors/slack.py +674 -0
  10. pythia/consumer.py +268 -0
  11. pythia/daemon.py +650 -0
  12. pythia/db.py +80 -0
  13. pythia/docker-compose.yml +15 -0
  14. pythia/embed.py +39 -0
  15. pythia/events.py +339 -0
  16. pythia/evolution.py +392 -0
  17. pythia/ids.py +12 -0
  18. pythia/jobs.py +103 -0
  19. pythia/knowledge.py +494 -0
  20. pythia/llm/__init__.py +0 -0
  21. pythia/llm/client.py +328 -0
  22. pythia/mcp_server.py +73 -0
  23. pythia/migrations/001_schema.sql +536 -0
  24. pythia/migrations/__init__.py +0 -0
  25. pythia/pipeline/__init__.py +0 -0
  26. pythia/pipeline/adjudicate.py +297 -0
  27. pythia/pipeline/batch.py +254 -0
  28. pythia/pipeline/correct.py +227 -0
  29. pythia/pipeline/derive.py +317 -0
  30. pythia/pipeline/live.py +149 -0
  31. pythia/pipeline/process.py +472 -0
  32. pythia/pipeline/prompts.py +260 -0
  33. pythia/pipeline/reconcile.py +168 -0
  34. pythia/pipeline/schemas.py +154 -0
  35. pythia/pipeline/sweep.py +155 -0
  36. pythia/quality.py +359 -0
  37. pythia/reexplain.py +248 -0
  38. pythia/retrieval.py +137 -0
  39. pythia/services.py +41 -0
  40. pythia/settings.py +194 -0
  41. pythia/usage.py +135 -0
  42. pythia/value.py +265 -0
  43. pythia/vault.py +31 -0
  44. pythia/web/__init__.py +0 -0
  45. pythia/web/app.py +779 -0
  46. pythia/web/graph.py +167 -0
  47. pythia/web/processing.py +131 -0
  48. pythia/web/static/explore.js +242 -0
  49. pythia/web/static/style.css +120 -0
  50. pythia/web/templates/_now.html +25 -0
  51. pythia/web/templates/base.html +30 -0
  52. pythia/web/templates/config.html +231 -0
  53. pythia/web/templates/costs.html +30 -0
  54. pythia/web/templates/evolution.html +153 -0
  55. pythia/web/templates/explore.html +36 -0
  56. pythia/web/templates/label.html +22 -0
  57. pythia/web/templates/quality.html +141 -0
  58. pythia/web/templates/sources.html +249 -0
  59. pythia/web/templates/usage.html +33 -0
  60. pythia_knowledge-1.0.0.dist-info/METADATA +197 -0
  61. pythia_knowledge-1.0.0.dist-info/RECORD +64 -0
  62. pythia_knowledge-1.0.0.dist-info/WHEEL +4 -0
  63. pythia_knowledge-1.0.0.dist-info/entry_points.txt +2 -0
  64. pythia_knowledge-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,444 @@
1
+ """GitHub connector: PRs of the repository allowlist.
2
+
3
+ A PR is processed when it SETTLES: merged, closed, or open and idle for more
4
+ than `stale_days`. Activity after that becomes a delta (only what is new). Each
5
+ description, review, comment and the diff summary is a piece of evidence; editing a
6
+ description/comment retracts the previous version; a deleted comment (in a complete
7
+ listing) becomes a tombstone. Backfill of `horizon_days`, from most recent to
8
+ oldest. Everything deterministic: read, split and store.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from datetime import datetime, timedelta, timezone
15
+ from typing import Any, Callable
16
+
17
+ import httpx
18
+ from psycopg.types.json import Jsonb
19
+
20
+ from .. import vault
21
+ from ..db import Database
22
+ from .common import Item, NotFound, SourceUnavailable, create_unit, sync_stream
23
+
24
+ KIND = "github"
25
+ API = "https://api.github.com"
26
+ _NEXT = re.compile(r'<([^>]+)>;\s*rel="next"')
27
+
28
+
29
+ def source_id_for(repo: str) -> str:
30
+ return f"{KIND}:{repo.lower()}"
31
+
32
+
33
+ def _ts(value: str | None) -> datetime | None:
34
+ return datetime.fromisoformat(value.replace("Z", "+00:00")) if value else None
35
+
36
+
37
+ def resolve_token(cfg: dict) -> str:
38
+ """API-only integration: personal token stored in the Keychain (nothing from the user's local environment)."""
39
+ token = vault.get_secret(vault.GITHUB_TOKEN)
40
+ if not token:
41
+ raise SourceUnavailable("GitHub token not configured (Settings → GitHub)")
42
+ return token
43
+
44
+
45
+ class GitHubClient:
46
+ def __init__(self, token: str, transport: httpx.BaseTransport | None = None):
47
+ self.http = httpx.Client(base_url=API, transport=transport, timeout=30, headers={
48
+ "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json",
49
+ "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "pythia"})
50
+
51
+ def get(self, path: str, params: dict | None = None) -> Any:
52
+ try:
53
+ r = self.http.get(path, params=params)
54
+ except httpx.HTTPError as exc:
55
+ raise SourceUnavailable(f"GitHub unreachable: {exc}") from exc
56
+ self._check(r)
57
+ return r.json()
58
+
59
+ def pages(self, path: str, params: dict | None = None, stop: Callable[[dict], bool] | None = None):
60
+ """Iterates paginated items (Link: rel=next). `stop(item)` interrupts pagination."""
61
+ url, query = path, {"per_page": 100, **(params or {})}
62
+ while url:
63
+ try:
64
+ r = self.http.get(url, params=query)
65
+ except httpx.HTTPError as exc:
66
+ raise SourceUnavailable(f"GitHub unreachable: {exc}") from exc
67
+ self._check(r)
68
+ for item in r.json():
69
+ if stop and stop(item):
70
+ return
71
+ yield item
72
+ m = _NEXT.search(r.headers.get("link", ""))
73
+ url, query = (m.group(1), None) if m else (None, None)
74
+
75
+ @staticmethod
76
+ def _check(r: httpx.Response) -> None:
77
+ if r.status_code in (401,):
78
+ raise SourceUnavailable("GitHub rejected the credential (401)")
79
+ if r.status_code in (403, 429) and (r.headers.get("x-ratelimit-remaining") == "0" or r.status_code == 429):
80
+ raise SourceUnavailable(f"GitHub rate limit (reset {r.headers.get('x-ratelimit-reset')})")
81
+ if r.status_code == 404:
82
+ raise NotFound(f"not found or no access: {r.request.url.path}")
83
+ if r.status_code >= 500:
84
+ raise SourceUnavailable(f"GitHub {r.status_code}")
85
+ r.raise_for_status()
86
+
87
+
88
+ def owner_login(cfg: dict, client: GitHubClient) -> str:
89
+ return cfg.get("owner_login") or client.get("/user")["login"]
90
+
91
+
92
+ def verify_token(client: GitHubClient, cfg: dict) -> None:
93
+ """Checks the token before reading. Classic: needs the `repo` scope (GitHub has no read-only
94
+ scope for private repositories). Fine-grained: permissions are per repository and GitHub
95
+ does not report them here; a repository without access shows up as an error of that source."""
96
+ try:
97
+ r = client.http.get("/user")
98
+ except httpx.HTTPError as exc:
99
+ raise SourceUnavailable(f"GitHub unreachable: {exc}") from exc
100
+ client._check(r)
101
+ if (cfg.get("token_type") or "classic") != "classic":
102
+ return
103
+ scopes = {x.strip() for x in (r.headers.get("x-oauth-scopes") or "").split(",") if x.strip()}
104
+ if "repo" not in scopes:
105
+ raise SourceUnavailable("classic token without the `repo` scope (required to read PRs of private repositories)")
106
+
107
+
108
+ class GitHubConnector:
109
+ def __init__(self, db: Database, client: GitHubClient, cfg: dict, owner_name: str, team: list[dict] | None = None):
110
+ self.db = db
111
+ self.gh = client
112
+ self.cfg = cfg
113
+ self.owner_name = owner_name
114
+ self.team = team or []
115
+ self._owner_login: str | None = None
116
+
117
+ @property
118
+ def me(self) -> str:
119
+ if self._owner_login is None:
120
+ self._owner_login = owner_login(self.cfg, self.gh)
121
+ return self._owner_login
122
+
123
+ def scan(self, source: dict, now: datetime | None = None) -> dict:
124
+ now = now or datetime.now(timezone.utc)
125
+ repo = source["config"]["repo"]
126
+ stats = {"listed": 0, "settled": 0, "units": 0}
127
+ state_key = f"github_cursor:{repo.lower()}"
128
+ row = self.db.one("SELECT value FROM system_state WHERE key = %s", (state_key,))
129
+ cursor = _ts(row["value"]["updated_at"]) if row else None
130
+ horizon = now - timedelta(days=int(source["config"].get("horizon_days") or self.cfg["horizon_days"]))
131
+ floor = max(horizon, cursor - timedelta(hours=1)) if cursor else horizon
132
+ info = self.gh.get(f"/repos/{repo}")
133
+ newest = cursor
134
+ for pr in self.gh.pages(f"/repos/{repo}/pulls", {"state": "all", "sort": "updated", "direction": "desc"},
135
+ stop=lambda p: _ts(p["updated_at"]) < floor):
136
+ stats["listed"] += 1
137
+ updated = _ts(pr["updated_at"])
138
+ newest = max(newest, updated) if newest else updated
139
+ self._upsert_stream(source, repo, pr, info.get("archived", False))
140
+ if newest:
141
+ self.db.execute(
142
+ """INSERT INTO system_state (key, value) VALUES (%s, %s)
143
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()""",
144
+ (state_key, Jsonb({"updated_at": newest.isoformat()})))
145
+ # Settles what is eligible (including open PRs that went idle without new activity).
146
+ stale_before = now - timedelta(days=int(self.cfg["stale_days"]))
147
+ for st in self.db.query("SELECT * FROM streams WHERE source_id = %s AND status = 'active'", (source["id"],)):
148
+ m = st["meta"]
149
+ updated = _ts(m.get("updated_at"))
150
+ if updated is None or updated < horizon:
151
+ continue
152
+ if m.get("settled_updated_at") == m.get("updated_at"):
153
+ continue
154
+ done = m.get("merged_at") or m.get("state") == "closed"
155
+ if not done and updated > stale_before:
156
+ continue
157
+ stats["settled"] += 1
158
+ if self._settle(source, repo, st):
159
+ stats["units"] += 1
160
+ return stats
161
+
162
+ def _upsert_stream(self, source: dict, repo: str, pr: dict, archived: bool) -> None:
163
+ sid = f"{KIND}:{repo.lower()}#{pr['number']}"
164
+ meta = {"number": pr["number"], "state": pr["state"], "merged_at": pr.get("merged_at"),
165
+ "updated_at": pr["updated_at"], "title": pr["title"], "author": pr["user"]["login"],
166
+ "url": pr["html_url"], "archived": archived}
167
+ self.db.execute(
168
+ """INSERT INTO streams (id, source_id, locator, title, meta, last_change_at)
169
+ VALUES (%s, %s, %s, %s, %s, now())
170
+ ON CONFLICT (id) DO UPDATE SET title = EXCLUDED.title,
171
+ meta = streams.meta || EXCLUDED.meta, last_change_at = CASE
172
+ WHEN streams.meta->>'updated_at' IS DISTINCT FROM EXCLUDED.meta->>'updated_at' THEN now()
173
+ ELSE streams.last_change_at END, updated_at = now()""",
174
+ (sid, source["id"], pr["html_url"], pr["title"], Jsonb(meta)))
175
+
176
+ # ------------------------------------------------------------ who and what is read
177
+
178
+ def _excluded_author(self, user: dict | None) -> bool:
179
+ return bool(user) and user.get("login", "").lower() in {a.lower() for a in self.cfg.get("exclude_authors") or []}
180
+
181
+ def _is_bot(self, user: dict | None) -> bool:
182
+ """A bot is whatever GitHub itself flags as a bot (never inferred from the name). Exceptions: bots the owner reads."""
183
+ if not user or user.get("type") != "Bot":
184
+ return False
185
+ return user.get("login", "").lower() not in {b.lower() for b in self.cfg.get("read_bots") or []}
186
+
187
+ def _skip(self, user: dict | None) -> bool:
188
+ return self._excluded_author(user) or self._is_bot(user)
189
+
190
+ def _excluded_path(self, path: str) -> bool:
191
+ return excluded_path(path, self.cfg.get("exclude_paths") or [])
192
+
193
+ def _who(self, login: str) -> str:
194
+ return f"{login} ({self.owner_name}, the owner)" if login.lower() == self.me.lower() else login
195
+
196
+ def collect(self, repo: str, number: int, source: dict | None = None) -> tuple[dict, list[Item], list[str]]:
197
+ """Fetches everything of the PR and assembles the evidence. Returns (pr, items, participants).
198
+
199
+ Listings are complete or raise an error. If the PR does not pass the repository mode, the
200
+ files are not even fetched (empty items)."""
201
+ pr = self.gh.get(f"/repos/{repo}/pulls/{number}")
202
+ reviews = list(self.gh.pages(f"/repos/{repo}/pulls/{number}/reviews"))
203
+ rcomments = list(self.gh.pages(f"/repos/{repo}/pulls/{number}/comments"))
204
+ icomments = list(self.gh.pages(f"/repos/{repo}/issues/{number}/comments"))
205
+ participants = pr_participants(pr, reviews, rcomments, icomments)
206
+ if source is not None and not passes_mode(source, participants, self.me, self.team_logins()):
207
+ return pr, [], participants
208
+
209
+ status = ("merged on " + pr["merged_at"][:10]) if pr.get("merged_at") else (
210
+ "closed without merge on " + (pr.get("closed_at") or "")[:10] if pr["state"] == "closed" else "open")
211
+ author = pr["user"]["login"]
212
+ items: list[Item] = []
213
+ if not self._excluded_author(pr["user"]):
214
+ items.append(Item(
215
+ external_id=f"pr:{pr['id']}", author=author, role="author", occurred_at=_ts(pr["created_at"]),
216
+ content=(f"PR {repo}#{number}: {pr['title']}\nAuthor: {self._who(author)} · {status} · "
217
+ f"{pr['base']['ref']} ← {pr['head']['ref']}\n\n{pr.get('body') or '(no description)'}"),
218
+ meta={"url": pr["html_url"], "kind": "description"}))
219
+ for rv in reviews:
220
+ if self._skip(rv.get("user")):
221
+ continue
222
+ if not (rv.get("body") or "").strip() and rv["state"] not in ("APPROVED", "CHANGES_REQUESTED"):
223
+ continue
224
+ login = rv["user"]["login"] if rv.get("user") else "?"
225
+ items.append(Item(
226
+ external_id=f"review:{rv['id']}", author=login, role="reviewer",
227
+ occurred_at=_ts(rv.get("submitted_at")) or _ts(pr["updated_at"]),
228
+ content=f"Review by {self._who(login)} ({rv['state']}):\n{rv.get('body') or ''}",
229
+ meta={"url": rv.get("html_url"), "kind": "review", "bot": (rv.get("user") or {}).get("type") == "Bot"}))
230
+ # A thread that starts with a bot leaves whole (including human replies).
231
+ by_id = {c["id"]: c for c in rcomments}
232
+
233
+ def root(c):
234
+ seen = set()
235
+ while c.get("in_reply_to_id") and c["in_reply_to_id"] in by_id and c["id"] not in seen:
236
+ seen.add(c["id"])
237
+ c = by_id[c["in_reply_to_id"]]
238
+ return c
239
+
240
+ for c in rcomments:
241
+ if self._skip(c.get("user")) or self._is_bot(root(c).get("user")):
242
+ continue
243
+ if self._excluded_path(c.get("path") or ""):
244
+ continue
245
+ where = f"{c.get('path')}:{c.get('line') or c.get('original_line') or '?'}"
246
+ hunk = c.get("diff_hunk") or ""
247
+ reply = " (reply)" if c.get("in_reply_to_id") else ""
248
+ items.append(Item(
249
+ external_id=f"rcomment:{c['id']}", author=c["user"]["login"], role="reviewer",
250
+ occurred_at=_ts(c["created_at"]),
251
+ content=(f"Comment{reply} by {self._who(c['user']['login'])} on {where}:\n"
252
+ + (f"Commented excerpt:\n```diff\n{hunk}\n```\n" if hunk else "") + c["body"]),
253
+ meta={"url": c.get("html_url"), "kind": "code_comment", "path": c.get("path"),
254
+ "thread": root(c)["id"], "bot": c["user"].get("type") == "Bot"}))
255
+ for c in icomments:
256
+ if self._skip(c.get("user")):
257
+ continue
258
+ items.append(Item(
259
+ external_id=f"icomment:{c['id']}", author=c["user"]["login"], role="comment",
260
+ occurred_at=_ts(c["created_at"]),
261
+ content=f"Comment by {self._who(c['user']['login'])}:\n{c['body']}",
262
+ meta={"url": c.get("html_url"), "kind": "comment", "bot": c["user"].get("type") == "Bot"}))
263
+ items.extend(self._file_items(repo, number, pr))
264
+ return pr, items, participants
265
+
266
+ def _file_items(self, repo: str, number: int, pr: dict) -> list[Item]:
267
+ """Whole diff, one piece of evidence per file. Nothing is cut; a missing patch is recorded."""
268
+ when = _ts(pr.get("merged_at") or pr.get("closed_at") or pr["updated_at"])
269
+ out = []
270
+ for f in self.gh.pages(f"/repos/{repo}/pulls/{number}/files"):
271
+ if self._excluded_path(f["filename"]):
272
+ continue
273
+ renamed = f" (before: {f['previous_filename']})" if f.get("previous_filename") else ""
274
+ patch = f.get("patch")
275
+ body = patch if patch else "(GitHub did not provide this file's patch: binary or too large)"
276
+ out.append(Item(
277
+ external_id=f"file:{pr['id']}:{f['filename']}", author=pr["user"]["login"], role="artifact",
278
+ occurred_at=when,
279
+ content=f"File {f['filename']}{renamed} — {f['status']}, +{f['additions']}/-{f['deletions']}\n```diff\n{body}\n```",
280
+ meta={"kind": "file", "path": f["filename"], "patch_missing": not patch}))
281
+ return out
282
+
283
+ def team_logins(self) -> set[str]:
284
+ return {m["github"].lower() for m in self.team if m.get("github")}
285
+
286
+ def _settle(self, source: dict, repo: str, stream: dict) -> bool:
287
+ number = stream["meta"]["number"]
288
+ pr, items, participants = self.collect(repo, number, source)
289
+ passes = bool(items) or passes_mode(source, participants, self.me, self.team_logins())
290
+ created = []
291
+ with self.db.tx() as conn:
292
+ # Outside the repository mode: what had already been read from this PR is retracted.
293
+ fresh = sync_stream(conn, source_id=source["id"], stream_id=stream["id"], items=items, complete=True,
294
+ reason="edited, removed on GitHub or outside the filters")
295
+ meta = {"repo": repo, "number": number, "url": pr["html_url"], "state": pr["state"],
296
+ "merged_at": pr.get("merged_at"), "archived": stream["meta"].get("archived", False),
297
+ "delta": bool(stream["meta"].get("settled_updated_at"))}
298
+ for i, part in enumerate(split_items(fresh)):
299
+ uid = create_unit(conn, source_id=source["id"], stream_id=stream["id"], kind="pull_request",
300
+ title=f"{repo}#{number}: {pr['title']}" + (f" (part {i + 1})" if i else ""),
301
+ items=part, meta={**meta, "part": i + 1})
302
+ if uid:
303
+ created.append(uid)
304
+ conn.execute("UPDATE streams SET meta = meta || %s, last_settled_at = now() WHERE id = %s",
305
+ (Jsonb({"settled_updated_at": stream["meta"]["updated_at"], "participants": participants,
306
+ "filtered": not passes}), stream["id"]))
307
+ return bool(created)
308
+
309
+
310
+ # ---------------------------------------------------------------- filters (structural, configured by the owner)
311
+
312
+ MODES = {"all": "all PRs", "owner": "only those involving you", "team": "those involving you or your team"}
313
+ DEFAULT_MODE = "team"
314
+ _MENTION = re.compile(r"(?<![\w@])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))")
315
+ MAX_UNIT_CHARS = 300_000
316
+
317
+
318
+ def pr_participants(pr: dict, reviews: list, rcomments: list, icomments: list) -> list[str]:
319
+ """Who takes part in the PR, per what GitHub itself records (author, reviewers, commenters,
320
+ review requests, assignees and @mentions in the description)."""
321
+ logins = {pr["user"]["login"]}
322
+ logins |= {r["user"]["login"] for r in reviews if r.get("user")}
323
+ logins |= {c["user"]["login"] for c in rcomments + icomments if c.get("user")}
324
+ logins |= {u["login"] for u in pr.get("requested_reviewers") or []}
325
+ logins |= {u["login"] for u in pr.get("assignees") or []}
326
+ logins |= set(_MENTION.findall(pr.get("body") or ""))
327
+ return sorted(l.lower() for l in logins)
328
+
329
+
330
+ def passes_mode(source: dict, participants: list[str], owner_login: str, team_logins: set[str]) -> bool:
331
+ mode = source["config"].get("mode") or DEFAULT_MODE
332
+ if mode == "all":
333
+ return True
334
+ people = {owner_login.lower()} | (team_logins if mode == "team" else set())
335
+ return bool(people & set(participants))
336
+
337
+
338
+ def excluded_path(path: str, patterns: list[str]) -> bool:
339
+ from fnmatch import fnmatch
340
+ return any(fnmatch(path, p) or fnmatch(path.rsplit("/", 1)[-1], p) for p in patterns)
341
+
342
+
343
+ def split_items(items: list[Item], limit: int = MAX_UNIT_CHARS) -> list[list[Item]]:
344
+ """A PR larger than the context becomes several units (by file), without cutting or discarding anything."""
345
+ head = [i for i in items if i.meta.get("kind") != "file"]
346
+ files = [i for i in items if i.meta.get("kind") == "file"]
347
+ parts: list[list[Item]] = []
348
+ current, size = list(head), sum(len(i.content) for i in head)
349
+ for f in files:
350
+ if current and size + len(f.content) > limit:
351
+ parts.append(current)
352
+ current, size = [], 0
353
+ current.append(f)
354
+ size += len(f.content)
355
+ if current:
356
+ parts.append(current)
357
+ return parts
358
+
359
+
360
+ # ---------------------------------------------------------------- reapply filters, remove, estimate
361
+
362
+
363
+ def reapply_filters(db, source: dict, cfg: dict, owner_login: str, team_logins: set[str]) -> dict:
364
+ """The filters changed: retracts what fell outside and forces a re-read of the rest (what passes
365
+ again comes in as new evidence; what did not change is deduplicated by hash, at no LLM cost)."""
366
+ from .. import knowledge as K
367
+
368
+ stats = {"retracted": 0, "reread": 0}
369
+ excluded = {a.lower() for a in cfg.get("exclude_authors") or []}
370
+ read_bots = {b.lower() for b in cfg.get("read_bots") or []}
371
+ paths = cfg.get("exclude_paths") or []
372
+ with db.tx() as conn:
373
+ ids = []
374
+ for ev in conn.execute(
375
+ """SELECT e.id, e.author, e.meta, s.meta AS stream_meta FROM evidence e JOIN streams s ON s.id = e.stream_id
376
+ WHERE e.source_id = %s AND e.status = 'active'""", (source["id"],)).fetchall():
377
+ m, sm = ev["meta"], ev["stream_meta"]
378
+ out = (ev["author"] or "").lower() in excluded
379
+ out |= bool(m.get("bot")) and (ev["author"] or "").lower() not in read_bots
380
+ out |= bool(m.get("path")) and excluded_path(m["path"], paths)
381
+ out |= bool(sm.get("participants") is not None) and not passes_mode(source, sm["participants"],
382
+ owner_login, team_logins)
383
+ if out:
384
+ ids.append(ev["id"])
385
+ if ids:
386
+ K.tombstone_evidence(conn, "connector", ids, "outside the owner's filters")
387
+ conn.execute("UPDATE evidence SET external_id = NULL WHERE id = ANY(%s)", (ids,))
388
+ stats["retracted"] = len(ids)
389
+ # Re-read: on the next scan every already settled PR is collected again.
390
+ stats["reread"] = conn.execute(
391
+ "UPDATE streams SET meta = meta - 'settled_updated_at' WHERE source_id = %s", (source["id"],)).rowcount
392
+ return stats
393
+
394
+
395
+ def remove_source(db, source_id: str) -> dict:
396
+ """Remove: stops reading and retracts everything that came only from this source. Pausing is just turning off."""
397
+ from .. import knowledge as K
398
+
399
+ with db.tx() as conn:
400
+ src = conn.execute("SELECT config FROM sources WHERE id = %s", (source_id,)).fetchone()
401
+ repo = ((src or {}).get("config") or {}).get("repo")
402
+ ids = [r["id"] for r in conn.execute( # including the version history and the live-read proofs for it
403
+ """SELECT id FROM evidence WHERE (source_id = %s AND status IN ('active', 'superseded'))
404
+ OR (source_id = 'live:github' AND status = 'active' AND meta->>'repo' = %s)""",
405
+ (source_id, (repo or "").lower())).fetchall()]
406
+ stats = K.tombstone_evidence(conn, "connector", ids, "source removed by the owner") if ids else {"evidence": 0}
407
+ conn.execute("UPDATE evidence SET external_id = NULL WHERE source_id = %s", (source_id,))
408
+ conn.execute("DELETE FROM batch_requests WHERE source_id = %s", (source_id,))
409
+ conn.execute("DELETE FROM deferred_derivations WHERE source_id = %s", (source_id,))
410
+ conn.execute("DELETE FROM system_state WHERE key LIKE %s", (f"%{source_id}%",))
411
+ src = conn.execute("SELECT config FROM sources WHERE id = %s", (source_id,)).fetchone()
412
+ if src and src["config"].get("repo"):
413
+ conn.execute("DELETE FROM system_state WHERE key = %s", (f"github_cursor:{src['config']['repo'].lower()}",))
414
+ conn.execute("DELETE FROM sources WHERE id = %s", (source_id,))
415
+ return stats
416
+
417
+
418
+ def estimate_backfill(client: GitHubClient, source: dict, cfg: dict, owner_login: str, team_logins: set[str],
419
+ avg_cost: float, already_read: set[int] | None = None) -> dict:
420
+ """Estimate: PRs in the horizon that pass the mode × measured average cost per PR. `already_read`
421
+ (already settled PRs) is left out: after the backfill, only what remains to be read matters."""
422
+ import time as _t
423
+
424
+ repo = source["config"]["repo"]
425
+ days = int(source["config"].get("horizon_days") or cfg["horizon_days"])
426
+ since = (datetime.now(timezone.utc) - timedelta(days=days)).date().isoformat()
427
+ mode = source["config"].get("mode") or DEFAULT_MODE
428
+ base = f"repo:{repo} is:pr updated:>={since}"
429
+ queries = [base] if mode == "all" else [
430
+ f"{base} involves:{person}" for person in sorted({owner_login.lower()} | (team_logins if mode == "team" else set()))]
431
+ seen, exact = set(), True
432
+ for q in queries:
433
+ for page in range(1, 11): # GitHub search returns at most 1000 results
434
+ r = client.get("/search/issues", {"q": q, "per_page": 100, "page": page})
435
+ seen |= {i["number"] for i in r["items"]}
436
+ _t.sleep(2.1) # GitHub search limit: 30 per minute
437
+ if page * 100 >= r["total_count"]:
438
+ break
439
+ else:
440
+ exact = False
441
+ new = seen - (already_read or set())
442
+ return {"prs": len(seen), "new": len(new), "exact": exact, "avg_cost": avg_cost,
443
+ "usd": round(len(seen) * avg_cost, 2), "usd_new": round(len(new) * avg_cost, 2), "mode": mode,
444
+ "horizon_days": days, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")}