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/daemon.py ADDED
@@ -0,0 +1,650 @@
1
+ """Daemon: bootstrap, per-lane workers and periodic scheduler."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ import time
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ from psycopg.types.json import Jsonb
12
+
13
+ from . import events
14
+ from . import knowledge as K
15
+ from .connectors import confluence, github, incident_io, slack
16
+ from .connectors import claude_code as cc
17
+ from .connectors.claude_code import KIND as CLAUDE_CODE, ClaudeCodeConnector
18
+ from .connectors.common import SourceUnavailable
19
+ from .jobs import enqueue
20
+ from .llm.client import LLMError, LLMHalted, LLMUnavailable
21
+ from .pipeline import adjudicate, batch, correct, derive, process, reconcile, sweep
22
+ from .quality import run_golden
23
+ from .services import Services
24
+
25
+ log = logging.getLogger("pythia")
26
+
27
+ LLM_KINDS = {"process_unit", "adjudicate", "drift_sweep", "derive_entity", "derive_narratives", "integrate_inferences",
28
+ "integrate_structured", "reconcile_entities", "apply_correction", "golden_run", "poll_batches",
29
+ "apply_batch_synthesis"}
30
+
31
+
32
+ def bootstrap(svc: Services, requeue: bool = True) -> None:
33
+ """Ensures the owner entity (seeded from the settings) and the human source.
34
+
35
+ `requeue` only at daemon startup (never with workers running)."""
36
+ owner_cfg = svc.settings.get("owner")
37
+ token = events.CAUSE.set("startup:config")
38
+ try:
39
+ _bootstrap_owner(svc, owner_cfg)
40
+ finally:
41
+ events.CAUSE.reset(token)
42
+ if requeue:
43
+ svc.queue.requeue_stuck()
44
+
45
+
46
+ def _bootstrap_owner(svc: Services, owner_cfg: dict) -> None:
47
+ with svc.db.tx() as conn:
48
+ correct.ensure_human_source(conn, owner_cfg["name"])
49
+ own = K.owner(conn)
50
+ if own is None:
51
+ K.create_entity(conn, "config", name=owner_cfg["name"], type="person", origin="anchored",
52
+ aliases=owner_cfg.get("aliases", []), description="Owner of Pythia.", is_owner=True)
53
+ else:
54
+ wanted = sorted(set(owner_cfg.get("aliases", [])) - {own["name"]})
55
+ # Aliases that came from other sources (catalog, Slack) stay; only writes if any from the settings is missing.
56
+ if own["name"] != owner_cfg["name"] or not set(wanted) <= set(own["aliases"]):
57
+ K.update_entity(conn, "config", own["id"], name=owner_cfg["name"],
58
+ aliases=sorted(set(own["aliases"]) | set(wanted)))
59
+
60
+
61
+ # ---------------------------------------------------------------- job execution
62
+
63
+
64
+ def run_job(svc: Services, job: dict) -> dict | None:
65
+ kind, p, jid = job["kind"], job["payload"], job["id"]
66
+ if kind == "scan_sources":
67
+ return scan_sources(svc)
68
+ if kind == "process_unit":
69
+ return process.process_unit(svc, p["unit_id"], jid)
70
+ if kind == "adjudicate":
71
+ return adjudicate.adjudicate(svc, p["tension_id"], jid)
72
+ if kind == "derive_entity":
73
+ return derive.derive_entity(svc, p["entity_id"], jid)
74
+ if kind == "derive_narratives":
75
+ return derive.derive_narratives(svc, jid, review=bool(p.get("review")))
76
+ if kind == "integrate_inferences":
77
+ return derive.integrate_inferences(svc, p["candidates"], jid)
78
+ if kind == "integrate_structured":
79
+ return derive.integrate_structured(svc, p["candidates"], jid)
80
+ if kind == "reconcile_entities":
81
+ return reconcile.reconcile(svc, jid)
82
+ if kind == "apply_team_identities":
83
+ return reconcile.apply_team_identities(svc)
84
+ if kind == "reapply_filters" and p["source_id"].startswith(confluence.KIND + ":"):
85
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (p["source_id"],))
86
+ if not source:
87
+ return {"skipped": True}
88
+ with source_lock(svc, p["source_id"]):
89
+ return confluence.reapply_filters(svc.db, source, svc.settings.get("confluence"))
90
+ if kind == "reapply_filters":
91
+ if p["source_id"].startswith(slack.KIND + ":"):
92
+ return reapply_slack_filters(svc, p["source_id"])
93
+ return reapply_github_filters(svc, p["source_id"])
94
+ if kind == "remove_source":
95
+ with source_lock(svc, p["source_id"]):
96
+ return github.remove_source(svc.db, p["source_id"])
97
+ if kind == "scan_confluence":
98
+ return scan_confluence(svc, p["source_id"])
99
+ if kind == "list_confluence_spaces":
100
+ return list_confluence_spaces(svc)
101
+ if kind == "list_confluence_pages":
102
+ return list_confluence_pages(svc, p["space_key"])
103
+ if kind == "drift_sweep":
104
+ return sweep.run(svc, jid)
105
+ if kind == "estimate_backfill" and p["source_id"].startswith(confluence.KIND + ":"):
106
+ return estimate_confluence_backfill(svc, p["source_id"])
107
+ if kind == "estimate_backfill":
108
+ if p["source_id"].startswith(slack.KIND + ":"):
109
+ return estimate_slack_backfill(svc, p["source_id"])
110
+ return estimate_github_backfill(svc, p["source_id"])
111
+ if kind == "scan_slack":
112
+ return scan_slack(svc, p["source_id"])
113
+ if kind == "list_slack_conversations":
114
+ return list_slack_conversations(svc)
115
+ if kind == "submit_batches":
116
+ return batch.submit_pending(svc)
117
+ if kind == "poll_batches":
118
+ return batch.poll(svc)
119
+ if kind == "check_backfills":
120
+ return {"finished": batch.check_backfills(svc)}
121
+ if kind == "backfill_synthesis":
122
+ return batch.backfill_synthesis(svc, p["source_id"])
123
+ if kind == "apply_batch_synthesis":
124
+ return batch.apply_batch_synthesis(svc, p["custom_id"])
125
+ if kind == "scan_github":
126
+ return scan_github(svc, p["source_id"])
127
+ if kind == "sync_catalog":
128
+ return sync_catalog(svc)
129
+ if kind == "apply_correction":
130
+ return correct.apply_correction(svc, p["correction_id"], jid)
131
+ if kind == "apply_ops":
132
+ return correct.apply_direct(svc, p["correction_id"])
133
+ if kind == "tombstone_stream":
134
+ return tombstone_stream(svc, p["stream_id"], p.get("reset", False))
135
+ if kind == "derive_sweep":
136
+ return {"enqueued": derive.sweep(svc)}
137
+ if kind == "reexplain_scan":
138
+ from . import reexplain
139
+ return reexplain.run(svc, int(p.get("since_days") or 30), jid)
140
+ if kind == "golden_run":
141
+ return run_golden(svc, p["run_id"], jid)
142
+ raise ValueError(f"unknown job: {kind}")
143
+
144
+
145
+ def cause_of(job: dict) -> str:
146
+ """The cause of the changes the job makes (Evolution). Plumbing: comes from the job's kind and payload."""
147
+ kind, p = job["kind"], job["payload"] or {}
148
+ if kind == "process_unit":
149
+ return f"unit:{p['unit_id']}"
150
+ if kind == "adjudicate":
151
+ return f"tension:{p['tension_id']}"
152
+ if kind in ("apply_correction", "apply_ops"):
153
+ return f"correction:{p['correction_id']}"
154
+ if kind == "drift_sweep":
155
+ return f"sweep:{job['id']}"
156
+ if kind in ("backfill_synthesis", "apply_batch_synthesis"):
157
+ return f"synthesis:{p.get('source_id') or 'batch'}"
158
+ if p.get("source_id"):
159
+ return f"source:{p['source_id']}"
160
+ if p.get("stream_id"):
161
+ return f"stream:{p['stream_id']}"
162
+ if p.get("entity_id"):
163
+ return f"{kind}:{p['entity_id']}"
164
+ return f"{kind}:{job['id']}"
165
+
166
+
167
+ def execute(svc: Services, job: dict) -> None:
168
+ """Runs a job with halt semantics: without an LLM, it goes back to the queue without spending an attempt."""
169
+ llm_ok_before = svc.llm.last_ok
170
+ token = events.CAUSE.set(cause_of(job))
171
+ try:
172
+ try:
173
+ run_job(svc, job)
174
+ except batch.WaitingForBatch:
175
+ pass # the stage is in a batch; the result requeues the unit
176
+ svc.queue.done(job["id"])
177
+ # Only a successful LLM call proves cognition is back.
178
+ if svc.llm.last_ok != llm_ok_before and svc.state.get("cognition"):
179
+ svc.state.clear("cognition")
180
+ except SourceUnavailable as exc:
181
+ # Source down/without credentials: not a program or LLM error; try later.
182
+ src = job["payload"].get("source_id") or job["kind"]
183
+ svc.state.set(f"source_error:{src}", {"error": str(exc)[:300],
184
+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds")})
185
+ svc.queue.retry_later(job["id"], 300, str(exc), count_attempt=False)
186
+ except LLMHalted as exc:
187
+ _pause(svc, str(exc))
188
+ svc.queue.retry_later(job["id"], 300, str(exc), count_attempt=False)
189
+ except LLMUnavailable as exc:
190
+ _pause(svc, str(exc))
191
+ svc.queue.retry_later(job["id"], 60, str(exc), count_attempt=False)
192
+ except LLMError as exc:
193
+ log.warning("job %s (%s) LLM error: %s", job["id"], job["kind"], exc)
194
+ _final_failure(svc, job, svc.queue.fail(job, f"LLM: {exc}"))
195
+ except Exception as exc: # program error: records it and lets it retry up to the limit
196
+ log.exception("job %s (%s) failed", job["id"], job["kind"])
197
+ _final_failure(svc, job, svc.queue.fail(job, f"{type(exc).__name__}: {exc}"))
198
+ finally:
199
+ events.CAUSE.reset(token)
200
+
201
+
202
+ def _final_failure(svc: Services, job: dict, final: bool) -> None:
203
+ if final and job["kind"] == "process_unit":
204
+ svc.db.execute("UPDATE units SET status = 'failed' WHERE id = %s AND status = 'pending'",
205
+ (job["payload"]["unit_id"],))
206
+
207
+
208
+ def _pause(svc: Services, reason: str) -> None:
209
+ current = svc.state.get("cognition") or {}
210
+ svc.state.set("cognition", {
211
+ "paused_since": current.get("paused_since") or datetime.now(timezone.utc).isoformat(timespec="seconds"),
212
+ "reason": reason[:300],
213
+ })
214
+
215
+
216
+ def drain(svc: Services, lanes=("io", "cognition", "derivation"), max_jobs: int = 1000) -> int:
217
+ """Runs ready jobs until empty (used in tests and validation)."""
218
+ ran = 0
219
+ while ran < max_jobs:
220
+ progressed = False
221
+ for lane in lanes:
222
+ job = svc.queue.claim(lane, "drain")
223
+ if job:
224
+ execute(svc, job)
225
+ ran += 1
226
+ progressed = True
227
+ if not progressed:
228
+ break
229
+ return ran
230
+
231
+
232
+ # ---------------------------------------------------------------- sources
233
+
234
+
235
+ def _due(svc: Services, key: str, minutes: float) -> bool:
236
+ last = svc.state.get(f"last_scan:{key}")
237
+ return not last or time.time() - float(last["t"]) >= minutes * 60
238
+
239
+
240
+ def _mark(svc: Services, key: str) -> None:
241
+ svc.state.set(f"last_scan:{key}", {"t": time.time()})
242
+
243
+
244
+ def scan_github(svc: Services, source_id: str) -> dict:
245
+ cfg = svc.settings.get("github")
246
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s AND enabled", (source_id,))
247
+ if not source:
248
+ return {"skipped": "source turned off"}
249
+ client = github.GitHubClient(github.resolve_token(cfg))
250
+ github.verify_token(client, cfg)
251
+ stats = github.GitHubConnector(svc.db, client, cfg, svc.owner_name,
252
+ svc.settings.get("team")["members"]).scan(source)
253
+ svc.state.clear(f"source_error:{source_id}")
254
+ batch.mark_scanned(svc, source_id)
255
+ return stats
256
+
257
+
258
+ def _gh(svc: Services):
259
+ cfg = svc.settings.get("github")
260
+ client = github.GitHubClient(github.resolve_token(cfg))
261
+ github.verify_token(client, cfg)
262
+ team = {m["github"].lower() for m in svc.settings.get("team")["members"] if m.get("github")}
263
+ return cfg, client, github.owner_login(cfg, client), team
264
+
265
+
266
+ def reapply_github_filters(svc: Services, source_id: str) -> dict:
267
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (source_id,))
268
+ if not source:
269
+ return {"skipped": True}
270
+ cfg, _client, me, team = _gh(svc)
271
+ stats = github.reapply_filters(svc.db, source, cfg, me, team)
272
+ svc.state.clear(f"last_scan:{source_id}")
273
+ return stats
274
+
275
+
276
+ def estimate_github_backfill(svc: Services, source_id: str) -> dict:
277
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (source_id,))
278
+ if not source:
279
+ return {"skipped": True}
280
+ cfg, client, me, team = _gh(svc)
281
+ row = svc.db.one(
282
+ """SELECT coalesce(sum(c.cost_usd), 0) AS usd,
283
+ (SELECT count(DISTINCT stream_id) FROM units WHERE source_id LIKE 'github:%%' AND status <> 'pending') AS prs
284
+ FROM llm_calls c WHERE c.source_id LIKE 'github:%%'""")
285
+ avg = float(row["usd"]) / row["prs"] if row["prs"] else 0.10
286
+ read = {r["n"] for r in svc.db.query(
287
+ """SELECT (meta->>'number')::int AS n FROM streams WHERE source_id = %s AND meta ? 'settled_updated_at'""",
288
+ (source_id,))}
289
+ est = github.estimate_backfill(client, source, cfg, me, team, round(avg, 4), already_read=read)
290
+ svc.state.set(f"estimate:{source_id}", est)
291
+ return est
292
+
293
+
294
+ from contextlib import contextmanager
295
+
296
+
297
+ @contextmanager
298
+ def source_lock(svc: Services, source_id: str):
299
+ """One job per source at a time (read, reapply filters, remove): without it, a read that
300
+ started before a filter changed re-reads what was just retracted, or stores evidence after
301
+ Remove."""
302
+ with svc.db.pool.connection() as conn:
303
+ conn.execute("SELECT pg_advisory_lock(hashtext(%s))", (source_id,))
304
+ try:
305
+ yield
306
+ finally:
307
+ conn.execute("SELECT pg_advisory_unlock(hashtext(%s))", (source_id,))
308
+
309
+
310
+ def _slack(svc: Services):
311
+ client = slack.SlackClient(slack.resolve_token())
312
+ me = slack.verify_token(client)
313
+ return client, me, slack.users_cached(svc.db, client)
314
+
315
+
316
+ def scan_slack(svc: Services, source_id: str) -> dict:
317
+ client, me, users = _slack(svc)
318
+ with source_lock(svc, source_id):
319
+ # Read with the lock held: the source and the owner's lists as they are now.
320
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s AND enabled", (source_id,))
321
+ if not source:
322
+ return {"skipped": "source turned off or removed"}
323
+ missing = slack.missing_scopes(client, source["config"].get("kind") or "channel")
324
+ if missing:
325
+ raise SourceUnavailable(f"Slack token without the scopes: {', '.join(sorted(missing))}")
326
+ stats = slack.SlackConnector(svc.db, client, svc.settings.get("slack"), svc.owner_name, users, me).scan(source)
327
+ svc.state.clear(f"source_error:{source_id}")
328
+ batch.mark_scanned(svc, source_id)
329
+ return stats
330
+
331
+
332
+ def list_slack_conversations(svc: Services) -> dict:
333
+ client, me, users = _slack(svc)
334
+ convs = slack.list_conversations(client, users, me.get("user_id"))
335
+ svc.state.set("slack_conversations", {"items": convs, "team": me.get("team"),
336
+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds")})
337
+ svc.state.clear("source_error:slack")
338
+ return {"conversations": len(convs)}
339
+
340
+
341
+ def reapply_slack_filters(svc: Services, source_id: str) -> dict:
342
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (source_id,))
343
+ if not source:
344
+ return {"skipped": True}
345
+ _client, _me, users = _slack(svc)
346
+ with source_lock(svc, source_id):
347
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (source_id,))
348
+ if not source:
349
+ return {"skipped": True}
350
+ stats = slack.reapply_filters(svc.db, source, svc.settings.get("slack"), users)
351
+ svc.state.clear(f"last_scan:{source_id}")
352
+ return stats
353
+
354
+
355
+ def usd_per_char(svc: Services) -> float:
356
+ """Measured average cost per character read. Uses Slack itself once there is a measurement; before that,
357
+ the conversations of the other sources (without GitHub diffs, which lower the per-character average).
358
+ Counts the text that went through the LLM, including what was later erased."""
359
+ for where in ("source_id LIKE 'slack:%%'", "source_id NOT LIKE 'slack:%%'"):
360
+ row = svc.db.one(
361
+ f"""SELECT (SELECT coalesce(sum(cost_usd), 0) FROM llm_calls WHERE {where}
362
+ AND source_id IN (SELECT DISTINCT source_id FROM units WHERE status <> 'pending')) AS usd,
363
+ (SELECT coalesce(sum(coalesce(length(content), 0)), 0) FROM evidence
364
+ WHERE unit_id IS NOT NULL AND {where} AND role <> 'artifact') AS chars""")
365
+ if row["chars"] and row["usd"]:
366
+ return float(row["usd"]) / row["chars"]
367
+ return 0.00002
368
+
369
+
370
+ def estimate_slack_backfill(svc: Services, source_id: str) -> dict:
371
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (source_id,))
372
+ if not source:
373
+ return {"skipped": True}
374
+ client, _me, _users = _slack(svc)
375
+ known = {r["external_id"] for r in svc.db.query(
376
+ "SELECT external_id FROM evidence WHERE source_id = %s AND external_id IS NOT NULL", (source_id,))}
377
+ est = slack.estimate_backfill(client, source, svc.settings.get("slack"), usd_per_char(svc), known=known)
378
+ svc.state.set(f"estimate:{source_id}", est)
379
+ return est
380
+
381
+
382
+ def _confluence(svc: Services):
383
+ cfg = svc.settings.get("confluence")
384
+ client = confluence.client_from(cfg)
385
+ if not cfg.get("cloud_id") and cfg.get("token_type", "scoped") == "scoped":
386
+ # Stores the cloudId discovered from the site (avoids the lookup on every read).
387
+ cfg["cloud_id"] = client.http.base_url.path.split("/")[3]
388
+ svc.settings.set("confluence", cfg)
389
+ return cfg, client
390
+
391
+
392
+ def scan_confluence(svc: Services, source_id: str) -> dict:
393
+ cfg, client = _confluence(svc)
394
+ with source_lock(svc, source_id):
395
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s AND enabled", (source_id,))
396
+ if not source:
397
+ return {"skipped": "source turned off or removed"}
398
+ with svc.db.tx() as conn:
399
+ in_backfill = batch.source_in_backfill(conn, source_id)
400
+ token = K.DEFER.set(source_id) if in_backfill else None
401
+ try:
402
+ owner = svc.settings.get("owner")
403
+ stats = confluence.ConfluenceConnector(svc.db, client, cfg, svc.owner_name,
404
+ owner.get("aliases")).scan(source)
405
+ finally:
406
+ if token is not None:
407
+ K.DEFER.reset(token)
408
+ svc.state.clear(f"source_error:{source_id}")
409
+ batch.mark_scanned(svc, source_id)
410
+ return stats
411
+
412
+
413
+ def list_confluence_spaces(svc: Services) -> dict:
414
+ _cfg, client = _confluence(svc)
415
+ spaces = confluence.list_spaces(client)
416
+ svc.state.set("confluence_spaces", {"items": spaces, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")})
417
+ svc.state.clear("source_error:confluence")
418
+ return {"spaces": len(spaces)}
419
+
420
+
421
+ def list_confluence_pages(svc: Services, space_key: str) -> dict:
422
+ _cfg, client = _confluence(svc)
423
+ spaces = {s["key"]: s for s in (svc.state.get("confluence_spaces") or {}).get("items") or []}
424
+ space = spaces.get(space_key)
425
+ if not space:
426
+ return {"skipped": "unknown space"}
427
+ pages = confluence.space_pages(client, space["id"])
428
+ outline = confluence.page_outline(confluence.space_nodes(client, space["id"], pages))
429
+ svc.state.set(f"confluence_outline:{space_key}", {"items": outline,
430
+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds")})
431
+ return {"pages": len(outline)}
432
+
433
+
434
+ def estimate_confluence_backfill(svc: Services, source_id: str) -> dict:
435
+ source = svc.db.one("SELECT * FROM sources WHERE id = %s", (source_id,))
436
+ if not source:
437
+ return {"skipped": True}
438
+ _cfg, client = _confluence(svc)
439
+ read = {r["page_id"] for r in svc.db.query(
440
+ """SELECT meta->>'page_id' AS page_id FROM streams WHERE source_id LIKE 'confluence:%%'
441
+ AND meta->>'confluence' = 'page' AND meta ? 'version_seen'""")}
442
+ est = confluence.estimate_backfill(client, source, usd_per_char(svc), read)
443
+ svc.state.set(f"estimate:{source_id}", est)
444
+ return est
445
+
446
+
447
+ def resync_catalog(svc: Services) -> None:
448
+ """Full re-read of the catalog (e.g. the ignored-attributes list changed). Counts as backfill:
449
+ page regeneration is left for a single batch pass at the end."""
450
+ svc.db.execute("UPDATE sources SET backfill_until = now(), backfill_done_at = NULL WHERE id = %s",
451
+ (incident_io.SOURCE_ID,))
452
+ svc.state.clear(f"last_scan:{incident_io.SOURCE_ID}")
453
+
454
+
455
+ def sync_catalog(svc: Services) -> dict:
456
+ cfg = svc.settings.get("incident_io")
457
+ with svc.db.tx() as conn:
458
+ in_backfill = batch.source_in_backfill(conn, incident_io.SOURCE_ID)
459
+ token = K.DEFER.set(incident_io.SOURCE_ID) if in_backfill else None
460
+ try:
461
+ stats = incident_io.CatalogConnector(svc.db, incident_io.client_from(cfg), cfg).sync()
462
+ finally:
463
+ if token is not None:
464
+ K.DEFER.reset(token)
465
+ svc.state.clear(f"source_error:{incident_io.SOURCE_ID}")
466
+ batch.mark_scanned(svc, incident_io.SOURCE_ID)
467
+ svc.state.set("catalog_last_sync", {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), **stats})
468
+ # New people in the catalog may be those on the team list: the declared GitHub login goes to them.
469
+ svc.queue.enqueue("apply_team_identities", "cognition", {}, priority=40, dedup_key="team_identities")
470
+ return stats
471
+
472
+
473
+ def _sync_profile_source(svc: Services, cfg: dict) -> None:
474
+ """"Owner profile" source: all chats that are not fully enabled, except the excluded ones. On creation, what
475
+ already exists comes in as backfill (Batch API and deferred synthesis); what arrives later is processed right away."""
476
+ chats = cc.discover_chats(cc.projects_root(cfg), cc.app_sessions_root(cfg))
477
+ enabled = {r["chat_id"] for r in svc.db.query(
478
+ """SELECT config->>'chat_id' AS chat_id FROM sources
479
+ WHERE kind = %s AND id <> %s AND config ? 'chat_id'""", (CLAUDE_CODE, cc.PROFILE_SOURCE))}
480
+ files = cc.profile_files(chats, enabled, cfg.get("profile_excluded_chats") or [])
481
+ with svc.db.tx() as conn:
482
+ row = conn.execute("SELECT config FROM sources WHERE id = %s", (cc.PROFILE_SOURCE,)).fetchone()
483
+ if row is None:
484
+ conn.execute("""INSERT INTO sources (id, kind, name, config, enabled, backfill_until)
485
+ VALUES (%s, %s, 'Chats: owner profile (all chats, only his messages)', %s, true, now())""",
486
+ (cc.PROFILE_SOURCE, CLAUDE_CODE, Jsonb({"profile_only": True, "files": files})))
487
+ elif sorted(row["config"].get("files") or []) != files:
488
+ conn.execute("UPDATE sources SET config = config || %s WHERE id = %s",
489
+ (Jsonb({"profile_only": True, "files": files}), cc.PROFILE_SOURCE))
490
+
491
+
492
+ def scan_sources(svc: Services) -> dict:
493
+ # Sources with their own interval: only enqueue when due (the work runs in separate jobs).
494
+ gh_cfg = svc.settings.get("github")
495
+ for src in svc.db.query("SELECT id FROM sources WHERE enabled AND kind = 'github'"):
496
+ if _due(svc, src["id"], float(gh_cfg["poll_minutes"])):
497
+ svc.queue.enqueue("scan_github", "io", {"source_id": src["id"]}, priority=8,
498
+ dedup_key=f"scan:{src['id']}", max_attempts=3)
499
+ _mark(svc, src["id"])
500
+ sl_cfg = svc.settings.get("slack")
501
+ for src in svc.db.query("SELECT id FROM sources WHERE enabled AND kind = 'slack'"):
502
+ if _due(svc, src["id"], float(sl_cfg["poll_minutes"])):
503
+ svc.queue.enqueue("scan_slack", "io", {"source_id": src["id"]}, priority=8,
504
+ dedup_key=f"scan:{src['id']}", max_attempts=3)
505
+ _mark(svc, src["id"])
506
+ cf_cfg = svc.settings.get("confluence")
507
+ for src in svc.db.query("SELECT id FROM sources WHERE enabled AND kind = 'confluence'"):
508
+ if _due(svc, src["id"], float(cf_cfg["poll_minutes"])):
509
+ svc.queue.enqueue("scan_confluence", "io", {"source_id": src["id"]}, priority=8,
510
+ dedup_key=f"scan:{src['id']}", max_attempts=3)
511
+ _mark(svc, src["id"])
512
+ # Drift sweep: only with the cognition queue empty and budget left for the day.
513
+ if sweep.budget_left(svc) > 0 and sweep.cognition_idle(svc):
514
+ svc.queue.enqueue("drift_sweep", "cognition", {}, priority=5000, dedup_key="drift_sweep", max_attempts=1)
515
+ inc = svc.db.one("SELECT enabled FROM sources WHERE id = %s", (incident_io.SOURCE_ID,))
516
+ if inc and inc["enabled"] and _due(svc, incident_io.SOURCE_ID, float(svc.settings.get("incident_io")["poll_minutes"])):
517
+ svc.queue.enqueue("sync_catalog", "io", {"source_id": incident_io.SOURCE_ID}, priority=6,
518
+ dedup_key="sync_catalog", max_attempts=3)
519
+ _mark(svc, incident_io.SOURCE_ID)
520
+ cfg = svc.settings.get("claude_code")
521
+ connector = ClaudeCodeConnector(svc.db, svc.owner_name)
522
+ totals = {"streams": 0, "units": 0, "deleted": 0}
523
+ if cfg.get("profile_all_chats"):
524
+ _sync_profile_source(svc, cfg)
525
+ sources = svc.db.query("SELECT * FROM sources WHERE enabled AND kind = %s", (CLAUDE_CODE,))
526
+ paths = cc.session_paths(cc.projects_root(cfg)) if sources else {}
527
+ chats = {c["id"]: c for c in cc.discover_chats(cc.projects_root(cfg), cc.app_sessions_root(cfg))} if sources else {}
528
+ for source in sources:
529
+ chat = chats.get(source["config"].get("chat_id"))
530
+ if chat: # the chat may have gained files (resume) or another title since it was enabled
531
+ files = sorted(set(source["config"].get("files") or []) | set(chat["files"]))
532
+ if files != source["config"].get("files") or chat["title"] != source["name"]:
533
+ svc.db.execute("UPDATE sources SET name = %s, config = config || %s WHERE id = %s",
534
+ (chat["title"], Jsonb({"files": files}), source["id"]))
535
+ source["config"]["files"] = files
536
+ stats = connector.scan(source, debounce_s=float(cfg["debounce_minutes"]) * 60,
537
+ include_sidechains=bool(cfg.get("include_sidechains")), paths=paths)
538
+ batch.mark_scanned(svc, source["id"])
539
+ for k in totals:
540
+ totals[k] += stats[k]
541
+ return totals
542
+
543
+
544
+ def _ids_in_other_streams(conn, stream_id: str) -> dict[str, str]:
545
+ """external_id → another active stream of the same source that still contains the message."""
546
+ from .connectors.claude_code import read_delta
547
+ # In any chat: a chat resumed in the terminal may repeat messages from another.
548
+ others = conn.execute(
549
+ """SELECT o.id, o.locator FROM streams o
550
+ WHERE o.source_id LIKE 'claude_code:%%' AND o.id <> %s AND o.status = 'active'""", (stream_id,)).fetchall()
551
+ found: dict[str, str] = {}
552
+ for o in others:
553
+ path = Path(o["locator"])
554
+ if path.exists():
555
+ for m in read_delta(path, 0, include_sidechains=True).messages:
556
+ found.setdefault(m.external_id, o["id"])
557
+ return found
558
+
559
+
560
+ def tombstone_stream(svc: Services, stream_id: str, reset: bool) -> dict:
561
+ with svc.db.tx() as conn:
562
+ rows = conn.execute("SELECT id, external_id FROM evidence WHERE stream_id = %s AND status = 'active'",
563
+ (stream_id,)).fetchall()
564
+ elsewhere = _ids_in_other_streams(conn, stream_id) if rows else {}
565
+ ids = []
566
+ for r in rows:
567
+ if r["external_id"] in elsewhere:
568
+ # The message still exists in another session (resume): it was not deleted at the source.
569
+ conn.execute("UPDATE evidence SET stream_id = %s WHERE id = %s", (elsewhere[r["external_id"]], r["id"]))
570
+ else:
571
+ ids.append(r["id"])
572
+ stats = K.tombstone_evidence(conn, "connector", ids, "removed at the source")
573
+ if reset:
574
+ conn.execute("UPDATE streams SET cursor = '{}', status = 'active' WHERE id = %s", (stream_id,))
575
+ # The old evidence stays recorded (without content) with the same external id; free it for re-ingestion.
576
+ conn.execute("UPDATE evidence SET external_id = NULL WHERE stream_id = %s AND status = 'tombstoned'",
577
+ (stream_id,))
578
+ return stats
579
+
580
+
581
+ # ---------------------------------------------------------------- process
582
+
583
+
584
+ class Daemon:
585
+ def __init__(self, svc: Services, scan_every_s: int = 30, sweep_every_s: int = 600, batch_every_s: int = 60):
586
+ self.svc = svc
587
+ self.batch_every_s = batch_every_s
588
+ self.scan_every_s = scan_every_s
589
+ self.sweep_every_s = sweep_every_s
590
+ self.stop = threading.Event()
591
+ self.threads: list[threading.Thread] = []
592
+
593
+ def start(self) -> None:
594
+ bootstrap(self.svc)
595
+ from .quality import check_prompt_version
596
+ check_prompt_version(self.svc)
597
+ workers = [("io", 2), ("cognition", 1), ("derivation", 2)]
598
+ for lane, n in workers:
599
+ for i in range(n):
600
+ t = threading.Thread(target=self._worker, args=(lane, f"{lane}-{i}"), daemon=True, name=f"w-{lane}-{i}")
601
+ t.start()
602
+ self.threads.append(t)
603
+ t = threading.Thread(target=self._scheduler, daemon=True, name="scheduler")
604
+ t.start()
605
+ self.threads.append(t)
606
+
607
+ def shutdown(self) -> None:
608
+ self.stop.set()
609
+ for t in self.threads:
610
+ t.join(timeout=5)
611
+
612
+ def _worker(self, lane: str, name: str) -> None:
613
+ while not self.stop.is_set():
614
+ try:
615
+ job = self.svc.queue.claim(lane, name)
616
+ except Exception:
617
+ log.exception("failed to fetch job")
618
+ self.stop.wait(5)
619
+ continue
620
+ if job is None:
621
+ self.stop.wait(1.0)
622
+ continue
623
+ try:
624
+ execute(self.svc, job)
625
+ except Exception: # the worker never dies: the cognition lane has only one
626
+ log.exception("failed to record the result of job %s", job["id"])
627
+ self.stop.wait(5)
628
+
629
+ def _scheduler(self) -> None:
630
+ last_scan = last_sweep = last_batch = 0.0
631
+ while not self.stop.is_set():
632
+ now = time.time()
633
+ try:
634
+ if now - last_scan >= self.scan_every_s:
635
+ self.svc.queue.enqueue("scan_sources", "io", {}, priority=5, dedup_key="scan_sources", max_attempts=1)
636
+ last_scan = now
637
+ if now - last_batch >= self.batch_every_s:
638
+ q = self.svc.queue
639
+ q.enqueue("submit_batches", "io", {}, priority=7, dedup_key="submit_batches", max_attempts=1)
640
+ q.enqueue("poll_batches", "io", {}, priority=7, dedup_key="poll_batches", max_attempts=1)
641
+ q.enqueue("check_backfills", "io", {}, priority=9, dedup_key="check_backfills", max_attempts=1)
642
+ last_batch = now
643
+ if now - last_sweep >= self.sweep_every_s:
644
+ self.svc.queue.enqueue("derive_sweep", "derivation", {}, priority=95, dedup_key="derive_sweep")
645
+ # Plumbing: jobs completed more than 2 days ago are of no use.
646
+ self.svc.db.execute("DELETE FROM jobs WHERE status = 'done' AND finished_at < now() - interval '2 days'")
647
+ last_sweep = now
648
+ except Exception:
649
+ log.exception("scheduler")
650
+ self.stop.wait(2.0)