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/brief.py ADDED
@@ -0,0 +1,208 @@
1
+ """Compact text views for agents: the whole map in a fixed budget, and one symbol at a time.
2
+
3
+ These are what keep the token cost low. An agent asks for the map (about 600 tokens by default)
4
+ instead of listing directories and opening files to rediscover structure, and asks for one
5
+ symbol's callers, callees and tables instead of reading the file. No source code is included.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+
12
+ from . import analyze as A
13
+ from . import concepts as C
14
+
15
+
16
+ def _cut(items: list[str], n: int) -> str:
17
+ return ", ".join(items[:n]) + (f" +{len(items) - n}" if len(items) > n else "")
18
+
19
+
20
+ def project_brief(p, budget: int = 2400, focus: str | None = None) -> str:
21
+ p.ensure()
22
+ m = p.model
23
+ st = p.verify()
24
+ steps = p.steps()
25
+ pend = p.pending(counts=False)
26
+ notes = {n.get("resolved") or n["symbol"]: n["role"] for n in st["notes"] if n.get("status") == "ok"}
27
+ head = [f"# {p.name} · map at step {steps[-1]['n'] if steps else 0}"
28
+ + (f" (+{len(pend)} file changes since)" if pend else "")]
29
+ c = {"files": len(p.cache), "modules": len(m["modules"]), "functions": len(m["functions"]), "classes": len(m["classes"]),
30
+ "tables": len(m["tables"]), "routes": len(m["routes"])}
31
+ head.append(f"{c['files']} files · {c['modules']} modules · {c['functions']} functions · {c['classes']} classes · "
32
+ f"{c['tables']} tables · {c['routes']} routes")
33
+ layers = {}
34
+ for k, mod in m["modules"].items():
35
+ layers.setdefault(mod["layer"], []).append(k)
36
+ head.append("Layers: " + " · ".join(f"{l_} {len(layers[l_])}" for l_ in A.LAYERS if l_ in layers))
37
+
38
+ sections: list[tuple[str, list[str]]] = []
39
+ if m["routes"]:
40
+ sections.append(("Entry points", [f"{r['method']} {r['path']} → {(r.get('fid') or r.get('handler') or '?').split(':')[-1]}"
41
+ for r in m["routes"]]))
42
+ mods = []
43
+ for layer in A.LAYERS:
44
+ for k in sorted(layers.get(layer, [])):
45
+ mod = m["modules"][k]
46
+ if focus and not mod["file"].startswith(focus.rstrip("/")):
47
+ continue
48
+ if layer == "test" and not focus:
49
+ continue
50
+ fids = [f"{k}:{q}" for q in mod.get("functions", [])]
51
+ fns = sorted((m["functions"][x] for x in fids if x in m["functions"]),
52
+ key=lambda f: (-(len(f["callers"]) + len(f["callees"])), f["line"]))
53
+ syms = [f["qual"] + (f"(cx {f['complexity']})" if f["complexity"] >= 8 else "") for f in fns if not f["name"].startswith("_")]
54
+ role = notes.get(k) or notes.get(mod["file"])
55
+ mods.append(f"{mod['file']} [{layer}] {_cut(syms, 6 if not focus else 30)}" + (f" — {role}" if role else ""))
56
+ if "test" in layers and not focus:
57
+ mods.append(f"tests: {len(layers['test'])} modules")
58
+ sections.append(("Modules [layer] key symbols — role", mods))
59
+ if m["tables"]:
60
+ tbl = []
61
+ for t, d in sorted(m["tables"].items()):
62
+ cols = [col["name"] + (" PK" if col["pk"] else f" →{col['fk']}" if col["fk"] else "") for col in d["columns"]]
63
+ if d.get("kind") in ("firestore", "storage"):
64
+ tbl.append(f"{t} [{d['kind']} collection; {d['source']}]({_cut(list(d.get('ops', {})), 6)})")
65
+ continue
66
+ tbl.append(f"{t}({_cut(cols, 6)})")
67
+ sections.append(("Tables", tbl))
68
+ if p.infra["nodes"]:
69
+ sections.append(("Infra", [f"{n['label']} [{n['kind']}] from {n['sources'][0]}" for n in p.infra["nodes"]]))
70
+ if p.concepts:
71
+ sections.append(("Mechanisms (detected)", [f"{cid}: {_cut(sorted({e['file'] for e in evs}), 2)}" for cid, evs in p.concepts.items()]))
72
+ algos = [f"{', '.join(h for h in f['hints'] if h != 'async I/O')}: {fid.split(':')[-1]} ({f['file']})"
73
+ for fid, f in m["functions"].items() if any(h not in ("async I/O", "database query", "HTTP call") for h in f["hints"])
74
+ and A.layer_of(f["file"]) != "test"]
75
+ if algos:
76
+ sections.append(("Algorithms (hints)", algos))
77
+ todos = [f"{t['id']} {t['text']}" for t in st["todos"] if t["status"] == "open"]
78
+ if todos:
79
+ sections.append(("Open todos", todos))
80
+ if st["problems"]:
81
+ sections.append(("Unverified", [x["text"] for x in st["problems"] if x["kind"] != "parse"][:8]
82
+ + [x["text"] for x in st["problems"] if x["kind"] == "parse"][:3]))
83
+ if steps:
84
+ sections.append(("Recent steps", [f"{s['n']} {s['title']} (+{s['summary']['added']}/-{s['summary']['removed']} in {s['summary']['files']} files)"
85
+ for s in reversed(steps[-4:]) if s["n"] > 0] or ["only the baseline so far"]))
86
+ tail = "Tools: find(query) · symbol(name) · step(title) after each change · todo · claim(concept, symbol)"
87
+
88
+ # fit the budget: shrink the longest sections first, never drop the headers
89
+ limits = {name: len(rows) for name, rows in sections}
90
+
91
+ def render() -> str:
92
+ out = head[:]
93
+ for name, rows in sections:
94
+ k = limits[name]
95
+ if k <= 0:
96
+ continue
97
+ body = rows[:k]
98
+ more = len(rows) - k
99
+ out.append(f"{name}:" + ("\n " + "\n ".join(body) if body else "") + (f"\n … {more} more" if more > 0 else ""))
100
+ out.append(tail)
101
+ return "\n".join(out)
102
+ text = render()
103
+ guard = 0
104
+ while len(text) > budget and guard < 400:
105
+ guard += 1
106
+ name = max(limits, key=lambda n: (limits[n] * (2 if n.startswith("Modules") else 1), n))
107
+ if limits[name] <= 1:
108
+ break
109
+ limits[name] -= 1 if limits[name] < 8 else max(1, limits[name] // 4)
110
+ text = render()
111
+ return text[: budget + 200]
112
+
113
+
114
+ def symbol_card(p, ref: str) -> str:
115
+ p.ensure()
116
+ hit = A.resolve(p.model, ref)
117
+ if not hit:
118
+ found = A.find_symbols(p.model, ref, 8)
119
+ if not found:
120
+ return f"No symbol matches {ref!r}."
121
+ return "Ambiguous or not found. Candidates:\n" + "\n".join(f" {f['id']} ({f['kind']}) {f['file']}:{f['line'] or ''}" for f in found)
122
+ kind, sid, n = hit
123
+ v = p.verify()
124
+ lines = []
125
+ if kind == "functions":
126
+ lines.append(f"function {sid}({', '.join(n['args'])}) · {n['file']}:{n['line']}-{n['end']} · {n['loc']} lines · complexity {n['complexity']}")
127
+ if n.get("doc"):
128
+ lines.append(f"doc: {n['doc']}")
129
+ if n["hints"]:
130
+ lines.append("hints: " + ", ".join(n["hints"]))
131
+ lines.append("calls: " + (_cut([c.split(':')[-1] for c in n["callees"]], 10) or "—"))
132
+ lines.append("called by: " + (_cut([c.split(':')[-1] for c in n["callers"]], 10) or "—"))
133
+ routes = [f"{r['method']} {r['path']}" for r in p.model["routes"] if r.get("fid") == sid]
134
+ if routes:
135
+ lines.append("serves: " + ", ".join(routes))
136
+ if n.get("tables"):
137
+ lines.append("tables: " + ", ".join(n["tables"]))
138
+ elif kind == "classes":
139
+ lines.append(f"class {sid} · {n['file']}:{n['line']} · bases {', '.join(n['bases']) or '—'}")
140
+ lines.append("attributes: " + (_cut([a for a, _ in n["attrs"]], 12) or "—"))
141
+ lines.append("methods: " + (_cut(n["methods"], 14) or "—"))
142
+ elif kind == "tables":
143
+ lines.append(f"table {sid} · {n['file']}:{n.get('line')}")
144
+ if n.get("kind") in ("firestore", "storage"):
145
+ lines.append(f"{n['kind']} collection {n.get('path')} from {n['source']}")
146
+ lines += [f"allow {op}: {cond}" for op, cond in n.get("ops", {}).items()]
147
+ lines.append("columns: " + ", ".join(c["name"] + (" PK" if c["pk"] else f" →{c['fk']}" if c["fk"] else "") for c in n["columns"]))
148
+ users = [fid.split(":")[-1] for fid, f in p.model["functions"].items() if sid in f.get("tables", [])]
149
+ if users:
150
+ lines.append("used by: " + _cut(users, 10))
151
+ else:
152
+ lines.append(f"module {sid} · {n['file']} · layer {n['layer']} · {n['loc']} lines")
153
+ lines.append("imports: " + (_cut(n["deps"], 10) or "—") + (" · external: " + _cut(n["ext"], 8) if n["ext"] else ""))
154
+ lines.append("defines: " + (_cut(n.get("functions", []), 14) or "—"))
155
+ users = [k for k, m in p.model["modules"].items() if sid in m["deps"]]
156
+ lines.append("imported by: " + (_cut(users, 10) or "—"))
157
+ role = next((x["role"] for x in v["notes"] if x.get("resolved") == sid), None)
158
+ if role:
159
+ lines.append(f"role (agent note): {role}")
160
+ cl = [f"{c['concept']} ({c['status']})" for c in v["claims"] if c.get("resolved") == sid]
161
+ if cl:
162
+ lines.append("claimed: " + ", ".join(cl))
163
+ det = [cid for cid, evs in p.concepts.items() if any(e["file"] == n["file"] and (kind == "modules" or e.get("symbol") == (n.get("qual") or n.get("name"))) for e in evs)]
164
+ if det:
165
+ lines.append("detected: " + ", ".join(det))
166
+ hist = symbol_history(p, kind, sid)
167
+ if hist:
168
+ lines.append("history: " + hist)
169
+ return "\n".join(lines)
170
+
171
+
172
+ def symbol_history(p, kind: str, sid: str, max_steps: int = 30) -> str:
173
+ out, seen_prev = [], None
174
+ for s in p.steps()[-max_steps:]:
175
+ data = p.load_step(s["n"])
176
+ if not data:
177
+ continue
178
+ node = data["model"].get(kind, {}).get(sid)
179
+ sig = A._sig(kind, node) if node else None
180
+ if node and seen_prev is None:
181
+ out.append(f"added in step {s['n']}" if s["n"] > 0 else "present at baseline")
182
+ elif node and sig != seen_prev:
183
+ out.append(f"changed in step {s['n']}")
184
+ elif not node and seen_prev is not None:
185
+ out.append(f"removed in step {s['n']}")
186
+ seen_prev = sig
187
+ return ", ".join(out[-6:])
188
+
189
+
190
+ def catalog_text() -> str:
191
+ rows = [f"{c['id']}: {c['meaning']}" for c in C.catalog()]
192
+ return "Concept ids for claim(concept, symbol):\n" + "\n".join(rows)
193
+
194
+
195
+ def step_receipt(data: dict) -> str:
196
+ s = data["summary"]
197
+ parts = [f"step {data['n']} recorded: {s['files']} files (+{s['added']} -{s['removed']})"]
198
+ for kind, d in s["delta"].items():
199
+ parts.append(f"{kind}: " + ", ".join(f"{v} {k}" for k, v in d.items()))
200
+ if data.get("title_check", "ok") != "ok":
201
+ parts.append("check: " + data["title_check"])
202
+ if not s["files"]:
203
+ parts.append("note: nothing changed since the previous step")
204
+ return " · ".join(parts)
205
+
206
+
207
+ def files_line(changes: list[dict]) -> str:
208
+ return ", ".join(f"{c['kind'][0].upper()} {os.path.basename(c['path'])}" for c in changes[:8])