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/__init__.py +3 -0
- mapwright/__main__.py +3 -0
- mapwright/analyze.py +809 -0
- mapwright/brief.py +208 -0
- mapwright/cli.py +596 -0
- mapwright/concepts.py +190 -0
- mapwright/config.py +204 -0
- mapwright/connect.py +337 -0
- mapwright/export.py +42 -0
- mapwright/firestore.py +168 -0
- mapwright/flow.py +238 -0
- mapwright/hooks.py +111 -0
- mapwright/ignore.py +248 -0
- mapwright/infra.py +253 -0
- mapwright/mcp.py +153 -0
- mapwright/noise.py +80 -0
- mapwright/redact.py +39 -0
- mapwright/render.py +428 -0
- mapwright/routes_js.py +282 -0
- mapwright/server.py +388 -0
- mapwright/titles.py +111 -0
- mapwright/track.py +715 -0
- mapwright/ui/app.css +277 -0
- mapwright/ui/app.js +1025 -0
- mapwright/ui/icons.svg +73 -0
- mapwright/ui/index.html +35 -0
- mapwright/ui/mark.svg +1 -0
- mapwright/ui/vendor/mermaid.LICENSE +21 -0
- mapwright/ui/vendor/mermaid.min.js +2029 -0
- mapwright_agent-0.2.0.dist-info/METADATA +179 -0
- mapwright_agent-0.2.0.dist-info/RECORD +34 -0
- mapwright_agent-0.2.0.dist-info/WHEEL +4 -0
- mapwright_agent-0.2.0.dist-info/entry_points.txt +3 -0
- mapwright_agent-0.2.0.dist-info/licenses/LICENSE +21 -0
mapwright/concepts.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""The concept catalog: mechanisms a codebase uses, each with an icon, a one-line meaning and the
|
|
2
|
+
signals that give it away in code.
|
|
3
|
+
|
|
4
|
+
This is the "component library" agents use. An agent never draws a diagram or an icon: it names a
|
|
5
|
+
concept id from this catalog and the symbol that implements it (`claim`). Mapwright then checks the
|
|
6
|
+
claim against the code with the same signals it uses for detection, so a claim without evidence is
|
|
7
|
+
shown as unverified instead of being taken at its word.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
# id: (title, icon, group, meaning, import prefixes, code patterns)
|
|
15
|
+
CATALOG: dict[str, tuple[str, str, str, str, tuple[str, ...], tuple[str, ...]]] = {
|
|
16
|
+
"http-api": ("HTTP API", "globe", "interface", "Serves requests over HTTP routes.",
|
|
17
|
+
("flask", "fastapi", "django.urls", "starlette", "aiohttp.web", "express", "koa", "hono", "@nestjs", "next/server", "bottle", "tornado"),
|
|
18
|
+
(r"@\w+\.(get|post|put|patch|delete|route)\(", r"\b(app|router)\.(get|post|put|patch|delete)\(\s*['\"`]/", r"export\s+(async\s+)?function\s+(GET|POST)\b")),
|
|
19
|
+
"graphql": ("GraphQL", "graph", "interface", "Exposes a typed query API.",
|
|
20
|
+
("graphene", "strawberry", "ariadne", "graphql", "@apollo", "apollo-server", "type-graphql"), (r"\btype\s+Query\s*\{", r"gql`")),
|
|
21
|
+
"websockets": ("WebSockets", "bolt", "interface", "Keeps live two-way connections with clients.",
|
|
22
|
+
("websockets", "socket.io", "ws", "socketio", "channels"), (r"@\w+\.websocket\(", r"new\s+WebSocket\(", r"\.on\(\s*['\"]connection['\"]")),
|
|
23
|
+
"cli": ("Command line", "terminal", "interface", "Is driven from a terminal.",
|
|
24
|
+
("argparse", "click", "typer", "commander", "yargs", "fire", "docopt"), (r"add_subparsers\(", r"@click\.command", r"\.command\(\s*['\"]")),
|
|
25
|
+
"auth": ("Authentication", "key", "security", "Checks who is calling.",
|
|
26
|
+
("jwt", "jose", "authlib", "passport", "next-auth", "flask_login", "django.contrib.auth", "oauthlib", "fastapi.security", "jsonwebtoken"),
|
|
27
|
+
(r"\b(login|logout|authenticate|verify_token|get_current_user|require_auth|is_authenticated)\b", r"Authorization['\"]?\s*[:\]]", r"\bBearer\b")),
|
|
28
|
+
"password-hashing": ("Password hashing", "lock", "security", "Stores passwords as slow salted hashes.",
|
|
29
|
+
("bcrypt", "argon2", "passlib", "scrypt"), (r"\bpbkdf2_hmac\(", r"\b(hash_password|check_password|verify_password)\b", r"bcrypt\.(hash|compare|gensalt)")),
|
|
30
|
+
"encryption": ("Encryption", "shield", "security", "Encrypts data with a key.",
|
|
31
|
+
("cryptography", "nacl", "Crypto", "crypto-js"), (r"\bFernet\(", r"createCipheriv\(", r"\bAES\b", r"\bencrypt\(")),
|
|
32
|
+
"input-validation": ("Input validation", "check", "security", "Checks the shape of incoming data.",
|
|
33
|
+
("pydantic", "marshmallow", "cerberus", "voluptuous", "zod", "joi", "yup", "class-validator", "ajv"),
|
|
34
|
+
(r"class\s+\w+\(BaseModel\)", r"\bz\.object\(", r"Joi\.object\(")),
|
|
35
|
+
"rate-limiting": ("Rate limiting", "gauge", "security", "Caps how often a caller can do something.",
|
|
36
|
+
("slowapi", "ratelimit", "flask_limiter", "express-rate-limit", "limits", "rate-limiter-flexible"),
|
|
37
|
+
(r"\b(rate_?limit|token_?bucket|leaky_?bucket|throttle)\w*", r"\bRateLimit\w*")),
|
|
38
|
+
"caching": ("Caching", "layers", "performance", "Keeps results to avoid recomputing or refetching them.",
|
|
39
|
+
("cachetools", "diskcache", "redis", "memcache", "pymemcache", "aiocache", "node-cache", "lru-cache", "ioredis"),
|
|
40
|
+
(r"@(functools\.)?(lru_cache|cache)\b", r"\bcache\.(get|set)\(", r"\b(setex|expire)\(", r"\bttl\b")),
|
|
41
|
+
"retry-backoff": ("Retry with backoff", "rotate", "resilience", "Tries a failing call again, waiting longer each time.",
|
|
42
|
+
("tenacity", "backoff", "retrying", "p-retry", "async-retry"),
|
|
43
|
+
(r"@retry\b", r"\bfor\s+\w+\s+in\s+range\([^)]*\):[\s\S]{0,300}?\bsleep\(", r"\b(max_retries|backoff|retry_count)\b")),
|
|
44
|
+
"circuit-breaker": ("Circuit breaker", "zap-off", "resilience", "Stops calling a dependency that keeps failing.",
|
|
45
|
+
("pybreaker", "circuitbreaker", "opossum"), (r"\bcircuit_?breaker\b", r"\bCircuitBreaker\b")),
|
|
46
|
+
"queue-jobs": ("Background jobs", "inbox", "async", "Hands work to a queue processed outside the request.",
|
|
47
|
+
("celery", "rq", "dramatiq", "huey", "arq", "bull", "bullmq", "kafka", "aiokafka", "confluent_kafka", "pika", "aio_pika", "kombu", "sqs"),
|
|
48
|
+
(r"\.delay\(", r"\.enqueue\(", r"\.apply_async\(", r"@\w+\.task\b", r"new\s+Queue\(", r"send_message\(")),
|
|
49
|
+
"events": ("Events & pub/sub", "radio", "async", "Publishes events that other parts react to.",
|
|
50
|
+
("blinker", "pyee", "eventemitter3", "events", "redis.client"), (r"\.(emit|publish|subscribe)\(", r"\bEventEmitter\b", r"\bon_event\b", r"\bwebhook")),
|
|
51
|
+
"scheduling": ("Scheduled tasks", "clock", "async", "Runs work on a timer or calendar.",
|
|
52
|
+
("apscheduler", "schedule", "croniter", "node-cron", "agenda", "celery.schedules"),
|
|
53
|
+
(r"\bcrontab\(", r"schedule\.every\(", r"@(scheduled|periodic_task)\b", r"\bbeat_schedule\b", r"cron\.schedule\(")),
|
|
54
|
+
"concurrency": ("Concurrency", "split", "async", "Does several things at once.",
|
|
55
|
+
("threading", "multiprocessing", "concurrent.futures", "asyncio", "worker_threads", "trio", "anyio", "gevent"),
|
|
56
|
+
(r"asyncio\.gather\(", r"ThreadPoolExecutor\(", r"Promise\.all\(", r"\bThread\(", r"create_task\(")),
|
|
57
|
+
"orm": ("ORM / data mapper", "table", "data", "Maps tables to classes.",
|
|
58
|
+
("sqlalchemy", "django.db", "peewee", "tortoise", "sqlmodel", "pony", "@prisma/client", "prisma", "typeorm", "sequelize", "mongoose", "drizzle-orm", "mikro-orm", "objection"),
|
|
59
|
+
(r"class\s+\w+\((Base|db\.Model|models\.Model|SQLModel)\)", r"\bprisma\.\w+\.(find|create|update)", r"@Entity\(")),
|
|
60
|
+
"sql": ("Raw SQL", "database", "data", "Talks to a database in SQL.",
|
|
61
|
+
("sqlite3", "psycopg", "psycopg2", "asyncpg", "pymysql", "mysql", "pg", "better-sqlite3", "mysql2", "knex"),
|
|
62
|
+
(r"""['"`]\s*(?i:select)\s+[\w*,\s.()]+\s+(?i:from)\s+\w+""", r"""['"`]\s*(?i:insert\s+into|update\s+\w+\s+set|delete\s+from)\s""", r"(?i)\bcreate\s+table\b")),
|
|
63
|
+
"migrations": ("Schema migrations", "git-merge", "data", "Changes the database schema in tracked steps.",
|
|
64
|
+
("alembic", "yoyo", "flyway", "knex", "umzug", "django.db.migrations"), (r"\bop\.(create_table|add_column)\(", r"class\s+Migration\b", r"exports\.up\s*=")),
|
|
65
|
+
"transactions": ("Transactions", "repeat", "data", "Groups writes so they all happen or none do.",
|
|
66
|
+
(), (r"\.begin\(\)", r"\.transaction\(", r"\.rollback\(", r"(?i)\bBEGIN\s+TRANSACTION\b", r"\batomic\(")),
|
|
67
|
+
"search": ("Search index", "search", "data", "Indexes data for fast search.",
|
|
68
|
+
("elasticsearch", "opensearchpy", "meilisearch", "typesense", "whoosh", "algoliasearch", "@elastic/elasticsearch", "lunr"),
|
|
69
|
+
(r"\bfull[_ ]?text\b", r"\bto_tsvector\(", r"\bindex\.search\(")),
|
|
70
|
+
"file-storage": ("File & object storage", "box", "data", "Stores files or blobs.",
|
|
71
|
+
("boto3", "botocore", "google.cloud.storage", "azure.storage", "minio", "@aws-sdk/client-s3", "multer", "aws-sdk"),
|
|
72
|
+
(r"\bupload_file\(", r"\bput_object\(", r"\bS3Client\b", r"\bupload\(")),
|
|
73
|
+
"config-env": ("Configuration from environment", "sliders", "operations", "Reads settings from the environment.",
|
|
74
|
+
("dotenv", "python-dotenv", "decouple", "pydantic_settings", "environs", "convict"),
|
|
75
|
+
(r"os\.environ\b", r"os\.getenv\(", r"process\.env\.", r"\bBaseSettings\b")),
|
|
76
|
+
"logging": ("Logging & observability", "activity", "operations", "Records what happens for later inspection.",
|
|
77
|
+
("logging", "structlog", "loguru", "opentelemetry", "prometheus_client", "sentry_sdk", "winston", "pino", "@sentry", "datadog"),
|
|
78
|
+
(r"logging\.getLogger\(", r"\blogger\.(info|warning|error|debug)\(", r"\bconsole\.(error|warn)\(")),
|
|
79
|
+
"feature-flags": ("Feature flags", "flag", "operations", "Switches behaviour on and off without a deploy.",
|
|
80
|
+
("launchdarkly", "unleash", "flagsmith", "growthbook", "posthog"), (r"\bfeature_?flag\w*", r"\bis_enabled\(\s*['\"]")),
|
|
81
|
+
"payments": ("Payments", "card", "external", "Takes payments through a provider.",
|
|
82
|
+
("stripe", "paypalrestsdk", "braintree", "adyen", "@stripe"), (r"\bPaymentIntent\b", r"\bcheckout\.Session\b")),
|
|
83
|
+
"email": ("Email", "mail", "external", "Sends email.",
|
|
84
|
+
("smtplib", "sendgrid", "mailgun", "postmark", "nodemailer", "resend", "email.mime"), (r"\bsend_mail\(", r"\bsendMail\(", r"\bSMTP\(")),
|
|
85
|
+
"llm": ("LLM / AI model calls", "sparkles", "external", "Calls a language or ML model.",
|
|
86
|
+
("anthropic", "openai", "langchain", "llama_index", "transformers", "@anthropic-ai", "ai", "cohere", "google.generativeai", "ollama"),
|
|
87
|
+
(r"\bmessages\.create\(", r"\bchat\.completions\.create\(", r"\bgenerateText\(")),
|
|
88
|
+
"testing": ("Automated tests", "beaker", "quality", "Checks behaviour with tests.",
|
|
89
|
+
("pytest", "unittest", "hypothesis", "jest", "vitest", "mocha", "@testing-library", "playwright", "cypress"),
|
|
90
|
+
(r"^\s*def\s+test_\w+\(", r"\b(describe|it|test)\(\s*['\"`]", r"\bassert\b")),
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
# Words that name a mechanism in identifiers. Matched against the claimed symbol's own code with
|
|
94
|
+
# case and underscores removed, so TokenBucketLimiter, token_bucket and tokenBucket all count.
|
|
95
|
+
WORDS: dict[str, tuple[str, ...]] = {
|
|
96
|
+
"http-api": ("route", "endpoint", "requesthandler", "dopost", "doget", "httpserver", "router", "view"),
|
|
97
|
+
"graphql": ("graphql", "resolver"), "websockets": ("websocket", "socketio"), "cli": ("argparse", "subcommand", "argv"),
|
|
98
|
+
"auth": ("authenticat", "authoriz", "login", "jwt", "bearer", "credential"), "password-hashing": ("bcrypt", "argon2", "pbkdf2", "scrypt", "hashpassword"),
|
|
99
|
+
"encryption": ("encrypt", "decrypt", "cipher", "fernet"), "input-validation": ("validat", "sanitiz", "isvalid", "schema"),
|
|
100
|
+
"rate-limiting": ("ratelimit", "tokenbucket", "leakybucket", "throttl", "limiter", "retryafter", "toomanyrequests"),
|
|
101
|
+
"caching": ("cache", "memoiz", "lru"), "retry-backoff": ("retry", "backoff", "maxretries", "attempt"),
|
|
102
|
+
"circuit-breaker": ("circuitbreaker", "halfopen", "tripped"), "queue-jobs": ("enqueue", "queue", "celery", "worker", "job"),
|
|
103
|
+
"events": ("emit", "publish", "subscribe", "eventbus", "listener", "webhook"), "scheduling": ("schedule", "cron", "periodic"),
|
|
104
|
+
"concurrency": ("thread", "asyncio", "gather", "executor", "lock", "concurrent", "multiprocess"),
|
|
105
|
+
"orm": ("session", "declarativebase", "orm", "model"), "sql": ("select", "insert", "execute", "cursor", "sqlite"),
|
|
106
|
+
"migrations": ("migrat", "alembic", "altertable"), "transactions": ("transaction", "commit", "rollback", "atomic"),
|
|
107
|
+
"search": ("search", "fulltext", "invertedindex"), "file-storage": ("upload", "bucket", "putobject", "blob"),
|
|
108
|
+
"config-env": ("environ", "getenv", "dotenv", "settings"), "logging": ("logger", "logging"),
|
|
109
|
+
"feature-flags": ("featureflag", "isenabled"), "payments": ("payment", "charge", "stripe", "invoice"),
|
|
110
|
+
"email": ("smtp", "sendmail", "email"), "llm": ("anthropic", "openai", "completion", "llm"), "testing": ("pytest", "assert", "expect"),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
GROUPS = {"interface": "Interface", "security": "Security", "performance": "Performance", "resilience": "Resilience",
|
|
114
|
+
"async": "Async & jobs", "data": "Data", "operations": "Operations", "external": "External services", "quality": "Quality"}
|
|
115
|
+
|
|
116
|
+
_RX = {cid: [re.compile(p, re.M) for p in spec[5]] for cid, spec in CATALOG.items()}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def catalog() -> list[dict]:
|
|
120
|
+
return [{"id": cid, "title": t, "icon": icon, "group": g, "meaning": m} for cid, (t, icon, g, m, _, _) in CATALOG.items()]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _imports_hit(raw_imports: list[str], prefixes: tuple[str, ...]) -> str | None:
|
|
124
|
+
for imp in raw_imports:
|
|
125
|
+
for p in prefixes:
|
|
126
|
+
if imp == p or imp.startswith(p + ".") or imp.startswith(p + "/"):
|
|
127
|
+
return imp
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def detect_file(rel: str, text: str, part: dict | None) -> dict[str, list[dict]]:
|
|
132
|
+
"""concept id -> evidence in this file: [{line, signal, symbol}]. At most 3 per concept."""
|
|
133
|
+
raw = (part or {}).get("raw_imports", [])
|
|
134
|
+
funcs = (part or {}).get("functions", [])
|
|
135
|
+
out: dict[str, list[dict]] = {}
|
|
136
|
+
|
|
137
|
+
def symbol_at(line: int) -> str | None:
|
|
138
|
+
best = None
|
|
139
|
+
for f in funcs:
|
|
140
|
+
if f["line"] <= line <= f.get("end", f["line"]) and (best is None or f["line"] >= best["line"]):
|
|
141
|
+
best = f
|
|
142
|
+
return best["qual"] if best else None
|
|
143
|
+
|
|
144
|
+
for cid, spec in CATALOG.items():
|
|
145
|
+
ev = []
|
|
146
|
+
imp = _imports_hit(raw, spec[4])
|
|
147
|
+
if imp:
|
|
148
|
+
line = next((i + 1 for i, ln in enumerate(text.splitlines()) if re.search(rf"\b{re.escape(imp.split('/')[0].split('.')[0])}\b", ln)
|
|
149
|
+
and ("import" in ln or "require" in ln)), 1)
|
|
150
|
+
ev.append({"line": line, "signal": f"imports {imp}", "symbol": None})
|
|
151
|
+
for rx in _RX[cid]:
|
|
152
|
+
m = rx.search(text)
|
|
153
|
+
if m:
|
|
154
|
+
line = text.count("\n", 0, m.start()) + 1
|
|
155
|
+
ev.append({"line": line, "signal": "code: " + m.group(0).strip()[:48], "symbol": symbol_at(line)})
|
|
156
|
+
if len(ev) >= 3:
|
|
157
|
+
break
|
|
158
|
+
if cid == "testing" and not re.search(r"(^|/)(tests?|spec|__tests__)/|test_|_test\.|\.(spec|test)\.", rel):
|
|
159
|
+
ev = [e for e in ev if e["signal"].startswith("imports")] # a bare `assert` is not a test suite
|
|
160
|
+
if cid == "concurrency" and imp == "asyncio" and len(ev) == 1:
|
|
161
|
+
continue # importing asyncio alone is not doing things at once
|
|
162
|
+
if ev:
|
|
163
|
+
out[cid] = ev[:3]
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def evidence_in(cid: str, text: str, raw_imports: list[str] | None = None) -> str | None:
|
|
168
|
+
"""Is there a signal for concept `cid` in this piece of code? Returns the signal, or None.
|
|
169
|
+
Used to verify an agent's claim that a symbol implements a concept."""
|
|
170
|
+
spec = CATALOG.get(cid)
|
|
171
|
+
if not spec:
|
|
172
|
+
return None
|
|
173
|
+
for rx in _RX[cid]:
|
|
174
|
+
m = rx.search(text)
|
|
175
|
+
if m:
|
|
176
|
+
return "code: " + m.group(0).strip()[:48]
|
|
177
|
+
squashed = re.sub(r"[^a-z0-9]", "", text.lower())
|
|
178
|
+
for w in WORDS.get(cid, ()):
|
|
179
|
+
if w in squashed:
|
|
180
|
+
return f"names: {w}"
|
|
181
|
+
low = text.lower()
|
|
182
|
+
for p in spec[4]:
|
|
183
|
+
tail = p.split("/")[-1].split(".")[0].lower()
|
|
184
|
+
if len(tail) > 2 and re.search(rf"\b{re.escape(tail)}\b", low):
|
|
185
|
+
return f"uses {tail}"
|
|
186
|
+
if raw_imports:
|
|
187
|
+
imp = _imports_hit(raw_imports, spec[4])
|
|
188
|
+
if imp:
|
|
189
|
+
return f"module imports {imp}"
|
|
190
|
+
return None
|
mapwright/config.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Local state: home directory, token, port, settings and the list of tracked projects. Stdlib only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import secrets
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
DEFAULT_PORT = 7979
|
|
12
|
+
DEFAULTS = {
|
|
13
|
+
"theme": "dark", # dark | light
|
|
14
|
+
"font_size": 13,
|
|
15
|
+
"auto_step": "turn", # turn: at the end of each agent turn · idle: after a quiet period · off: only explicit steps
|
|
16
|
+
"idle_seconds": 60,
|
|
17
|
+
"watch_interval": 2.0, # seconds between scans of tracked projects while the daemon runs
|
|
18
|
+
"brief_budget": 2400, # characters in `map` / `brief` (about 600 tokens)
|
|
19
|
+
"max_files": 5000,
|
|
20
|
+
"ignore": [], # extra names or gitignore-style patterns to skip (e.g. "public/bank/**", "*.pdf")
|
|
21
|
+
"web_origins": ["https://mapwright.pages.dev"], # hosted sites allowed to call this daemon from the browser (exact origins; the token is still required)
|
|
22
|
+
"respect_gitignore": True, # also skip what .gitignore / .git/info/exclude ignore
|
|
23
|
+
"redact": True,
|
|
24
|
+
"keep_blobs_days": 0, # 0 = keep every file version
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_START: str | None = None # where project-local discovery starts (default: the current directory)
|
|
29
|
+
_CACHE: dict[tuple, Path] = {}
|
|
30
|
+
MARKER_DIR = ".mapwright"
|
|
31
|
+
MARKER = "home.json"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def set_start(path: str | os.PathLike | None) -> None:
|
|
35
|
+
"""Start project-local home discovery from this directory (a --path / --root / hook cwd) instead of the cwd."""
|
|
36
|
+
global _START
|
|
37
|
+
_START = os.path.abspath(os.fspath(path)) if path else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def reset_cache() -> None:
|
|
41
|
+
_CACHE.clear()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def local_home(start: str | os.PathLike | None = None) -> Path | None:
|
|
45
|
+
"""The project-local home found by walking up from start (default cwd) for .mapwright/home.json, or None."""
|
|
46
|
+
try:
|
|
47
|
+
cur = Path(os.path.abspath(os.fspath(start) if start else (_START or os.getcwd())))
|
|
48
|
+
except OSError:
|
|
49
|
+
return None
|
|
50
|
+
user_home = Path.home()
|
|
51
|
+
for d in [cur, *cur.parents]:
|
|
52
|
+
if d == user_home:
|
|
53
|
+
break # ~/.mapwright is the default home, not a project marker
|
|
54
|
+
marker = d / MARKER_DIR / MARKER
|
|
55
|
+
if marker.is_file():
|
|
56
|
+
data = read_json(marker, {})
|
|
57
|
+
h = data.get("home") if isinstance(data, dict) else None
|
|
58
|
+
if isinstance(h, str) and os.path.isabs(h):
|
|
59
|
+
return Path(h)
|
|
60
|
+
return None
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def write_marker(root: str, home_dir: str) -> Path:
|
|
65
|
+
"""Record home_dir as the home for the project at root (<root>/.mapwright/home.json)."""
|
|
66
|
+
m = Path(root) / MARKER_DIR / MARKER
|
|
67
|
+
write_json(m, {"home": home_dir})
|
|
68
|
+
reset_cache()
|
|
69
|
+
return m
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def home() -> Path:
|
|
73
|
+
env = os.environ.get("MAPWRIGHT_HOME")
|
|
74
|
+
key = (env, _START or os.getcwd())
|
|
75
|
+
p = _CACHE.get(key)
|
|
76
|
+
if p is None:
|
|
77
|
+
p = Path(env) if env else (local_home() or Path.home() / ".mapwright")
|
|
78
|
+
_CACHE[key] = p
|
|
79
|
+
p.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
80
|
+
try:
|
|
81
|
+
if p.stat().st_mode & 0o077:
|
|
82
|
+
p.chmod(0o700)
|
|
83
|
+
except OSError:
|
|
84
|
+
pass
|
|
85
|
+
return p
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def port() -> int:
|
|
89
|
+
try:
|
|
90
|
+
p = int(os.environ.get("MAPWRIGHT_PORT", DEFAULT_PORT))
|
|
91
|
+
except ValueError:
|
|
92
|
+
return DEFAULT_PORT
|
|
93
|
+
return p if 0 < p < 65536 else DEFAULT_PORT
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def base_url() -> str:
|
|
97
|
+
return f"http://127.0.0.1:{port()}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def token() -> str:
|
|
101
|
+
f = home() / "token"
|
|
102
|
+
for _ in range(2):
|
|
103
|
+
try:
|
|
104
|
+
tok = f.read_text().strip()
|
|
105
|
+
if tok:
|
|
106
|
+
return tok
|
|
107
|
+
f.unlink()
|
|
108
|
+
except OSError:
|
|
109
|
+
pass
|
|
110
|
+
tok = secrets.token_urlsafe(32)
|
|
111
|
+
try:
|
|
112
|
+
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
113
|
+
except FileExistsError:
|
|
114
|
+
continue
|
|
115
|
+
with os.fdopen(fd, "w") as fh:
|
|
116
|
+
fh.write(tok)
|
|
117
|
+
return tok
|
|
118
|
+
return f.read_text().strip()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def read_json(path: Path | str, default):
|
|
122
|
+
try:
|
|
123
|
+
return json.loads(Path(path).read_text(encoding="utf-8"))
|
|
124
|
+
except (OSError, ValueError):
|
|
125
|
+
return default
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def write_json(path: Path | str, data) -> None:
|
|
129
|
+
path = Path(path)
|
|
130
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
131
|
+
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
132
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
133
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
134
|
+
json.dump(data, fh, indent=1)
|
|
135
|
+
os.replace(tmp, path)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def settings() -> dict:
|
|
139
|
+
s = dict(DEFAULTS)
|
|
140
|
+
saved = read_json(home() / "settings.json", {})
|
|
141
|
+
if isinstance(saved, dict):
|
|
142
|
+
for k, v in saved.items():
|
|
143
|
+
want = DEFAULTS.get(k)
|
|
144
|
+
if want is None:
|
|
145
|
+
continue
|
|
146
|
+
if type(v) is type(want) or (isinstance(want, float) and isinstance(v, int) and not isinstance(v, bool)):
|
|
147
|
+
s[k] = v
|
|
148
|
+
return s
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def save_settings(changes: dict) -> dict:
|
|
152
|
+
"""Validate and save. Unknown keys and wrong types are rejected with a message."""
|
|
153
|
+
errors = []
|
|
154
|
+
s = settings()
|
|
155
|
+
for k, v in changes.items():
|
|
156
|
+
if k not in DEFAULTS:
|
|
157
|
+
errors.append(f"unknown setting {k}")
|
|
158
|
+
continue
|
|
159
|
+
want = DEFAULTS[k]
|
|
160
|
+
if isinstance(want, bool):
|
|
161
|
+
ok = isinstance(v, bool)
|
|
162
|
+
elif isinstance(want, (int, float)) and not isinstance(want, bool):
|
|
163
|
+
ok = isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0
|
|
164
|
+
v = type(want)(v) if ok else v
|
|
165
|
+
elif isinstance(want, list):
|
|
166
|
+
ok = isinstance(v, list) and all(isinstance(x, str) and x.strip() and "\n" not in x for x in v)
|
|
167
|
+
else:
|
|
168
|
+
ok = isinstance(v, str)
|
|
169
|
+
if k == "theme" and v not in ("dark", "light"):
|
|
170
|
+
ok = False
|
|
171
|
+
if k == "web_origins" and ok and not all(re.fullmatch(r"https://[A-Za-z0-9.-]+(:\d{2,5})?|http://(127\.0\.0\.1|localhost)(:\d{2,5})?", x) for x in v):
|
|
172
|
+
ok = False # exact origins only: no paths, no wildcards, https unless loopback
|
|
173
|
+
if k == "auto_step" and v not in ("turn", "idle", "off"):
|
|
174
|
+
ok = False
|
|
175
|
+
if k == "brief_budget" and ok and not 400 <= v <= 20000:
|
|
176
|
+
ok = False
|
|
177
|
+
if not ok:
|
|
178
|
+
errors.append(f"bad value for {k}")
|
|
179
|
+
else:
|
|
180
|
+
s[k] = v
|
|
181
|
+
if errors:
|
|
182
|
+
raise ValueError("; ".join(errors))
|
|
183
|
+
write_json(home() / "settings.json", {k: s[k] for k in DEFAULTS if s[k] != DEFAULTS[k]})
|
|
184
|
+
return s
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def projects() -> dict:
|
|
188
|
+
return read_json(home() / "projects.json", {})
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def register(key: str, root: str) -> None:
|
|
192
|
+
reg = projects()
|
|
193
|
+
if reg.get(key, {}).get("root") != root:
|
|
194
|
+
import time
|
|
195
|
+
reg[key] = {"root": root, "added": reg.get(key, {}).get("added", time.time())}
|
|
196
|
+
write_json(home() / "projects.json", reg)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def unregister(key: str) -> bool:
|
|
200
|
+
reg = projects()
|
|
201
|
+
if reg.pop(key, None) is None:
|
|
202
|
+
return False
|
|
203
|
+
write_json(home() / "projects.json", reg)
|
|
204
|
+
return True
|