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,365 @@
1
+ """The incident.io catalog as an entity seed (deterministic, no LLM).
2
+
3
+ Each entry of the configured types becomes an `anchored` entity with its
4
+ external identifiers (catalog id, GitHub login, Slack, email...).
5
+ Attributes that point to other synced entities become relation claims
6
+ (`state`, source `incident_io_catalog`); useful literal attributes become
7
+ simple claims. These claims do NOT skip integration: they go through the LLM, which
8
+ confronts them with what is already known — this is where conflict between sources is born.
9
+
10
+ Each entry is a stream with one piece of evidence (the entry's rendered snapshot):
11
+ changed → the previous version is retracted and the new one generates claims; gone from the
12
+ complete listing → tombstone (claims that depended only on it are retracted).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ import unicodedata
19
+ from datetime import datetime, timezone
20
+ from typing import Any
21
+
22
+ import httpx
23
+
24
+ from .. import events
25
+ from .. import knowledge as K
26
+ from .. import vault
27
+ from ..db import Database
28
+ from ..ids import new_id, sha
29
+ from ..jobs import enqueue
30
+ from .common import Item, SourceUnavailable, sync_stream
31
+
32
+ KIND = "incident_io"
33
+ SOURCE_ID = "incident_io:catalog"
34
+ LABEL = "incident_io_catalog"
35
+ PRIMITIVES = {"String", "Text", "Number", "Bool"}
36
+ # Identity, not knowledge: they go to external_ids instead of becoming a claim.
37
+ IDENTITY_ATTRS = {"email": "email", "slack": "slack", "slack user": "slack", "github": "github",
38
+ "github user": "github", "jira": "jira", "jira user": "jira", "zoom": "zoom", "zoom user": "zoom",
39
+ "google workspace": "google", "google workspace user": "google", "incident.io user": "incident_io_user"}
40
+ SKIP_ATTRS = {"avatar", "timezone", "phone number", "state", "role"}
41
+
42
+
43
+ def _slug(text: str) -> str:
44
+ text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
45
+ return re.sub(r"[^a-z0-9]+", "_", text).strip("_") or "attribute"
46
+
47
+
48
+ def _text(v: dict | None) -> str:
49
+ if not v:
50
+ return ""
51
+ if isinstance(v, str):
52
+ return v
53
+ return (v.get("label") or v.get("literal") or "").strip()
54
+
55
+
56
+ def store_available_types(conn, types: list[dict]) -> None:
57
+ """Stores the types the catalog has, so Settings can list all of them (not just the default ones)."""
58
+ from psycopg.types.json import Jsonb
59
+ conn.execute(
60
+ """INSERT INTO system_state (key, value) VALUES ('catalog_types_available', %s)
61
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()""",
62
+ (Jsonb({"types": [{"type_name": t["type_name"], "name": t["name"]} for t in types]}),))
63
+
64
+
65
+ def type_options(conn, mapping: dict[str, str]) -> dict[str, str]:
66
+ """Types for Settings: those in the mapping and those the catalog has, in stable order."""
67
+ row = conn.execute("SELECT value FROM system_state WHERE key = 'catalog_types_available'").fetchone()
68
+ available = [t["type_name"] for t in (row["value"]["types"] if row else [])]
69
+ return {t: mapping.get(t, "") for t in sorted(set(mapping) | set(available))}
70
+
71
+
72
+ class IncidentIOClient:
73
+ def __init__(self, api_key: str, base_url: str = "https://api.incident.io", transport: httpx.BaseTransport | None = None):
74
+ self.http = httpx.Client(base_url=base_url, transport=transport, timeout=30,
75
+ headers={"Authorization": f"Bearer {api_key}", "User-Agent": "pythia"})
76
+
77
+ def get(self, path: str, params: dict | None = None) -> dict:
78
+ try:
79
+ r = self.http.get(path, params=params)
80
+ except httpx.HTTPError as exc:
81
+ raise SourceUnavailable(f"incident.io unreachable: {exc}") from exc
82
+ if r.status_code in (401, 403):
83
+ raise SourceUnavailable(f"incident.io rejected the key ({r.status_code})")
84
+ if r.status_code == 429 or r.status_code >= 500:
85
+ raise SourceUnavailable(f"incident.io {r.status_code}")
86
+ r.raise_for_status()
87
+ return r.json()
88
+
89
+ def types(self) -> list[dict]:
90
+ return self.get("/v3/catalog_types")["catalog_types"]
91
+
92
+ def entries(self, type_id: str) -> list[dict]:
93
+ out, after = [], None
94
+ while True:
95
+ params = {"catalog_type_id": type_id, "page_size": 250}
96
+ if after:
97
+ params["after"] = after
98
+ page = self.get("/v3/catalog_entries", params)
99
+ out.extend(page["catalog_entries"])
100
+ after = (page.get("pagination_meta") or {}).get("after")
101
+ if not after or not page["catalog_entries"]:
102
+ return out
103
+
104
+
105
+ def client_from(cfg: dict) -> IncidentIOClient:
106
+ key = vault.get_secret(vault.INCIDENT_IO_KEY)
107
+ if not key:
108
+ raise SourceUnavailable("incident.io API key not configured")
109
+ return IncidentIOClient(key, cfg.get("base_url") or "https://api.incident.io")
110
+
111
+
112
+ class CatalogConnector:
113
+ def __init__(self, db: Database, client: IncidentIOClient, cfg: dict):
114
+ self.db = db
115
+ self.api = client
116
+ self.cfg = cfg
117
+ self._names: dict[str, str] = {}
118
+
119
+ def sync(self) -> dict:
120
+ mapping: dict[str, str] = {k: v for k, v in self.cfg["types"].items() if v}
121
+ available = self.api.types()
122
+ types = [t for t in available if t["type_name"] in mapping]
123
+ # Complete listings first: nothing is deleted if one of them fails.
124
+ data = {t["id"]: (t, [e for e in self.api.entries(t["id"])]) for t in types}
125
+ stats = {"types": len(types), "entities_created": 0, "entities_updated": 0, "claims": 0, "removed": 0}
126
+ now = datetime.now(timezone.utc)
127
+ with self.db.tx() as conn:
128
+ store_available_types(conn, available)
129
+ conn.execute("""INSERT INTO sources (id, kind, name, config, backfill_until)
130
+ VALUES (%s, %s, 'incident.io catalog', '{}', now())
131
+ ON CONFLICT (id) DO NOTHING""", (SOURCE_ID, KIND))
132
+ entity_of: dict[str, str] = {} # entry id → entity
133
+ by_name: dict[tuple[str, str], str] = {} # (type_name, name) → entity
134
+ # Step 1: entities and identities.
135
+ for type_id, (t, entries) in data.items():
136
+ attrs = {a["id"]: a for a in t["schema"]["attributes"]}
137
+ for e in entries:
138
+ if e.get("archived_at"):
139
+ continue
140
+ ext = {"incident_io": e["id"]}
141
+ if e.get("external_id"):
142
+ ext["incident_io_external"] = e["external_id"]
143
+ for aid, val in (e.get("attribute_values") or {}).items():
144
+ a = attrs.get(aid)
145
+ key = IDENTITY_ATTRS.get(a["name"].lower()) if a else None
146
+ if key and _text(val.get("value")):
147
+ ext[key] = _text(val.get("value"))
148
+ eid, created, updated = self._upsert_entity(conn, e, mapping[t["type_name"]], ext, t["name"])
149
+ entity_of[e["id"]] = eid
150
+ by_name[(t["type_name"], e["name"].lower())] = eid
151
+ self._names[eid] = e["name"]
152
+ stats["entities_created"] += created
153
+ stats["entities_updated"] += updated
154
+ # Step 1b: the SCIM group is a Team's member list (the Team itself points to it):
155
+ # it is the same thing per the record, so the group is merged into the Team (the members go to
156
+ # it). A group cited by more than one Team, or by none, stays as its own entity.
157
+ self._fold_scim_groups(conn, data, entity_of, by_name)
158
+ # Step 2: evidence per entry and claims for the new/changed entries.
159
+ candidates: list[dict] = []
160
+ live_streams = set()
161
+ for type_id, (t, entries) in data.items():
162
+ attrs = {a["id"]: a for a in t["schema"]["attributes"]}
163
+ for e in entries:
164
+ if e.get("archived_at"):
165
+ continue
166
+ stream_id = f"{KIND}:{e['id']}"
167
+ live_streams.add(stream_id)
168
+ rendered, facts = self._render(t, attrs, e, entity_of, by_name)
169
+ conn.execute(
170
+ """INSERT INTO streams (id, source_id, locator, title, meta) VALUES (%s, %s, %s, %s, '{}')
171
+ ON CONFLICT (id) DO UPDATE SET title = EXCLUDED.title, status = 'active', updated_at = now()""",
172
+ (stream_id, SOURCE_ID, f"incident.io catalog {t['type_name']} {e['id']}", e["name"]))
173
+ item = Item(external_id=f"entry:{e['id']}", author="incident.io", role="catalog",
174
+ occurred_at=_ts(e.get("updated_at")) or now, content=rendered,
175
+ meta={"catalog_type": t["type_name"]})
176
+ ev_id = new_id("ev")
177
+ facts = self._carry_over(conn, stream_id, item, entity_of[e["id"]], facts, ev_id)
178
+ fresh = sync_stream(conn, source_id=SOURCE_ID, stream_id=stream_id, items=[item], complete=True,
179
+ reason="entry changed or removed in the catalog")
180
+ if not fresh:
181
+ continue
182
+ self._store_evidence(conn, stream_id, fresh[0], ev_id)
183
+ for f in facts:
184
+ candidates.append({
185
+ "kind": "state", "subject_mention_id": None, "subject_entity_id": entity_of[e["id"]],
186
+ "predicate": f["predicate"], "object_value": f["value"], "object_mention_id": None,
187
+ "object_entity_id": f.get("object_entity_id"), "statement": f["statement"],
188
+ "valid_from": None, "valid_to": None, "origin": "observed", "source_id": SOURCE_ID,
189
+ "source_label": LABEL, "confidence": 1.0, "extractor_version": "catalog-v1",
190
+ "evidence_ids": [ev_id], "supporting_claim_ids": []})
191
+ # Entries that vanished (complete listing of all types): the record stopped saying that.
192
+ gone = conn.execute(
193
+ "SELECT id FROM streams WHERE source_id = %s AND status = 'active' AND NOT (id = ANY(%s))",
194
+ (SOURCE_ID, list(live_streams))).fetchall()
195
+ for g in gone:
196
+ ids = [r["id"] for r in conn.execute(
197
+ "SELECT id FROM evidence WHERE stream_id = %s AND status = 'active'", (g["id"],)).fetchall()]
198
+ K.tombstone_evidence(conn, "connector", ids, "entry removed from the catalog")
199
+ conn.execute("UPDATE streams SET status = 'deleted' WHERE id = %s", (g["id"],))
200
+ stats["removed"] += 1
201
+ # Structured claims go to integration (LLM) in batches.
202
+ for i in range(0, len(candidates), 40):
203
+ batch = [{"ref": f"N{j + 1}", **c} for j, c in enumerate(candidates[i:i + 40])]
204
+ enqueue(conn, "integrate_structured", "cognition", {"candidates": batch}, priority=40)
205
+ stats["claims"] = len(candidates)
206
+ enqueue(conn, "reconcile_entities", "cognition", {}, priority=45, dedup_key="reconcile_entities")
207
+ return stats
208
+
209
+ def _upsert_entity(self, conn, e: dict, etype: str, ext: dict, type_label: str) -> tuple[str, int, int]:
210
+ aliases = [a for a in (e.get("aliases") or []) if a and len(a) <= 60][:40]
211
+ if ext.get("github"):
212
+ aliases.append(ext["github"])
213
+ description = f"{type_label} in the incident.io catalog."
214
+ row = conn.execute("""SELECT * FROM entities WHERE external_ids @> %s::jsonb
215
+ ORDER BY (status = 'active') DESC, is_owner DESC LIMIT 1""",
216
+ (f'{{"incident_io": "{e["id"]}"}}',)).fetchone()
217
+ if row is None:
218
+ eid = K.create_entity(conn, "connector", name=e["name"], type=etype, origin="anchored", aliases=aliases,
219
+ description=description, external_ids=ext)
220
+ return eid, 1, 0
221
+ if row["status"] == "merged": # merged (into the owner, into the Team…): the entry points to the final entity
222
+ target = row
223
+ while target and target["status"] == "merged" and target["merged_into"]:
224
+ target = conn.execute("SELECT * FROM entities WHERE id = %s", (target["merged_into"],)).fetchone()
225
+ if target:
226
+ return target["id"], 0, 0
227
+ changes: dict[str, Any] = {}
228
+ if row["name"] != e["name"] and not row["is_owner"]:
229
+ changes["name"] = e["name"]
230
+ merged_aliases = sorted(set(row["aliases"]) | {a for a in aliases if a != e["name"]})
231
+ if merged_aliases != sorted(row["aliases"]):
232
+ changes["aliases"] = merged_aliases
233
+ merged_ext = {**row["external_ids"], **ext}
234
+ if merged_ext != row["external_ids"]:
235
+ changes["external_ids"] = merged_ext
236
+ if changes:
237
+ K.update_entity(conn, "connector", row["id"], **changes)
238
+ return row["id"], 0, int(bool(changes))
239
+
240
+ def _render(self, t: dict, attrs: dict, e: dict, entity_of: dict, by_name: dict) -> tuple[str, list[dict]]:
241
+ lines = [f"incident.io catalog · {t['name']}: {e['name']}"]
242
+ if e.get("aliases"):
243
+ lines.append("Aliases: " + ", ".join(e["aliases"][:40]))
244
+ facts = []
245
+ for aid, val in sorted((e.get("attribute_values") or {}).items(), key=lambda kv: attrs.get(kv[0], {}).get("name", "")):
246
+ a = attrs.get(aid)
247
+ if not a:
248
+ continue
249
+ name = a["name"]
250
+ if self._excluded(t["type_name"], name):
251
+ continue
252
+ values = val.get("array_value") or ([val["value"]] if val.get("value") else [])
253
+ ref = a.get("type") not in PRIMITIVES
254
+
255
+ def target_of(v):
256
+ if not ref:
257
+ return None
258
+ return entity_of.get((v or {}).get("literal") or "") or by_name.get((a["type"], _text(v).lower()))
259
+
260
+ def shown(v):
261
+ # Reference: name of the synced entity + id at the source, so that changing the target changes the snapshot.
262
+ t = target_of(v)
263
+ literal = (v or {}).get("literal") if isinstance(v, dict) else None
264
+ label = self._names.get(t) or _text(v)
265
+ return f"{label} [{literal}]" if ref and literal else label
266
+
267
+ labels = [shown(v) for v in values if _text(v)]
268
+ if not labels:
269
+ continue
270
+ lines.append(f"{name}: {', '.join(labels)}")
271
+ low = name.lower()
272
+ if low in IDENTITY_ATTRS or low in SKIP_ATTRS or a.get("type", "").startswith("Image"):
273
+ continue
274
+ for v in values:
275
+ label = _text(v)
276
+ if not label:
277
+ continue
278
+ target = target_of(v)
279
+ if ref:
280
+ if target is None:
281
+ continue # points to something that is not a synced entity (e.g. escalation path)
282
+ if target == entity_of.get(e["id"]):
283
+ continue # points to itself (e.g. the SCIM group merged into the Team)
284
+ label = self._names.get(target, label)
285
+ facts.append({"predicate": _slug(name), "value": label, "object_entity_id": target,
286
+ "statement": f"According to the incident.io catalog, {name} of {e['name']}: {label}."})
287
+ return "\n".join(lines), facts
288
+
289
+ def _carry_over(self, conn, stream_id: str, item: Item, entity_id: str, facts: list[dict], ev_id: str) -> list[dict]:
290
+ """Changed entry: a fact identical to that of a current claim from the previous version now cites the new
291
+ evidence (corroboration) instead of being retracted and reintegrated by the LLM. Only what changed goes on."""
292
+ old = conn.execute(
293
+ """SELECT id, content_hash FROM evidence WHERE stream_id = %s AND external_id = %s AND status = 'active'""",
294
+ (stream_id, item.external_id)).fetchone()
295
+ if not old or old["content_hash"] == sha(item.content):
296
+ return facts
297
+ current = {r["statement"]: r["id"] for r in conn.execute(
298
+ """SELECT id, statement FROM claims WHERE %s = ANY(evidence_ids) AND subject_entity_id = %s
299
+ AND status IN ('current', 'disputed')""", (old["id"], entity_id)).fetchall()}
300
+ rest = []
301
+ for f in facts:
302
+ cid = current.get(f["statement"])
303
+ if cid:
304
+ events.append(conn, "claim_corroborated", "connector", {"id": cid, "evidence_ids": [ev_id]})
305
+ else:
306
+ rest.append(f)
307
+ return rest
308
+
309
+ def _fold_scim_groups(self, conn, data: dict, entity_of: dict[str, str], by_name: dict) -> None:
310
+ owners: dict[str, list[str]] = {}
311
+ # The reference may come by the entry's ID or by its external_id (as is the case for SCIM).
312
+ by_external = {e["external_id"]: e["id"] for _t, (_ty, es) in data.items() for e in es if e.get("external_id")}
313
+ for _type_id, (t, entries) in data.items():
314
+ scim_attrs = {a["id"] for a in t["schema"]["attributes"] if a.get("type") == "SCIMGroup"}
315
+ if not scim_attrs:
316
+ continue
317
+ for e in entries:
318
+ if e.get("archived_at") or e["id"] not in entity_of:
319
+ continue
320
+ for aid in scim_attrs:
321
+ val = (e.get("attribute_values") or {}).get(aid) or {}
322
+ for v in val.get("array_value") or ([val["value"]] if val.get("value") else []):
323
+ lit = (v or {}).get("literal")
324
+ lit = lit if lit in entity_of else by_external.get(lit)
325
+ if lit:
326
+ owners.setdefault(lit, []).append(entity_of[e["id"]])
327
+ for scim_entry, teams in owners.items():
328
+ teams = sorted(set(teams))
329
+ group = entity_of.get(scim_entry)
330
+ if len(teams) != 1 or not group or group == teams[0]:
331
+ continue
332
+ row = conn.execute("SELECT status FROM entities WHERE id = %s", (group,)).fetchone()
333
+ if row and row["status"] == "active":
334
+ K.merge_entities(conn, "connector", group, teams[0],
335
+ "catalog: the Team points to this SCIM group (its member list)")
336
+ # The "Team → SCIM group" claim became a relation of the Team with itself: it says nothing.
337
+ for c in conn.execute(
338
+ """SELECT id FROM claims WHERE subject_entity_id = %s AND object_entity_id = %s
339
+ AND status IN ('current', 'disputed')""", (teams[0], teams[0])).fetchall():
340
+ from .. import events
341
+ events.append(conn, "claim_status_changed", "connector",
342
+ {"id": c["id"], "to": "retracted", "reason": "Team relation to its own SCIM group"})
343
+ K.invalidate_claims(conn, [c["id"]])
344
+ entity_of[scim_entry] = teams[0]
345
+ for k, v in list(by_name.items()): # references by name also become the Team
346
+ if v == group:
347
+ by_name[k] = teams[0]
348
+
349
+ def _excluded(self, type_name: str, attr: str) -> bool:
350
+ rules = {r.strip().lower() for r in self.cfg.get("exclude_attributes") or []}
351
+ return attr.lower() in rules or f"{type_name}: {attr}".lower() in rules
352
+
353
+ def _store_evidence(self, conn, stream_id: str, item: Item, ev: str) -> str:
354
+ from psycopg.types.json import Jsonb
355
+ conn.execute(
356
+ """INSERT INTO evidence (id, source_id, stream_id, external_id, author, role, occurred_at, content,
357
+ content_hash, meta)
358
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
359
+ (ev, SOURCE_ID, stream_id, item.external_id, item.author, item.role, item.occurred_at, item.content,
360
+ sha(item.content), Jsonb(item.meta)))
361
+ return ev
362
+
363
+
364
+ def _ts(value: str | None) -> datetime | None:
365
+ return datetime.fromisoformat(value.replace("Z", "+00:00")) if value else None