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/cli.py ADDED
@@ -0,0 +1,596 @@
1
+ """mapwright command line. Stdlib only (argparse)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ from . import __version__, brief, config, connect, render
16
+ from . import analyze as A
17
+
18
+ USE_COLOR = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
19
+
20
+
21
+ def c(text: str, code: str) -> str:
22
+ return f"\033[{code}m{text}\033[0m" if USE_COLOR else text
23
+
24
+
25
+ BLUE, GREEN, AMBER, RED, DIM, BOLD = "38;5;75", "38;5;71", "38;5;179", "38;5;167", "38;5;245", "1"
26
+
27
+
28
+ def project(args):
29
+ from .track import open_project
30
+ p = open_project(getattr(args, "path", None) or os.getcwd())
31
+ p.refresh()
32
+ return p
33
+
34
+
35
+ def api(method: str, path: str, body=None, timeout: float = 2.0):
36
+ req = urllib.request.Request(config.base_url() + path, method=method, data=json.dumps(body).encode() if body is not None else None,
37
+ headers={"Authorization": f"Bearer {config.token()}", "Content-Type": "application/json"})
38
+ with urllib.request.urlopen(req, timeout=timeout) as r:
39
+ return json.loads(r.read() or b"{}")
40
+
41
+
42
+ def daemon_state() -> str:
43
+ """none: nothing on the port · ours: a daemon with this home · other: something else (a daemon with another home) holds the port."""
44
+ try:
45
+ r = api("GET", "/v1/ping", timeout=0.6)
46
+ if r.get("ok"):
47
+ h = r.get("home")
48
+ return "ours" if not h or os.path.realpath(h) == os.path.realpath(str(config.home())) else "other"
49
+ except (urllib.error.URLError, OSError, ValueError):
50
+ pass
51
+ import socket
52
+ try:
53
+ with socket.create_connection(("127.0.0.1", config.port()), timeout=0.3):
54
+ return "other"
55
+ except OSError:
56
+ return "none"
57
+
58
+
59
+ def _other_daemon_msg() -> str:
60
+ return (f"another process (probably a daemon with a different MAPWRIGHT_HOME) already listens on {config.base_url()}; "
61
+ f"this project's home is {config.home()}. One daemon serves one home: stop it (`mapwright down` with its home) "
62
+ f"or set MAPWRIGHT_PORT to another port.")
63
+
64
+
65
+ def _daemon_env() -> dict:
66
+ return dict(os.environ, MAPWRIGHT_HOME=str(config.home()))
67
+
68
+
69
+ def alive() -> bool:
70
+ try:
71
+ return bool(api("GET", "/v1/ping", timeout=0.6).get("ok"))
72
+ except (urllib.error.URLError, OSError, ValueError):
73
+ return False
74
+
75
+
76
+ # ------------------------------------------------------------------ commands
77
+ def _gitignore_add(root: str, entries: list[str]) -> None:
78
+ path = os.path.join(root, ".gitignore")
79
+ try:
80
+ text = open(path, encoding="utf-8").read() if os.path.exists(path) else ""
81
+ except OSError:
82
+ return
83
+ have = {ln.strip().strip("/") for ln in text.splitlines()}
84
+ add = [e for e in entries if e.strip("/") not in have]
85
+ if add:
86
+ with open(path, "w", encoding="utf-8") as fh:
87
+ fh.write(text + ("" if not text or text.endswith("\n") else "\n") + "\n".join(add) + "\n")
88
+
89
+
90
+ def _setup_local_home(a) -> str | None:
91
+ """init --local / --home DIR: create the home (0700), write the discovery marker, ignore it in version control, use it from here on."""
92
+ if a.local and a.home:
93
+ raise ValueError("use either --local or --home DIR, not both")
94
+ if not (a.local or a.home):
95
+ return None
96
+ root = os.path.realpath(A.find_root(os.path.abspath(getattr(a, "path", None) or os.getcwd())))
97
+ target = os.path.join(root, config.MARKER_DIR) if a.local else os.path.abspath(os.path.join(root, os.path.expanduser(a.home)))
98
+ os.makedirs(target, mode=0o700, exist_ok=True)
99
+ os.chmod(target, 0o700)
100
+ config.write_marker(root, target)
101
+ os.environ["MAPWRIGHT_HOME"] = target
102
+ config.reset_cache()
103
+ entries = [config.MARKER_DIR + "/"]
104
+ rel = os.path.relpath(target, root)
105
+ if not rel.startswith("..") and rel != config.MARKER_DIR:
106
+ entries.append(rel.replace(os.sep, "/") + "/")
107
+ if os.sep not in rel and rel not in A.IGNORE_DIRS: # the tracker must not scan its own home
108
+ ign = config.settings()["ignore"]
109
+ if rel not in ign:
110
+ config.save_settings({"ignore": [*ign, rel]})
111
+ _gitignore_add(root, entries)
112
+ return target
113
+
114
+
115
+ def _truncation_warning(p):
116
+ info = p.truncated_info
117
+ if not (p.truncated and info):
118
+ return
119
+ top = ", ".join(f"{t['dir']} ({t['files']})" for t in info["top"][:3])
120
+ print(c(f" ! file cap reached: {info['seen']} candidate files, tracking the first {info['cap']} (largest: {top})", AMBER))
121
+ print(c(" raise max_files, or skip bulky folders: mapwright settings ignore '[\"path/\"]'", AMBER))
122
+
123
+
124
+ def _ignore_suggestions(p, apply: bool):
125
+ from . import ignore as I
126
+ st = config.settings()
127
+ sug = I.suggest_ignores(I.survey(p.root, I.Matcher(p.root, st["ignore"], st["respect_gitignore"])))
128
+ sug = [x for x in sug if x["pattern"] not in st["ignore"]]
129
+ if not sug:
130
+ return
131
+ print(c(" ! bulky generated/data folders are being scanned:", AMBER))
132
+ for x in sug[:8]:
133
+ print(f" {x['pattern']:<32} {x['reason']}")
134
+ pats = st["ignore"] + [x["pattern"] for x in sug]
135
+ if apply:
136
+ config.save_settings({"ignore": pats})
137
+ p.refresh()
138
+ print(f" {c('✓', GREEN)} added {len(sug)} pattern(s) to the ignore setting · now {len(p.cache)} files tracked")
139
+ else:
140
+ print(f" skip them: {c('mapwright settings ignore ' + shlex.quote(json.dumps(pats)), BLUE)} (or re-run init with --apply-ignore)")
141
+
142
+
143
+ def cmd_init(a):
144
+ local = _setup_local_home(a)
145
+ p = project(a)
146
+ if local:
147
+ print(f" {c('✓', GREEN)} project-local home {c(local, DIM)} (found automatically from this project)")
148
+ print(f"{c('◆', BLUE)} tracking {c(p.name, BOLD)} {c(p.root, DIM)}")
149
+ print(f" {len(p.cache)} files · {len(p.model['modules'])} modules · {len(p.model['functions'])} functions · baseline recorded as step 0")
150
+ _truncation_warning(p)
151
+ _ignore_suggestions(p, getattr(a, "apply_ignore", False))
152
+ for t in a.connect or []:
153
+ files = connect.install(t, a.scope, p.root, home=str(local or config.local_home(p.root) or "") or None)
154
+ print(f" {c('✓', GREEN)} connected {connect.TARGETS[t]['title']}: {', '.join(files)}")
155
+ if a.agents_md:
156
+ print(f" {c('✓', GREEN)} wrote {connect.write_agents_md(p.root, a.agents_md)}")
157
+ print(f" next: {c('mapwright open', BLUE)} to see the map · {c('mapwright connect --list', BLUE)} to connect an agent")
158
+
159
+
160
+ def cmd_up(a):
161
+ st = daemon_state()
162
+ if st == "ours":
163
+ print(f"{c('●', GREEN)} already running on {config.base_url()}")
164
+ return
165
+ if st == "other":
166
+ print(c(f"✖ {_other_daemon_msg()}", RED))
167
+ sys.exit(1)
168
+ if a.detach:
169
+ log = open(config.home() / "daemon.log", "a")
170
+ args = [sys.executable, "-m", "mapwright", "up"] + (["--no-watch"] if a.no_watch else [])
171
+ subprocess.Popen(args, stdout=log, stderr=log, stdin=subprocess.DEVNULL, start_new_session=True, env=_daemon_env())
172
+ for _ in range(50):
173
+ time.sleep(0.1)
174
+ if alive():
175
+ print(f"{c('●', GREEN)} started on {config.base_url()} open the map: {c('mapwright open', BLUE)}")
176
+ return
177
+ print(c(f"✖ did not start; see {config.home() / 'daemon.log'}", RED))
178
+ sys.exit(1)
179
+ from .server import Daemon
180
+ os.environ["MAPWRIGHT_HOME"] = str(config.home()) # pin: the daemon serves one home whatever its cwd
181
+ try:
182
+ d = Daemon(watch=not a.no_watch)
183
+ except OSError as e:
184
+ print(c(f"✖ cannot listen on {config.base_url()}: {e.strerror or e}. Set MAPWRIGHT_PORT to use another port.", RED))
185
+ sys.exit(1)
186
+ print(f"{c('◆', BLUE)} mapwright {__version__} on {config.base_url()} {c('(Ctrl-C to stop)', DIM)}")
187
+ try:
188
+ d.serve_forever()
189
+ except KeyboardInterrupt:
190
+ pass
191
+ finally:
192
+ d.stopping.set()
193
+ d.httpd.server_close()
194
+
195
+
196
+ def cmd_down(a):
197
+ if not alive():
198
+ print(c("not running", DIM))
199
+ return
200
+ api("POST", "/v1/shutdown", {})
201
+ print(f"{c('●', GREEN)} stopped")
202
+
203
+
204
+ def cmd_open(a):
205
+ p = project(a)
206
+ st = daemon_state()
207
+ if st == "other":
208
+ print(c(f"✖ {_other_daemon_msg()}", RED), file=sys.stderr)
209
+ sys.exit(1)
210
+ if st == "none":
211
+ subprocess.run([sys.executable, "-m", "mapwright", "up", "-d"], stdout=subprocess.DEVNULL, check=False, env=_daemon_env())
212
+ if a.web:
213
+ site = (a.site or (config.settings()["web_origins"] or [""])[0]).rstrip("/")
214
+ if not site:
215
+ sys.exit("no hosted site configured: mapwright open --web --site https://... (or set web_origins)")
216
+ if site not in config.settings()["web_origins"]:
217
+ config.save_settings({"web_origins": [*config.settings()["web_origins"], site]}) # the daemon must allow this origin
218
+ url = f"{site}/app/#a={config.base_url()}&p={p.key}&t={config.token()}"
219
+ else:
220
+ url = f"{config.base_url()}/#p={p.key}&t={config.token()}"
221
+ if a.json:
222
+ print(json.dumps({"url": url, "key": p.key, "root": p.root}))
223
+ return
224
+ print(url)
225
+ print(c("the link carries your local token; don't share it", DIM))
226
+ if not a.print:
227
+ import webbrowser
228
+ webbrowser.open(url)
229
+
230
+
231
+ def cmd_status(a):
232
+ p = project(a)
233
+ st = p.state()
234
+ if a.json:
235
+ print(json.dumps({k: st[k] for k in ("key", "name", "root", "counts", "layers")} | {
236
+ "steps": len(st["steps"]), "pending": len(st["pending"]), "open_todos": sum(t["status"] == "open" for t in st["todos"]),
237
+ "problems": len(st["problems"]), "daemon": alive()}))
238
+ return
239
+ print(f"{c('◆', BLUE)} {c(st['name'], BOLD)} · step {st['steps'][-1]['n'] if st['steps'] else 0} · "
240
+ f"{len(st['pending'])} file changes pending · daemon {'on' if alive() else 'off'}")
241
+ k = st["counts"]
242
+ print(f" {k['files']} files · {k['modules']} modules · {k['functions']} functions · {k['classes']} classes · {k['tables']} tables · "
243
+ f"{k['routes']} routes · {k['concepts']} mechanisms · {k['infra']} infra nodes")
244
+ for s in st["steps"][-5:]:
245
+ print(f" {c(str(s['n']).rjust(3), DIM)} {s['title'][:70]} {c('+%d/-%d' % (s['summary']['added'], s['summary']['removed']), DIM)}"
246
+ + (c(f" ⚠ {s['title_check']}", AMBER) if s.get("title_check", "ok") != "ok" else ""))
247
+ todos = [t for t in st["todos"] if t["status"] == "open"]
248
+ if todos:
249
+ print(" todos: " + " · ".join(f"{t['id']} {t['text'][:40]}" for t in todos[:5]))
250
+ if st["problems"]:
251
+ print(c(f" {len(st['problems'])} unverified item(s): mapwright problems", AMBER))
252
+
253
+
254
+ def cmd_brief(a):
255
+ p = project(a)
256
+ print(brief.project_brief(p, a.budget or config.settings()["brief_budget"], a.focus))
257
+
258
+
259
+ def cmd_find(a):
260
+ p = project(a)
261
+ for r in A.find_symbols(p.model, a.query, 25):
262
+ print(f"{r['id']} {c(r['kind'], DIM)} {r['file']}:{r['line'] or ''}")
263
+
264
+
265
+ def cmd_symbol(a):
266
+ print(brief.symbol_card(project(a), a.name))
267
+
268
+
269
+ def cmd_step(a):
270
+ data = project(a).step(a.title, a.intent or "", source=a.source)
271
+ print(brief.step_receipt(data))
272
+
273
+
274
+ def cmd_steps(a):
275
+ p = project(a)
276
+ for s in p.steps():
277
+ sm = s["summary"]
278
+ delta = "; ".join(f"{k} " + ", ".join(f"{n} {st}" for st, n in v.items()) for k, v in sm["delta"].items())
279
+ print(f"{c(str(s['n']).rjust(3), BLUE)} {time.strftime('%H:%M', time.localtime(s['ts']))} {c(s['source'][:5], DIM)} "
280
+ f"{s['title'][:60]} {c('%d files +%d/-%d' % (sm['files'], sm['added'], sm['removed']), DIM)} {delta}")
281
+
282
+
283
+ def cmd_changes(a):
284
+ p = project(a)
285
+ if a.step is None:
286
+ changes, label = p.pending(), "since the last step"
287
+ frm, to = (str(p.steps()[-1]["n"]) if p.steps() else "live"), "live"
288
+ else:
289
+ data = p.load_step(a.step)
290
+ if not data:
291
+ sys.exit(f"no step {a.step}")
292
+ changes, label, frm, to = data["changes"], f"in step {a.step}", str(max(0, a.step - 1)), str(a.step)
293
+ print(c(f"{len(changes)} file change(s) {label}", DIM))
294
+ for ch in changes:
295
+ pm = f"+{ch.get('added', 0)} -{ch.get('removed', 0)}" if "added" in ch else ch.get("note", "")
296
+ col = {"added": GREEN, "deleted": RED}.get(ch["kind"], BLUE)
297
+ print(f" {c(ch['kind'][:3].upper(), col)} {ch['path']} {c(pm, DIM)}")
298
+ if a.diff and "added" in ch:
299
+ import difflib
300
+ def idx(s):
301
+ return p.index if s == "live" else p.step_files(int(s))
302
+ ta, tb = p.blob(idx(frm).get(ch["path"])), p.blob(idx(to).get(ch["path"]))
303
+ from .redact import redact
304
+ for ln in difflib.unified_diff((ta or "").splitlines(), (tb or "").splitlines(), lineterm="", n=2):
305
+ if ln.startswith(("+++", "---")):
306
+ continue
307
+ print(" " + c(redact(ln), GREEN if ln.startswith("+") else RED if ln.startswith("-") else DIM))
308
+
309
+
310
+ def cmd_todo(a):
311
+ p = project(a)
312
+ if a.action == "add":
313
+ print("added", p.todo_add(" ".join(a.rest), by=a.by)["tid"])
314
+ elif a.action == "done":
315
+ if not a.rest:
316
+ sys.exit("usage: mapwright todo done ID [--evidence SYMBOL_OR_FILE]")
317
+ t = p.todo_done(a.rest[0], a.evidence or "")
318
+ print(f"{t['id']} done · " + (c("verified", GREEN) if t.get("verified") else c("unverified", AMBER)) + f": {t.get('reason')}")
319
+ elif a.action == "drop":
320
+ p.todo_drop(a.rest[0])
321
+ print("dropped")
322
+ else:
323
+ for t in p.verify()["todos"]:
324
+ mark = {"open": "○", "done": "●" if t.get("verified") else "◐", "dropped": "×"}[t["status"]]
325
+ print(f"{mark} {t['id']} {t['text']}" + (c(f" ({t.get('reason')})", DIM) if t["status"] == "done" else ""))
326
+
327
+
328
+ def cmd_claim(a):
329
+ cl = project(a).claim(a.concept, a.symbol, a.note or "")
330
+ col = GREEN if cl["status"] == "verified" else AMBER
331
+ print(f"{cl['concept']} → {cl['symbol']}: {c(cl['status'], col)} ({cl.get('reason')})")
332
+
333
+
334
+ def cmd_note(a):
335
+ print("noted", project(a).note(a.symbol, " ".join(a.role))["status"])
336
+
337
+
338
+ def cmd_link(a):
339
+ print("linked", project(a).link(a.source, a.target, a.label or "")["status"])
340
+
341
+
342
+ def cmd_catalog(a):
343
+ print(brief.catalog_text())
344
+
345
+
346
+ def cmd_problems(a):
347
+ v = project(a).verify()
348
+ if not v["problems"]:
349
+ print(f"{c('✓', GREEN)} everything the agent claimed checks out")
350
+ for x in v["problems"]:
351
+ print(f"{c('⚠', AMBER)} [{x['kind']}] {x['text']}")
352
+
353
+
354
+ def cmd_diagram(a):
355
+ from .server import Daemon
356
+ p = project(a)
357
+ out = Daemon.diagram(None, p, a.kind, {"step": str(a.step) if a.step is not None else "live", "focus": a.focus}) # type: ignore[arg-type]
358
+ print(out["mermaid"])
359
+
360
+
361
+ def cmd_flow(a):
362
+ from .server import Daemon
363
+ p = project(a)
364
+ hit = A.resolve(p.model, a.symbol)
365
+ if not hit or hit[0] != "functions":
366
+ sys.exit(f"no function named {a.symbol}; try `mapwright find {a.symbol}`")
367
+ print(Daemon.flow(None, p, hit[1], "live")["mermaid"]) # type: ignore[arg-type]
368
+
369
+
370
+ def cmd_connect(a):
371
+ root = os.path.realpath(A.find_root(os.path.abspath(a.path or os.getcwd())))
372
+ if a.list or not a.target:
373
+ for t in connect.status(root):
374
+ if t.get("manual"):
375
+ print(f" {c('·', DIM)} {t['title']:<30} {c('manual: mapwright connect --print ' + t['id'], DIM)}")
376
+ continue
377
+ sc = " ".join((c(f"{s}✓", GREEN) if v["connected"] else c(s, DIM)) for s, v in t["scopes"].items())
378
+ print(f" {c('●', GREEN) if t['installed'] else c('○', DIM)} {t['id']:<15} {t['title']:<30} {sc}")
379
+ print(c("\n mapwright connect <id> [--scope project|user] · --print <id> shows the config to paste", DIM))
380
+ return
381
+ if a.print:
382
+ print(connect.snippet(a.target, root, home=str(config.local_home(root) or "") or None))
383
+ if a.target in connect.MANUAL:
384
+ print(c("\n" + connect.MANUAL[a.target][1], DIM))
385
+ return
386
+ files = connect.install(a.target, a.scope, root, home=str(config.local_home(root) or "") or None)
387
+ print(f"{c('✓', GREEN)} {connect.TARGETS[a.target]['title']} connected ({a.scope}): " + ", ".join(files))
388
+ print(c(" restart the agent (or start a new session) so it loads the MCP server", DIM))
389
+
390
+
391
+ def cmd_disconnect(a):
392
+ root = os.path.realpath(A.find_root(os.path.abspath(a.path or os.getcwd())))
393
+ files = connect.uninstall(a.target, a.scope, root)
394
+ print(f"{c('✓', GREEN)} removed from: " + ", ".join(files) if files else c("nothing to remove", DIM))
395
+
396
+
397
+ def cmd_agents_md(a):
398
+ p = project(a)
399
+ print(f"{c('✓', GREEN)} wrote {connect.write_agents_md(p.root, a.file)}")
400
+
401
+
402
+ def cmd_watch(a):
403
+ p = project(a)
404
+ print(f"{c('◆', BLUE)} watching {p.root} {c('(steps close after a quiet period; Ctrl-C to stop)', DIM)}")
405
+ try:
406
+ while True:
407
+ changed = p.refresh()
408
+ if changed:
409
+ print(f" {time.strftime('%H:%M:%S')} {len(changed)} changed: " + ", ".join(changed[:5]))
410
+ data = p.maybe_auto_step()
411
+ if data:
412
+ print(f" {c('step', BLUE)} {brief.step_receipt(data)}")
413
+ time.sleep(max(0.5, config.settings()["watch_interval"]))
414
+ except KeyboardInterrupt:
415
+ pass
416
+
417
+
418
+ def cmd_export(a):
419
+ from .export import export
420
+ out = export(project(a), a.out)
421
+ print(f"{c('✓', GREEN)} wrote {out}")
422
+
423
+
424
+ def cmd_mcp(a):
425
+ from . import mcp
426
+ sys.exit(mcp.serve(a.root))
427
+
428
+
429
+ def cmd_hook(a):
430
+ from . import hooks
431
+ sys.exit(hooks.main([a.agent]))
432
+
433
+
434
+ def cmd_settings(a):
435
+ if a.key:
436
+ val = a.value
437
+ try:
438
+ val = json.loads(val)
439
+ except (ValueError, TypeError):
440
+ pass
441
+ try:
442
+ config.save_settings({a.key: val})
443
+ except ValueError as e:
444
+ sys.exit(str(e))
445
+ for k, v in config.settings().items():
446
+ print(f" {k:<16} {json.dumps(v)}" + (c(" (default)", DIM) if v == config.DEFAULTS[k] else ""))
447
+
448
+
449
+ def cmd_doctor(a):
450
+ ok = True
451
+ print(f"{c('◆', BLUE)} mapwright {__version__} · python {sys.version.split()[0]} · home {config.home()}")
452
+ print(f" {'✓' if alive() else '!'} daemon " + ("running on " + config.base_url() if alive() else "not running (only the UI needs it): mapwright up -d"))
453
+ p = project(a)
454
+ print(f" ✓ project {p.name}: {len(p.cache)} files tracked" + (c(" (file cap reached)", AMBER) if p.truncated else ""))
455
+ _truncation_warning(p)
456
+ errs = [r for r, e in p.cache.items() if (e.get("part") or {}).get("error")]
457
+ if errs:
458
+ print(c(f" ! {len(errs)} file(s) do not parse: {', '.join(errs[:3])}", AMBER))
459
+ conn = [t["title"] for t in connect.status(p.root) if any(s["connected"] for s in t["scopes"].values())]
460
+ print(f" {'✓' if conn else '!'} agents: " + (", ".join(conn) if conn else "none connected; see `mapwright connect --list`"))
461
+ ok = ok and bool(conn)
462
+ log = config.home() / "hook-errors.log"
463
+ if log.exists() and log.stat().st_size:
464
+ print(c(f" ! hook errors logged in {log}", AMBER))
465
+ sys.exit(0)
466
+
467
+
468
+ GUIDE = """Mapwright quick guide
469
+
470
+ Start mapwright init track this project (baseline = step 0)
471
+ mapwright connect --list see agents you can connect
472
+ mapwright connect claude-code MCP server + hooks for this project (--scope user for all)
473
+ mapwright open the map in your browser (starts the daemon)
474
+ While working mapwright status steps, pending changes, todos
475
+ mapwright step "Add refunds" close a step yourself
476
+ mapwright changes [--step N] --diff what changed
477
+ mapwright problems claims and todos that do not check out
478
+ For agents mapwright brief the map as compact text (~600 tokens)
479
+ mapwright find NAME · symbol NAME locate code, callers, callees
480
+ mapwright todo add|done|list plan items, verified on done
481
+ mapwright claim CONCEPT SYMBOL tag a mechanism (see: mapwright catalog)
482
+ Diagrams mapwright diagram architecture|files|classes|data|cloud|processes|calls|concepts
483
+ mapwright flow FUNCTION flowchart of one function (Mermaid)
484
+ mapwright export -o docs/map MAP.md + every diagram, ready to commit
485
+ Stop / remove mapwright down stop the daemon
486
+ mapwright disconnect claude-code remove the MCP entry and hooks
487
+ rm -rf ~/.mapwright delete all tracked history
488
+ """
489
+
490
+
491
+ def main(argv=None) -> int:
492
+ ap = argparse.ArgumentParser(prog="mapwright", description="A live map of what your coding agent is building.")
493
+ ap.add_argument("--version", action="version", version=f"mapwright {__version__}")
494
+ sp = ap.add_subparsers(dest="cmd")
495
+
496
+ def add(name, fn, help_, path=True):
497
+ p_ = sp.add_parser(name, help=help_, description=help_)
498
+ p_.set_defaults(fn=fn)
499
+ if path:
500
+ p_.add_argument("--path", default=None, help="project directory (default: current)")
501
+ return p_
502
+
503
+ x = add("init", cmd_init, "Track this project and record the baseline.")
504
+ x.add_argument("--connect", action="append", choices=list(connect.TARGETS), help="also connect an agent (repeatable)")
505
+ x.add_argument("--scope", default="project", choices=["project", "user"])
506
+ x.add_argument("--apply-ignore", action="store_true", help="add the suggested ignore patterns to the settings")
507
+ x.add_argument("--agents-md", nargs="?", const="AGENTS.md", default=None, help="add usage notes to AGENTS.md (or a file you name)")
508
+ x.add_argument("--local", action="store_true", help="keep history in <project>/.mapwright instead of ~/.mapwright")
509
+ x.add_argument("--home", metavar="DIR", default=None, help="keep history in DIR (relative to the project root)")
510
+ x = add("up", cmd_up, "Start the daemon (UI + background tracking).", path=False)
511
+ x.add_argument("-d", "--detach", action="store_true")
512
+ x.add_argument("--no-watch", action="store_true")
513
+ add("down", cmd_down, "Stop the daemon.", path=False)
514
+ x = add("open", cmd_open, "Open the map in the browser.")
515
+ x.add_argument("--print", action="store_true", help="print the URL only")
516
+ x.add_argument("--json", action="store_true")
517
+ x.add_argument("--web", action="store_true", help="open the hosted website, connected to your local daemon")
518
+ x.add_argument("--site", help="hosted site origin for --web (default: first of the web_origins setting)")
519
+ x = add("status", cmd_status, "Steps, pending changes, todos.")
520
+ x.add_argument("--json", action="store_true")
521
+ x = add("brief", cmd_brief, "The project map as compact text for an agent.")
522
+ x.add_argument("--budget", type=int)
523
+ x.add_argument("--focus")
524
+ x = add("find", cmd_find, "Locate symbols by name.")
525
+ x.add_argument("query")
526
+ x = add("symbol", cmd_symbol, "One symbol: callers, callees, tables, history.")
527
+ x.add_argument("name")
528
+ x = add("step", cmd_step, "Close a step (the changes are computed).")
529
+ x.add_argument("title")
530
+ x.add_argument("--intent")
531
+ x.add_argument("--source", default="user", choices=["user", "agent"])
532
+ add("steps", cmd_steps, "List steps.")
533
+ x = add("changes", cmd_changes, "File changes since the last step, or in a step.")
534
+ x.add_argument("--step", type=int)
535
+ x.add_argument("--diff", action="store_true")
536
+ x = add("todo", cmd_todo, "Plan items: add TEXT | done ID | drop ID | list.")
537
+ x.add_argument("action", choices=["add", "done", "drop", "list"])
538
+ x.add_argument("rest", nargs="*")
539
+ x.add_argument("--evidence")
540
+ x.add_argument("--by", default="user")
541
+ x = add("claim", cmd_claim, "Tag a symbol with a mechanism from the catalog.")
542
+ x.add_argument("concept")
543
+ x.add_argument("symbol")
544
+ x.add_argument("--note")
545
+ x = add("note", cmd_note, "One-line role of a module or symbol.")
546
+ x.add_argument("symbol")
547
+ x.add_argument("role", nargs="+")
548
+ x = add("link", cmd_link, "A relation the code does not show (queue, event, service call).")
549
+ x.add_argument("source")
550
+ x.add_argument("target")
551
+ x.add_argument("--label")
552
+ add("catalog", cmd_catalog, "Concept ids for claims.", path=False)
553
+ add("problems", cmd_problems, "Claims, notes, links and todos that do not check out.")
554
+ x = add("diagram", cmd_diagram, "Print a diagram as Mermaid.")
555
+ x.add_argument("kind", choices=list(render.KINDS))
556
+ x.add_argument("--step", type=int)
557
+ x.add_argument("--focus")
558
+ x = add("flow", cmd_flow, "Flowchart of one function (Mermaid).")
559
+ x.add_argument("symbol")
560
+ x = add("connect", cmd_connect, "Connect an agent (writes its MCP config; hooks for Claude Code).")
561
+ x.add_argument("target", nargs="?", choices=list(connect.TARGETS) + list(connect.MANUAL))
562
+ x.add_argument("--scope", default="project", choices=["project", "user"])
563
+ x.add_argument("--list", action="store_true")
564
+ x.add_argument("--print", action="store_true", help="print the config to paste instead of writing it")
565
+ x = add("disconnect", cmd_disconnect, "Remove Mapwright from an agent's config.")
566
+ x.add_argument("target", choices=list(connect.TARGETS))
567
+ x.add_argument("--scope", default="project", choices=["project", "user"])
568
+ x = add("agents-md", cmd_agents_md, "Add short usage notes for agents to AGENTS.md / CLAUDE.md.")
569
+ x.add_argument("--file", default="AGENTS.md", choices=["AGENTS.md", "CLAUDE.md", ".cursorrules", "GEMINI.md"])
570
+ add("watch", cmd_watch, "Track from the files alone (any agent, no integration).")
571
+ x = add("export", cmd_export, "Write MAP.md and every diagram to a folder.")
572
+ x.add_argument("-o", "--out", default="mapwright-export")
573
+ x = add("mcp", cmd_mcp, "Run the MCP server on stdio (agents start this).", path=False)
574
+ x.add_argument("--root")
575
+ x = add("hook", cmd_hook, "Hook entry point (agents call this).", path=False)
576
+ x.add_argument("agent", nargs="?", default="claude-code")
577
+ x = add("settings", cmd_settings, "Show or change a setting: settings KEY VALUE.", path=False)
578
+ x.add_argument("key", nargs="?")
579
+ x.add_argument("value", nargs="?")
580
+ add("doctor", cmd_doctor, "Check the setup.")
581
+ add("guide", lambda a: print(GUIDE), "Quick guide.", path=False)
582
+ a = ap.parse_args(argv)
583
+ if not getattr(a, "fn", None):
584
+ print(GUIDE)
585
+ return 0
586
+ config.set_start(getattr(a, "path", None) or getattr(a, "root", None))
587
+ try:
588
+ a.fn(a)
589
+ except ValueError as e:
590
+ print(c(f"✖ {e}", RED), file=sys.stderr)
591
+ return 1
592
+ return 0
593
+
594
+
595
+ if __name__ == "__main__":
596
+ raise SystemExit(main())