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,674 @@
1
+ """Slack connector: allowlisted channels and DMs, read with the owner's user token (no bot).
2
+
3
+ Units (§6.1):
4
+ - **thread**: the replies to a message. Settles `settle_minutes` after the last reply;
5
+ a new reply after that becomes a delta (only what is new, with the rest of the thread as context);
6
+ - **window**: loose channel messages (no thread), grouped while the gap between one and
7
+ the next is less than `settle_minutes`. The window settles when the channel stays idle that long.
8
+
9
+ Each message is a piece of evidence. On every read, the last `revision_days` are re-read in full:
10
+ an edited message retracts the previous version; a message that vanished becomes a tombstone, but only when the
11
+ listing covers the whole stream (never delete based on an incomplete scan). Everything here is
12
+ plumbing: read, group by time, format Slack markup and store.
13
+
14
+ Bots: every message Slack flags as from a bot (`bot_id` or `subtype=bot_message`) is ignored,
15
+ and so is the whole thread that starts with a bot; `read_bots` are the exceptions. Ignored authors and subtypes
16
+ are owner lists.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import html
22
+ import re
23
+ import time
24
+ from datetime import datetime, timedelta, timezone
25
+
26
+ import httpx
27
+ from psycopg.types.json import Jsonb
28
+
29
+ from .. import vault
30
+ from ..db import Database
31
+ from ..ids import sha
32
+ from .common import Item, SourceUnavailable, create_unit, sync_stream
33
+
34
+ KIND = "slack"
35
+ API = "https://slack.com/api/"
36
+ # User token scopes: read history and list conversations of each type, and user names.
37
+ REQUIRED_SCOPES = {
38
+ "channel": {"channels:history", "channels:read"},
39
+ "private": {"groups:history", "groups:read"},
40
+ "dm": {"im:history", "im:read"},
41
+ "group": {"mpim:history", "mpim:read"},
42
+ }
43
+ BASE_SCOPES = {"users:read"}
44
+ MAX_UNIT_CHARS = 300_000
45
+ _USER = re.compile(r"<@([UW][A-Z0-9]+)(?:\|[^>]*)?>")
46
+ _CHANNEL = re.compile(r"<#([CG][A-Z0-9]+)(?:\|([^>]*))?>")
47
+ _SPECIAL = re.compile(r"<!(here|channel|everyone)(?:\|[^>]*)?>")
48
+ _SUBTEAM = re.compile(r"<!subteam\^([A-Z0-9]+)(?:\|([^>]*))?>")
49
+ _LINK = re.compile(r"<((?:https?|mailto):[^|>]+)(?:\|([^>]*))?>")
50
+
51
+
52
+ def source_id_for(channel_id: str) -> str:
53
+ return f"{KIND}:{channel_id}"
54
+
55
+
56
+ def _dt(ts: str | float) -> datetime:
57
+ return datetime.fromtimestamp(float(ts), tz=timezone.utc)
58
+
59
+
60
+ def resolve_token() -> str:
61
+ """API + owner token only, stored in the Keychain."""
62
+ token = vault.get_secret(vault.SLACK_TOKEN)
63
+ if not token:
64
+ raise SourceUnavailable("Slack token not configured (Settings → Slack)")
65
+ return token
66
+
67
+
68
+ class NotFound(SourceUnavailable):
69
+ """Slack states that the object does not exist (e.g. deleted thread): it is a complete answer, not a failure."""
70
+
71
+
72
+ class SlackClient:
73
+ def __init__(self, token: str, transport: httpx.BaseTransport | None = None, max_wait_s: float = 60):
74
+ self.http = httpx.Client(base_url=API, transport=transport, timeout=30,
75
+ headers={"Authorization": f"Bearer {token}", "User-Agent": "pythia"})
76
+ self.max_wait_s = max_wait_s
77
+ self.scopes: set[str] = set()
78
+
79
+ def call(self, method: str, params: dict | None = None) -> dict:
80
+ """One Web API call. Rate limit: waits for Retry-After (up to `max_wait_s` in
81
+ total per call) and tries again; beyond that, the source is unavailable and the job goes back."""
82
+ waited = 0.0
83
+ while True:
84
+ try:
85
+ r = self.http.get(method, params=params)
86
+ except httpx.HTTPError as exc:
87
+ raise SourceUnavailable(f"Slack unreachable: {exc}") from exc
88
+ if r.status_code == 429:
89
+ wait = float(r.headers.get("retry-after") or 30)
90
+ if waited + wait > self.max_wait_s:
91
+ raise SourceUnavailable(f"Slack rate limit ({method}); will retry later")
92
+ time.sleep(wait)
93
+ waited += wait
94
+ continue
95
+ if r.status_code >= 500:
96
+ raise SourceUnavailable(f"Slack {r.status_code}")
97
+ r.raise_for_status()
98
+ if r.headers.get("x-oauth-scopes") is not None:
99
+ self.scopes = {s.strip() for s in r.headers["x-oauth-scopes"].split(",") if s.strip()}
100
+ body = r.json()
101
+ if not body.get("ok"):
102
+ err = body.get("error", "unknown error")
103
+ if err in ("invalid_auth", "not_authed", "token_revoked", "token_expired", "account_inactive"):
104
+ raise SourceUnavailable(f"Slack rejected the token ({err})")
105
+ if err == "missing_scope":
106
+ raise SourceUnavailable(f"Slack token without the required scope: {body.get('needed')}")
107
+ if err in ("thread_not_found", "message_not_found"):
108
+ raise NotFound(err)
109
+ if err in ("channel_not_found", "not_in_channel"):
110
+ raise SourceUnavailable(f"no access to the conversation ({err})")
111
+ if err == "ratelimited":
112
+ raise SourceUnavailable("Slack rate limit")
113
+ raise SourceUnavailable(f"Slack: {err}")
114
+ return body
115
+
116
+ def pages(self, method: str, key: str, params: dict | None = None):
117
+ """Iterates a cursor listing; ends only when Slack says it is over (complete listing)."""
118
+ cursor = None
119
+ while True:
120
+ body = self.call(method, {**(params or {}), "limit": 200, **({"cursor": cursor} if cursor else {})})
121
+ yield from body.get(key) or []
122
+ cursor = (body.get("response_metadata") or {}).get("next_cursor")
123
+ if not cursor:
124
+ return
125
+
126
+
127
+ def verify_token(client: SlackClient) -> dict:
128
+ """Checks the token before reading: it must be a user token (no bot) and have the read scopes."""
129
+ me = client.call("auth.test")
130
+ if me.get("bot_id"):
131
+ raise SourceUnavailable("the token is a bot token; Pythia reads with the owner's user token (xoxp-)")
132
+ missing = BASE_SCOPES - client.scopes if client.scopes else set()
133
+ if missing:
134
+ raise SourceUnavailable(f"Slack token without the scopes: {', '.join(sorted(missing))}")
135
+ return me
136
+
137
+
138
+ def conversation_kind(c: dict) -> str:
139
+ if c.get("is_im"):
140
+ return "dm"
141
+ if c.get("is_mpim"):
142
+ return "group"
143
+ return "private" if c.get("is_private") else "channel"
144
+
145
+
146
+ def k_scope(kind: str) -> str:
147
+ return {"channel": "channels", "private": "groups", "dm": "im", "group": "mpim"}[kind]
148
+
149
+
150
+ def group_name(mpdm: str, users: dict[str, dict], me_id: str | None = None) -> str:
151
+ """`mpdm-alex.moreira--ana.lima--bruno.reis-1` (Slack's format for group conversations) →
152
+ "Ana Lima, Bruno Reis": logins become names, and the owner is dropped from the list."""
153
+ if not mpdm.startswith("mpdm-"):
154
+ return ""
155
+ by_login = {u.get("login"): u for u in users.values() if u.get("login")}
156
+ body = re.sub(r"-\d+$", "", mpdm[len("mpdm-"):])
157
+ names = []
158
+ for login in body.split("--"):
159
+ u = by_login.get(login)
160
+ if u and u.get("id") == me_id:
161
+ continue
162
+ names.append((u or {}).get("name") or login)
163
+ return ", ".join(names)
164
+
165
+
166
+ def list_conversations(client: SlackClient, users: dict[str, dict], me_id: str | None = None) -> list[dict]:
167
+ """Conversations the owner takes part in (to choose the allowlist on the web)."""
168
+ out = []
169
+ api_types = {"channel": "public_channel", "private": "private_channel", "dm": "im", "group": "mpim"}
170
+ kinds = [k for k in api_types if not client.scopes or f"{k_scope(k)}:read" in client.scopes]
171
+ if not kinds:
172
+ return []
173
+ for c in client.pages("users.conversations", "channels",
174
+ {"types": ",".join(api_types[k] for k in kinds), "exclude_archived": "false"}):
175
+ kind = conversation_kind(c)
176
+ if kind == "dm":
177
+ other = users.get(c.get("user") or "", {})
178
+ name = f"DM with {display_name(other) or c.get('user')}"
179
+ elif kind == "group":
180
+ name = group_name(c.get("name") or "", users, me_id) or c.get("name") or c["id"]
181
+ else:
182
+ name = f"#{c.get('name') or c['id']}"
183
+ out.append({"id": c["id"], "name": name, "kind": kind, "archived": bool(c.get("is_archived"))})
184
+ order = {"channel": 0, "private": 1, "dm": 2, "group": 3}
185
+ return sorted(out, key=lambda c: (order[c["kind"]], c["name"].lower()))
186
+
187
+
188
+ def load_users(client: SlackClient) -> dict[str, dict]:
189
+ users = {}
190
+ for u in client.pages("users.list", "members"):
191
+ users[u["id"]] = {"id": u["id"], "name": display_name(u), "is_bot": bool(u.get("is_bot")),
192
+ "deleted": bool(u.get("deleted")), "login": u.get("name") or ""}
193
+ return users
194
+
195
+
196
+ def display_name(u: dict) -> str:
197
+ if not u:
198
+ return ""
199
+ if "profile" not in u:
200
+ return u.get("name") or ""
201
+ p = u.get("profile") or {}
202
+ return p.get("real_name") or p.get("display_name") or u.get("real_name") or u.get("name") or ""
203
+
204
+
205
+ def raw_hash(msg: dict) -> str:
206
+ """Only what the person wrote or attached (not the formatting nor the resolved names)."""
207
+ import json
208
+ basis = {"text": msg.get("text") or "", "subtype": msg.get("subtype"), "user": msg.get("user"),
209
+ "files": [[f.get("id"), f.get("name"), f.get("title")] for f in msg.get("files") or []],
210
+ "attachments": [[a.get("title"), a.get("text"), a.get("fallback")] for a in msg.get("attachments") or []]}
211
+ return sha(json.dumps(basis, sort_keys=True, ensure_ascii=False))
212
+
213
+
214
+ def is_bot(msg: dict) -> bool:
215
+ """A bot is whatever Slack itself flags as a bot (never inferred from the name)."""
216
+ return bool(msg.get("bot_id")) or msg.get("subtype") == "bot_message"
217
+
218
+
219
+ def bot_name(msg: dict) -> str:
220
+ return (msg.get("bot_profile") or {}).get("name") or msg.get("username") or msg.get("bot_id") or "bot"
221
+
222
+
223
+ class SlackConnector:
224
+ def __init__(self, db: Database, client: SlackClient, cfg: dict, owner_name: str,
225
+ users: dict[str, dict] | None = None, me: dict | None = None):
226
+ self.db = db
227
+ self.api = client
228
+ self.cfg = cfg
229
+ self.owner_name = owner_name
230
+ self.users = users if users is not None else {}
231
+ self.me = me or {}
232
+
233
+ # ------------------------------------------------------------ filters (structural, owner lists)
234
+
235
+ def _bot_allowed(self, msg: dict) -> bool:
236
+ allowed = {b.lower() for b in self.cfg.get("read_bots") or []}
237
+ return bot_name(msg).lower() in allowed or (msg.get("bot_id") or "").lower() in allowed
238
+
239
+ def _excluded_author(self, msg: dict) -> bool:
240
+ excluded = {a.lower() for a in self.cfg.get("exclude_authors") or []}
241
+ uid = msg.get("user") or ""
242
+ u = self.users.get(uid, {})
243
+ return bool(excluded & {uid.lower(), (u.get("name") or "").lower(), (u.get("login") or "").lower()})
244
+
245
+ def skip(self, msg: dict) -> bool:
246
+ if msg.get("subtype") in set(self.cfg.get("ignore_subtypes") or []):
247
+ return True
248
+ if msg.get("subtype") == "tombstone": # "This message was deleted" (kept because it has replies)
249
+ return True
250
+ if is_bot(msg) and not self._bot_allowed(msg):
251
+ return True
252
+ return self._excluded_author(msg)
253
+
254
+ # ------------------------------------------------------------ formatting (Slack markup → text)
255
+
256
+ def who(self, msg: dict) -> str:
257
+ if is_bot(msg):
258
+ return f"{bot_name(msg)} (bot)"
259
+ uid = msg.get("user") or "?"
260
+ name = self.users.get(uid, {}).get("name") or uid
261
+ if uid == self.me.get("user_id"):
262
+ return f"{name} ({self.owner_name}, the owner) [slack:{uid}]"
263
+ return f"{name} [slack:{uid}]"
264
+
265
+ def render_text(self, text: str) -> str:
266
+ def user(m):
267
+ uid = m.group(1)
268
+ name = self.users.get(uid, {}).get("name") or uid
269
+ return f"@{name} [slack:{uid}]"
270
+
271
+ text = _USER.sub(user, text or "")
272
+ text = _CHANNEL.sub(lambda m: f"#{m.group(2) or m.group(1)}", text)
273
+ text = _SPECIAL.sub(lambda m: f"@{m.group(1)}", text)
274
+ text = _SUBTEAM.sub(lambda m: f"@{m.group(2) or m.group(1)}".replace("@@", "@"), text)
275
+ text = _LINK.sub(lambda m: f"{m.group(2)} ({m.group(1)})" if m.group(2) else m.group(1), text)
276
+ return html.unescape(text)
277
+
278
+ def item(self, channel: str, msg: dict, *, reply: bool = False) -> Item:
279
+ parts = [self.render_text(msg.get("text") or "")]
280
+ for a in msg.get("attachments") or []:
281
+ body = a.get("text") or a.get("fallback") or ""
282
+ title = a.get("title") or ""
283
+ if body or title:
284
+ parts.append(f"[attachment: {title}] {self.render_text(body)}".strip())
285
+ for f in msg.get("files") or []:
286
+ parts.append(f"[file: {f.get('title') or f.get('name') or '?'} ({f.get('filetype') or f.get('mimetype') or '?'})]")
287
+ edited = " (edited)" if msg.get("edited") else ""
288
+ head = f"{'Reply' if reply else 'Message'}{edited} by {self.who(msg)}:"
289
+ return Item(external_id=f"msg:{channel}:{msg['ts']}", author=msg.get("user") or bot_name(msg),
290
+ role="reply" if reply else "message", occurred_at=_dt(msg["ts"]),
291
+ content=head + "\n" + "\n".join(p for p in parts if p),
292
+ meta={"kind": "slack", "ts": msg["ts"], "thread_ts": msg.get("thread_ts"),
293
+ "user": msg.get("user"), "bot": is_bot(msg), "subtype": msg.get("subtype"),
294
+ "bot_name": bot_name(msg) if is_bot(msg) else None, "bot_id": msg.get("bot_id"),
295
+ "raw_hash": raw_hash(msg)})
296
+
297
+ def permalink(self, channel: str, ts: str, thread_ts: str | None = None) -> str:
298
+ base = (self.me.get("url") or "https://slack.com/").rstrip("/")
299
+ link = f"{base}/archives/{channel}/p{ts.replace('.', '')}"
300
+ return link + (f"?thread_ts={thread_ts}&cid={channel}" if thread_ts and thread_ts != ts else "")
301
+
302
+ # ------------------------------------------------------------ reading
303
+
304
+ def scan(self, source: dict, now: datetime | None = None) -> dict:
305
+ now = now or datetime.now(timezone.utc)
306
+ cfg = source["config"]
307
+ channel = cfg["channel"]
308
+ settle = float(self.cfg["settle_minutes"]) * 60
309
+ horizon = (now - timedelta(days=int(cfg.get("horizon_days") or self.cfg["horizon_days"]))).timestamp()
310
+ revision = (now - timedelta(days=float(self.cfg["revision_days"]))).timestamp()
311
+ state = dict(cfg.get("state") or {})
312
+ full = not state.get("initialized") or bool(state.get("full_rescan"))
313
+ frontier = float(state.get("last_settled_ts") or 0)
314
+ # First read (or re-read requested by a filter/horizon): the whole horizon. Afterwards, the
315
+ # revision period re-read in full (edits and deletions), going back to the last settled
316
+ # window if the source sat idle longer than that — nothing from the gap is lost.
317
+ start = horizon if full else max(horizon, min(revision, frontier or revision))
318
+ history = list(self.api.pages("conversations.history", "messages",
319
+ {"channel": channel, "oldest": f"{start:.6f}", "inclusive": "true"}))
320
+ # Channel level only; replies "also sent to the channel" belong to the thread.
321
+ top = sorted((m for m in history
322
+ if (not m.get("thread_ts") or m["thread_ts"] == m["ts"]) and m.get("subtype") != "thread_broadcast"),
323
+ key=lambda m: float(m["ts"]))
324
+ stats = {"messages": len(top), "windows": 0, "threads": 0, "units": 0}
325
+ stats["units"] += self._windows(source, channel, top, start, now.timestamp(), settle, frontier, stats)
326
+ stats["units"] += self._threads(source, channel, top, start, now.timestamp(), settle, full, stats)
327
+ self._save_state(source["id"], {"initialized": True}, drop=("full_rescan",))
328
+ return stats
329
+
330
+ def _save_state(self, source_id: str, updates: dict, drop: tuple[str, ...] = ()) -> None:
331
+ """State written by key, right away (checkpoint): an interrupted scan neither loses what it did nor
332
+ erases what another job marked."""
333
+ with self.db.tx() as conn:
334
+ conn.execute(
335
+ """UPDATE sources SET config = jsonb_set(config, '{state}',
336
+ (coalesce(config->'state', '{}'::jsonb) - %s::text[]) || %s, true) WHERE id = %s""",
337
+ (list(drop), Jsonb(updates), source_id))
338
+
339
+ def _windows(self, source, channel, top, start, now, settle, frontier, stats) -> int:
340
+ """Channel-level messages → windows (the one that opens a thread too: the thread keeps only the
341
+ replies). Already settled windows are checked (edit/deletion); new messages are
342
+ grouped while the gap between one and the next is less than `settle` (measured only with what
343
+ passes the filters) and the window lasts at most `window_max_hours`."""
344
+ units = 0
345
+ max_span = float(self.cfg.get("window_max_hours") or 6) * 3600
346
+ ext = lambda m: f"msg:{channel}:{m['ts']}" # noqa: E731
347
+ with self.db.tx() as conn:
348
+ known = {r["external_id"]: r["stream_id"] for r in conn.execute(
349
+ """SELECT e.external_id, e.stream_id FROM evidence e JOIN streams s ON s.id = e.stream_id
350
+ WHERE e.source_id = %s AND e.status = 'active' AND s.meta->>'slack' = 'window'
351
+ AND e.occurred_at >= %s""", (source["id"], _dt(start))).fetchall()}
352
+ windows = conn.execute(
353
+ """SELECT * FROM streams WHERE source_id = %s AND status = 'active' AND meta->>'slack' = 'window'
354
+ AND (meta->>'last_ts')::float >= %s""", (source["id"], start)).fetchall()
355
+ spans = [(float(w["meta"]["first_ts"]), float(w["meta"]["last_ts"]), w["id"]) for w in windows]
356
+
357
+ def window_of(m):
358
+ t = float(m["ts"])
359
+ return next((wid for lo, hi, wid in spans if lo <= t <= hi), None)
360
+
361
+ # 1) Already settled windows: what changed comes in as a delta (edit, or a message that passes
362
+ # the filters again) and what vanished goes out (deletion) — only if the re-read covered the whole window.
363
+ for lo, _hi, wid in spans:
364
+ msgs = [m for m in top if known.get(ext(m)) == wid or (ext(m) not in known and window_of(m) == wid)]
365
+ items = [self.item(channel, m) for m in msgs if not self.skip(m)]
366
+ units += self._settle_stream(source, wid, items, complete=lo >= start, delta=True)
367
+ # 2) Messages not yet in any window: group them and settle the idle ones.
368
+ pending = [m for m in top if not self.skip(m) and ext(m) not in known and window_of(m) is None]
369
+ group: list[dict] = []
370
+ for m in pending:
371
+ t = float(m["ts"])
372
+ if group and (t - float(group[-1]["ts"]) >= settle or t - float(group[0]["ts"]) >= max_span):
373
+ units += self._new_window(source, channel, group, stats)
374
+ frontier = max(frontier, float(group[-1]["ts"]))
375
+ self._save_state(source["id"], {"last_settled_ts": f"{frontier:.6f}"})
376
+ group = []
377
+ group.append(m)
378
+ if group and (now - float(group[-1]["ts"]) >= settle or now - float(group[0]["ts"]) >= max_span):
379
+ units += self._new_window(source, channel, group, stats)
380
+ frontier = max(frontier, float(group[-1]["ts"]))
381
+ self._save_state(source["id"], {"last_settled_ts": f"{frontier:.6f}"})
382
+ return units
383
+
384
+ def _new_window(self, source, channel, msgs, stats) -> int:
385
+ stats["windows"] += 1
386
+ first, last = msgs[0]["ts"], msgs[-1]["ts"]
387
+ sid = f"{source['id']}:w:{first}"
388
+ meta = {"slack": "window", "channel": channel, "first_ts": first, "last_ts": last}
389
+ with self.db.tx() as conn:
390
+ conn.execute(
391
+ """INSERT INTO streams (id, source_id, locator, title, meta, last_change_at)
392
+ VALUES (%s, %s, %s, %s, %s, now()) ON CONFLICT (id) DO UPDATE SET meta = streams.meta || EXCLUDED.meta""",
393
+ (sid, source["id"], self.permalink(channel, first), f"{source['name']} · {_dt(first):%Y-%m-%d %H:%M}",
394
+ Jsonb(meta)))
395
+ return self._settle_stream(source, sid, [self.item(channel, m) for m in msgs], True, delta=False)
396
+
397
+ def _replies(self, channel: str, ts: str, oldest: str | None = None) -> list[dict] | None:
398
+ """Thread replies (complete listing, without `oldest`). None = Slack says the thread does not exist."""
399
+ params = {"channel": channel, "ts": ts, **({"oldest": oldest} if oldest else {})}
400
+ try:
401
+ return list(self.api.pages("conversations.replies", "messages", params))
402
+ except NotFound:
403
+ return None
404
+
405
+ def _threads(self, source, channel, top, start, now, settle, full, stats) -> int:
406
+ """Threads rooted in the period read, already known threads whose root is in the period (the root may
407
+ have lost its replies or vanished) and older threads still watched (new reply)."""
408
+ units = 0
409
+ revision_s = float(self.cfg["revision_hours"]) * 3600
410
+ watch_from = now - float(self.cfg.get("thread_watch_days") or 30) * 86400
411
+ parents = {m["ts"]: m for m in top if m.get("reply_count")}
412
+ with self.db.tx() as conn:
413
+ known = {r["meta"]["thread_ts"]: r for r in conn.execute(
414
+ """SELECT * FROM streams WHERE source_id = %s AND status = 'active' AND meta->>'slack' = 'thread'
415
+ AND ((meta->>'thread_ts')::float >= %s OR (meta->>'latest_reply_seen')::float >= %s)""",
416
+ (source["id"], start, watch_from)).fetchall()}
417
+ for ts in sorted(set(parents) | set(known), key=float):
418
+ st = known.get(ts)
419
+ seen = (st["meta"] if st else {}).get("latest_reply_seen")
420
+ # Per thread (checkpoint): an interrupted full read does not re-read threads already
421
+ # done. The filter re-read erases `latest_reply_seen`, and that is enough to re-read.
422
+ due = not st or now - float(st["meta"].get("revised_at") or 0) >= revision_s
423
+ parent = parents.get(ts)
424
+ if parent is not None:
425
+ latest = parent.get("latest_reply") or ts
426
+ if now - float(latest) < settle:
427
+ continue # still active: wait for it to settle
428
+ with self.db.tx() as conn:
429
+ has_root = root_ready(conn, source["id"], channel, ts)
430
+ if not has_root and not self.skip(parent):
431
+ continue # the message that opens the thread has not been stored yet (its window has not settled)
432
+ if seen == latest and not due:
433
+ continue
434
+ elif float(ts) >= start:
435
+ if not due:
436
+ continue # root in the period, but no replies in the listing: check at revision
437
+ else:
438
+ # Old watched thread: only checks whether there is a new reply (cheap); if there is, re-reads it whole.
439
+ if not due:
440
+ continue
441
+ probe = self._replies(channel, ts, oldest=seen)
442
+ if probe is not None and not any(float(r["ts"]) > float(seen or 0) for r in probe if r["ts"] != ts):
443
+ self._mark_thread(st["id"], {"revised_at": now})
444
+ continue
445
+ listing = self._replies(channel, ts)
446
+ root = parent or next((r for r in listing or [] if r["ts"] == ts), None)
447
+ replies = [r for r in listing or [] if r["ts"] != ts]
448
+ latest = parent.get("latest_reply") if parent else (max((r["ts"] for r in replies), key=float, default=ts))
449
+ if replies and now - float(latest) < settle:
450
+ continue
451
+ # A thread that starts with a bot leaves whole, including human replies.
452
+ root_skipped = root is not None and is_bot(root) and not self._bot_allowed(root)
453
+ if (root_skipped or not replies) and st is None:
454
+ continue # never read and nothing to read
455
+ sid = st["id"] if st else f"{source['id']}:t:{ts}"
456
+ meta = {"slack": "thread", "channel": channel, "thread_ts": ts, "latest_reply_seen": latest,
457
+ "revised_at": now}
458
+ with self.db.tx() as conn:
459
+ conn.execute(
460
+ """INSERT INTO streams (id, source_id, locator, title, meta, last_change_at)
461
+ VALUES (%s, %s, %s, %s, %s, now())
462
+ ON CONFLICT (id) DO UPDATE SET meta = streams.meta || EXCLUDED.meta, updated_at = now()""",
463
+ (sid, source["id"], self.permalink(channel, ts),
464
+ f"{source['name']} · thread of {_dt(ts):%Y-%m-%d %H:%M}", Jsonb(meta)))
465
+ items = [] if root_skipped else [self.item(channel, r, reply=True) for r in replies if not self.skip(r)]
466
+ stats["threads"] += 0 if root_skipped else 1
467
+ # Complete listing (or Slack said the thread does not exist): what vanished goes out.
468
+ units += self._settle_stream(source, sid, items, True, delta=bool(seen))
469
+ return units
470
+
471
+ def _mark_thread(self, stream_id: str, updates: dict) -> None:
472
+ with self.db.tx() as conn:
473
+ conn.execute("UPDATE streams SET meta = meta || %s WHERE id = %s", (Jsonb(updates), stream_id))
474
+
475
+ def _settle_stream(self, source, stream_id, items, complete, delta) -> int:
476
+ created = 0
477
+ with self.db.tx() as conn:
478
+ fresh = sync_stream(conn, source_id=source["id"], stream_id=stream_id, items=items, complete=complete,
479
+ reason="edited, deleted on Slack or outside the filters")
480
+ st = conn.execute("SELECT meta, title FROM streams WHERE id = %s", (stream_id,)).fetchone()
481
+ kind = st["meta"].get("slack")
482
+ meta = {"slack": {"channel": source["config"]["channel"], "name": source["name"], "kind": kind,
483
+ "thread_ts": st["meta"].get("thread_ts"), "conversation": source["config"].get("kind"),
484
+ "permalink": self.permalink(source["config"]["channel"], st["meta"].get("thread_ts") or st["meta"].get("first_ts") or "0")},
485
+ "delta": delta and bool(fresh)}
486
+ for i, part in enumerate(_split(fresh)):
487
+ uid = create_unit(conn, source_id=source["id"], stream_id=stream_id,
488
+ kind="slack_thread" if kind == "thread" else "slack_window",
489
+ title=st["title"] + (f" (part {i + 1})" if i else ""), items=part,
490
+ meta={**meta, "part": i + 1})
491
+ if uid:
492
+ created += 1
493
+ conn.execute("UPDATE streams SET last_settled_at = now() WHERE id = %s", (stream_id,))
494
+ return created
495
+
496
+
497
+ def _split(items: list[Item], limit: int = MAX_UNIT_CHARS) -> list[list[Item]]:
498
+ """A conversation larger than the context becomes several units, in order, without cutting or discarding anything."""
499
+ parts, current, size = [], [], 0
500
+ for it in items:
501
+ if current and size + len(it.content) > limit:
502
+ parts.append(current)
503
+ current, size = [], 0
504
+ current.append(it)
505
+ size += len(it.content)
506
+ if current:
507
+ parts.append(current)
508
+ return parts
509
+
510
+
511
+ # ---------------------------------------------------------------- context, live read, filters, estimate
512
+
513
+
514
+ CONTEXT_CHARS = 60_000
515
+
516
+
517
+ def unit_context(conn, unit: dict, evidence: list[dict]) -> list[dict]:
518
+ """The rest of the conversation, so extraction understands the unit: in a thread, the message that opened it and
519
+ the earlier replies; in a window (edit), its earlier messages. Only what came BEFORE the
520
+ unit, the closest first up to `CONTEXT_CHARS` (the root always goes in). Read at processing
521
+ time and only from what is still active — what was erased does not come back as context."""
522
+ m = (unit.get("meta") or {}).get("slack") or {}
523
+ if not m or not evidence:
524
+ return []
525
+ first = min(e["occurred_at"] for e in evidence)
526
+ ids = [e["id"] for e in evidence]
527
+ before = conn.execute(
528
+ """SELECT * FROM evidence WHERE stream_id = %s AND status = 'active' AND NOT (id = ANY(%s))
529
+ AND occurred_at < %s ORDER BY occurred_at DESC""", (unit["stream_id"], ids, first)).fetchall()
530
+ root = None
531
+ if m.get("kind") == "thread" and m.get("thread_ts"):
532
+ root = conn.execute("SELECT * FROM evidence WHERE source_id = %s AND external_id = %s AND status = 'active'",
533
+ (unit["source_id"], f"msg:{m['channel']}:{m['thread_ts']}")).fetchone()
534
+ picked, size = [], len(root["content"]) if root else 0
535
+ for e in before:
536
+ if size + len(e["content"]) > CONTEXT_CHARS:
537
+ break
538
+ picked.append(e)
539
+ size += len(e["content"])
540
+ return ([root] if root else []) + list(reversed(picked))
541
+
542
+
543
+ def context_units(conn, ev: dict) -> set[int]:
544
+ """Pending units that use this message as context: those of the same stream and, if it opens a
545
+ thread, those of the thread."""
546
+ ts = (ev["external_id"] or "").rsplit(":", 1)[-1]
547
+ rows = conn.execute(
548
+ """SELECT id FROM units WHERE status = 'pending' AND source_id = %s
549
+ AND (stream_id = %s OR meta->'slack'->>'thread_ts' = %s)""",
550
+ (ev["source_id"], ev["stream_id"], ts)).fetchall()
551
+ return {r["id"] for r in rows}
552
+
553
+
554
+ def root_ready(conn, source_id: str, channel: str, thread_ts: str) -> bool:
555
+ return bool(conn.execute("SELECT 1 FROM evidence WHERE source_id = %s AND external_id = %s",
556
+ (source_id, f"msg:{channel}:{thread_ts}")).fetchone())
557
+
558
+
559
+ def read_live(client: SlackClient, channel: str, ts: str, thread_ts: str | None, users: dict[str, dict],
560
+ cfg: dict | None = None) -> str:
561
+ """Live read for the adjudicator: the thread (or the surrounding messages) as they are now on Slack,
562
+ with the owner's same lists (ignored bots and authors do not appear)."""
563
+ reader = SlackConnector(None, client, cfg or {}, "", users=users)
564
+ if thread_ts:
565
+ try:
566
+ msgs = list(client.pages("conversations.replies", "messages", {"channel": channel, "ts": thread_ts}))
567
+ except NotFound:
568
+ msgs = []
569
+ exists = any(m["ts"] == ts for m in msgs)
570
+ else:
571
+ target = client.call("conversations.history", {"channel": channel, "oldest": ts, "latest": ts,
572
+ "inclusive": "true", "limit": 1}).get("messages") or []
573
+ exists = any(m["ts"] == ts for m in target)
574
+ around = []
575
+ for m in client.pages("conversations.history", "messages", {"channel": channel, "inclusive": "true",
576
+ "oldest": f"{float(ts) - 3600:.6f}",
577
+ "latest": f"{float(ts) + 3600:.6f}"}):
578
+ around.append(m)
579
+ if len(around) >= 200:
580
+ break
581
+ msgs = sorted({m["ts"]: m for m in around + target}.values(), key=lambda x: float(x["ts"]))
582
+ if not exists:
583
+ return "the message no longer exists on Slack (deleted at the origin)"
584
+ out = []
585
+ for m in msgs:
586
+ if m["ts"] != ts and reader.skip(m):
587
+ continue
588
+ mark = " ← this one" if m["ts"] == ts else ""
589
+ out.append(f"{_dt(m['ts']):%Y-%m-%d %H:%M} {reader.who(m)}{mark}: {reader.render_text(m.get('text') or '')}")
590
+ return "\n".join(out)
591
+
592
+
593
+ def reapply_filters(db, source: dict, cfg: dict, users: dict[str, dict]) -> dict:
594
+ """The owner's lists changed: retracts what fell outside and re-reads the horizon (what holds again
595
+ comes in; what did not change is deduplicated by hash, at no LLM cost)."""
596
+ from .. import knowledge as K
597
+
598
+ excluded = {a.lower() for a in cfg.get("exclude_authors") or []}
599
+ read_bots = {b.lower() for b in cfg.get("read_bots") or []}
600
+ subtypes = set(cfg.get("ignore_subtypes") or [])
601
+ stats = {"retracted": 0}
602
+ with db.tx() as conn:
603
+ ids = []
604
+ for ev in conn.execute("SELECT id, author, meta FROM evidence WHERE source_id = %s AND status = 'active'",
605
+ (source["id"],)).fetchall():
606
+ m = ev["meta"]
607
+ author = (ev["author"] or "").lower()
608
+ u = users.get(m.get("user") or "", {})
609
+ out = not m.get("bot") and bool(excluded & {(m.get("user") or "").lower(), (u.get("name") or "").lower(),
610
+ (u.get("login") or "").lower()})
611
+ out |= bool(m.get("bot")) and not ({(m.get("bot_name") or "").lower(), (m.get("bot_id") or "").lower(),
612
+ author} & read_bots)
613
+ out |= (m.get("subtype") or "") in subtypes
614
+ if out:
615
+ ids.append(ev["id"])
616
+ if ids:
617
+ stats.update(K.tombstone_evidence(conn, "connector", ids, "outside the owner's filters"))
618
+ conn.execute("UPDATE evidence SET external_id = NULL WHERE id = ANY(%s)", (ids,))
619
+ stats["retracted"] = len(ids)
620
+ conn.execute("""UPDATE sources SET config = jsonb_set(config, '{state,full_rescan}', 'true'::jsonb, true)
621
+ WHERE id = %s""", (source["id"],))
622
+ conn.execute("UPDATE streams SET meta = meta - 'latest_reply_seen' WHERE source_id = %s", (source["id"],))
623
+ return stats
624
+
625
+
626
+ def estimate_backfill(client: SlackClient, source: dict, cfg: dict, usd_per_char: float,
627
+ known: set[str] | None = None) -> dict:
628
+ """Estimate before turning on: reads the horizon's history only to count (no LLM), estimates the text
629
+ of the replies by the average message size and multiplies by the measured average cost per character."""
630
+ days = int(source["config"].get("horizon_days") or cfg["horizon_days"])
631
+ oldest = datetime.now(timezone.utc) - timedelta(days=days)
632
+ n = chars = replies = 0
633
+ new_n = new_chars = new_replies = 0 # what has not been read yet
634
+ known = known or set()
635
+ reader = SlackConnector(None, client, cfg, "")
636
+ for m in client.pages("conversations.history", "messages",
637
+ {"channel": source["config"]["channel"], "oldest": f"{oldest.timestamp():.6f}"}):
638
+ if m.get("subtype") == "thread_broadcast" or reader.skip(m):
639
+ continue
640
+ n += 1
641
+ chars += len(m.get("text") or "")
642
+ replies += int(m.get("reply_count") or 0)
643
+ if f"msg:{source['config']['channel']}:{m['ts']}" not in known:
644
+ new_n += 1
645
+ new_chars += len(m.get("text") or "")
646
+ new_replies += int(m.get("reply_count") or 0)
647
+ avg = chars / n if n else 0
648
+ total_chars = chars + replies * avg
649
+ new_chars += new_replies * avg # same computation as the total: replies by the average message size
650
+ return {"messages": n, "replies": replies, "chars": int(total_chars), "usd_per_char": usd_per_char,
651
+ "usd": round(total_chars * usd_per_char, 2), "new": new_n,
652
+ "usd_new": round(new_chars * usd_per_char, 2), "horizon_days": days,
653
+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds")}
654
+
655
+
656
+ def required_scopes(kind: str) -> set[str]:
657
+ return BASE_SCOPES | REQUIRED_SCOPES.get(kind, set())
658
+
659
+
660
+ def missing_scopes(client: SlackClient, kind: str) -> set[str]:
661
+ return required_scopes(kind) - client.scopes if client.scopes else set()
662
+
663
+
664
+ def users_cached(db, client: SlackClient, max_age_h: float = 24) -> dict[str, dict]:
665
+ """User names (to format authors and mentions), refreshed once a day."""
666
+ row = db.one("SELECT value, updated_at FROM system_state WHERE key = 'slack_users'")
667
+ if row and (datetime.now(timezone.utc) - row["updated_at"]).total_seconds() < max_age_h * 3600:
668
+ return row["value"]["users"]
669
+ users = load_users(client)
670
+ db.execute("""INSERT INTO system_state (key, value) VALUES ('slack_users', %s)
671
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()""",
672
+ (Jsonb({"users": users}),))
673
+ return users
674
+