mapwright-agent 0.2.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.
mapwright/render.py ADDED
@@ -0,0 +1,428 @@
1
+ """Diagrams as Mermaid text plus a node map, so the UI can make every box clickable.
2
+
3
+ Each renderer returns {"mermaid": str, "nodes": {mermaid id: {kind, ref, file, line}}, "note": str}.
4
+ `marks` (from analyze.diff_models) outlines what is new, changed or removed since the step the
5
+ user compares against.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import os
12
+ import re
13
+ from collections import Counter
14
+
15
+ from . import concepts as C
16
+ from .analyze import LAYER_TITLES, LAYERS
17
+
18
+ STYLE = {"new": "stroke:#5FB865,stroke-width:3px", "changed": "stroke:#5A9CF8,stroke-width:3px",
19
+ "removed": "stroke:#DB5C5C,stroke-width:2px,stroke-dasharray:5 4"}
20
+ KIND_SHAPE = {"app": ('["', '"]'), "container": ('["', '"]'), "function": ('[\\"', '"\\]'), "db": ('[("', '")]'),
21
+ "cache": ('{{"', '"}}'), "queue": ('[["', '"]]'), "storage": ('[("', '")]'), "search": ('{{"', '"}}'),
22
+ "external": ('(["', '"])'), "ci": ('[/"', '"\\]'), "cdn": ('{{"', '"}}'), "cloud": ('[/"', '"/]')}
23
+
24
+
25
+ def nid(prefix: str, key: str) -> str:
26
+ return prefix + hashlib.sha1(key.encode()).hexdigest()[:8]
27
+
28
+
29
+ def label(text: str, n: int = 56) -> str:
30
+ text = re.sub(r"[\"`<>{}\[\]|#;\\\n\r]", " ", str(text)).strip()
31
+ text = " ".join(text.split())
32
+ return (text[: n - 1] + "…") if len(text) > n else text or "?"
33
+
34
+
35
+ def word(text: str, default: str = "x") -> str:
36
+ w = re.sub(r"\W+", "_", str(text)).strip("_")
37
+ return w if w and not w[0].isdigit() else (f"_{w}" if w else default)
38
+
39
+
40
+ def _classdefs(marks: dict[str, str], ids: dict[str, str]) -> list[str]:
41
+ out = [f" classDef {k} {v}" for k, v in STYLE.items() if k in marks.values()]
42
+ for state in STYLE:
43
+ nodes = [ids[k] for k, v in marks.items() if v == state and k in ids]
44
+ if nodes:
45
+ out.append(f" class {','.join(nodes)} {state}")
46
+ return out
47
+
48
+
49
+ def _with_removed(cur: dict, prev: dict | None, marks: dict) -> dict:
50
+ out = dict(cur)
51
+ for k, v in marks.items():
52
+ if v == "removed" and prev and k in prev:
53
+ out[k] = prev[k]
54
+ return out
55
+
56
+
57
+ # ------------------------------------------------------------------ architecture (layers)
58
+ def architecture(model: dict, marks: dict, prev: dict | None = None, show_tests: bool = False) -> dict:
59
+ mods = _with_removed(model["modules"], (prev or {}).get("modules"), marks.get("modules", {}))
60
+ mk = marks.get("modules", {})
61
+ if not mods:
62
+ return {"mermaid": 'flowchart LR\n empty["No Python or JS/TS modules yet"]', "nodes": {}, "note": ""}
63
+ tests = {k for k, m in mods.items() if m.get("layer") == "test"}
64
+ trivial = {k for k, m in mods.items() if m["file"].endswith("__init__.py") and m["loc"] <= 3 and not m.get("functions") and not m.get("classes")
65
+ and not any(k in o["deps"] for o in mods.values())}
66
+ shown = {k: m for k, m in mods.items() if (show_tests or k not in tests) and k not in trivial}
67
+ lines, nodes = ["flowchart LR"], {}
68
+ package_level = len(shown) > 60
69
+ if package_level:
70
+ pk = {k: m["pkg"] for k, m in shown.items()}
71
+ groups: dict[str, dict[str, int]] = {}
72
+ for k, m in shown.items():
73
+ groups.setdefault(m.get("layer") or "core", Counter())[m["pkg"]] += 1
74
+ ids = {p: nid("p", p) for p in set(pk.values())}
75
+ for layer in LAYERS:
76
+ if layer in groups:
77
+ lines.append(f' subgraph {nid("L", layer)}["{LAYER_TITLES[layer]}"]')
78
+ for p, n in sorted(groups[layer].items()):
79
+ lines.append(f' {ids[p]}["{label(p)}/ · {n}"]')
80
+ nodes[ids[p]] = {"kind": "package", "ref": p}
81
+ lines.append(" end")
82
+ edges = Counter((pk[k], pk[d]) for k, m in shown.items() for d in m["deps"] if d in pk and pk[d] != pk[k])
83
+ lines += [f" {ids[a]} -->|{n}| {ids[b]}" for (a, b), n in sorted(edges.items())]
84
+ note = f"{len(shown)} modules drawn as {len(ids)} packages"
85
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "note": note}
86
+ ids = {k: nid("m", k) for k in shown}
87
+ by_layer: dict[str, list[str]] = {}
88
+ for k, m in shown.items():
89
+ by_layer.setdefault(m.get("layer") or "core", []).append(k)
90
+ for layer in LAYERS:
91
+ if layer not in by_layer:
92
+ continue
93
+ lines.append(f' subgraph {nid("L", layer)}["{LAYER_TITLES[layer]}"]')
94
+ lines.append(" direction TB")
95
+ for k in sorted(by_layer[layer]):
96
+ m = shown[k]
97
+ extra = f" · {len(m.get('functions', []))} fn" if m.get("functions") else ""
98
+ lines.append(f' {ids[k]}["{label(os.path.basename(m["file"]))}{extra}"]')
99
+ nodes[ids[k]] = {"kind": "module", "ref": k, "file": m["file"]}
100
+ lines.append(" end")
101
+ if tests and not show_tests:
102
+ lines.append(f' {nid("t", "tests")}[/"tests · {len(tests)} modules"/]')
103
+ nodes[nid("t", "tests")] = {"kind": "layer", "ref": "test"}
104
+ ext = Counter(e for m in shown.values() for e in m["ext"])
105
+ top = [e for e, _ in ext.most_common(10)]
106
+ if top:
107
+ lines.append(' subgraph Lext["External packages"]')
108
+ for e in top:
109
+ lines.append(f' {nid("x", e)}(["{label(e)}"])')
110
+ nodes[nid("x", e)] = {"kind": "package", "ref": e}
111
+ lines.append(" end")
112
+ for k in sorted(shown):
113
+ lines += [f" {ids[k]} --> {ids[d]}" for d in shown[k]["deps"] if d in ids]
114
+ lines += [f' {ids[k]} -.-> {nid("x", e)}' for e in shown[k]["ext"] if e in top]
115
+ lines += [" classDef default font-size:13px"] + _classdefs(mk, ids)
116
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "note": ""}
117
+
118
+
119
+ # ------------------------------------------------------------------ file organisation
120
+ def files(file_rows: list[dict], max_depth: int = 3, per_dir: int = 10) -> dict:
121
+ tree: dict = {}
122
+ for f in file_rows:
123
+ cur = tree
124
+ parts = f["path"].split("/")
125
+ for p in parts[:-1]:
126
+ cur = cur.setdefault(p + "/", {})
127
+ cur[parts[-1]] = f
128
+ lines, nodes = ["flowchart LR", ' root(["/"])'], {"root": {"kind": "dir", "ref": ""}}
129
+ marks: dict[str, str] = {}
130
+ ids: dict[str, str] = {}
131
+
132
+ def walk(node: dict, parent: str, path: str, depth: int) -> None:
133
+ dirs = sorted(k for k in node if k.endswith("/"))
134
+ leaves = sorted(k for k in node if not k.endswith("/"))
135
+ for d in dirs:
136
+ full = path + d
137
+ i = nid("d", full)
138
+ count = sum(1 for _ in _iter_files(node[d]))
139
+ lines.append(f' {i}["{label(d)} · {count}"]')
140
+ lines.append(f" {parent} --> {i}")
141
+ nodes[i] = {"kind": "dir", "ref": full.rstrip("/")}
142
+ ch = {x["status"] for x in _iter_files(node[d]) if x.get("status")}
143
+ if ch:
144
+ ids[full], marks[full] = i, "new" if ch == {"A"} else "removed" if ch == {"D"} else "changed"
145
+ if depth < max_depth:
146
+ walk(node[d], i, full, depth + 1)
147
+ shown = leaves[:per_dir]
148
+ for leaf in shown:
149
+ f = node[leaf]
150
+ i = nid("f", path + leaf)
151
+ lines.append(f' {i}("{label(leaf, 40)}")')
152
+ lines.append(f" {parent} --- {i}")
153
+ nodes[i] = {"kind": "file", "ref": f["path"], "file": f["path"]}
154
+ if f.get("status"):
155
+ ids[f["path"]], marks[f["path"]] = i, {"A": "new", "M": "changed", "D": "removed"}[f["status"]]
156
+ if len(leaves) > per_dir:
157
+ i = nid("more", path)
158
+ lines.append(f' {i}["+{len(leaves) - per_dir} more"]:::muted')
159
+ lines.append(f" {parent} --- {i}")
160
+ walk(tree, "root", "", 1)
161
+ lines += [" classDef muted stroke-dasharray:3 3,color:#868A91"] + _classdefs(marks, ids)
162
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "note": "" if len(file_rows) < 400 else "large tree: deep folders are collapsed"}
163
+
164
+
165
+ def _iter_files(node: dict):
166
+ for k, v in node.items():
167
+ if k.endswith("/"):
168
+ yield from _iter_files(v)
169
+ else:
170
+ yield v
171
+
172
+
173
+ # ------------------------------------------------------------------ classes
174
+ def classes(model: dict, marks: dict, prev: dict | None = None) -> dict:
175
+ cls = _with_removed(model["classes"], (prev or {}).get("classes"), marks.get("classes", {}))
176
+ mk = marks.get("classes", {})
177
+ if not cls:
178
+ return {"mermaid": "classDiagram\n class NoClassesYet", "nodes": {}, "note": ""}
179
+ by_name: dict[str, list[str]] = {}
180
+ for k, c in cls.items():
181
+ by_name.setdefault(c["name"], []).append(k)
182
+ degree, rel = Counter(), []
183
+ for k, c in cls.items():
184
+ for b in c["bases"]:
185
+ for target in by_name.get(b.split(".")[-1].split("[")[0], [])[:1]:
186
+ rel.append((target, k, "<|--"))
187
+ degree[target] += 1
188
+ degree[k] += 1
189
+ seen = set()
190
+ for _, typ in c["attrs"]:
191
+ for w in re.findall(r"[A-Za-z_]\w*", typ or ""):
192
+ for target in by_name.get(w, [])[:1]:
193
+ if target != k and target not in seen:
194
+ seen.add(target)
195
+ rel.append((k, target, "-->"))
196
+ degree[target] += 1
197
+ degree[k] += 1
198
+ keep = sorted(cls, key=lambda k: (k not in mk, -degree[k], k))[:45]
199
+ names, nodes = {}, {}
200
+ for k in keep:
201
+ base = word(cls[k]["name"], "Class")
202
+ names[k] = base if base not in names.values() else word(f'{cls[k]["module"].split(".")[-1].split("/")[-1]}_{base}')
203
+ nodes["class:" + names[k]] = {"kind": "class", "ref": k, "file": cls[k]["file"], "line": cls[k].get("line")}
204
+ lines = ["classDiagram"]
205
+ for k in sorted(keep):
206
+ c = cls[k]
207
+ lines.append(f" class {names[k]} {{")
208
+ if c.get("kind") == "interface":
209
+ lines.append(" <<interface>>")
210
+ for a, typ in c["attrs"][:7]:
211
+ t = re.match(r"[A-Za-z_][\w.]*", typ or "")
212
+ lines.append(f' +{word(a)}{" " + word(t.group(0).split(".")[-1]) if t else ""}')
213
+ for meth in [x for x in c["methods"] if not x.startswith("_")][:7]:
214
+ lines.append(f" +{word(meth)}()")
215
+ if len(c["attrs"]) > 7 or len(c["methods"]) > 7:
216
+ lines.append(f' +more_{len(c["attrs"])}_attrs_{len(c["methods"])}_methods')
217
+ lines.append(" }")
218
+ lines += sorted({f" {names[a]} {arrow} {names[b]}" for a, b, arrow in rel if a in names and b in names})
219
+ lines += [f" style {names[k]} {STYLE[v]}" for k, v in sorted(mk.items()) if k in names]
220
+ return {"mermaid": "\n".join(lines), "nodes": nodes,
221
+ "note": f"{len(cls) - len(keep)} more classes not drawn" if len(cls) > len(keep) else ""}
222
+
223
+
224
+ # ------------------------------------------------------------------ data model
225
+ def erd(model: dict, marks: dict, prev: dict | None = None) -> dict:
226
+ tables = _with_removed(model["tables"], (prev or {}).get("tables"), marks.get("tables", {}))
227
+ if not tables:
228
+ return {"mermaid": 'erDiagram\n NO_TABLES_YET {\n string hint "SQL, SQLAlchemy, Django, Prisma, zod or Firestore collections appear here"\n }',
229
+ "nodes": {}, "note": ""}
230
+ names = {k: word(k, "table") for k in tables}
231
+ low = {k.lower(): k for k in tables}
232
+ lines, nodes = ["erDiagram"], {}
233
+ for k in sorted(tables):
234
+ nodes["entity:" + names[k]] = {"kind": "table", "ref": k, "file": tables[k]["file"], "line": tables[k].get("line")}
235
+ lines.append(f" {names[k]} {{")
236
+ for c in tables[k]["columns"][:30]:
237
+ key = " PK" if c["pk"] else " FK" if c["fk"] else ""
238
+ lines.append(f' {word(c["type"], "col")} {word(c["name"], "col")}{key}')
239
+ for op, cond in list(tables[k].get("ops", {}).items())[:8]: # Firestore rules: allowed operations
240
+ lines.append(f' rule {word(op, "op")} "{label(cond, 40)}"')
241
+ lines.append(" }")
242
+ for k in sorted(tables):
243
+ for c in tables[k]["columns"]:
244
+ target = low.get((c["fk"] or "").lower()) or low.get((c["fk"] or "").lower() + "s")
245
+ if target:
246
+ lines.append(f' {names[target]} ||--o{{ {names[k]} : "{label(c["name"], 30)}"')
247
+ status = {names[k]: v for k, v in marks.get("tables", {}).items() if k in names}
248
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "marks": status, "note": ""}
249
+
250
+
251
+ # ------------------------------------------------------------------ cloud / infrastructure
252
+ def cloud(inf: dict) -> dict:
253
+ ns = inf.get("nodes", [])
254
+ if not ns:
255
+ return {"mermaid": 'flowchart LR\n none["No infrastructure files found yet: Dockerfile, compose, Terraform, k8s, CI, .env.example"]',
256
+ "nodes": {}, "note": ""}
257
+ lines, nodes = ["flowchart LR"], {}
258
+ groups: dict[str, list[dict]] = {}
259
+ for n in ns:
260
+ groups.setdefault(n.get("group") or "services", []).append(n)
261
+ order = ["application", "containers", "docker compose", "processes", "kubernetes", "serverless", "terraform", "hosting", "services", "delivery"]
262
+ for g in sorted(groups, key=lambda x: order.index(x) if x in order else 99):
263
+ lines.append(f' subgraph {nid("g", g)}["{label(g.title())}"]')
264
+ for n in groups[g]:
265
+ a, b = KIND_SHAPE.get(n["kind"], ('["', '"]'))
266
+ i = "i_" + word(n["id"])
267
+ lines.append(f' {i}{a}{label(n["label"], 40)}{b}:::{n["kind"]}')
268
+ nodes[i] = {"kind": "infra", "ref": n["id"], "file": (n.get("sources") or [None])[0]}
269
+ lines.append(" end")
270
+ for e in inf.get("edges", []):
271
+ lines.append(f' i_{word(e["from"])} -->|{label(e["label"], 20)}| i_{word(e["to"])}')
272
+ lines += [" classDef app stroke:#3574F0,stroke-width:2.5px", " classDef db stroke:#C77DBB,stroke-width:2px",
273
+ " classDef cache stroke:#E5A13E,stroke-width:2px", " classDef queue stroke:#E5A13E,stroke-width:2px",
274
+ " classDef external stroke:#57965C,stroke-width:2px", " classDef cloud stroke:#5A9CF8,stroke-width:2px",
275
+ " classDef ci stroke-dasharray:4 3"]
276
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "note": ""}
277
+
278
+
279
+ # ------------------------------------------------------------------ API & core processes
280
+ def processes(model: dict, focus: str | None = None, depth: int = 2) -> dict:
281
+ fns, routes = model["functions"], model["routes"]
282
+ lines, nodes = ["flowchart LR"], {}
283
+ entries = []
284
+ if routes:
285
+ for r in routes[:30]:
286
+ entries.append((f'{r["method"]} {r["path"]}', r.get("fid"), r))
287
+ else:
288
+ for fid, f in fns.items():
289
+ if f["name"] in ("main", "run", "cli", "handler", "lambda_handler", "start", "serve") or any("command" in d for d in f["decorators"]):
290
+ entries.append((f["qual"] + "()", fid, None))
291
+ entries = entries[:20]
292
+ if focus:
293
+ entries = [e for e in entries if e[0] == focus or e[1] == focus] or entries
294
+ if not entries:
295
+ return {"mermaid": 'flowchart LR\n none["No HTTP routes or entry points found yet"]', "nodes": {}, "note": ""}
296
+ seen_fn, tables, ext = set(), set(), set()
297
+ lines.append(' subgraph Lroutes["Entry points"]')
298
+ for title, fid, r in entries:
299
+ i = nid("r", title)
300
+ lines.append(f' {i}(["{label(title, 44)}"]):::route')
301
+ nodes[i] = {"kind": "route", "ref": title, "file": r["file"] if r else fns.get(fid, {}).get("file"),
302
+ "line": r["line"] if r else fns.get(fid, {}).get("line")}
303
+ lines.append(" end")
304
+ edges = set()
305
+
306
+ def visit(fid: str, d: int) -> None:
307
+ if fid not in fns:
308
+ return
309
+ f = fns[fid]
310
+ if fid not in seen_fn:
311
+ seen_fn.add(fid)
312
+ i = nid("f", fid)
313
+ hints = [h for h in f["hints"] if h in ("database query", "HTTP call", "retry with backoff", "async I/O")]
314
+ lines.append(f' {i}["{label(f["qual"], 36)}()' + (f' · {label(hints[0], 16)}' if hints else "") + '"]')
315
+ nodes[i] = {"kind": "function", "ref": fid, "file": f["file"], "line": f["line"]}
316
+ for t in f.get("tables", []):
317
+ tables.add(t)
318
+ edges.add((i, nid("t", t), "reads/writes"))
319
+ if "HTTP call" in f["hints"]:
320
+ ext.add("HTTP")
321
+ edges.add((i, "extHTTP", "calls"))
322
+ if d >= depth:
323
+ return
324
+ for c in f["callees"][:6]:
325
+ if c != fid and fns.get(c, {}).get("module", "").split(".")[0] not in ("tests", "test"):
326
+ edges.add((nid("f", fid), nid("f", c), ""))
327
+ visit(c, d + 1)
328
+ for title, fid, r in entries:
329
+ if fid:
330
+ edges.add((nid("r", title), nid("f", fid), ""))
331
+ visit(fid, 0)
332
+ for t in sorted(tables):
333
+ lines.append(f' {nid("t", t)}[("{label(t, 30)}")]:::table')
334
+ nodes[nid("t", t)] = {"kind": "table", "ref": t, "file": model["tables"].get(t, {}).get("file")}
335
+ if ext:
336
+ lines.append(' extHTTP(["external HTTP"]):::ext')
337
+ for a, b, lab in sorted(edges):
338
+ lines.append(f" {a} -->|{lab}| {b}" if lab else f" {a} --> {b}")
339
+ lines += [" classDef route stroke:#3574F0,stroke-width:2px", " classDef table stroke:#C77DBB,stroke-width:2px",
340
+ " classDef ext stroke:#57965C,stroke-width:2px"]
341
+ return {"mermaid": "\n".join(lines), "nodes": nodes,
342
+ "note": "" if routes else "no HTTP routes found: showing entry-point functions"}
343
+
344
+
345
+ # ------------------------------------------------------------------ call graph
346
+ def calls(model: dict, marks: dict, focus: str | None = None, limit: int = 40) -> dict:
347
+ fns = model["functions"]
348
+ mk = marks.get("functions", {})
349
+ if not fns:
350
+ return {"mermaid": 'flowchart LR\n none["No functions yet"]', "nodes": {}, "note": ""}
351
+ if focus and focus in fns:
352
+ keep = {focus}
353
+ for c in fns[focus]["callees"]:
354
+ keep.add(c)
355
+ keep |= set(fns.get(c, {}).get("callees", [])[:4])
356
+ for c in fns[focus]["callers"][:8]:
357
+ keep.add(c)
358
+ keep |= set(fns.get(c, {}).get("callers", [])[:3])
359
+ note = f"callers and callees of {fns[focus]['qual']}"
360
+ else:
361
+ score = {fid: len(f["callees"]) + len(f["callers"]) + (5 if fid in mk else 0) for fid, f in fns.items()
362
+ if not f["module"].split(".")[0].split("/")[0] in ("tests", "test") and "test" != (f["file"].split("/")[0])}
363
+ keep = {fid for fid, _ in sorted(score.items(), key=lambda kv: -kv[1])[:limit] if score[fid] > 0}
364
+ note = f"the {len(keep)} most connected functions of {len(fns)}" if len(fns) > len(keep) else ""
365
+ by_mod: dict[str, list[str]] = {}
366
+ for fid in keep:
367
+ if fid in fns:
368
+ by_mod.setdefault(fns[fid]["module"], []).append(fid)
369
+ lines, nodes, ids = ["flowchart LR"], {}, {}
370
+ for mod in sorted(by_mod):
371
+ lines.append(f' subgraph {nid("M", mod)}["{label(mod, 40)}"]')
372
+ for fid in sorted(by_mod[mod]):
373
+ f = fns[fid]
374
+ ids[fid] = nid("c", fid)
375
+ heavy = ":::hot" if f["complexity"] >= 10 else ""
376
+ lines.append(f' {ids[fid]}["{label(f["qual"], 34)}()"]{heavy}')
377
+ nodes[ids[fid]] = {"kind": "function", "ref": fid, "file": f["file"], "line": f["line"]}
378
+ lines.append(" end")
379
+ for fid in sorted(ids):
380
+ for c in fns[fid]["callees"]:
381
+ if c in ids:
382
+ lines.append(f" {ids[fid]} --> {ids[c]}" if c != fid else f" {ids[fid]} -.->|recursion| {ids[fid]}")
383
+ if focus and focus in ids:
384
+ lines.append(f" class {ids[focus]} focus")
385
+ lines += [" classDef hot stroke:#E5A13E,stroke-width:2px", " classDef focus stroke:#3574F0,stroke-width:3px"] + _classdefs(mk, ids)
386
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "note": note}
387
+
388
+
389
+ # ------------------------------------------------------------------ concept map
390
+ def concept_map(model: dict, concepts: dict, claims: list[dict]) -> dict:
391
+ if not concepts and not claims:
392
+ return {"mermaid": 'flowchart LR\n none["No mechanisms detected yet"]', "nodes": {}, "note": ""}
393
+ lines, nodes = ["flowchart LR"], {}
394
+ groups: dict[str, list[str]] = {}
395
+ for cid in list(concepts) + [c["concept"] for c in claims if c["concept"] not in concepts]:
396
+ if cid in C.CATALOG and cid not in groups.get(C.CATALOG[cid][2], []):
397
+ groups.setdefault(C.CATALOG[cid][2], []).append(cid)
398
+ files_used: dict[str, str] = {}
399
+ for g in [x for x in C.GROUPS if x in groups]:
400
+ lines.append(f' subgraph {nid("G", g)}["{C.GROUPS[g]}"]')
401
+ for cid in groups[g]:
402
+ i = "k_" + word(cid)
403
+ lines.append(f' {i}(["{label(C.CATALOG[cid][0], 32)}"])')
404
+ nodes[i] = {"kind": "concept", "ref": cid}
405
+ lines.append(" end")
406
+ edges = set()
407
+ for cid, evs in concepts.items():
408
+ for e in evs[:4]:
409
+ f = e["file"]
410
+ files_used.setdefault(f, nid("f", f))
411
+ edges.add(("k_" + word(cid), files_used[f], "", "-.-"))
412
+ for c in claims:
413
+ f = c.get("file")
414
+ if not f:
415
+ continue
416
+ files_used.setdefault(f, nid("f", f))
417
+ edges.add(("k_" + word(c["concept"]), files_used[f], "claimed" if c.get("status") == "verified" else "claimed?", "-->"))
418
+ for f, i in sorted(files_used.items()):
419
+ lines.append(f' {i}["{label(f, 40)}"]:::file')
420
+ nodes[i] = {"kind": "file", "ref": f, "file": f}
421
+ for a, b, lab, arrow in sorted(edges):
422
+ lines.append(f" {a} {arrow}|{lab}| {b}" if lab else f" {a} {arrow} {b}")
423
+ lines.append(" classDef file font-size:12px")
424
+ return {"mermaid": "\n".join(lines), "nodes": nodes, "note": "dotted: detected in code · solid: claimed by the agent"}
425
+
426
+
427
+ KINDS = {"architecture": "Architecture", "files": "Files", "classes": "Classes", "data": "Data model", "cloud": "Cloud & infra",
428
+ "processes": "API & processes", "calls": "Call graph", "concepts": "Concept map"}