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
pythia/consumer.py ADDED
@@ -0,0 +1,268 @@
1
+ """Interface for the consuming LLM: the 5 MCP operations and the push briefing.
2
+
3
+ Reads do not use an LLM (they serve what has already been concluded), so they keep
4
+ working with cognition paused — always with the lag notice.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from . import knowledge as K
12
+ from .llm.client import CallContext, LLMError, LLMUnavailable
13
+ from .pipeline import correct, prompts, schemas
14
+ from .pipeline.derive import knowledge_map
15
+ from .services import Services
16
+
17
+
18
+ def pause_note(svc: Services) -> str:
19
+ st = svc.state.get("cognition")
20
+ if st and st.get("paused_since"):
21
+ return (f"⚠ Cognition paused since {st['paused_since']} ({st.get('reason', '')}); "
22
+ "the knowledge may be lagging.\n")
23
+ return ""
24
+
25
+
26
+ def search(svc: Services, query: str, limit: int = 10) -> str:
27
+ items = svc.retriever.search(query, limit=limit)
28
+ if not items:
29
+ return pause_note(svc) + "Nothing found."
30
+ lines = [f"{it['id']} · [{it['type']}] {it['title']} — {it['l0']}" for it in items]
31
+ return pause_note(svc) + "\n".join(lines) + "\n\nUse open(id, level) to go deeper: 1 = page, 2 = claims, 3 = evidence."
32
+
33
+
34
+ def _evidence_line(ev: dict, full: bool = False) -> str:
35
+ if ev["content"] is None:
36
+ return f"{ev['id']} (removed at the source)"
37
+ meta = ev.get("meta") or {}
38
+ where = f" · {meta.get('cwd')}" if meta.get("cwd") else ""
39
+ content = ev["content"] if full else ev["content"][:500]
40
+ return f"{ev['id']} · {ev['occurred_at']:%Y-%m-%d %H:%M} · {ev['source_id']}{where} · {ev['role']}:\n{content}"
41
+
42
+
43
+ def open_item(svc: Services, item_id: str, level: int = 1) -> str:
44
+ prefix = item_id.split("_")[0]
45
+ with svc.db.tx() as conn:
46
+ if prefix == "en":
47
+ view = conn.execute("SELECT id FROM views WHERE kind = 'entity' AND entity_id = %s AND status = 'active'",
48
+ (item_id,)).fetchone()
49
+ if view:
50
+ item_id, prefix = view["id"], "vw"
51
+ else:
52
+ ent = K.entity(conn, item_id)
53
+ if not ent:
54
+ return "Not found."
55
+ claims = K.entity_claims(conn, item_id, limit=50)
56
+ return pause_note(svc) + f"{ent['name']} ({ent['type']}), no page yet.\n" + "\n".join(
57
+ K.format_claim(c) for c in claims)
58
+ if prefix == "vw":
59
+ v = conn.execute("SELECT * FROM views WHERE id = %s", (item_id,)).fetchone()
60
+ if not v:
61
+ return "Not found."
62
+ head = pause_note(svc) + (f"{v['title']} ({v['kind']}{', stale' if v['stale'] else ''}, "
63
+ f"generated {v['generated_at']:%Y-%m-%d})\n")
64
+ if level <= 0:
65
+ return head + v["l0"]
66
+ if level == 1:
67
+ return head + v["l1"] + f"\n\nCited claims: {', '.join(v['cited_claim_ids'])}"
68
+ claims = conn.execute("SELECT * FROM claims WHERE id = ANY(%s) ORDER BY recorded_at", (v["cited_claim_ids"],)).fetchall()
69
+ if level == 2:
70
+ return head + "\n".join(K.format_claim(c) for c in claims)
71
+ evs = conn.execute("SELECT * FROM evidence WHERE id = ANY(%s) ORDER BY occurred_at, seq",
72
+ ([e for c in claims for e in c["evidence_ids"]],)).fetchall()
73
+ return head + "\n\n".join(_evidence_line(e) for e in evs)
74
+ if prefix == "cl":
75
+ c = conn.execute("""SELECT c.*, s.name AS subject_name, o.name AS object_name FROM claims c
76
+ LEFT JOIN entities s ON s.id = c.subject_entity_id
77
+ LEFT JOIN entities o ON o.id = c.object_entity_id WHERE c.id = %s""", (item_id,)).fetchone()
78
+ if not c:
79
+ return "Not found."
80
+ text = pause_note(svc) + f"Subject: {c['subject_name']} ({c['subject_entity_id']})\n" + K.format_claim(c)
81
+ if c["supporting_claim_ids"]:
82
+ text += f"\nInferred from: {', '.join(c['supporting_claim_ids'])}"
83
+ if level < 3:
84
+ return text + f"\nEvidence: {', '.join(c['evidence_ids']) or '-'}"
85
+ evs = conn.execute("SELECT * FROM evidence WHERE id = ANY(%s) ORDER BY occurred_at, seq", (c["evidence_ids"],)).fetchall()
86
+ return text + "\n\n" + "\n\n".join(_evidence_line(e, full=True) for e in evs)
87
+ if prefix == "ev":
88
+ ev = conn.execute("SELECT * FROM evidence WHERE id = %s", (item_id,)).fetchone()
89
+ return _evidence_line(ev, full=True) if ev else "Not found."
90
+ if prefix == "vd":
91
+ v = conn.execute("SELECT * FROM verdicts WHERE id = %s", (item_id,)).fetchone()
92
+ if not v:
93
+ return "Not found."
94
+ changes = "; ".join(f"{c['claim_id']}: {c['from']} → {c['to']}" for c in v["changes"])
95
+ return (f"Verdict {v['id']} ({v['kind']}, {v['status']}, by {v['decided_by']}, {v['created_at']:%Y-%m-%d %H:%M})\n"
96
+ f"{v['summary']}\nRationale: {v['rationale']}\nChanges: {changes}")
97
+ return "ID not recognized."
98
+
99
+
100
+ def timeline(svc: Services, item_id: str) -> str:
101
+ prefix = item_id.split("_")[0]
102
+ with svc.db.tx() as conn:
103
+ if prefix == "vw":
104
+ v = conn.execute("SELECT entity_id, cited_claim_ids FROM views WHERE id = %s", (item_id,)).fetchone()
105
+ if not v:
106
+ return "Not found."
107
+ if v["entity_id"]:
108
+ item_id, prefix = v["entity_id"], "en"
109
+ else:
110
+ claim_ids = v["cited_claim_ids"]
111
+ if prefix == "en":
112
+ claim_ids = [r["id"] for r in conn.execute(
113
+ "SELECT id FROM claims WHERE subject_entity_id = %s OR object_entity_id = %s", (item_id, item_id)).fetchall()]
114
+ elif prefix == "cl":
115
+ claim_ids = [item_id]
116
+ elif prefix != "vw":
117
+ return "Timeline available for entities, pages, narratives and claims."
118
+ rows = conn.execute(
119
+ """SELECT h.from_ts, h.status, h.verdict_id, c.id, c.statement, v.summary, v.kind AS vkind
120
+ FROM claim_status_history h JOIN claims c ON c.id = h.claim_id
121
+ LEFT JOIN verdicts v ON v.id = h.verdict_id
122
+ WHERE h.claim_id = ANY(%s) ORDER BY h.from_ts""", (claim_ids,)).fetchall()
123
+ lines = []
124
+ for r in rows:
125
+ if r["verdict_id"]:
126
+ lines.append(f"{r['from_ts']:%Y-%m-%d %H:%M} · {r['id']} → {r['status']} "
127
+ f"(verdict {r['verdict_id']}, {r['vkind']}: {r['summary']})")
128
+ else:
129
+ lines.append(f"{r['from_ts']:%Y-%m-%d %H:%M} · {r['id']} {r['status']}: {r['statement']}")
130
+ return pause_note(svc) + ("\n".join(lines) or "No history.")
131
+
132
+
133
+ def request_correction(svc: Services, item_id: str | None, text: str) -> str:
134
+ cid = correct.request_correction(svc, item_id, text, via="mcp")
135
+ return f"Correction {cid} recorded with maximum authority; it will be applied shortly." + (
136
+ "\n" + pause_note(svc) if pause_note(svc) else "")
137
+
138
+
139
+ def request_definition(svc: Services, text: str) -> str:
140
+ unit_id = correct.request_definition(svc, text, via="mcp")
141
+ return f"Definition recorded (unit {unit_id}); it will be incorporated shortly." + (
142
+ "\n" + pause_note(svc) if pause_note(svc) else "")
143
+
144
+
145
+ # ---------------------------------------------------------------- push
146
+
147
+
148
+ def briefing(svc: Services, *, event: str, prompt: str | None, cwd: str | None, session_id: str | None,
149
+ source: str | None = None) -> str:
150
+ """What the hook injects: the rules (at the start of the conversation) and the briefing chosen by an LLM."""
151
+ rules = rules_block(svc, event, source)
152
+ text = _briefing(svc, event=event, prompt=prompt, cwd=cwd, session_id=session_id, source=source)
153
+ return "\n\n".join(t for t in (rules, text) if t)
154
+
155
+
156
+ def rules_block(svc: Services, event: str, source: str | None) -> str:
157
+ """Rules for using Pythia: fixed text from the settings, at the start of each conversation and after /clear or
158
+ compaction (a resume keeps the history, so it does not repeat). It is not judgment: it is the owner's text."""
159
+ cfg = svc.settings.get("push")
160
+ if event != "SessionStart" or source == "resume" or not cfg.get("enabled", True) or not cfg.get("rules_enabled", True):
161
+ return ""
162
+ return (cfg.get("rules") or "").replace("{owner}", svc.owner_name).strip()
163
+
164
+
165
+ def _briefing(svc: Services, *, event: str, prompt: str | None, cwd: str | None, session_id: str | None,
166
+ source: str | None = None) -> str:
167
+ """Briefing chosen by an LLM. The LLM only chooses IDs; the text is their L0, with no free text.
168
+ Without an LLM, it injects nothing (there is no heuristically assembled briefing)."""
169
+ cfg = svc.settings.get("push")
170
+ if not cfg.get("enabled", True):
171
+ _log_push(svc, session_id, event, [], 0, "disabled", cwd=cwd)
172
+ return ""
173
+ with svc.db.tx() as conn:
174
+ kmap = knowledge_map(conn)
175
+ own = K.owner(conn)
176
+ own_view = conn.execute("SELECT l0 FROM views WHERE kind = 'entity' AND entity_id = %s AND status = 'active'",
177
+ (own["id"],)).fetchone() if own else None
178
+ valid_ids = {r["id"] for r in conn.execute("SELECT id FROM views WHERE status = 'active'").fetchall()}
179
+ recent_verdicts = conn.execute(
180
+ """SELECT v.id, v.kind, v.summary FROM verdicts v WHERE v.status = 'applied'
181
+ ORDER BY v.created_at DESC LIMIT 30""").fetchall()
182
+ if not kmap:
183
+ _log_push(svc, session_id, event, [], 0, "no knowledge", cwd=cwd)
184
+ return ""
185
+ user = f"Event: {event}\nWorking directory: {cwd or '?'}\n"
186
+ user += f"Current request from {svc.owner_name}:\n{prompt}" if prompt else "Session start (no request yet)."
187
+ if recent_verdicts:
188
+ user += "\n\nRecent verdicts:\n" + "\n".join(f"{v['id']} ({v['kind']}): {v['summary']}" for v in recent_verdicts)
189
+ try:
190
+ out = svc.llm.structured("briefing", prompts.BRIEFING.format(owner=svc.owner_name), user, schemas.BRIEFING,
191
+ max_tokens=1500, cached_context="KNOWLEDGE MAP\n" + kmap,
192
+ ctx=CallContext(source_id="push"))
193
+ except (LLMUnavailable, LLMError) as exc:
194
+ _log_push(svc, session_id, event, [], 0, f"no LLM: {exc}"[:200], cwd=cwd)
195
+ return ""
196
+ selected = [i for i in out["relevant_ids"] if i in valid_ids][:8]
197
+ from .usage import view_ref
198
+ with svc.db.tx() as conn:
199
+ own_ref = conn.execute("SELECT id FROM views WHERE kind = 'entity' AND entity_id = %s AND status = 'active'",
200
+ (own["id"],)).fetchone() if own else None
201
+ resets = event == "SessionStart" and source != "resume"
202
+ delivered = set() if resets else already_delivered(conn, chat_sessions(svc, session_id))
203
+ candidates = ([("own", view_ref(conn, own_ref["id"]))] if own_view and own_ref else []) + \
204
+ [("view", view_ref(conn, vid)) for vid in selected]
205
+ rows = {r["id"]: r for r in conn.execute(
206
+ "SELECT id, title, l0 FROM views WHERE id = ANY(%s)", (selected,)).fetchall()} if selected else {}
207
+ # Only what has not yet been delivered in this conversation (same ID and version): what is already in the
208
+ # LLM's context is not repeated on every request. Conversation start (or resume after compaction) delivers everything.
209
+ # The owner profile goes once per conversation (it is background; a page rewrite does not justify
210
+ # repeating it); the subject pages come back when they change version.
211
+ delivered_ids = {i for i, _v in delivered}
212
+ fresh = [(k, r) for k, r in candidates
213
+ if (r["id"] not in delivered_ids if k == "own" else (r["id"], r.get("version")) not in delivered)]
214
+ by_id = {v["id"]: v for v in recent_verdicts}
215
+ verdicts = [by_id[v] for v in out["verdict_ids"][:2] if v in by_id and (v, None) not in delivered]
216
+ if not fresh and not verdicts:
217
+ _log_push(svc, session_id, event, selected, 0, "already delivered in this conversation", cwd=cwd, source=source)
218
+ return ""
219
+ parts = [f"[Pythia — context about {svc.owner_name}. Go deeper with the pythia MCP tools: open(id, level).]"]
220
+ for kind, ref in fresh:
221
+ if kind == "own":
222
+ parts.append(f"About {svc.owner_name}: {own_view['l0']}")
223
+ elif ref["id"] in rows:
224
+ r = rows[ref["id"]]
225
+ parts.append(f"- {r['id']} · {r['title']}: {r['l0']}")
226
+ for v in verdicts:
227
+ parts.append(f"Attention: recent verdict {v['id']} ({v['kind']}): {v['summary']}")
228
+ note = pause_note(svc)
229
+ if note:
230
+ parts.append(note.strip())
231
+ text = "\n".join(parts)[: int(cfg.get("max_chars", 6000))]
232
+ # Usage: references only, with the delivered version of each page/narrative.
233
+ refs = [r for _, r in fresh] + [{"id": v["id"]} for v in verdicts]
234
+ _log_push(svc, session_id, event, [r["id"] for k, r in fresh if k == "view"], len(text), None, refs=refs, cwd=cwd,
235
+ source=source)
236
+ return text
237
+
238
+
239
+ def chat_sessions(svc: Services, session_id: str | None) -> list[str]:
240
+ """All session files of this session's chat: resuming creates a new file, but it is the same
241
+ conversation, with the same history in the LLM."""
242
+ if not session_id:
243
+ return []
244
+ from .connectors import claude_code as cc
245
+ cfg = svc.settings.get("claude_code")
246
+ for chat in cc.discover_chats(cc.projects_root(cfg), cc.app_sessions_root(cfg)):
247
+ if session_id in chat["files"]:
248
+ return chat["files"]
249
+ return [session_id]
250
+
251
+
252
+ def already_delivered(conn, sessions: list[str]) -> set[tuple[str, int | None]]:
253
+ """(ID, version) already injected in this chat since the last restart of the LLM's context (SessionStart of
254
+ type startup, /clear or compaction; a resume does not count, the history continues)."""
255
+ if not sessions:
256
+ return set()
257
+ start = conn.execute("""SELECT max(ts) AS t FROM pushes WHERE session_id = ANY(%s) AND event = 'SessionStart'
258
+ AND coalesce(source, 'startup') <> 'resume'""", (sessions,)).fetchone()["t"]
259
+ rows = conn.execute("""SELECT refs FROM pushes WHERE session_id = ANY(%s) AND skipped IS NULL
260
+ AND ts >= coalesce(%s, '-infinity'::timestamptz)""", (sessions, start)).fetchall()
261
+ return {(r["id"], r.get("version")) for row in rows for r in row["refs"] if r.get("id")}
262
+
263
+
264
+ def _log_push(svc: Services, session_id, event, selected, chars, skipped, refs=None, cwd=None, source=None) -> None:
265
+ from psycopg.types.json import Jsonb
266
+ svc.db.execute("""INSERT INTO pushes (session_id, event, selected_ids, chars, skipped, refs, cwd, source)
267
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
268
+ (session_id, event, selected, chars, skipped, Jsonb(refs or []), cwd, source))