# maponce [![ci](https://github.com/shivampatel0714/maponce/actions/workflows/ci.yml/badge.svg)](https://github.com/shivampatel0714/maponce/actions/workflows/ci.yml) ![python](https://img.shields.io/badge/python-3.10%2B-blue) ![license](https://img.shields.io/badge/license-MIT-green) **AI-built, self-healing page object repositories for Playwright — map once, replay forever.** AI browser agents re-derive *"where is the submit button?"* on every single run. Each step ships an accessibility tree or screenshot to the model (5–50K tokens on a real page), so a 20-step workflow can burn six figures of tokens **per run** — plus seconds of LLM latency per step, plus non-determinism. `maponce` inverts that: **AI pays tokens once** (initial mapping, or when a selector breaks), **deterministic Playwright replays for free forever.** ``` map (AI or heuristic, once) run (every time) ┌──────────────────────────┐ ┌────────────────────────────────┐ │ page ──► object repo │ ───► │ repo ──► Playwright locators │ │ (YAML, versioned)│ │ 0 tokens, ms latency, │ └──────────────────────────┘ │ deterministic & auditable │ └───────────┬────────────────────┘ │ selector broke? ┌───────────▼────────────────────┐ │ healing ladder │ │ 1. stored selectors free │ │ 2. role + accessible name free │ │ 3. fuzzy metadata match free │ │ 4. Claude, top-K scoped ~1-2K │ │ candidates only tokens │ │ verify → promote → provenance │ └────────────────────────────────┘ ``` ## Why this architecture | | AI agent per run | maponce | |---|---|---| | Tokens per 20-step run | ~100K–500K (est.*) | **0** steady-state | | Latency per step | seconds (LLM round-trip) | milliseconds | | Determinism | low — same flow may diverge | high — same run, same result | | On UI change | re-reasons every run, forever | heals **once**, writes it back | | Auditability | prompt logs | YAML diff + per-heal provenance | \* Estimate assumes ~12K tokens per AI-driven browser step (accessibility tree + reasoning). Configure your own baseline with `MAPONCE_BASELINE_TOKENS`; the `stats` command reports `est_tokens_avoided` using that documented assumption — order-of-magnitude honesty, not false precision. The same idea powers UiPath object repositories, Healenium's self-healing selectors, and action-caching in tools like Stagehand. `maponce` is the lightweight, Playwright-native, YAML-diffable version — built on a principle I apply everywhere: **use LLMs at build time, keep the production runtime deterministic and auditable.** ## Quickstart ```bash pip install -e ".[all,dev]" # ai + creds; or plain `pip install -e .` for the 0-token core playwright install chromium ``` Extras: `ai` (Claude mapping/healing/recording), `creds` (Windows Credential Manager backend). The deterministic core needs neither. **60-second demo** (bundled site, no API key needed — v2 is a "redesign" that renames every id and drops every data-testid the v1 repo depends on): ```bash cd examples # 1. Map v1 into an object repository (heuristic backend, 0 tokens) maponce map "file:///$(pwd)/demo_site/v1/index.html" -o repo.yaml # 2. Replay on v1 — every step hits the stored-selector rung. 0 tokens. # The flow references cred:ACME_PASSWORD; the demo site accepts any password, # so supply one via the env backend (PowerShell: $env:ACME_PASSWORD="demo"). ACME_PASSWORD=demo maponce run login_flow.yaml -r repo.yaml # 3. Point the SAME repo at v2 — selectors are all broken; watch them heal # through the free rungs, pass the flow, and write the fixes back. ACME_PASSWORD=demo maponce run login_flow.yaml -r repo.yaml --base "file:///$(pwd)/demo_site/v2/index.html" # 4. Token economics (add --html for a self-contained dashboard) maponce stats maponce stats --html # -> maponce_stats.html ``` With an Anthropic API key (`export ANTHROPIC_API_KEY=...`): ```bash maponce map -o repo.yaml --ai # Claude curates the repo (claude-opus-4-8) maponce run flow.yaml -r repo.yaml # AI rung available as the last-resort healer ``` ## Record mode — AI authors the flow once, code replays it forever Mapping builds the *object repo*; recording authors the *flow itself*. `maponce record` runs Claude in a tool-use loop over a small set of Playwright actions (navigate / fill / click / assert). Claude sees a compact digest of the page, picks the next action toward your goal, and maponce **executes and records** it — every touched element becomes an object, every action becomes a step. ```bash maponce record "log in and search orders for 'playwright'" \ -r repo.yaml -f flow.yaml --backends env,windows # ... then, at 0 tokens, forever: maponce run flow.yaml -r repo.yaml ``` This is the whole thesis as a workflow: **use the LLM at build time, keep the runtime deterministic.** The recording is the one-time AI cost the architecture is built to amortize; the replay is free. **Recording verifies itself.** As soon as it's authored, the flow is replayed on a *fresh* browser context with AI healing turned **off** — so the recorded steps have to re-establish state from scratch. If it reproduces at 0 tokens the recording is trustworthy; the summary reports `verified: {ok, steps, heals, ai_calls, tokens_used}`, and a recording that can't replay itself deterministically is flagged rather than silently shipped (`--no-verify` to skip). Secrets typed at record time are kept in memory only for this pass — never persisted to run it. Secrets are handled at the boundary: when Claude targets a password/secret field it sets `is_secret=true` and is given **no value** — maponce injects the real value locally (from a credential backend or a hidden prompt) to drive the page, and records only `cred:NAME`. The password never reaches the model or the YAML. > Approach A (AI drives the browser) is what ships today. A `--from-recording` > mode (you click through once, AI adds naming/assertions/rules) is the natural > next step and reuses the same object-registration path. ## Use it as an MCP server maponce also speaks the **Model Context Protocol**, so any MCP host (Claude Desktop, an agent runtime) can call it as a tool — record or map an automation once, then replay it deterministically at zero token cost, behind standard tool calls. ```bash pip install 'maponce[mcp]' # add 'ai' for record mode maponce-mcp # stdio transport ``` Register it with Claude Desktop (`claude_desktop_config.json`): ```json { "mcpServers": { "maponce": { "command": "maponce-mcp" } } } ``` Exposed tools: `map_page`, `run_flow`, `record_flow`, `stats`, `credential_backends`. Secret handling is identical to the CLI — `record_flow` writes `cred:NAME`, never values, and resolves them from a backend at runtime. Playwright's sync API can't run inside the server's event loop, so each browser tool hops to a worker thread. ## The healing ladder 1. **Stored selectors** — the ordered ladder in the repo, most stable first (`data-testid` → `id` → `name` → `placeholder`). Pure Playwright. 2. **Role + accessible name** — `get_by_role("textbox", name="Username")`. Survives most redesigns because labels outlive markup. 3. **Fuzzy metadata match** — `difflib` similarity over candidate labels/aria/placeholder/ id/text, with tag/role verification so healing never silently grabs the wrong element. 4. **AI fallback** — only now does Claude get involved, and only with the **top-K scoped candidates** (hundreds of tokens), never the whole page. Conservative by prompt: a wrong pick is worse than no pick. Every heal is **verified** (tag/role invariants), **promoted** (the new selector is written to the front of the ladder), and **recorded** (`provenance.heals[]` with timestamp and rung) — so the repo is a reviewable artifact, not hidden state. Rungs 2–3 heal without promoting a selector; they're free at runtime, and the YAML diff still shows the heal event. ## Object repository format ```yaml version: 1 base_url: https://app.example.com objects: username: role: textbox name: Username tag: input selectors: # ordered ladder, most stable first - '#username' text_hint: Username provenance: created_by: heuristic # or: ai (model recorded) heals: - {at: '2026-07-14T22:11:04+00:00', rung: fuzzy, selector: '#user-email'} last_verified: '2026-07-14T22:11:04+00:00' ``` ## Business rules & control flow Recorded flows aren't just linear scripts — they carry a small, **deterministic** control-flow vocabulary, so an AI-authored automation can encode real business rules that then run as code at 0 tokens: ```yaml data: invoices: - { id: "A-1", amount: "500" } - { id: "A-2", amount: "125" } steps: - for_each: { data: invoices, as: inv } # loop over data do: - fill: { object: invoice_id, value: "{inv.id}" } # {var} interpolation - if: { object: past_due_banner, exists: true } # branch on the page then: - click: { object: pay_now } else: - click: { object: skip } - run: mypkg.reconcile # escape hatch: call func(page, context) in Python ``` - **`if` / `then` / `else`** — condition on an object's presence (`exists`) or text (`contains`); existence checks are deterministic and never spend AI tokens. - **`for_each` / `do`** — iterate a named data list, binding each row. - **`{var}` / `{row.field}` / `{base}`** — interpolation in `fill` values and `goto`. - **`run: module.func`** — the escape hatch to Python (`func(page, context)`) for anything the declarative steps don't cover. "Fall back to code" is a first-class exit, not an afterthought — reach for it rather than growing a DSL. (It executes whatever the flow names, so only run trusted flows.) ## Observability `maponce stats` summarizes the token economics across runs; `maponce stats --html` renders a self-contained, theme-aware dashboard (KPI tiles, tokens-used-vs-avoided, a per-run table) with zero external dependencies — open it straight in a browser. ## Housing credentials Flows reference secrets by **name**, never by value. `cred:ACME_PASSWORD` is resolved at runtime from a backend chain — the value never lands in the flow YAML, the object repo, or the logs. ```yaml credentials: backends: [env, windows] # tried in order; first hit wins steps: - fill: { object: password, value: "cred:ACME_PASSWORD" } ``` | Backend | Where the value lives | Setup | |---|---|---| | `env` | process environment | `export`/`$env:`; also how GitHub Actions secrets arrive | | `windows` | Windows Credential Manager (keyring) | `maponce creds set ACME_PASSWORD` | | GitHub Secrets | the repo's Actions secrets | `maponce creds set ACME_PASSWORD --backend github` | ```bash maponce creds set ACME_PASSWORD # -> Windows Credential Manager (hidden prompt) maponce creds set ACME_PASSWORD --backend github # -> gh secret set (repo Actions secret) maponce creds get ACME_PASSWORD # reports which backend resolves it; never prints the value maponce creds backends # show the active chain ``` **Secrets never reach the model.** In record mode the page digest sent to Claude has all text-field values stripped, so a password typed to drive the page can't ride along in the next observation — [`tests/test_security.py`](tests/test_security.py) asserts a filled password never appears in the digest. GitHub Secrets aren't a separate runtime backend: in CI you map `secrets.NAME` into the environment, where the `env` backend resolves it — see [`examples/github/run-flow.yml`](examples/github/run-flow.yml). Precedence: a flow's `credentials.backends` → `MAPONCE_CRED_BACKENDS` → platform default (`env,windows` on Windows, `env` elsewhere). Unavailable backends (e.g. `windows` without keyring installed) are dropped from the chain automatically. `maponce` never persists a secret itself — storage is delegated to the OS vault or `gh`, with the plaintext fed over a hidden prompt / stdin, never argv. ## Anthropic API usage The AI layer follows current Claude API best practice: - `claude-opus-4-8` (override with `MAPONCE_MODEL`) - **Prompt caching** — stable system prompts carry `cache_control`; the volatile DOM digest rides in the user turn after the cache breakpoint - **Structured outputs** — `output_config.format` with a JSON schema; no brittle parsing - **Adaptive thinking** for the mapping/healing/recording judgment - **Tool use** — record mode is a tool-use loop (navigate/fill/click/assert); thinking blocks are preserved across turns - Scoped context — healing sends the top-K candidate shortlist, not the page; recording sends a trimmed per-turn digest, not the raw DOM ## Honest limitations - Low cache-hit workloads (run-once flows on fast-changing pages) live in the AI rung and save little — this tool shines on **stable, repeated** workflows. - Canvas-rendered or aggressively randomized DOMs rot faster than healing keeps up. - Anti-bot walls are out of scope. - The repo itself is an artifact to maintain (that's also the point: it's *reviewable*). ## Transparency Built AI-assisted (Claude Code) — fitting, since AI-assisted engineering with a deterministic, auditable runtime is exactly what this project argues for. Every line was reviewed, and the demo + tests run without any AI in the loop. ## License MIT