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/web/graph.py ADDED
@@ -0,0 +1,167 @@
1
+ """Reads for Explore: ego graph and side panel, with support for "how it was at T"."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any
7
+
8
+ from .. import knowledge as K
9
+
10
+ MAX_NODES = 50
11
+
12
+
13
+ def _claims_at(conn, entity_ids: list[str], at: datetime | None) -> list[dict]:
14
+ """Claims that touch the entities, with status and endpoints as they were at `at` (or now)."""
15
+ if at is None:
16
+ return conn.execute(
17
+ """SELECT c.*, c.status AS status_at, c.subject_entity_id AS subj_at, c.object_entity_id AS obj_at
18
+ FROM claims c WHERE (c.subject_entity_id = ANY(%s) OR c.object_entity_id = ANY(%s))""",
19
+ (entity_ids, entity_ids)).fetchall()
20
+ return conn.execute(
21
+ """WITH base AS (
22
+ SELECT c.*,
23
+ (SELECT h.status FROM claim_status_history h WHERE h.claim_id = c.id AND h.from_ts <= %(t)s
24
+ AND (h.to_ts IS NULL OR h.to_ts > %(t)s) LIMIT 1) AS status_at,
25
+ coalesce((SELECT l.entity_id FROM mention_link_history l WHERE l.mention_id = c.subject_mention_id
26
+ AND l.from_ts <= %(t)s AND (l.to_ts IS NULL OR l.to_ts > %(t)s) LIMIT 1),
27
+ CASE WHEN c.subject_mention_id IS NULL THEN c.subject_entity_id END) AS subj_at,
28
+ coalesce((SELECT l.entity_id FROM mention_link_history l WHERE l.mention_id = c.object_mention_id
29
+ AND l.from_ts <= %(t)s AND (l.to_ts IS NULL OR l.to_ts > %(t)s) LIMIT 1),
30
+ CASE WHEN c.object_mention_id IS NULL THEN c.object_entity_id END) AS obj_at
31
+ FROM claims c WHERE c.recorded_at <= %(t)s)
32
+ SELECT * FROM base WHERE status_at IS NOT NULL AND (subj_at = ANY(%(ids)s) OR obj_at = ANY(%(ids)s))""",
33
+ {"t": at, "ids": entity_ids}).fetchall()
34
+
35
+
36
+ def _view_at(conn, view_id: str, at: datetime | None) -> dict | None:
37
+ if at is None:
38
+ return conn.execute("SELECT * FROM views WHERE id = %s", (view_id,)).fetchone()
39
+ return conn.execute(
40
+ """SELECT v.id, v.kind, v.entity_id, vv.title, vv.l0, vv.l1, vv.cited_claim_ids, vv.member_entity_ids,
41
+ vv.status, vv.generated_at, false AS stale
42
+ FROM views v JOIN view_versions vv ON vv.view_id = v.id
43
+ WHERE v.id = %s AND vv.generated_at <= %s ORDER BY vv.version DESC LIMIT 1""", (view_id, at)).fetchone()
44
+
45
+
46
+ def _entities_at(conn, ids: list[str], at: datetime | None) -> dict[str, dict]:
47
+ rows = conn.execute("SELECT * FROM entities WHERE id = ANY(%s)", (ids,)).fetchall()
48
+ out = {}
49
+ for r in rows:
50
+ if at is not None and r["created_at"] > at:
51
+ continue
52
+ if at is None and r["status"] != "active":
53
+ continue
54
+ out[r["id"]] = r
55
+ return out
56
+
57
+
58
+ def ego_graph(conn, center: str | None, depth: int, at: datetime | None) -> dict[str, Any]:
59
+ if not center:
60
+ own = K.owner(conn)
61
+ center = own["id"] if own else None
62
+ if not center:
63
+ return {"center": None, "nodes": [], "edges": []}
64
+ if center.startswith("vw_"):
65
+ v = _view_at(conn, center, at)
66
+ if v and v["kind"] == "entity":
67
+ center = v["entity_id"]
68
+ elif v:
69
+ return _narrative_graph(conn, v, at)
70
+ nodes: dict[str, dict] = {}
71
+ edges: dict[str, dict] = {}
72
+ frontier = [center]
73
+ seen = {center}
74
+ for _ in range(max(1, depth)):
75
+ claims = _claims_at(conn, frontier, at)
76
+ nxt = []
77
+ for c in claims:
78
+ if c["status_at"] not in ("current", "disputed"):
79
+ continue
80
+ s, o = c["subj_at"], c["obj_at"]
81
+ if s and o and s != o:
82
+ edges[c["id"]] = {"id": c["id"], "source": s, "target": o, "label": c["predicate"],
83
+ "status": c["status_at"]}
84
+ for e in (s, o):
85
+ if e not in seen and len(seen) < MAX_NODES:
86
+ seen.add(e)
87
+ nxt.append(e)
88
+ frontier = nxt
89
+ if not frontier:
90
+ break
91
+ ents = _entities_at(conn, list(seen), at)
92
+ counts = {}
93
+ for c in _claims_at(conn, list(ents), at):
94
+ if c["status_at"] in ("current", "disputed") and c["subj_at"] in ents:
95
+ counts[c["subj_at"]] = counts.get(c["subj_at"], 0) + 1
96
+ views = {r["entity_id"]: r for r in conn.execute(
97
+ "SELECT id, entity_id FROM views WHERE kind = 'entity' AND entity_id = ANY(%s)", (list(ents),)).fetchall()}
98
+ for eid, e in ents.items():
99
+ l0 = None
100
+ if eid in views:
101
+ vv = _view_at(conn, views[eid]["id"], at)
102
+ l0 = vv["l0"] if vv else None
103
+ nodes[eid] = {"id": eid, "label": e["name"], "kind": e["type"], "group": "entity", "l0": l0 or "",
104
+ "claims": counts.get(eid, 0), "owner": e["is_owner"], "center": eid == center}
105
+ # Narratives that contain the center.
106
+ narr = conn.execute(
107
+ "SELECT id FROM views WHERE kind = 'narrative' AND %s = ANY(member_entity_ids)", (center,)).fetchall()
108
+ for r in narr:
109
+ v = _view_at(conn, r["id"], at)
110
+ if not v or v["status"] != "active" or len(nodes) >= MAX_NODES:
111
+ continue
112
+ nodes[v["id"]] = {"id": v["id"], "label": v["title"], "kind": "narrative", "group": "narrative",
113
+ "l0": v["l0"], "claims": len(v["cited_claim_ids"]), "owner": False, "center": False}
114
+ for m in v["member_entity_ids"]:
115
+ if m in nodes:
116
+ edges[f"{v['id']}:{m}"] = {"id": f"{v['id']}:{m}", "source": v["id"], "target": m,
117
+ "label": "", "status": "member"}
118
+ edges = {k: e for k, e in edges.items() if e["source"] in nodes and e["target"] in nodes}
119
+ return {"center": center, "nodes": list(nodes.values()), "edges": list(edges.values())}
120
+
121
+
122
+ def _narrative_graph(conn, v: dict, at: datetime | None) -> dict[str, Any]:
123
+ ents = _entities_at(conn, v["member_entity_ids"], at)
124
+ nodes = [{"id": v["id"], "label": v["title"], "kind": "narrative", "group": "narrative", "l0": v["l0"],
125
+ "claims": len(v["cited_claim_ids"]), "owner": False, "center": True}]
126
+ edges = []
127
+ for eid, e in list(ents.items())[:MAX_NODES]:
128
+ nodes.append({"id": eid, "label": e["name"], "kind": e["type"], "group": "entity", "l0": e["description"] or "",
129
+ "claims": 0, "owner": e["is_owner"], "center": False})
130
+ edges.append({"id": f"{v['id']}:{eid}", "source": v["id"], "target": eid, "label": "", "status": "member"})
131
+ return {"center": v["id"], "nodes": nodes, "edges": edges}
132
+
133
+
134
+ def node_detail(conn, node_id: str, at: datetime | None) -> dict[str, Any]:
135
+ if node_id.startswith("vw_"):
136
+ v = _view_at(conn, node_id, at)
137
+ if not v:
138
+ return {"error": "not found"}
139
+ claims = conn.execute("SELECT * FROM claims WHERE id = ANY(%s) ORDER BY recorded_at", (v["cited_claim_ids"],)).fetchall()
140
+ members = conn.execute("SELECT id, name, type FROM entities WHERE id = ANY(%s)", (v["member_entity_ids"],)).fetchall()
141
+ return {"kind": "narrative" if v["kind"] == "narrative" else "page", "id": v["id"], "title": v["title"],
142
+ "l0": v["l0"], "l1": v["l1"], "stale": v["stale"], "generated_at": v["generated_at"],
143
+ "members": members, "claims": [_claim_row(c, c["status"]) for c in claims]}
144
+ ent = K.entity(conn, node_id)
145
+ if not ent:
146
+ return {"error": "not found"}
147
+ view = conn.execute("SELECT id FROM views WHERE kind = 'entity' AND entity_id = %s", (node_id,)).fetchone()
148
+ vv = _view_at(conn, view["id"], at) if view else None
149
+ claims = [c for c in _claims_at(conn, [node_id], at)]
150
+ claims.sort(key=lambda c: c["recorded_at"], reverse=True)
151
+ ids = [c["id"] for c in claims]
152
+ verdicts = conn.execute(
153
+ """SELECT id, kind, status, summary, created_at FROM verdicts WHERE claim_ids && %s::text[]
154
+ ORDER BY created_at DESC LIMIT 20""", (ids,)).fetchall()
155
+ mentions = conn.execute(
156
+ "SELECT id, surface, context, confidence FROM mentions WHERE entity_id = %s ORDER BY created_at DESC LIMIT 30",
157
+ (node_id,)).fetchall()
158
+ return {"kind": "entity", "id": ent["id"], "title": ent["name"], "type": ent["type"], "aliases": ent["aliases"],
159
+ "origin": ent["origin"], "owner": ent["is_owner"], "view_id": view["id"] if view else None,
160
+ "l0": vv["l0"] if vv else "", "l1": vv["l1"] if vv else "", "stale": bool(vv and vv["stale"]),
161
+ "claims": [_claim_row(c, c["status_at"]) for c in claims], "verdicts": verdicts, "mentions": mentions}
162
+
163
+
164
+ def _claim_row(c: dict, status: str) -> dict:
165
+ return {"id": c["id"], "kind": c["kind"], "statement": c["statement"], "status": status, "origin": c["origin"],
166
+ "source": c["source_label"], "recorded_at": c["recorded_at"], "evidence_ids": c["evidence_ids"],
167
+ "predicate": c["predicate"], "subject_mention_id": c["subject_mention_id"]}
@@ -0,0 +1,131 @@
1
+ """"Processing now": what each worker is doing, in which stage, for how long, and the forecast.
2
+
3
+ Pure plumbing: reads the queue, the units and the call ledger. Forecasts are averages of the measured
4
+ durations (per LLM role or per job kind), not judgment.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime, timezone
10
+
11
+ from ..services import Services
12
+
13
+ WORKERS = {"io": 2, "cognition": 1, "derivation": 2}
14
+ LABELS = {
15
+ "process_unit": "process unit", "derive_entity": "entity page", "derive_narratives": "narratives",
16
+ "adjudicate": "adjudicate tension", "integrate_inferences": "integrate inferences",
17
+ "integrate_structured": "integrate catalog claims", "reconcile_entities": "reconcile identities",
18
+ "scan_sources": "scan sources", "scan_github": "read GitHub", "scan_slack": "read Slack", "sync_catalog": "read catalog",
19
+ "submit_batches": "submit batches", "poll_batches": "check batches", "check_backfills": "check backfills",
20
+ "backfill_synthesis": "assemble batch synthesis", "apply_batch_synthesis": "apply batch synthesis",
21
+ "derive_sweep": "derived-items sweep", "golden_run": "golden questions", "reexplain_scan": "measure re-explanation", "estimate_backfill": "estimate backfill",
22
+ "reapply_filters": "reapply filters", "remove_source": "remove source", "apply_correction": "apply correction",
23
+ "tombstone_stream": "erase what vanished at the source", "list_slack_conversations": "list Slack conversations",
24
+ }
25
+ STAGES = {"triage": "triage", "extraction": "extraction", "resolution": "resolution", "integration": "integration"}
26
+ ROLE_OF_JOB = {"derive_entity": "synthesis", "derive_narratives": "synthesis", "adjudicate": "adjudication",
27
+ "integrate_structured": "integration", "integrate_inferences": "integration",
28
+ "reconcile_entities": "reconciliation"}
29
+
30
+
31
+ def _since(ts) -> float:
32
+ if ts is None:
33
+ return 0.0
34
+ if isinstance(ts, str):
35
+ ts = datetime.fromisoformat(ts)
36
+ return max(0.0, (datetime.now(timezone.utc) - ts).total_seconds())
37
+
38
+
39
+ def snapshot(svc: Services) -> dict:
40
+ db = svc.db
41
+ role_avg = {r["role"]: float(r["s"]) for r in db.query(
42
+ """SELECT role, avg(duration_ms) / 1000.0 AS s FROM llm_calls
43
+ WHERE NOT batch AND ok AND ts > now() - interval '7 days' GROUP BY role""")}
44
+ job_avg = {r["kind"]: float(r["s"]) for r in db.query(
45
+ """SELECT kind, avg(extract(epoch FROM finished_at - started_at)) AS s FROM jobs
46
+ WHERE status = 'done' AND started_at IS NOT NULL AND finished_at IS NOT NULL GROUP BY kind""")}
47
+
48
+ running = []
49
+ for j in db.query("SELECT * FROM jobs WHERE status = 'running' ORDER BY started_at"):
50
+ p = j["payload"] or {}
51
+ what, stage, since, eta = LABELS.get(j["kind"], j["kind"]), None, j["started_at"], job_avg.get(j["kind"])
52
+ if j["kind"] == "process_unit" and p.get("unit_id"):
53
+ u = db.one("""SELECT u.title, u.meta, s.name AS source FROM units u JOIN sources s ON s.id = u.source_id
54
+ WHERE u.id = %s""", (p["unit_id"],))
55
+ if u:
56
+ what = f"{u['title'] or 'unit'} · {u['source']}"
57
+ now = (u["meta"] or {}).get("now") or {}
58
+ if now.get("stage"):
59
+ stage, since = STAGES.get(now["stage"], now["stage"]), now.get("since") or since
60
+ eta = role_avg.get(now["stage"])
61
+ elif j["kind"] == "derive_entity" and p.get("entity_id"):
62
+ e = db.one("SELECT name FROM entities WHERE id = %s", (p["entity_id"],))
63
+ what, stage, eta = f"page of {e['name'] if e else p['entity_id']}", "synthesis", role_avg.get("synthesis")
64
+ elif j["kind"] in ROLE_OF_JOB:
65
+ stage = {"synthesis": "synthesis", "adjudication": "adjudication", "integration": "integration",
66
+ "reconciliation": "reconciliation"}[ROLE_OF_JOB[j["kind"]]]
67
+ elapsed = _since(since)
68
+ running.append({"lane": j["lane"], "worker": j["worker"], "what": what, "stage": stage or "—",
69
+ "elapsed": elapsed, "remaining": max(0.0, eta - elapsed) if eta else None})
70
+
71
+ lanes = []
72
+ for lane, workers in WORKERS.items():
73
+ rows = db.query("""SELECT kind, count(*) AS n FROM jobs WHERE status = 'queued' AND lane = %s
74
+ AND run_after <= now() GROUP BY kind""", (lane,))
75
+ later = db.one("SELECT count(*) AS n FROM jobs WHERE status = 'queued' AND lane = %s AND run_after > now()", (lane,))["n"]
76
+ ready = sum(r["n"] for r in rows)
77
+ known = [r for r in rows if r["kind"] in job_avg]
78
+ eta = sum(r["n"] * job_avg[r["kind"]] for r in known) / workers if known else None
79
+ lanes.append({"lane": lane, "workers": workers, "ready": ready, "later": later, "eta": eta,
80
+ "kinds": sorted(({"kind": LABELS.get(r["kind"], r["kind"]), "n": r["n"]} for r in rows),
81
+ key=lambda r: -r["n"])[:4]})
82
+
83
+ history = sorted(float(r["s"]) for r in db.query(
84
+ """SELECT extract(epoch FROM ended_at - submitted_at) AS s FROM llm_batches WHERE ended_at IS NOT NULL"""))
85
+ batches = []
86
+ for b in db.query("SELECT * FROM llm_batches WHERE ended_at IS NULL ORDER BY submitted_at"):
87
+ elapsed = _since(b["submitted_at"])
88
+ batches.append({"id": b["id"], "requests": b["request_count"], "elapsed": elapsed,
89
+ **batch_eta(elapsed, b["request_count"], b.get("progress"), history)})
90
+ staged = db.one("SELECT count(*) AS n FROM batch_requests WHERE status = 'pending'")["n"]
91
+
92
+ waiting = db.query("""SELECT kind, count(*) AS n, max(last_error) AS err, min(run_after) AS next FROM jobs
93
+ WHERE status = 'queued' AND last_error IS NOT NULL GROUP BY kind ORDER BY 2 DESC""")
94
+ for w in waiting:
95
+ w["kind"] = LABELS.get(w["kind"], w["kind"])
96
+ w["in"] = max(0.0, (w["next"] - datetime.now(timezone.utc)).total_seconds()) if w["next"] else None
97
+ # tensions under judgment live here (the Verdicts tab is gone).
98
+ tensions = db.query("""SELECT t.id, t.reason, t.opened_by, t.created_at,
99
+ EXISTS (SELECT 1 FROM verdicts v WHERE v.tension_id = t.id AND v.status = 'reverted') AS reopened
100
+ FROM tensions t WHERE t.status = 'open' ORDER BY t.created_at LIMIT 20""")
101
+ return {"running": running, "lanes": lanes, "batches": batches, "staged": staged, "waiting": waiting,
102
+ "cognition": svc.state.get("cognition"), "tensions": tensions}
103
+
104
+
105
+ def batch_eta(elapsed: float, total: int, progress: dict | None, history: list[float]) -> dict:
106
+ """Forecast of when the batch returns, redone on every read:
107
+ 1. from the real pace, when Anthropic already reports completed requests;
108
+ 2. otherwise, from the history: the shortest turnaround seen that is still greater than the elapsed time
109
+ (the expired average is no use: the batch has already passed it);
110
+ 3. past all those seen: says so, with the limit guaranteed by Anthropic (24 h)."""
111
+ done = sum((progress or {}).get(k, 0) for k in ("succeeded", "errored", "canceled", "expired"))
112
+ if progress and 0 < done < total and elapsed > 0:
113
+ return {"remaining": (total - done) * elapsed / done, "done": done, "basis": "current pace"}
114
+ later = [h for h in history if h > elapsed]
115
+ if later:
116
+ return {"remaining": later[0] - elapsed, "done": done or None, "basis": "batch history"}
117
+ if history:
118
+ return {"remaining": None, "done": done or None,
119
+ "basis": f"already past the slowest seen ({human(history[-1])}); Anthropic guarantees up to 24 h"}
120
+ return {"remaining": None, "done": done or None, "basis": "no history; Anthropic guarantees up to 24 h"}
121
+
122
+
123
+ def human(seconds: float | None) -> str:
124
+ if seconds is None:
125
+ return "—"
126
+ s = int(seconds)
127
+ if s < 60:
128
+ return f"{s} s"
129
+ if s < 3600:
130
+ return f"{s // 60} min {s % 60:02d} s"
131
+ return f"{s // 3600} h {(s % 3600) // 60:02d} min"
@@ -0,0 +1,242 @@
1
+ (() => {
2
+ const P = window.PYTHIA;
3
+ const state = { center: P.center || null, depth: 1, t: null, selected: null };
4
+ const $ = (id) => document.getElementById(id);
5
+ const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
6
+ const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
7
+ const qs = () => (state.t ? `&t=${encodeURIComponent(state.t)}` : "");
8
+
9
+ if (typeof cytoscape === "undefined") {
10
+ $("cy").innerHTML = '<p class="muted" style="padding:20px">Could not load the graph library (offline?).</p>';
11
+ return;
12
+ }
13
+
14
+ const palette = () => ({
15
+ person: css("--accent"), team: "#8a6fd1", system: "#2e8b7a", repository: "#2e8b7a", project: "#c07a2c",
16
+ concept: "#8c8c8c", narrative: css("--warn"), other: "#8c8c8c",
17
+ });
18
+
19
+ const cy = cytoscape({
20
+ container: $("cy"),
21
+ wheelSensitivity: 0.25,
22
+ style: [
23
+ { selector: "node", style: {
24
+ "background-color": (n) => palette()[n.data("kind")] || palette().other,
25
+ "label": "data(label)", "color": css("--text"), "font-size": 11, "text-valign": "bottom", "text-margin-y": 4,
26
+ "width": (n) => 18 + Math.min(n.data("claims") || 0, 30), "height": (n) => 18 + Math.min(n.data("claims") || 0, 30),
27
+ "text-wrap": "ellipsis", "text-max-width": 140 } },
28
+ { selector: "node[group = 'narrative']", style: { "shape": "round-rectangle", "width": 34, "height": 22 } },
29
+ { selector: "node[?center]", style: { "border-width": 3, "border-color": css("--text") } },
30
+ { selector: "node:selected", style: { "border-width": 3, "border-color": css("--accent") } },
31
+ { selector: "edge", style: {
32
+ "width": 1.4, "line-color": css("--line"), "target-arrow-color": css("--line"), "target-arrow-shape": "triangle",
33
+ "curve-style": "bezier", "label": "data(label)", "font-size": 9, "color": css("--muted"),
34
+ "text-rotation": "autorotate", "text-background-color": css("--bg"), "text-background-opacity": 0.8 } },
35
+ { selector: "edge[status = 'disputed']", style: { "line-style": "dashed", "line-color": css("--bad") } },
36
+ { selector: "edge[status = 'member']", style: { "line-style": "dotted", "target-arrow-shape": "none" } },
37
+ ],
38
+ });
39
+
40
+ async function loadGraph() {
41
+ const url = `/api/graph?depth=${state.depth}${state.center ? `&center=${encodeURIComponent(state.center)}` : ""}${qs()}`;
42
+ const g = await (await fetch(url)).json();
43
+ state.center = g.center;
44
+ cy.elements().remove();
45
+ cy.add(g.nodes.map((n) => ({ data: n })));
46
+ cy.add(g.edges.map((e) => ({ data: e })));
47
+ if (!g.nodes.length) {
48
+ $("side").innerHTML = '<p class="muted">Nothing to show yet at this point in time.</p>';
49
+ return;
50
+ }
51
+ cy.layout({ name: "concentric", concentric: (n) => (n.data("center") ? 10 : n.data("group") === "narrative" ? 5 : 1),
52
+ levelWidth: () => 1, minNodeSpacing: 60, animate: false }).run();
53
+ cy.fit(undefined, 60);
54
+ if (cy.zoom() > 1.2) { cy.zoom(1.2); cy.center(); }
55
+ if (g.center) loadDetail(state.selected && cy.getElementById(state.selected).length ? state.selected : g.center);
56
+ }
57
+
58
+ function md(text) {
59
+ return esc(text)
60
+ .replace(/\[(cl_[0-9a-f]+)\]/g, '<a href="#" data-claim="$1" class="mono">[$1]</a>')
61
+ .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
62
+ .replace(/^### (.*)$/gm, "<strong>$1</strong>")
63
+ .replace(/^## (.*)$/gm, "<strong>$1</strong>")
64
+ .replace(/^# (.*)$/gm, "<strong>$1</strong>");
65
+ }
66
+
67
+ async function loadDetail(id) {
68
+ state.selected = id;
69
+ const d = await (await fetch(`/api/node/${encodeURIComponent(id)}?${qs().slice(1)}`)).json();
70
+ if (d.error) { $("side").innerHTML = `<p class="muted">${esc(d.error)}</p>`; return; }
71
+ const claims = (d.claims || []).map((c) => `
72
+ <div class="claim ${esc(c.status)}" id="${esc(c.id)}">
73
+ <div>${esc(c.statement)}</div>
74
+ <div class="meta"><span class="chip">${esc(c.kind)}</span> <span class="chip ${c.status === "disputed" ? "bad" : ""}">${esc(c.status)}</span>
75
+ ${esc(c.origin)} · ${esc(c.source || "")} · ${esc((c.recorded_at || "").slice(0, 10))}
76
+ · <a href="#" data-ev="${esc(c.id)}">evidence</a>
77
+ · <a href="#" data-fix="${esc(c.id)}">correct</a>
78
+ · <a href="#" data-retract="${esc(c.id)}">retract</a>
79
+ <span class="mono">${esc(c.id)}</span></div>
80
+ <div class="evbox"></div>
81
+ </div>`).join("");
82
+ const verdicts = (d.verdicts || []).map((v) =>
83
+ `<div class="claim"><span class="chip accent">${esc(v.kind.replaceAll("_", " "))}</span> ${esc(v.summary)}
84
+ <div class="meta">${esc(v.status)} · ${esc((v.created_at || "").slice(0, 16))} · <a href="/verdicts">${esc(v.id)}</a></div></div>`).join("");
85
+ const mentions = (d.mentions || []).map((m) =>
86
+ `<div class="claim"><strong>“${esc(m.surface)}”</strong> <span class="muted">${esc(m.context || "(context removed)")}</span>
87
+ <div class="meta">confidence ${m.confidence == null ? "?" : Math.round(m.confidence * 100) + "%"} ·
88
+ <a href="#" data-relink="${esc(m.id)}">relink</a> <span class="mono">${esc(m.id)}</span></div></div>`).join("");
89
+ const members = (d.members || []).map((m) => `<a href="#" data-center="${esc(m.id)}">${esc(m.name)}</a>`).join(", ");
90
+ $("side").innerHTML = `
91
+ <h2>${esc(d.title)}</h2>
92
+ <div class="row">
93
+ <span class="chip accent">${esc(d.type || d.kind)}</span>
94
+ ${d.owner ? '<span class="chip">owner</span>' : ""}
95
+ ${d.origin ? `<span class="chip">${esc(d.origin)}</span>` : ""}
96
+ ${d.stale ? '<span class="chip warn">stale</span>' : ""}
97
+ <span class="mono muted">${esc(d.id)}</span>
98
+ </div>
99
+ ${d.aliases && d.aliases.length ? `<p class="muted">Also: ${esc(d.aliases.join(", "))}</p>` : ""}
100
+ ${members ? `<p class="muted">Members: ${members}</p>` : ""}
101
+ <p><strong>${esc(d.l0 || "No page yet.")}</strong></p>
102
+ <div class="row">
103
+ ${d.id !== state.center ? `<button data-center="${esc(d.id)}">Center</button>` : ""}
104
+ <button data-fix="${esc(d.view_id || d.id)}">Correct</button>
105
+ ${d.kind === "entity" ? `<button data-merge="${esc(d.id)}">Merge into…</button>` : ""}
106
+ </div>
107
+ <div id="fixbox"></div>
108
+ ${d.l1 ? `<h2>Page</h2><div class="l1">${md(d.l1)}</div>` : ""}
109
+ <h2>Claims (${(d.claims || []).length})</h2>${claims || '<p class="muted">None.</p>'}
110
+ ${verdicts ? `<h2>Verdicts</h2>${verdicts}` : ""}
111
+ ${mentions ? `<h2>Mentions</h2>${mentions}` : ""}`;
112
+ cy.$(":selected").unselect();
113
+ cy.getElementById(id).select();
114
+ }
115
+
116
+ function fixForm(targetId, placeholder) {
117
+ $("fixbox").innerHTML = `<div class="card"><label>Correction for ${esc(targetId)} (maximum authority)</label>
118
+ <textarea id="fixtext" placeholder="${esc(placeholder || "What is wrong and what is true?")}"></textarea>
119
+ <button class="primary" id="fixsend">Send</button> <span id="fixmsg" class="muted"></span></div>`;
120
+ $("fixsend").onclick = async () => {
121
+ const r = await fetch("/api/correct", { method: "POST", headers: { "content-type": "application/json" },
122
+ body: JSON.stringify({ target_id: targetId, text: $("fixtext").value }) });
123
+ const j = await r.json();
124
+ $("fixmsg").textContent = `Recorded (${j.correction_id}); it will be applied shortly.`;
125
+ };
126
+ }
127
+
128
+ function pickEntity(title, onPick) {
129
+ $("fixbox").innerHTML = `<div class="card"><label>${esc(title)}</label>
130
+ <input type="text" id="entq" placeholder="Search entity…"><div id="entres"></div>
131
+ <label>or create a new entity</label><div class="row"><input type="text" id="newname" placeholder="Name">
132
+ <select id="newtype">${["person","team","system","project","repository","concept","organization","tool","other"].map((t) => `<option>${t}</option>`).join("")}</select>
133
+ <button id="newgo">Create and use</button></div></div>`;
134
+ const search = async () => {
135
+ const rows = await (await fetch(`/api/entities?q=${encodeURIComponent($("entq").value)}`)).json();
136
+ $("entres").innerHTML = rows.map((r) => `<div><a href="#" data-pick="${esc(r.id)}">${esc(r.name)}</a> <span class="muted">${esc(r.type)} · ${esc(r.id)}</span></div>`).join("");
137
+ };
138
+ $("entq").oninput = search; search();
139
+ $("entres").onclick = (e) => { const id = e.target.dataset.pick; if (id) { e.preventDefault(); onPick({ entity_id: id }); } };
140
+ $("newgo").onclick = () => onPick({ new_name: $("newname").value, new_type: $("newtype").value });
141
+ }
142
+
143
+ const post = (url, body) => fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
144
+
145
+ $("side").addEventListener("click", async (e) => {
146
+ const t = e.target;
147
+ if (t.dataset.center) { e.preventDefault(); state.center = t.dataset.center; state.selected = null; loadGraph(); }
148
+ else if (t.dataset.claim) { e.preventDefault(); const el = document.getElementById(t.dataset.claim); if (el) el.scrollIntoView({ behavior: "smooth" }); }
149
+ else if (t.dataset.ev) {
150
+ e.preventDefault();
151
+ const box = t.closest(".claim").querySelector(".evbox");
152
+ if (box.innerHTML) { box.innerHTML = ""; return; }
153
+ const j = await (await fetch(`/api/open/${t.dataset.ev}?level=3`)).json();
154
+ box.innerHTML = `<pre>${esc(j.text)}</pre>`;
155
+ }
156
+ else if (t.dataset.fix) { e.preventDefault(); fixForm(t.dataset.fix); }
157
+ else if (t.dataset.retract) {
158
+ e.preventDefault();
159
+ if (confirm("Retract this claim?")) { await post("/api/retract", { claim_id: t.dataset.retract }); setTimeout(() => loadDetail(state.selected), 400); }
160
+ }
161
+ else if (t.dataset.relink) {
162
+ e.preventDefault();
163
+ const mention = t.dataset.relink;
164
+ pickEntity(`Relink mention ${mention} to:`, async (choice) => {
165
+ await post("/api/relink", { mention_id: mention, ...choice }); setTimeout(loadGraph, 400);
166
+ });
167
+ }
168
+ else if (t.dataset.merge) {
169
+ e.preventDefault();
170
+ const from = t.dataset.merge;
171
+ pickEntity(`Merge ${from} into:`, async (choice) => {
172
+ if (!choice.entity_id) return;
173
+ await post("/api/merge", { from, into: choice.entity_id }); state.center = choice.entity_id; setTimeout(loadGraph, 400);
174
+ });
175
+ }
176
+ });
177
+
178
+ cy.on("tap", "node", (e) => loadDetail(e.target.id()));
179
+ cy.on("dbltap", "node", (e) => { state.center = e.target.id(); state.selected = null; loadGraph(); });
180
+
181
+ // Search
182
+ let timer;
183
+ $("q").addEventListener("input", () => {
184
+ clearTimeout(timer);
185
+ const q = $("q").value.trim();
186
+ if (!q) { $("results").style.display = "none"; return; }
187
+ timer = setTimeout(async () => {
188
+ const rows = await (await fetch(`/api/search?q=${encodeURIComponent(q)}`)).json();
189
+ $("results").innerHTML = rows.map((r) => `<div data-id="${esc(r.type === "claim" ? r.entity_id : (r.entity_id || r.id))}">
190
+ <span class="chip">${esc(r.type)}</span> <strong>${esc(r.title)}</strong><br><span class="muted">${esc(r.l0)}</span></div>`).join("") || '<div class="muted">Nothing.</div>';
191
+ $("results").style.display = "block";
192
+ }, 250);
193
+ });
194
+ $("results").addEventListener("click", (e) => {
195
+ const row = e.target.closest("[data-id]");
196
+ if (!row || !row.dataset.id) return;
197
+ state.center = row.dataset.id; state.selected = null; $("results").style.display = "none"; loadGraph();
198
+ });
199
+ $("depth").onchange = () => { state.depth = +$("depth").value; loadGraph(); };
200
+ $("home").onclick = () => { state.center = null; state.selected = null; loadGraph(); };
201
+
202
+ // Time
203
+ const first = P.first ? new Date(P.first).getTime() : Date.now();
204
+ const updateTime = () => {
205
+ const v = +$("time").value;
206
+ if (v >= 1000 || !P.first) { state.t = null; $("timelabel").textContent = "now"; }
207
+ else {
208
+ const ts = new Date(first + (Date.now() - first) * (v / 1000));
209
+ state.t = ts.toISOString();
210
+ $("timelabel").textContent = ts.toLocaleString("en-US");
211
+ }
212
+ };
213
+ let ttimer;
214
+ $("time").addEventListener("input", () => { updateTime(); clearTimeout(ttimer); ttimer = setTimeout(loadGraph, 250); });
215
+
216
+ // Time markers under the slider: ~6 evenly spaced dates between the first record and now.
217
+ // Clicking a marker moves the slider to it.
218
+ const drawTicks = () => {
219
+ const box = $("ticklabels"), list = $("timeticks");
220
+ if (!box || !P.first) return;
221
+ const span = Date.now() - first, day = 86400000;
222
+ const fmt = (d) => span < 7 * day
223
+ ? d.toLocaleString("en-US", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })
224
+ : span < 120 * day ? d.toLocaleDateString("en-US", { day: "2-digit", month: "2-digit" })
225
+ : d.toLocaleDateString("en-US", { month: "2-digit", year: "numeric" });
226
+ const n = Math.max(2, Math.min(6, Math.floor(box.clientWidth / (span < 7 * day ? 110 : 80))));
227
+ box.innerHTML = ""; list.innerHTML = "";
228
+ for (let i = 0; i <= n; i++) {
229
+ const v = Math.round(1000 * i / n);
230
+ const label = i === n ? "now" : fmt(new Date(first + span * (v / 1000)));
231
+ const el = document.createElement("span");
232
+ el.style.left = `${v / 10}%`; el.textContent = label;
233
+ el.onclick = () => { $("time").value = v; updateTime(); loadGraph(); };
234
+ box.appendChild(el);
235
+ const opt = document.createElement("option"); opt.value = v; list.appendChild(opt);
236
+ }
237
+ };
238
+ drawTicks();
239
+ window.addEventListener("resize", drawTicks);
240
+
241
+ loadGraph();
242
+ })();