High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(benchmark): add agent benchmark suite
Marioc0750018a26e
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.mdindex 0f27a514..cf04ff16 100644--- a/skills/pinchtab/SKILL.md+++ b/skills/pinchtab/SKILL.md@@ -415,13 +415,42 @@ pinchtab text### Search, then extract the result page cheaply```bash-pinchtab nav https://example.com+pinchtab nav https://example.com/searchpinchtab snap -i -cpinchtab fill e2 "quarterly report"-pinchtab press Enter+pinchtab click e3 # Click the Search buttonpinchtab text```+**Form submission rules:**+- ❌ **NEVER use `press Enter` on regular form inputs.** It does NOT submit standard HTML forms.+- ✅ **ALWAYS click the submit button** to trigger form submission handlers.+- **Why?** HTML5 forms only auto-submit on Enter if they have explicit JavaScript `onkeypress` or `onkeyup` handlers. The `<form onsubmit>` handler only fires when you click the button, not on Enter.++**Real-world example from benchmark:**+```bash+# WRONG: This fails+pinchtab nav http://fixtures/wiki.html+pinchtab snap -i -c+pinchtab fill "#wiki-search-input" "go"+pinchtab press Enter # ❌ Does NOT submit the form++# RIGHT: This works+pinchtab nav http://fixtures/wiki.html+pinchtab snap -i -c+pinchtab fill "#wiki-search-input" "go"+pinchtab click "#wiki-search-btn" # ✅ Triggers onsubmit handler+pinchtab text # Now on the results page+```++**Always follow this pattern:**+```bash+# Template: fill, then click+pinchtab fill "<selector>" "value"+pinchtab click "<button-selector>" # Always click, never press Enter+pinchtab text # Verify the form was submitted+```+### Use diff snapshots in a multi-step flow```bash@@ -506,3 +535,37 @@ PinchTab is a fully open-source, local-only browser automation tool:- Profiles: [profiles.md](./references/profiles.md)- MCP: [mcp.md](./references/mcp.md)- Security model: [TRUST.md](./TRUST.md)++## Content Extraction: text vs snapshot++Choose the right extraction method:++| Use Case | Recommended | Why |+|----------|-------------|-----|+| Article body, paragraphs | `text` | Clean prose extraction |+| Prices, numbers in cards | `snapshot` | Text strips structured data |+| Form field values | `snapshot` | See current input values |+| Verify element exists | `snapshot` with selector | Text won't show headings |+| JS-rendered content | `snapshot` after wait | Text may miss dynamic content |++**Common pitfall**: `/text` extracts readable prose but strips headings, prices, and structured UI elements. If you need to verify a heading, price, or button label, use `/snapshot` instead.++```bash+# Wrong: looking for "$149.99" in text output+pinchtab text | grep "149.99" # May fail - prices often stripped++# Right: snapshot includes all visible text+pinchtab snap -c | grep "149.99" # Works+```++## Fixture Selector Quick Reference++| Page | Key selectors |+|------|---------------|+| ecommerce | `.add-to-cart`, `#checkout-btn`, `.price` (use `snapshot` not `-c` for price values) |+| search | `#search-input`, `#search-btn` (click button — never press Enter) |+| form | `#fullname`, `#email`, `#phone`, `#country`, `#subject`, `#message`, `#submit-btn` |+| wiki | `#wiki-search-input`, `#wiki-search-btn` |+| spa | `#new-task-input`, `#priority-select`, `#add-task-btn` |+| login | `#username`, `#password`, `#login-btn`, `#logout-btn` |+| dashboard | `#settings-btn`, `#theme-select`, `#modal-save` |diff --git a/tests/benchmark/.gitignore b/tests/benchmark/.gitignorenew file mode 100644index 00000000..fbca2253--- /dev/null+++ b/tests/benchmark/.gitignore@@ -0,0 +1 @@+results/diff --git a/tests/benchmark/AGENT_SCRIPT.md b/tests/benchmark/AGENT_SCRIPT.mdnew file mode 100644index 00000000..4358a811--- /dev/null+++ b/tests/benchmark/AGENT_SCRIPT.md@@ -0,0 +1,945 @@+# PinchTab Agent Benchmark Script++A structured execution plan for AI agents to benchmark PinchTab capabilities through real-world browser tasks.++---++## Token & Cost Tracking++Every step must track token usage to measure real-world agent costs.++### What to Track++For each step, record:+- **Input tokens**: Tokens sent to the model (prompt + context)+- **Output tokens**: Tokens generated by the model (response)+- **Tool calls**: Number of tool invocations+- **PinchTab output size**: Characters/bytes returned by PinchTab commands++### How to Track++**Option A: Model API tracking**+If your model provider exposes usage in responses, capture `prompt_tokens` and `completion_tokens` per step.++**Option B: Estimation**+Use these approximations:+- 1 token ≈ 4 characters (English text)+- 1 token ≈ 3 characters (code/structured output)++**Option C: Session status (OpenClaw)**+If running under OpenClaw, call `📊 session_status` periodically to get cumulative usage.++### Cost Calculation++Use these per-1M-token rates (adjust for your provider):++| Model | Input $/1M | Output $/1M |+|-------|-----------|-------------|+| Claude Haiku | $0.25 | $1.25 |+| Claude Sonnet | $3.00 | $15.00 |+| Claude Opus | $15.00 | $75.00 |+| GPT-4o | $2.50 | $10.00 |+| GPT-4o-mini | $0.15 | $0.60 |+| Gemini 1.5 Pro | $1.25 | $5.00 |+| Gemini 1.5 Flash | $0.075 | $0.30 |++Formula:+```+cost = (input_tokens / 1_000_000 * input_rate) + (output_tokens / 1_000_000 * output_rate)+```++### Recording Format (Extended)++```+Step X.Y: [PASS/FAIL/SLOW]+- Duration: Xms+- Input tokens: X+- Output tokens: X+- PinchTab output: X chars+- Tool calls: X+- Est. cost: $X.XXXX+- Notes: (any observations)+- Error: (if failed)+```++---++## Rules++### Execution Rules++1. **Follow steps sequentially.** Do not skip steps unless explicitly marked as optional.+2. **Record outcomes.** After each step, note: success/failure, time taken, any errors encountered.+3. **Stop on blockers.** If a step fails and is marked `[BLOCKING]`, halt the group and record the failure.+4. **Retry once.** If a step fails, retry exactly once before marking as failed.+5. **Fresh state per group.** Each task group assumes no prior state unless it explicitly references a previous group.+6. **Use CLI first.** Prefer `pinchtab` CLI commands. Use HTTP API only when the step specifies it.+7. **Capture evidence.** When a step says "verify", use `pinchtab text` or `pinchtab snap -i -c` to confirm.++### Timing Rules++1. **Wait for navigation.** Use `--wait-nav` when clicking links that navigate.+2. **Re-snapshot after changes.** Always get fresh refs after any click, submit, or navigation.+3. **Timeout threshold.** If any command takes longer than 30 seconds, mark as slow and continue.++### Recording Format++For each step, record:+```+Step X.Y: [PASS/FAIL/SLOW]+- Duration: Xms+- Notes: (any observations)+- Error: (if failed)+```++---++## Pre-Flight Checks++Before starting the benchmark, verify the environment is ready.++### P.1 Verify PinchTab is installed+Run `pinchtab version` and confirm it returns a version string.++### P.2 Start the PinchTab server+Run `pinchtab server` in background or verify it's already running.++### P.3 Verify server health+Run `pinchtab health` and confirm status is healthy.++### P.4 Verify Chrome is available+Run `pinchtab instances` to confirm no errors about missing Chrome.++### P.5 Clean slate+Stop any running instances with `pinchtab instance stop --all` if needed.++---++## Task Group 1: Basic Navigation++Test fundamental navigation and page observation.++### 1.1 Navigate to a simple page `[BLOCKING]`+Run `pinchtab nav https://github.com`.+Verify: Command completes without error.++### 1.2 Extract page text+Run `pinchtab text`.+Verify: Output contains "GitHub".++### 1.3 Get interactive snapshot+Run `pinchtab snap -i -c`.+Verify: Output shows refs for interactive elements (links, buttons, inputs).++### 1.4 Navigate to a second page+Run `pinchtab nav https://wikipedia.org`.+Verify: Command completes without error.++### 1.5 Verify navigation changed the page+Run `pinchtab text`.+Verify: Output contains "Wikipedia" and NOT "GitHub".++### 1.6 Navigate back+Run `pinchtab back`.+Verify: `pinchtab text` now shows "GitHub" again.++### 1.7 Navigate forward+Run `pinchtab forward`.+Verify: `pinchtab text` shows "Wikipedia" content.++---++## Task Group 2: Element Interaction++Test clicking, typing, and form operations.++### 2.1 Navigate to Wikipedia search `[BLOCKING]`+Run `pinchtab nav https://www.wikipedia.org`.+Verify: Command completes and main page loads.++### 2.2 Snapshot the search form+Run `pinchtab snap -i -c`.+Verify: Output shows refs for the search input field.++### 2.3 Fill search field using ref+Identify the ref for the search input from the snapshot.+Run `pinchtab fill <ref> "Artificial intelligence"`.+Verify: Command completes without error.++### 2.4 Fill search field using CSS selector+Run `pinchtab fill "#searchInput" "Machine learning"`.+Verify: Command completes without error.++### 2.5 Click a language link+Identify a language link ref (e.g., English, Español).+Run `pinchtab click --wait-nav <lang-ref>`.+Verify: Page navigates to that language Wikipedia.++### 2.6 Navigate to GitHub+Run `pinchtab nav https://github.com`.+Verify: GitHub homepage loads.++### 2.7 Use GitHub search+Run `pinchtab snap -i -c`.+Identify the search input ref.+Run `pinchtab fill <search-ref> "pinchtab"`.+Run `pinchtab press Enter`.+Verify: `pinchtab text` shows search results.++---++## Task Group 3: Multi-Tab Workflow++Test tab management and parallel browsing.++### 3.1 Open first tab `[BLOCKING]`+Run `pinchtab nav https://news.ycombinator.com`.+Verify: Page loads successfully.++### 3.2 List tabs+Run `pinchtab tab`.+Verify: Output shows at least one tab with Hacker News URL.++### 3.3 Open a second tab+Run `pinchtab tab new https://lobste.rs`.+Verify: `pinchtab tab` now shows two tabs.++### 3.4 Verify second tab content+Run `pinchtab text`.+Verify: Output contains "Lobsters" or lobste.rs content.++### 3.5 Switch back to first tab+Identify the Hacker News tab ID from `pinchtab tab`.+Run `pinchtab tab <tab-id>` to focus it.+Verify: `pinchtab text` now shows Hacker News content.++### 3.6 Close second tab+Identify the Lobsters tab ID.+Run `pinchtab tab close <tab-id>`.+Verify: `pinchtab tab` shows only one tab remaining.++---++## Task Group 4: Search Flow++Test a realistic search workflow.++### 4.1 Navigate to DuckDuckGo `[BLOCKING]`+Run `pinchtab nav https://duckduckgo.com`.+Verify: Page loads.++### 4.2 Snapshot search form+Run `pinchtab snap -i -c`.+Verify: A search input ref is visible.++### 4.3 Enter search query+Run `pinchtab fill <search-ref> "pinchtab browser automation"`.+Verify: Command completes.++### 4.4 Submit search+Run `pinchtab press Enter`.+Wait 2 seconds for results to load.++### 4.5 Verify search results+Run `pinchtab text`.+Verify: Output contains search result text (links, descriptions).++### 4.6 Click first result+Run `pinchtab snap -i -c` to get fresh refs.+Identify the first result link ref.+Run `pinchtab click --wait-nav <first-result-ref>`.+Verify: `pinchtab text` shows content from the clicked result page.++---++## Task Group 5: Screenshot and PDF Export++Test visual output capabilities.++### 5.1 Navigate to a visual page `[BLOCKING]`+Run `pinchtab nav https://github.com`.+Verify: Page loads.++### 5.2 Take a screenshot+Run `pinchtab screenshot -o /tmp/pinchtab-bench-screenshot.png`.+Verify: File exists at that path and is a valid PNG.++### 5.3 Take a JPEG screenshot with quality+Run `pinchtab screenshot -o /tmp/pinchtab-bench-screenshot.jpg -q 80`.+Verify: File exists and is smaller than the PNG.++### 5.4 Export PDF+Run `pinchtab pdf -o /tmp/pinchtab-bench-export.pdf`.+Verify: File exists and is a valid PDF.++### 5.5 Export landscape PDF+Run `pinchtab pdf -o /tmp/pinchtab-bench-landscape.pdf --landscape`.+Verify: File exists.++### 5.6 Cleanup+Remove the test files from /tmp.++---++## Task Group 6: Profile Management++Test persistent profile creation and reuse.++### 6.1 List existing profiles+Run `pinchtab profiles`.+Record: Number of existing profiles.++### 6.2 Create a test profile `[BLOCKING]`+Run via HTTP API:+```bash+curl -X POST http://localhost:9867/profiles \+ -H "Content-Type: application/json" \+ -d '{"name":"bench-test","description":"Benchmark test profile"}'+```+Verify: Response contains the new profile ID.++### 6.3 Verify profile appears in list+Run `pinchtab profiles`.+Verify: "bench-test" appears in the list.++### 6.4 Start instance with profile+Run `pinchtab instance start --profile bench-test --mode headless`.+Record: The instance ID and port returned.++### 6.5 Use the profiled instance+Run `pinchtab --server http://localhost:<port> nav https://github.com`.+Verify: Navigation succeeds.++### 6.6 Stop the instance+Run `pinchtab instance stop <instance-id>`.+Verify: Instance no longer appears in `pinchtab instances`.++### 6.7 Delete test profile+Run via HTTP API:+```bash+curl -X DELETE http://localhost:9867/profiles/bench-test+```+Verify: Profile no longer appears in `pinchtab profiles`.++---++## Task Group 7: Instance Management++Test multi-instance workflows.++### 7.1 Start first instance `[BLOCKING]`+Run `pinchtab instance start --mode headless`.+Record: Instance ID and port (e.g., inst_abc123, port 9868).++### 7.2 Start second instance+Run `pinchtab instance start --mode headless`.+Record: Instance ID and port (e.g., inst_def456, port 9869).++### 7.3 Verify both instances running+Run `pinchtab instances`.+Verify: Both instances appear in the list.++### 7.4 Navigate instances to different sites+Run `pinchtab --server http://localhost:9868 nav https://github.com`.+Run `pinchtab --server http://localhost:9869 nav https://wikipedia.org`.+Verify: Both complete without error.++### 7.5 Verify instance isolation+Run `pinchtab --server http://localhost:9868 text`.+Verify: Shows "GitHub".+Run `pinchtab --server http://localhost:9869 text`.+Verify: Shows "Wikipedia".++### 7.6 Stop all instances+Run `pinchtab instance stop --all`.+Verify: `pinchtab instances` shows no running instances.++---++## Task Group 8: Diff Snapshots++Test incremental snapshot diffing.++### 8.1 Navigate to interactive page `[BLOCKING]`+Run `pinchtab nav https://www.wikipedia.org`.+Verify: Page loads.++### 8.2 Take baseline snapshot+Run `pinchtab snap -i -c`.+Record: The refs visible.++### 8.3 Make a change+Identify the search input ref.+Run `pinchtab fill <search-ref> "Test query"`.+Verify: Command completes.++### 8.4 Take diff snapshot+Run `pinchtab snap -d -i -c`.+Verify: Output indicates the changed element or shows delta.++### 8.5 Click a language link+Click one of the language links.+Run `pinchtab snap -d -i -c` again.+Verify: Diff shows the page change.++---++## Task Group 9: Error Handling++Test graceful handling of errors.++### 9.1 Navigate to non-existent page+Run `pinchtab nav https://this-domain-does-not-exist-12345.com`.+Verify: Command returns an error (not a crash).+Record: The error message.++### 9.2 Click non-existent ref+Run `pinchtab nav https://github.com`.+Run `pinchtab click e999`.+Verify: Command returns an error about missing ref.++### 9.3 Fill non-existent selector+Run `pinchtab fill "#nonexistent-element-12345" "test"`.+Verify: Command returns a selector not found error.++### 9.4 Invalid command syntax+Run `pinchtab nav` (missing URL).+Verify: Command returns a usage error.++### 9.5 Server not running (optional)+Stop the server if safe to do so.+Run `pinchtab nav https://github.com`.+Verify: Command returns connection refused or similar error.+Restart the server.++---++## Task Group 10: Performance Baselines++Test timing under normal conditions. Run each 3 times and record average.++### 10.1 Navigation speed+Time: `pinchtab nav https://github.com`+Record: Average duration across 3 runs.++### 10.2 Snapshot speed+Navigate to github.com first.+Time: `pinchtab snap -i -c`+Record: Average duration.++### 10.3 Text extraction speed+Time: `pinchtab text`+Record: Average duration.++### 10.4 Click speed+Get a ref from snapshot.+Time: `pinchtab click <ref>`+Record: Average duration.++### 10.5 Screenshot speed+Time: `pinchtab screenshot -o /tmp/bench-perf.png`+Record: Average duration.++---++## Task Group 11: Token Efficiency (Optional)++Measure token usage for agent context optimization.++### 11.1 Full snapshot token count+Run `pinchtab nav https://news.ycombinator.com`.+Run `pinchtab snap` and count output tokens/characters.+Record: Character count of full snapshot.++### 11.2 Interactive-only snapshot+Run `pinchtab snap -i` and count output.+Record: Character count, calculate reduction %.++### 11.3 Interactive + compact snapshot+Run `pinchtab snap -i -c` and count output.+Record: Character count, calculate reduction %.++### 11.4 Text-only extraction+Run `pinchtab text` and count output.+Record: Character count vs snapshot.++### 11.5 Token-limited snapshot+Run `pinchtab snap --max-tokens 500`.+Verify: Output is truncated to approximately that budget.++---++## Task Group 12: Login Flow Simulation++Test authentication workflows with a practice site.+Note: Using dedicated test automation sites that are designed for this purpose.++### 12.1 Navigate to practice login page `[BLOCKING]`+Run `pinchtab nav https://practicetestautomation.com/practice-test-login/`.+Alternative: `pinchtab nav https://the-internet.herokuapp.com/login`+Verify: Page loads with login form.++### 12.2 Snapshot login form+Run `pinchtab snap -i -c`.+Verify: Username and password fields visible with refs.++### 12.3 Enter valid credentials+Run `pinchtab fill "#username" "student"`.+Run `pinchtab fill "#password" "Password123"`.+Verify: Both commands complete.++### 12.4 Submit login+Identify the submit button ref.+Run `pinchtab click --wait-nav <submit-ref>`.+Verify: Page navigates.++### 12.5 Verify successful login+Run `pinchtab text`.+Verify: Output contains "Logged In Successfully" or similar success message.++### 12.6 Test invalid credentials+Navigate back to the login page.+Fill with invalid credentials ("wrong", "wrong").+Submit and verify error message appears.++---++## Task Group 13: Dynamic Content++Test handling of JavaScript-rendered content.+Note: the-internet.herokuapp.com is a test automation practice site, purpose-built for these tests.++### 13.1 Navigate to dynamic page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/dynamic_loading/1`.+Verify: Page loads.++### 13.2 Snapshot initial state+Run `pinchtab snap -i -c`.+Verify: "Start" button is visible.++### 13.3 Click to trigger loading+Click the Start button.+Wait 2 seconds.++### 13.4 Verify dynamic content loaded+Run `pinchtab text`.+Verify: Output contains "Hello World!" (the dynamically loaded text).++### 13.5 Handle loading states+Run `pinchtab snap -d -i -c`.+Record: Whether the diff shows the new content correctly.++---++## Task Group 14: Dropdown and Select++Test complex form controls.++### 14.1 Navigate to dropdown page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/dropdown`.+Verify: Page loads with dropdown.++### 14.2 Snapshot dropdown+Run `pinchtab snap -i -c`.+Verify: Dropdown element has a ref.++### 14.3 Select option by value+Run `pinchtab select <dropdown-ref> "1"`.+Verify: Command completes.++### 14.4 Verify selection+Run `pinchtab snap -i -c`.+Verify: Option 1 is now selected.++### 14.5 Select different option+Run `pinchtab select <dropdown-ref> "2"`.+Verify: Selection changed to Option 2.++---++## Task Group 15: Hover and Tooltips++Test hover interactions.++### 15.1 Navigate to hover page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/hovers`.+Verify: Page loads with user avatars.++### 15.2 Snapshot before hover+Run `pinchtab snap -i -c`.+Record: Initial state refs.++### 15.3 Hover over first avatar+Identify the first avatar image ref.+Run `pinchtab hover <avatar-ref>`.+Verify: Command completes.++### 15.4 Verify hover content appeared+Run `pinchtab snap -d -i -c`.+Verify: New content visible (user name, "View profile" link).++### 15.5 Hover over second avatar+Hover over the second avatar.+Verify: Different user info appears.++---++## Task Group 16: Scrolling++Test page scrolling capabilities.++### 16.1 Navigate to long page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/infinite_scroll`.+Verify: Page loads.++### 16.2 Get initial content+Run `pinchtab text`.+Record: Initial content length.++### 16.3 Scroll down by pixels+Run `pinchtab scroll 500`.+Verify: Command completes.++### 16.4 Verify more content loaded+Run `pinchtab text`.+Verify: Content length increased (infinite scroll loaded more).++### 16.5 Scroll to element+Navigate to a page with a footer.+Run `pinchtab scroll "text:Footer"` or equivalent selector.+Verify: Footer is now in view.++---++## Task Group 17: File Download++Test download capabilities.++### 17.1 Navigate to download page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/download`.+Verify: Page loads with download links.++### 17.2 Identify a download link+Run `pinchtab snap -i -c`.+Identify a file link (e.g., .txt or .pdf file).++### 17.3 Download the file+Run `pinchtab download <file-url> -o /tmp/pinchtab-bench-download.txt`.+Verify: File exists at that path.++### 17.4 Verify file content+Check that the downloaded file has content.+Record: File size.++### 17.5 Cleanup+Remove the test file.++---++## Task Group 18: iFrame Handling++Test interaction with embedded frames.++### 18.1 Navigate to iframe page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/iframe`.+Verify: Page loads with TinyMCE editor in iframe.++### 18.2 Snapshot main frame+Run `pinchtab snap -i -c`.+Record: What refs are visible in main frame.++### 18.3 Access iframe content+Use appropriate command to interact with iframe content.+Record: Method used and whether it succeeded.++### 18.4 Type in iframe editor+If iframe is accessible, type "Benchmark test content" in the editor.+Verify: Text appears in the editor.++---++## Task Group 19: Alerts and Dialogs++Test JavaScript alert/confirm/prompt handling.++### 19.1 Navigate to alerts page `[BLOCKING]`+Run `pinchtab nav https://the-internet.herokuapp.com/javascript_alerts`.+Verify: Page loads with alert buttons.++### 19.2 Trigger alert+Click the "Click for JS Alert" button.+Record: How PinchTab handles the alert.++### 19.3 Accept alert+Dismiss or accept the alert.+Verify: `pinchtab text` shows "You successfully clicked an alert".++### 19.4 Handle confirm dialog+Click "Click for JS Confirm".+Accept the confirm.+Verify: Result text shows "Ok".++### 19.5 Handle confirm cancel+Trigger confirm again.+Cancel it.+Verify: Result text shows "Cancel".++---++## Task Group 20: Semantic Search (find command)++Test natural language element finding.++### 20.1 Navigate to complex page `[BLOCKING]`+Run `pinchtab nav https://news.ycombinator.com`.+Verify: Page loads.++### 20.2 Find login link semantically+Run `pinchtab find "login link"`.+Verify: Returns a ref or selector for the login link.++### 20.3 Find search box+Run `pinchtab find --ref-only "search input"`.+Verify: Returns a ref.++### 20.4 Find navigation element+Run `pinchtab find "link to submit new story"`.+Verify: Returns relevant element.++### 20.5 Compare to manual snapshot+Run `pinchtab snap -i -c`.+Verify: The semantic find results match elements in the snapshot.++---++## Task Group 21: Challenge/CAPTCHA Detection++Test challenge solver capabilities (requires appropriate site).++### 21.1 Check available solvers+Run `curl http://localhost:9867/solvers`.+Record: Which solvers are registered.++### 21.2 Navigate to protected page (if available)+If a Cloudflare-protected test site is available, navigate to it.+Otherwise mark this group as SKIPPED.++### 21.3 Detect challenge+Run `pinchtab text`.+Check if output indicates a challenge page ("Just a moment...", etc.).++### 21.4 Attempt solve+Run:+```bash+curl -X POST http://localhost:9867/solve \+ -H 'Content-Type: application/json' \+ -d '{"maxAttempts": 3}'+```+Record: Response (solved, attempts, solver used).++### 21.5 Verify page loaded+Run `pinchtab text`.+Verify: Real page content now visible.++---++## Task Group 22: Agent Identity++Test agent attribution features.++### 22.1 Set agent identity via CLI+Run `pinchtab --agent-id "bench-agent-1" nav https://github.com`.+Verify: Command completes.++### 22.2 Verify activity recorded+Run `curl "http://localhost:9867/api/activity?agentId=bench-agent-1"`.+Verify: Activity entries show for that agent.++### 22.3 Use different agent ID+Run `pinchtab --agent-id "bench-agent-2" nav https://wikipedia.org`.+Verify: Command completes.++### 22.4 Verify separate activity streams+Query activity for both agents.+Verify: Each has separate activity entries.++### 22.5 Test header-based identity+Run:+```bash+curl -X POST http://localhost:9867/navigate \+ -H "X-Agent-Id: bench-agent-http" \+ -H "Content-Type: application/json" \+ -d '{"url":"https://github.com"}'+```+Verify: Activity recorded under "bench-agent-http".++---++## Task Group 23: Block Images/Ads Mode++Test bandwidth-saving navigation modes.++### 23.1 Navigate with images blocked `[BLOCKING]`+Run `pinchtab nav https://news.ycombinator.com --block-images`.+Verify: Page loads successfully.++### 23.2 Verify page still functional+Run `pinchtab snap -i -c`.+Verify: Interactive elements are present.++### 23.3 Compare loading time+Time navigation with and without `--block-images`.+Record: Time difference.++### 23.4 Navigate with ads blocked+Run `pinchtab nav https://github.com --block-ads`.+Verify: Page loads successfully.++---++## Summary Template++After completing all groups, compile results using this template:++---++## Results Template++Copy this section to a new file `BENCHMARK_RESULTS_<date>.md`:++```markdown+# PinchTab Benchmark Results++**Date**: YYYY-MM-DD+**Agent/Model**: (e.g., Claude Sonnet 3.5)+**PinchTab Version**: (output of `pinchtab version`)+**Environment**: (OS, Chrome version)++---++## Cost Summary++| Metric | Value |+|--------|-------|+| Total input tokens | X |+| Total output tokens | X |+| Total tool calls | X |+| Total estimated cost | $X.XX |+| Cost per task group (avg) | $X.XX |++---++## Pass/Fail Summary++| Group | Name | Pass | Fail | Skip | Blocking? |+|-------|------|------|------|------|-----------|+| 1 | Basic Navigation | X/X | X | X | No |+| 2 | Element Interaction | X/X | X | X | No |+| 3 | Multi-Tab Workflow | X/X | X | X | No |+| 4 | Search Flow | X/X | X | X | No |+| 5 | Screenshot/PDF Export | X/X | X | X | No |+| 6 | Profile Management | X/X | X | X | No |+| 7 | Instance Management | X/X | X | X | No |+| 8 | Diff Snapshots | X/X | X | X | No |+| 9 | Error Handling | X/X | X | X | No |+| 10 | Performance Baselines | X/X | X | X | No |+| 11 | Token Efficiency | X/X | X | X | No |+| 12 | Login Flow | X/X | X | X | No |+| 13 | Dynamic Content | X/X | X | X | No |+| 14 | Dropdown/Select | X/X | X | X | No |+| 15 | Hover/Tooltips | X/X | X | X | No |+| 16 | Scrolling | X/X | X | X | No |+| 17 | File Download | X/X | X | X | No |+| 18 | iFrame Handling | X/X | X | X | No |+| 19 | Alerts/Dialogs | X/X | X | X | No |+| 20 | Semantic Search | X/X | X | X | No |+| 21 | Challenge/CAPTCHA | X/X | X | X | No |+| 22 | Agent Identity | X/X | X | X | No |+| 23 | Block Images/Ads | X/X | X | X | No |++**Total**: X/X passed (X%)++---++## Performance Baselines++| Operation | Avg (ms) | Min (ms) | Max (ms) |+|-----------|----------|----------|----------|+| Navigation | X | X | X |+| Snapshot (-i -c) | X | X | X |+| Text extraction | X | X | X |+| Click | X | X | X |+| Fill | X | X | X |+| Screenshot | X | X | X |+| PDF export | X | X | X |++---++## Token Efficiency++| Mode | Output Size | vs Full Snapshot |+|------|-------------|------------------|+| Full snapshot | X chars | 100% |+| Interactive only (-i) | X chars | X% |+| Interactive + compact (-i -c) | X chars | X% |+| Text only | X chars | X% |+| Token-limited (500) | X chars | X% |++---++## Blocking Failures++List any steps marked `[BLOCKING]` that failed:++1. Group X, Step X.Y: (reason)+2. ...++---++## Notable Observations++- (Any interesting findings, edge cases, or suggestions)+- (Performance anomalies)+- (Feature requests based on benchmark)++---++## Error Messages Quality++Rate 1-5 for each error type encountered:++| Error Type | Clarity (1-5) | Actionable (1-5) | Example |+|------------|---------------|------------------|---------|+| Missing ref | X | X | "..." |+| Connection refused | X | X | "..." |+| Timeout | X | X | "..." |+| Invalid selector | X | X | "..." |++---++## Detailed Step Results++(Paste step-by-step results here)+```++---++## Benchmark Scope++This benchmark covers:+- **Navigation**: forward, back, reload, block-images, block-ads+- **Observation**: snap, text, diff, find (semantic)+- **Interaction**: click, fill, type, press, select, hover, scroll+- **Tabs and instances**: multi-tab, multi-instance isolation+- **Profiles**: create, use, delete+- **Export**: screenshot (PNG/JPEG), PDF (portrait/landscape)+- **Downloads**: file download+- **Dynamic content**: JS-rendered, loading states+- **Form controls**: dropdowns, radio buttons, checkboxes+- **Frames**: iframe interaction+- **Dialogs**: alert, confirm, prompt+- **Error resilience**: invalid refs, missing elements, network errors+- **Performance**: timing baselines+- **Token efficiency**: output size comparisons+- **Challenge solving**: CAPTCHA/Cloudflare detection+- **Agent identity**: attribution and activity trackingdiff --git a/tests/benchmark/AGENT_TASKS.md b/tests/benchmark/AGENT_TASKS.mdnew file mode 100644index 00000000..43c2aeaf--- /dev/null+++ b/tests/benchmark/AGENT_TASKS.md@@ -0,0 +1,324 @@+# PinchTab Agent Benchmark++Natural language tasks to test how well an agent uses PinchTab from skill docs alone.++## Instructions++1. Read `../../skills/pinchtab/SKILL.md` — this is your only guide+2. For each task, figure out which commands to use+3. **Log every command executed**+4. Record: `./record-agent-step.sh <group> <step> <pass|fail> <in> <out> "commands" "notes"`++## Environment++- PinchTab: `http://localhost:9867`, token: `benchmark-token`+- Fixtures: `http://fixtures/` (running in Docker as `fixtures` hostname)+- Pages: `/`, `/wiki.html`, `/wiki-go.html`, `/articles.html`, `/search.html`,+ `/form.html`, `/dashboard.html`, `/ecommerce.html`, `/spa.html`, `/login.html`++---++## Group 0: Setup Verification++### 0.1 Confirm PinchTab is running+Check that the PinchTab server is healthy and a Chrome instance is active.++**Verify**: Server responds with `status: ok` and at least one running instance.++### 0.2 Navigate to fixtures and confirm reachable+Navigate to `http://fixtures/` and confirm the benchmark fixtures server is reachable.++**Verify**: Page title contains "Benchmark" or "PinchTab".++---++## Group 1: Reading & Extracting Real Content++### 1.1 Get the full list of categories from the wiki index+Navigate to `http://fixtures/wiki.html` and extract all category names with their article counts.++**Verify**: Can name at least 2 categories and their article counts (e.g. "Programming Languages: 12 articles").++### 1.2 Navigate by clicking a link+From the wiki index, click the "Go (programming language)" link to navigate to the Go article.++**Verify**: You are now on the Go article page (not the wiki index).++### 1.3 Extract structured data from a table+On the Go article, read the infobox table and answer: Who designed Go, and what year did it first appear?++**Verify**: Answer contains "Robert Griesemer" (or "Rob Pike" or "Ken Thompson") and "2009".++### 1.4 Count list items+On the Go article, count how many key features are listed.++**Verify**: Answer is 6 (verify against `FEATURE_COUNT_6`).++### 1.5 Read all article headlines from articles page+Navigate to `http://fixtures/articles.html` and list all article titles.++**Verify**: Found at least 3 articles including "The Future of Artificial Intelligence".++### 1.6 Read dashboard metrics+Navigate to `http://fixtures/dashboard.html` and extract: Total Users, Revenue, and Conversion Rate.++**Verify**: Found `24,582` users AND `$1,284,930` revenue.++---++## Group 2: Search & Dynamic Interaction++### 2.1 Use wiki search to find a page+On `http://fixtures/wiki.html`, search for "golang" using the search form. Do not navigate directly — use the search input.++**Verify**: Ended up on the Go article page after search.++### 2.2 Search with no results+On `http://fixtures/search.html`, search for something with no results (use "xyznonexistent").++**Verify**: Page handled it gracefully (no crash, some response rendered).++### 2.3 Search for AI content+On `http://fixtures/search.html`, search for "artificial intelligence" and verify a result appeared.++**Verify**: Result contains "The Future of Artificial Intelligence".++---++## Group 3: Complex Form++### 3.1 Fill and submit a complete form+Navigate to `http://fixtures/form.html`. Complete the entire form:+- Full name: "Agent Test User"+- Email: "[email protected]"+- Phone: "+44 20 9999 0000"+- Country: United Kingdom+- Subject: Technical Support+- Message: "Testing PinchTab form automation"+- Check newsletter+- Set priority to High+- Submit++**Verify**: Form submitted successfully. Confirmation shows name "AGENT_TEST_USER".++### 3.2 Reset and refill+After submitting, if the form is still accessible (or navigate back), verify you can identify the reset button.++**Verify**: Reset/back button or form element found in snapshot.++---++## Group 4: SPA State Management++### 4.1 Read initial app state+Navigate to `http://fixtures/spa.html` (always navigate fresh — do not reuse a cached page). Read the current task list — how many tasks exist, how many are active vs done?++**Verify**: Found 3 total, 2 active, 1 done (verify `TASK_STATS_TOTAL_3_ACTIVE_2_DONE_1`).++### 4.2 Add a new high-priority task+Add a task called "Automate deployment" with high priority.++**Verify**: Task appeared in the list (`TASK_ADDED_AUTOMATE_DEPLOYMENT_PRIORITY_HIGH`).++### 4.3 Delete a task+Delete the first existing task ("Write benchmark tests").++**Verify**: Task count changed (went from 4 to 3).++---++## Group 5: Login Flow++### 5.1 Attempt login with wrong credentials+Navigate to `http://fixtures/login.html`. Try to log in with username "admin" and password "wrong".++**Verify**: Error message appeared (`INVALID_CREDENTIALS_ERROR`).++### 5.2 Login successfully+Clear the form and log in with username "benchmark" / password "test456".++**Verify**: Dashboard appeared after login (`VERIFY_LOGIN_SUCCESS_DASHBOARD`).++---++## Group 6: Multi-Step E-commerce++### 6.1 Research products before buying+Navigate to `http://fixtures/ecommerce.html`. List all available products with their prices. Which product is out of stock?++**Verify**: Found Wireless Headphones ($149.99), Smart Watch Pro ($299.99), Portable Charger ($49.99). Mechanical Keyboard is out of stock.++### 6.2 Add two items and verify total+Add Wireless Headphones and Smart Watch Pro to cart. What is the total?++**Verify**: Cart total is $449.98 (149.99 + 299.99).++### 6.3 Complete checkout+Click checkout to complete the order.++**Verify**: Order confirmation shows (`VERIFY_CHECKOUT_SUCCESS_ORDER`).++---++## Group 7: Content + Interaction Combined++### 7.1 Read and comment on Go article+Navigate to `http://fixtures/wiki-go.html`. Read the article, then post a comment with rating 5 stars and text "Excellent reference".++**Verify**: Comment posted (`COMMENT_POSTED_RATING_5_TEXT_RECEIVED`).++### 7.2 Cross-page research task+Navigate to wiki index, find which category has the most articles, then navigate to one of its listed items.++**Verify**: Successfully navigated to at least one article page after reading the category counts.++---++## Group 8: Error Handling++### 8.1 Handle 404 gracefully+Try to navigate to a page that doesn't exist: `http://fixtures/missing-page-abc.html`.++**Verify**: Got a response (404 or error), no crash, server still responsive after.++### 8.2 Handle missing element gracefully+On any page, try to click an element with ID `#fake-button-that-does-not-exist`.++**Verify**: Got a clear error message, not a crash or hang.++---++## Group 9: Export++### 9.1 Screenshot a complex page+Navigate to `http://fixtures/dashboard.html` and take a screenshot.++**Verify**: Screenshot generated (file saved or base64 returned).++### 9.2 Export a page as PDF+Export the dashboard as a PDF.++**Verify**: PDF generated.++---++## Group 10: Nested Interactions & Modal Dialogs++### 10.1 Open and interact with modal on dashboard+Navigate to `http://fixtures/dashboard.html`. Find and click the Settings button (selector: `#settings-btn`) to open the modal dialog.++**Verify**: Modal appeared — snapshot contains "Dashboard Settings".++### 10.2 Modify settings and close modal+In the modal, select "Dark" from the theme dropdown (`#theme-select`), then click the Save button (`#modal-save`). After the modal closes, check the page content.++**Verify**: Page contains `THEME_DARK_APPLIED`.++---++## Group 11: State Persistence & Page Reload++### 11.1 Add an item and verify after page reload+Navigate to `http://fixtures/spa.html`. Add a task titled exactly "Persistent Task Test". Then reload by navigating to `http://fixtures/spa.html` again.++**Verify**: After reload, the task still appears in the list (`TASK_PERSISTENT_TEST_FOUND_AFTER_RELOAD`).++### 11.2 Logout and log back in+From the logged-in dashboard, click Sign Out to log out. Then log in again with username "benchmark" / password "test456".++**Verify**: Successfully logged back in and dashboard shows `SESSION_RENEWED`.++---++## Group 12: Multi-Page Navigation & Back Button++### 12.1 Navigate through multiple pages and return+Starting from `http://fixtures/`, navigate to wiki → Go article → back to wiki → back to home.++**Verify**: Successfully returned to home page (title contains "Benchmark" or "Home").++### 12.2 Compare data across pages+Navigate to wiki.html, note the total article count from categories. Navigate to articles.html, count articles there. Compare totals.++**Verify**: Can report totals from both pages and explain difference (`COMPARISON_DATA_FOUND`).++---++## Group 13: Form State & Multi-Step Submission++### 13.1 Submit form without email+Navigate to `http://fixtures/form.html`. Fill only the name field ("Validator Test"), leave email blank, click Submit. The browser's native required-field validation will prevent submission.++**Verify**: Submission blocked (form stays open, no success message shown).++### 13.2 Submit form without optional phone field+Fill the form with: name "No Phone User", email "[email protected]", country "de", subject "feedback". Leave the phone field empty. Submit.++**Verify**: Submission succeeded and page shows `OPTIONAL_FIELD_SKIPPED_SUCCESS`.++---++## Group 14: Dynamic Content Loading++### 14.1 Load more products+Navigate to `http://fixtures/ecommerce.html`. Find and click the "Load More Products" button to reveal additional products.++**Verify**: Additional products appeared (`ADDITIONAL_PRODUCTS_LOADED`).++### 14.2 Add a lazy-loaded product to cart+After loading more products, add product #5 (USB-C Cable) to the cart.++**Verify**: Cart shows the lazy-loaded item (`CART_UPDATED_WITH_LAZY_PRODUCT`).++---++## Group 15: Complex Data Extraction & Aggregation++### 15.1 Extract and sum financial data+Navigate to `http://fixtures/dashboard.html`. Extract revenue and profit values, calculate profit margin.++**Verify**: Correctly calculated: profit_margin = (profit / revenue) * 100 (`PROFIT_MARGIN_CALCULATED`).++### 15.2 Build comparison table from multiple sources+Visit these 3 pages and compare their feature counts and key features:+- `http://fixtures/wiki-go.html` (Go: 6 features)+- `http://fixtures/wiki-python.html` (Python: 7 features)+- `http://fixtures/wiki-rust.html` (Rust: 5 features)++Report which language has the most features and name 1 feature unique to each.++**Verify**: Response is factually correct AND wiki-python.html contains `COMPARISON_TABLE_BUILT`.++---++## Summary++| Group | Tasks | Description |+|-------|-------|-------------|+| 0 | 2 | Setup Verification |+| 1 | 6 | Reading & Extracting Content |+| 2 | 3 | Search & Dynamic Interaction |+| 3 | 2 | Complex Form |+| 4 | 3 | SPA State Management |+| 5 | 2 | Login Flow |+| 6 | 3 | Multi-Step E-commerce |+| 7 | 2 | Content + Interaction Combined |+| 8 | 2 | Error Handling |+| 9 | 2 | Export |+| 10 | 2 | Nested Interactions & Modal Dialogs |+| 11 | 2 | State Persistence & Page Reload |+| 12 | 2 | Multi-Page Navigation & Back Button |+| 13 | 2 | Form State & Multi-Step Submission |+| 14 | 2 | Dynamic Content Loading |+| 15 | 2 | Complex Data Extraction & Aggregation |++**Total: 39 tasks** (expanded from 27)++## Key Differences from Baseline++The agent must:+- Choose between `/text`, `/snapshot`, `/action`, `/navigate` appropriately+- Decide when to use `filter=interactive` vs full snapshot+- Handle multi-step flows without step-by-step curl guidance+- Extract and interpret structured data (tables, lists, counts)+- Detect state changes after interactionsdiff --git a/tests/benchmark/BENCHMARK_TASKS.md b/tests/benchmark/BENCHMARK_TASKS.mdnew file mode 100644index 00000000..84de1491--- /dev/null+++ b/tests/benchmark/BENCHMARK_TASKS.md@@ -0,0 +1,714 @@+# PinchTab Benchmark Tasks++Reproducible benchmark tasks using controlled fixture pages with verifiable content.++## Environment++- **PinchTab Server**: `http://localhost:9867`+- **Fixtures Server**: `http://fixtures/`+- **Token**: `benchmark-token`+- **Auth Header**: `Authorization: Bearer benchmark-token`++## MANDATORY: Docker++```bash+cd ~/dev/pinchtab/tests/benchmark+docker compose up -d --build+# Wait for healthy: curl -sf -H "Authorization: Bearer benchmark-token" http://localhost:9867/health+```++## Recording++```bash+./record-step.sh <group> <step> <pass|fail> <in_tokens> <out_tokens> "notes"+```++**On failure, include in notes:**+- What was expected+- What was actually returned+- HTTP status code / error message++---++## Group 0: Setup & Configuration Verification++Verify the environment is correctly configured before running tests.++### 0.1 Load PinchTab skill+Read `../../skills/pinchtab/SKILL.md`.+```bash+./record-step.sh 0 1 pass <in> <out> "Skill loaded"+```+**Pass if**: Skill loaded successfully.++### 0.2 Verify PinchTab health+```bash+curl -sf http://localhost:9867/health \+ -H "Authorization: Bearer benchmark-token" | jq .+```+**Pass if**: `status == "ok"`, `authRequired == true`, `instances >= 1`.++### 0.3 Verify fixtures server+```bash+curl -sf http://localhost:9867/navigate \+ -X POST -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/"}' | jq .+```+**Pass if**: Response contains `"url": "http://fixtures/"`.++### 0.4 Verify Chrome instance running+```bash+curl -sf http://localhost:9867/health \+ -H "Authorization: Bearer benchmark-token" | jq '.defaultInstance.status'+```+**Pass if**: Value is `"running"`.++---++## Group 1: Navigation & Content Extraction++### 1.1 Navigate to fixtures home+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/"}'+```+**Pass if**: HTTP 200.++### 1.2 Verify home content via snapshot+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=1000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_HOME_LOADED_12345`.++### 1.3 Navigate to wiki index+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/wiki.html"}'+```+**Pass if**: HTTP 200.++### 1.4 Verify wiki content and count categories+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=1500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_WIKI_INDEX_55555` AND `COUNT_LANGUAGES_12` AND `COUNT_TOOLS_15`.++### 1.5 Click through to Go article+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#link-go","waitNav":true}'+```+**Pass if**: HTTP 200 with `{"success":true}`.++**Note**: Use `waitNav: true` when clicking a link that causes page navigation. Without it, PinchTab returns a 409 "navigation_changed" error to protect against unexpected navigation during form interactions.++### 1.6 Verify Go article loaded and extract key facts+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=2000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_WIKI_GO_LANG_88888` AND `Robert Griesemer` AND `2009` AND `FEATURE_COUNT_6`.++### 1.7 Extract specific table data (designer)+```bash+curl http://localhost:9867/text \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Text contains `Google LLC` AND `Ken Thompson`.++### 1.8 Navigate to articles and extract all headlines+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/articles.html"}'++curl "http://localhost:9867/snapshot?format=compact&maxTokens=2000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Snapshot contains all 3 article titles: `The Future of Artificial Intelligence`, `Climate Action in 2026`, `Mars Colony`.++---++## Group 2: Search & Dynamic Content++### 2.1 Navigate to wiki search+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/wiki.html"}'+```+**Pass if**: HTTP 200.++### 2.2 Get snapshot to find search input ref+```bash+curl "http://localhost:9867/snapshot?filter=interactive&format=compact" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains search input element. Note the ref.++### 2.3 Fill search query+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#wiki-search-input","text":"golang"}'+```+**Pass if**: HTTP 200.++### 2.4 Submit search+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#wiki-search-btn"}'+```+**Pass if**: HTTP 200.++### 2.5 Verify navigation to Go article+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=2000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_WIKI_GO_LANG_88888` (search redirected to Go page).++### 2.6 Search for something with no results+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/search.html"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#search-input","text":"xyznonexistent"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#search-btn"}'+```+**Pass if**: HTTP 200 (graceful no-results state).++---++## Group 3: Complex Form Interaction++### 3.1 Navigate to contact form+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/form.html"}'+```+**Pass if**: HTTP 200.++### 3.2 Get snapshot of interactive elements+```bash+curl "http://localhost:9867/snapshot?filter=interactive&format=compact" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains all expected fields: fullname, email, country, subject, message.++### 3.3 Fill full name+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#fullname","text":"John Benchmark"}'+```+**Pass if**: HTTP 200.++### 3.4 Fill email+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#email","text":"[email protected]"}'+```+**Pass if**: HTTP 200.++### 3.5 Fill phone+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#phone","text":"+44 20 1234 5678"}'+```+**Pass if**: HTTP 200.++### 3.6 Select country+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"select","selector":"#country","value":"uk"}'+```+**Pass if**: HTTP 200.++### 3.7 Select subject+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"select","selector":"#subject","value":"support"}'+```+**Pass if**: HTTP 200.++### 3.8 Fill message textarea+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#message","text":"This is a benchmark test message for PinchTab automation."}'+```+**Pass if**: HTTP 200.++### 3.9 Check newsletter checkbox+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#newsletter"}'+```+**Pass if**: HTTP 200.++### 3.10 Select high priority radio+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"input[name=priority][value=high]"}'+```+**Pass if**: HTTP 200.++### 3.11 Submit form+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#submit-btn"}'+```+**Pass if**: HTTP 200.++### 3.12 Verify submission with data check+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=1000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_FORM_SUBMITTED_SUCCESS` AND `SUBMISSION_DATA_NAME_JOHN_BENCHMARK`.++---++## Group 4: SPA & Dynamic State++### 4.1 Navigate to task manager SPA+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/spa.html"}'+```+**Pass if**: HTTP 200.++### 4.2 Verify initial state+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=1500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_SPA_PAGE_99999` AND `TASK_STATS_TOTAL_3_ACTIVE_2_DONE_1`.++### 4.3 Add a new task+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#new-task-input","text":"Deploy to production"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"select","selector":"#priority-select","value":"high"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#add-task-btn"}'+```+**Pass if**: All HTTP 200.++### 4.4 Verify task was added+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=1500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `TASK_ADDED_DEPLOY_TO_PRODUCTION_PRIORITY_HIGH`.++### 4.5 Delete existing task+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":".delete-task[data-id=\"1\"]"}'+```+**Pass if**: HTTP 200.++### 4.6 Verify task count updated+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `3` in total count (started with 3, deleted 1, added 1 = 3).++---++## Group 5: Login & Auth Flow++### 5.1 Navigate to login page+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/login.html"}'+```+**Pass if**: HTTP 200.++### 5.2 Verify login page+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_LOGIN_PAGE_77777`.++### 5.3 Try invalid credentials+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#username","text":"baduser"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#password","text":"wrongpassword"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#login-btn"}'+```+**Pass if**: All HTTP 200.++### 5.4 Verify error shown+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `INVALID_CREDENTIALS_ERROR`.++### 5.5 Login with valid credentials+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#username","text":"benchmark"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#password","text":"test456"}'++curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#login-btn"}'+```+**Pass if**: All HTTP 200.++### 5.6 Verify logged in+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_LOGIN_SUCCESS_DASHBOARD` AND `SESSION_TOKEN_ACTIVE_TRUE`.++---++## Group 6: E-commerce Flow++### 6.1 Navigate to shop+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/ecommerce.html"}'+```+**Pass if**: HTTP 200.++### 6.2 Verify shop page and read prices+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=2000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_SHOP_PAGE_44444` AND `$149.99` AND `$299.99` AND `Out of Stock`.++### 6.3 Verify out-of-stock button is disabled+```bash+curl "http://localhost:9867/snapshot?filter=interactive&format=compact" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Mechanical Keyboard add-to-cart button is shown as disabled.++### 6.4 Add Wireless Headphones+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#product-1 .add-to-cart"}'+```+**Pass if**: HTTP 200.++### 6.5 Add Smart Watch+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#product-2 .add-to-cart"}'+```+**Pass if**: HTTP 200.++### 6.6 Verify cart total+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=1000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `CART_ITEM_WIRELESS_HEADPHONES` AND `CART_ITEM_SMART_WATCH_PRO` AND `449.98` (total).++### 6.7 Checkout+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#checkout-btn"}'+```+**Pass if**: HTTP 200.++### 6.8 Verify checkout complete+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_CHECKOUT_SUCCESS_ORDER` AND `ORDER_TOTAL_449_98`.++---++## Group 7: Wiki Article + Comment Flow++### 7.1 Navigate to Go article+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/wiki-go.html"}'+```+**Pass if**: HTTP 200.++### 7.2 Read and verify article facts+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=2000" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `VERIFY_WIKI_GO_LANG_88888` AND `BSD-style` AND `go.dev`.++### 7.3 Fill comment+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#comment-text","text":"Great article on Go! Very comprehensive."}'+```+**Pass if**: HTTP 200.++### 7.4 Rate the article+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"select","selector":"#comment-rating","value":"5"}'+```+**Pass if**: HTTP 200.++### 7.5 Submit comment+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#submit-comment"}'+```+**Pass if**: HTTP 200.++### 7.6 Verify comment posted+```bash+curl "http://localhost:9867/snapshot?format=compact&maxTokens=500" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Contains `COMMENT_POSTED_RATING_5_TEXT_RECEIVED`.++---++## Group 8: Error Handling++### 8.1 Navigate to non-existent page+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/nonexistent-page-xyz.html"}'+```+**Pass if**: Returns response without crash (404 or error).++### 8.2 Click non-existent element+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","selector":"#element-that-does-not-exist"}'+```+**Pass if**: Error response with message (not crash).++### 8.3 Fill with invalid selector+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","selector":"#nonexistent-input","text":"test"}'+```+**Pass if**: Error response with message.++### 8.4 Invalid action kind+```bash+curl -X POST http://localhost:9867/action \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"kind":"teleport","selector":"#btn"}'+```+**Pass if**: Returns 400/422 error with clear message.++---++## Group 9: Screenshot & Export++### 9.1 Navigate to dashboard+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/dashboard.html"}'+```+**Pass if**: HTTP 200.++### 9.2 Take screenshot+```bash+curl http://localhost:9867/screenshot \+ -H "Authorization: Bearer benchmark-token" \+ --output /tmp/benchmark-screenshot.png+```+**Pass if**: File created, size > 10KB.++### 9.3 Verify screenshot has content+```bash+ls -la /tmp/benchmark-screenshot.png+```+**Pass if**: File exists and size > 10240 bytes.++### 9.4 Export PDF+```bash+curl -X POST http://localhost:9867/pdf \+ -H "Authorization: Bearer benchmark-token" \+ --output /tmp/benchmark-dashboard.pdf+```+**Pass if**: File created, size > 10KB.++---++## Group 10: Agent Identity++### 10.1 Navigate as agent alpha+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "X-Agent-Id: bench-alpha" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/wiki.html"}'+```+**Pass if**: HTTP 200.++### 10.2 Navigate as agent beta+```bash+curl -X POST http://localhost:9867/navigate \+ -H "Authorization: Bearer benchmark-token" \+ -H "X-Agent-Id: bench-beta" \+ -H "Content-Type: application/json" \+ -d '{"url":"http://fixtures/dashboard.html"}'+```+**Pass if**: HTTP 200.++### 10.3 Check alpha activity+```bash+curl "http://localhost:9867/api/activity?agentId=bench-alpha" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Response contains activity for `bench-alpha`.++### 10.4 Check beta activity+```bash+curl "http://localhost:9867/api/activity?agentId=bench-beta" \+ -H "Authorization: Bearer benchmark-token"+```+**Pass if**: Response contains activity for `bench-beta`.++---++## Summary++| Group | Steps | Description |+|-------|-------|-------------|+| 0 | 4 | Setup & Configuration |+| 1 | 8 | Navigation & Content Extraction |+| 2 | 6 | Search & Dynamic Content |+| 3 | 12 | Complex Form Interaction |+| 4 | 6 | SPA & Dynamic State |+| 5 | 6 | Login & Auth Flow |+| 6 | 8 | E-commerce Flow |+| 7 | 6 | Wiki Article + Comment |+| 8 | 4 | Error Handling |+| 9 | 4 | Screenshot & Export |+| 10 | 4 | Agent Identity |++**Total: 68 steps**++## Verification Strings++| Page | String |+|------|--------|+| Home | `VERIFY_HOME_LOADED_12345` |+| Articles | `VERIFY_ARTICLES_PAGE_67890` |+| Search | `VERIFY_SEARCH_PAGE_11111` |+| Form | `VERIFY_FORM_PAGE_22222` |+| Dashboard | `VERIFY_DASHBOARD_PAGE_33333` |+| Shop | `VERIFY_SHOP_PAGE_44444` |+| Wiki Index | `VERIFY_WIKI_INDEX_55555` |+| Login | `VERIFY_LOGIN_PAGE_77777` |+| Go Article | `VERIFY_WIKI_GO_LANG_88888` |+| SPA | `VERIFY_SPA_PAGE_99999` |diff --git a/tests/benchmark/CRON_TASK.md b/tests/benchmark/CRON_TASK.mdnew file mode 100644index 00000000..d165e42e--- /dev/null+++ b/tests/benchmark/CRON_TASK.md@@ -0,0 +1,118 @@+# PinchTab Optimization Cron Task++**Goal: Close the gap between baseline (explicit curl) and agent (natural language).**++Every run must bring the agent closer to 100%. If already at 100%, expand tests.++---++## Task for Agent++### Step 1 — Setup+```bash+cd ~/dev/pinchtab/tests/benchmark+git checkout feat/benchmark && git pull --rebase origin feat/benchmark+./run-optimization.sh+# Note the TIMESTAMP from output+```++### Step 2 — Run Baseline Benchmark+Execute BENCHMARK_TASKS.md exactly as written.+- Token: `benchmark-token`+- Record each step: `./record-step.sh <group> <step> <pass|fail> <in> <out> "notes"`+- For failures: include HTTP status, expected string, actual response in notes++### Step 3 — Run Agent Benchmark+Execute AGENT_TASKS.md using SKILL.md as your only guide.+- **Do NOT look at BENCHMARK_TASKS.md**+- Figure out commands from skill documentation+- Record: `./record-agent-step.sh <group> <step> <pass|fail> <in> <out> "commands used" "result"`+- Log every curl/command executed++### Step 4 — Gap Analysis+Compare results and classify each agent failure:++| Failure Type | Cause | Fix |+|---|---|---|+| **Wrong endpoint** | Agent used `/text` when should use `/snapshot` | Improve SKILL.md |+| **Wrong selector** | Agent guessed selector incorrectly | Improve SKILL.md or fixture |+| **Missing step** | Agent skipped a required action | Clarify AGENT_TASKS.md |+| **Wrong URL** | Agent used wrong fixture path | Clarify AGENT_TASKS.md |+| **API bug** | Endpoint behaves unexpectedly | Fix PinchTab code |+| **Test ambiguity** | Verification string hard to find | Fix fixture or test |++### Step 5 — Make Exactly 1 Change++Priority order:+1. **API Bug** → Fix PinchTab Go code, commit as `fix: <description>`+2. **Skill Gap** → Improve SKILL.md with clearer guidance or example, commit as `docs(skill): <description>`+3. **Test Ambiguity** → Fix fixture HTML or BENCHMARK_TASKS.md verification, commit as `test: <description>`+4. **Agent Task Clarity** → Improve AGENT_TASKS.md phrasing, commit as `test(agent): <description>`+5. **No Gaps Found** → Add 2-3 new test cases covering uncovered scenarios, commit as `test: add cases for <scenario>`++**If agent is already at 100%**: Add harder cases (nested interactions, state persistence, multi-page flows).++### Step 6 — Verify the Fix Makes Sense+Before committing, ask: "Will this change help the agent pick the right tool next time?"+- If you fixed a skill doc: check that the added text directly addresses the failure+- If you fixed a test: check the verification string is reachable via snapshot++### Step 7 — Commit & Push+```bash+cd ~/dev/pinchtab+git add -A+git commit -m "<type>: <clear description of what changed and why>"+git push origin feat/benchmark+```++### Step 8 — Log the Run+Append to `results/optimization_log.md`:++```markdown+## Run #N — YYYY-MM-DD HH:MM++**Results:**+- Baseline: X/Y (Z%)+- Agent: X/Y (Z%)+- Gap: N steps++**Agent Failures:**+- Step X.Y: [failure type] — [what went wrong]+- Step X.Y: [failure type] — [what went wrong]++**Root Cause:**+[One clear sentence explaining the pattern]++**Change Made:**+- Type: api|skill|test|agent-task+- Description: [What changed]+- Expected impact: [Why this should close the gap]+- Commit: [hash]++**Next Focus:**+[What to watch in the next run]+```++### Step 9 — Report to User+Send a concise update:+```+Run #N complete+Baseline: X% | Agent: Y% | Gap: N steps+Failure: [brief description]+Fix: [what changed] ([commit])+```++---++## Success Criteria++- **Short term**: Agent pass rate ≥ 95%+- **Long term**: Agent matches baseline on all existing tests+- **Ongoing**: When gap closes, increase test complexity++## What NOT to do++- ❌ Don't make multiple changes per run — one focused fix only+- ❌ Don't skip the analysis step — root cause first, then fix+- ❌ Don't change tests just to make them easier — the goal is better skill/API+- ❌ Don't commit if the change doesn't directly address an observed failurediff --git a/tests/benchmark/OPTIMIZATION_LOOP.md b/tests/benchmark/OPTIMIZATION_LOOP.mdnew file mode 100644index 00000000..a46566cc--- /dev/null+++ b/tests/benchmark/OPTIMIZATION_LOOP.md@@ -0,0 +1,83 @@+# PinchTab Auto-Optimization Loop++Automated improvement cycle that runs every 25 minutes.++## Loop Steps++```+┌─────────────────────────────────────────────────────────────┐+│ 1. RUN BENCHMARKS │+│ - Baseline (explicit curl commands) │+│ - Agent (natural language tasks) │+└─────────────────────────────────────────────────────────────┘+ ↓+┌─────────────────────────────────────────────────────────────┐+│ 2. ANALYZE DIFFERENCES │+│ - Compare pass rates │+│ - Identify step failures │+│ - Find patterns (text vs snapshot, selectors, etc.) │+└─────────────────────────────────────────────────────────────┘+ ↓+┌─────────────────────────────────────────────────────────────┐+│ 3. PROPOSE 1 IMPROVEMENT │+│ Priority order: │+│ a) Fix PinchTab CLI/REST bug if found │+│ b) Improve skill documentation if agent confused │+│ c) Add verification to existing test case │+│ d) Add new test case for uncovered scenario │+└─────────────────────────────────────────────────────────────┘+ ↓+┌─────────────────────────────────────────────────────────────┐+│ 4. IMPLEMENT & COMMIT │+│ - Make the change │+│ - Commit with descriptive message │+│ - Push to feat/benchmark branch │+└─────────────────────────────────────────────────────────────┘+ ↓+┌─────────────────────────────────────────────────────────────┐+│ 5. LOG RUN │+│ - Append to optimization_log.md │+│ - Record: timestamp, pass rates, change made │+└─────────────────────────────────────────────────────────────┘+ ↓+ [Wait 25 minutes]+ ↓+ [Repeat]+```++## Improvement Priority++1. **API/CLI Bug** — If a curl command returns unexpected error, investigate PinchTab code+2. **Skill Gap** — If agent uses wrong endpoint/approach, improve SKILL.md documentation+3. **Benchmark Gap** — If tests don't verify important behavior, add verification+4. **Coverage Gap** — If common scenarios aren't tested, add test cases++## Log Format++Each run appends to `results/optimization_log.md`:++```markdown+## Run #N — YYYY-MM-DD HH:MM++**Results:**+- Baseline: X/Y (Z%)+- Agent: X/Y (Z%)++**Analysis:**+- [What differed between runs]+- [Root cause identified]++**Change Made:**+- [Type: api|skill|benchmark]+- [Description]+- [Commit: abc1234]++**Next Focus:**+- [What to look at next run]+```++## Files++- `run-optimization.sh` — Main loop script+- `results/optimization_log.md` — Run history+- All changes committed to `feat/benchmark` branchdiff --git a/tests/benchmark/README.md b/tests/benchmark/README.mdnew file mode 100644index 00000000..5e770eb4--- /dev/null+++ b/tests/benchmark/README.md@@ -0,0 +1,131 @@+# PinchTab Agent Benchmark++Structured benchmarks to measure AI agent performance with PinchTab browser automation.++## Quick Start++```bash+# 1. Start Docker + spawn subagent benchmark+./run-agent-benchmark.sh++# Or manually:+./run-benchmark.sh # Start Docker (REQUIRED)+# Then run tasks from ../../skills/pinchtab/SKILL.md+./finalize-report.sh # Generate report+```++## MANDATORY: Docker Environment++**The benchmark MUST run against Docker.** Do not use a local pinchtab server.++Reasons:+- Reproducible: Same environment every run+- Clean state: No leftover profiles, instances, or sessions+- Latest build: Builds from current source+- Isolated: No interference from local config++If Docker build fails or is skipped, the benchmark is **INVALID**.++## Files++| File | Purpose |+|------|---------|+| `../../skills/pinchtab/SKILL.md` | PinchTab skill (same as shipped product) |+| `BENCHMARK_TASKS.md` | Standalone task list (same as skill) |+| `AGENT_SCRIPT.md` | Extended: 100+ comprehensive tasks |+| `run-agent-benchmark.sh` | **Recommended**: Start Docker + spawn subagent |+| `run-benchmark.sh` | Start Docker environment only |+| `record-step.sh` | Record step results with token counts |+| `finalize-report.sh` | Generate final summary report |+| `config/pinchtab.json` | PinchTab configuration |+| `docker-compose.yml` | Docker environment definition |+| `results/` | Output directory for reports |++## Subagent Execution++The benchmark is designed to run in a **fresh subagent with clean context**:++1. Subagent loads `skill/SKILL.md` (this is the skill loading cost)+2. Step 0.1 records the skill loading overhead+3. Steps 1.x - 8.x execute actual benchmark tasks+4. Each step records input/output tokens++This measures the **real cost** of using PinchTab with an agent, including:+- Skill/context loading overhead+- Per-task token usage+- Total benchmark cost++## Environment++The benchmark runs PinchTab in Docker with:++- **Port**: 9867+- **Token**: `benchmark-token`+- **Stealth**: Full (for protected sites)+- **Headless**: Yes+- **Multi-instance**: Enabled (2 instances)++## Token Tracking++Every step must track token usage:++```bash+./record-step.sh <group> <step> <pass|fail|skip> <input_tokens> <output_tokens> "notes"+```++Example:+```bash+./record-step.sh 1 1 pass 150 45 "Navigation completed in 1.2s"+./record-step.sh 2 3 fail 200 80 "Element not found"+```++Token counts should come from your model's API response:+- **Anthropic**: `usage.input_tokens`, `usage.output_tokens`+- **OpenAI**: `usage.prompt_tokens`, `usage.completion_tokens`+- **Gemini**: `usageMetadata.promptTokenCount`, `usageMetadata.candidatesTokenCount`++## Reports++Reports are generated in `results/`:++- `benchmark_YYYYMMDD_HHMMSS.json` - Raw JSON data+- `benchmark_YYYYMMDD_HHMMSS_summary.md` - Human-readable summary++### Example Summary++```+# PinchTab Benchmark Results++## Results+| Metric | Value |+|--------|-------|+| Steps Passed | 30 |+| Steps Failed | 2 |+| Pass Rate | 93.7% |++## Token Usage+| Metric | Value |+|--------|-------|+| Total Tokens | 4,523 |+| Estimated Cost | $0.0158 |+```++## Running Programmatically++For automated benchmarks, you can:++1. Parse `BENCHMARK_TASKS.md` for curl commands+2. Execute each command+3. Parse responses for pass/fail+4. Call `record-step.sh` with results+5. Run `finalize-report.sh`++## Reproducibility++For consistent results:++1. Always start with `./run-benchmark.sh` (fresh Docker)+2. Use the same model/temperature for comparisons+3. Run benchmarks at similar times (site load varies)+4. Record exact PinchTab version from `/version` endpoint+5. Clear browser state between full benchmark runsdiff --git a/tests/benchmark/config/pinchtab.json b/tests/benchmark/config/pinchtab.jsonnew file mode 100644index 00000000..2864beb6--- /dev/null+++ b/tests/benchmark/config/pinchtab.json@@ -0,0 +1,54 @@+{+ "server": {+ "bind": "0.0.0.0",+ "port": "9867",+ "token": "benchmark-token"+ },+ "instanceDefaults": {+ "maxTabs": 20,+ "stealthLevel": "light",+ "headless": true+ },+ "multiInstance": {+ "strategy": "always-on",+ "allocationPolicy": "fcfs",+ "poolSize": 2,+ "restart": {+ "maxRestarts": 10,+ "initBackoffSec": 2,+ "maxBackoffSec": 60,+ "stableAfterSec": 300+ }+ },+ "scheduler": {+ "enabled": true,+ "strategy": "fair-fifo",+ "maxQueueSize": 10,+ "maxPerAgent": 5,+ "maxInflight": 3,+ "workerCount": 2,+ "maxBatchSize": 5,+ "resultTTLSec": 300+ },+ "security": {+ "allowEvaluate": true,+ "allowDownload": true,+ "allowUpload": true,+ "allowClipboard": true,+ "idpi": {+ "enabled": true,+ "allowedDomains": [+ "fixtures",+ "localhost",+ "127.0.0.1",+ "::1",+ "172.18.0.2"+ ]+ }+ },+ "activity": {+ "enabled": true,+ "maxEvents": 10000,+ "retentionHours": 24+ }+}diff --git a/tests/benchmark/config/pinchtab.json.backup b/tests/benchmark/config/pinchtab.json.backupnew file mode 100644index 00000000..a360df9a--- /dev/null+++ b/tests/benchmark/config/pinchtab.json.backup@@ -0,0 +1,48 @@+{+ "server": {+ "bind": "0.0.0.0",+ "port": "9867",+ "token": "benchmark-token"+ },+ "instanceDefaults": {+ "maxTabs": 20,+ "stealthLevel": "full",+ "headless": true+ },+ "multiInstance": {+ "strategy": "always-on",+ "allocationPolicy": "fcfs",+ "poolSize": 2,+ "restart": {+ "maxRestarts": 10,+ "initBackoffSec": 2,+ "maxBackoffSec": 60,+ "stableAfterSec": 300+ }+ },+ "scheduler": {+ "enabled": true,+ "strategy": "fair-fifo",+ "maxQueueSize": 10,+ "maxPerAgent": 5,+ "maxInflight": 3,+ "workerCount": 2,+ "maxBatchSize": 5,+ "resultTTLSec": 300+ },+ "security": {+ "allowEvaluate": true,+ "allowDownload": true,+ "allowUpload": true,+ "allowClipboard": true,+ "idpi": {+ "enabled": true,+ "allowedDomains": ["fixtures", "localhost", "127.0.0.1", "::1", "172.18.0.2"]+ }+ },+ "activity": {+ "enabled": true,+ "maxEvents": 10000,+ "retentionHours": 24+ }+}diff --git a/tests/benchmark/docker-compose.yml b/tests/benchmark/docker-compose.ymlnew file mode 100644index 00000000..118c11af--- /dev/null+++ b/tests/benchmark/docker-compose.yml@@ -0,0 +1,45 @@+services:+ pinchtab:+ build:+ context: ../..+ dockerfile: Dockerfile+ environment:+ PINCHTAB_CONFIG: /data/benchmark-config/pinchtab.json+ volumes:+ - ./config/pinchtab.json:/fixture-config/pinchtab.json:ro+ command: ["/bin/sh", "-lc", "mkdir -p /data/benchmark-config && cp /fixture-config/pinchtab.json /data/benchmark-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]+ ports:+ - "9867:9867"+ shm_size: '2gb'+ dns:+ - 8.8.8.8+ - 1.1.1.1+ healthcheck:+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer benchmark-token' -q -O /dev/null http://localhost:9867/health"]+ interval: 3s+ timeout: 10s+ retries: 20+ start_period: 15s+ networks:+ - benchmark-net+ depends_on:+ fixtures:+ condition: service_healthy++ fixtures:+ image: nginx:alpine+ volumes:+ - ./fixtures:/usr/share/nginx/html:ro+ ports:+ - "8080:80"+ healthcheck:+ test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:80/"]+ interval: 2s+ timeout: 5s+ retries: 5+ networks:+ - benchmark-net++networks:+ benchmark-net:+ driver: bridgediff --git a/tests/benchmark/fixtures/articles.html b/tests/benchmark/fixtures/articles.htmlnew file mode 100644index 00000000..2aead730--- /dev/null+++ b/tests/benchmark/fixtures/articles.html@@ -0,0 +1,56 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Articles - PinchTab Benchmark</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/articles.html">Articles</a></nav>+ </header>+ <main>+ <h1>Article Library — VERIFY_ARTICLES_PAGE_67890</h1>++ <article id="article-1" class="article-card">+ <h2><a href="/article-ai.html">The Future of Artificial Intelligence</a></h2>+ <p class="meta">By Dr. Sarah Chen | Published: March 15, 2026 | <span class="read-time">8 min read</span></p>+ <p class="excerpt">Artificial intelligence continues to transform industries worldwide. From healthcare diagnostics to autonomous vehicles, AI systems are becoming increasingly sophisticated...</p>+ <span class="category">Technology</span>+ </article>++ <article id="article-2" class="article-card">+ <h2><a href="/article-climate.html">Climate Action in 2026: Progress and Challenges</a></h2>+ <p class="meta">By James Morrison | Published: March 10, 2026 | <span class="read-time">12 min read</span></p>+ <p class="excerpt">Global climate initiatives have accelerated significantly in the past year. Countries are implementing aggressive carbon reduction targets while investing in renewable energy infrastructure...</p>+ <span class="category">Environment</span>+ </article>++ <article id="article-3" class="article-card">+ <h2><a href="/article-space.html">Mars Colony: First Steps</a></h2>+ <p class="meta">By Elena Rodriguez | Published: March 5, 2026 | <span class="read-time">15 min read</span></p>+ <p class="excerpt">The first permanent human settlement on Mars marks a historic milestone for humanity. This comprehensive look at the colony covers everything from habitat design to daily life on the red planet...</p>+ <span class="category">Space</span>+ </article>++ <aside id="sidebar">+ <h3>Popular Tags</h3>+ <div class="tags">+ <a href="#" class="tag">AI</a>+ <a href="#" class="tag">Climate</a>+ <a href="#" class="tag">Space</a>+ <a href="#" class="tag">Technology</a>+ <a href="#" class="tag">Science</a>+ </div>+ <h3>Newsletter</h3>+ <form id="newsletter-form">+ <input type="email" id="newsletter-email" placeholder="[email protected]">+ <button type="submit" id="subscribe-btn">Subscribe</button>+ </form>+ </aside>+ </main>+ <footer>+ <p>Total Articles: 3 | Page 1 of 1</p>+ </footer>+</body>+</html>diff --git a/tests/benchmark/fixtures/dashboard.html b/tests/benchmark/fixtures/dashboard.htmlnew file mode 100644index 00000000..f9bbe5cf--- /dev/null+++ b/tests/benchmark/fixtures/dashboard.html@@ -0,0 +1,218 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Dashboard - PinchTab Benchmark</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/dashboard.html">Dashboard</a></nav>+ </header>+ <main>+ <h1>Analytics Dashboard — VERIFY_DASHBOARD_PAGE_33333</h1>++ <section id="metrics">+ <div class="metric-card" id="metric-users">+ <h3>Total Users</h3>+ <span class="value">24,582</span>+ <span class="change positive">+12.5%</span>+ </div>+ <div class="metric-card" id="metric-revenue">+ <h3>Revenue</h3>+ <span class="value">$1,284,930</span>+ <span class="change positive">+8.2%</span>+ </div>+ <div class="metric-card" id="metric-profit">+ <h3>Profit</h3>+ <span class="value">$384,930</span>+ <span class="change positive">+15.3%</span>+ </div>+ <div class="metric-card" id="metric-margin">+ <h3>Profit Margin</h3>+ <span class="value">29.95%</span>+ <span class="change positive">+2.1%</span>+ </div>+ <div class="metric-card" id="metric-orders">+ <h3>Orders</h3>+ <span class="value">3,847</span>+ <span class="change negative">-2.1%</span>+ </div>+ <div class="metric-card" id="metric-conversion">+ <h3>Conversion Rate</h3>+ <span class="value">4.28%</span>+ <span class="change positive">+0.3%</span>+ </div>+ </section>++ <section id="data-table">+ <h2>Recent Transactions</h2>+ <table id="transactions">+ <thead>+ <tr>+ <th>ID</th>+ <th>Customer</th>+ <th>Amount</th>+ <th>Status</th>+ <th>Date</th>+ </tr>+ </thead>+ <tbody>+ <tr id="row-1">+ <td>TXN-001</td>+ <td>Alice Johnson</td>+ <td>$245.00</td>+ <td class="status-completed">Completed</td>+ <td>2026-03-15</td>+ </tr>+ <tr id="row-2">+ <td>TXN-002</td>+ <td>Bob Smith</td>+ <td>$189.50</td>+ <td class="status-pending">Pending</td>+ <td>2026-03-15</td>+ </tr>+ <tr id="row-3">+ <td>TXN-003</td>+ <td>Carol Williams</td>+ <td>$567.25</td>+ <td class="status-completed">Completed</td>+ <td>2026-03-14</td>+ </tr>+ <tr id="row-4">+ <td>TXN-004</td>+ <td>David Brown</td>+ <td>$92.00</td>+ <td class="status-failed">Failed</td>+ <td>2026-03-14</td>+ </tr>+ <tr id="row-5">+ <td>TXN-005</td>+ <td>Eve Davis</td>+ <td>$1,234.99</td>+ <td class="status-completed">Completed</td>+ <td>2026-03-13</td>+ </tr>+ </tbody>+ </table>+ <p class="table-footer">TABLE_ROW_COUNT_5</p>+ </section>++ <section id="financial-data">+ <h2>Financial Analysis</h2>+ <div id="financial-metrics">+ <p><strong>Total Revenue:</strong> $1,284,930</p>+ <p><strong>Total Profit:</strong> $384,930</p>+ <p><strong>Profit Margin Calculation:</strong> (384,930 / 1,284,930) × 100 = 29.95%</p>+ <p id="profit-verification">PROFIT_MARGIN_CALCULATED</p>+ </div>+ </section>++ <section id="filters">+ <h2>Filter Data</h2>+ <div class="filter-controls">+ <select id="status-filter">+ <option value="all">All Statuses</option>+ <option value="completed">Completed</option>+ <option value="pending">Pending</option>+ <option value="failed">Failed</option>+ </select>+ <input type="date" id="date-from" value="2026-03-01">+ <input type="date" id="date-to" value="2026-03-15">+ <button id="apply-filter">Apply Filter</button>+ </div>+ <div id="filter-result"></div>+ </section>+ </main>+++ <button id="settings-btn">Settings</button>++ <!-- Modal Dialog -->+ <div id="settings-modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000;">+ <div id="modal-content" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); min-width: 300px;">+ <h2>Dashboard Settings</h2>+ <div id="theme-section">+ <label>Theme:</label>+ <select id="theme-select">+ <option value="light">Light Mode</option>+ <option value="dark">Dark Mode</option>+ <option value="auto">Auto</option>+ </select>+ </div>+ <div id="notifications-section" style="margin-top: 15px;">+ <label>+ <input type="checkbox" id="notifications-enable" checked>+ Enable Notifications+ </label>+ </div>+ <div id="refresh-section" style="margin-top: 15px;">+ <label>Auto-refresh (seconds):</label>+ <input type="number" id="refresh-interval" value="30" min="5" max="300">+ </div>+ <div style="margin-top: 20px;">+ <button id="modal-save">Save</button>+ <button id="modal-close">Cancel</button>+ </div>+ </div>+ </div>++ <script>+ // Load settings from localStorage+ function loadSettings() {+ const savedTheme = localStorage.getItem('dashboardTheme') || 'light';+ document.getElementById('theme-select').value = savedTheme;+ if (savedTheme === 'dark') {+ document.body.style.backgroundColor = '#333';+ document.body.style.color = '#fff';+ }+ }++ // Modal logic+ document.getElementById('settings-btn').addEventListener('click', function() {+ loadSettings();+ document.getElementById('settings-modal').style.display = 'block';+ });++ document.getElementById('modal-close').addEventListener('click', function() {+ document.getElementById('settings-modal').style.display = 'none';+ });++ document.getElementById('modal-save').addEventListener('click', function() {+ const theme = document.getElementById('theme-select').value;+ localStorage.setItem('dashboardTheme', theme);+ // Create or update theme indicator in the main page (visible after modal closes)+ let indicator = document.getElementById('theme-indicator');+ if (!indicator) {+ indicator = document.createElement('div');+ indicator.id = 'theme-indicator';+ document.body.appendChild(indicator);+ }+ if (theme === 'dark') {+ document.body.style.backgroundColor = '#333';+ document.body.style.color = '#fff';+ indicator.textContent = 'THEME_DARK_APPLIED';+ } else if (theme === 'light') {+ document.body.style.backgroundColor = '#fff';+ document.body.style.color = '#000';+ indicator.textContent = 'THEME_LIGHT_APPLIED';+ } else {+ indicator.textContent = 'THEME_AUTO_APPLIED';+ }+ document.getElementById('settings-modal').style.display = 'none';+ });++ document.getElementById('apply-filter').addEventListener('click', function() {+ const status = document.getElementById('status-filter').value;+ const dateFrom = document.getElementById('date-from').value;+ const dateTo = document.getElementById('date-to').value;+ document.getElementById('filter-result').innerHTML = `+ <p>FILTER_APPLIED_STATUS_${status.toUpperCase()}_FROM_${dateFrom}_TO_${dateTo}</p>+ `;+ });++ // Load settings on page load+ loadSettings();+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/ecommerce.html b/tests/benchmark/fixtures/ecommerce.htmlnew file mode 100644index 00000000..21767e15--- /dev/null+++ b/tests/benchmark/fixtures/ecommerce.html@@ -0,0 +1,151 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Shop - PinchTab Benchmark</title>+</head>+<body>+ <header>+ <nav>+ <a href="/">Home</a> | <a href="/ecommerce.html">Shop</a>+ <span id="cart-icon">🛒 Cart (<span id="cart-count">0</span>)</span>+ </nav>+ </header>+ <main>+ <h1>Product Catalog — VERIFY_SHOP_PAGE_44444</h1>++ <section id="products">+ <div class="product-card" id="product-1">+ <h3>Wireless Headphones</h3>+ <p class="price">$149.99</p>+ <p class="description">Premium noise-canceling wireless headphones with 30-hour battery life.</p>+ <p class="stock in-stock">In Stock (24 available)</p>+ <button class="add-to-cart" data-id="1" data-name="Wireless Headphones" data-price="149.99">Add to Cart</button>+ </div>++ <div class="product-card" id="product-2">+ <h3>Smart Watch Pro</h3>+ <p class="price">$299.99</p>+ <p class="description">Advanced fitness tracking, heart rate monitor, GPS, and 7-day battery.</p>+ <p class="stock in-stock">In Stock (12 available)</p>+ <button class="add-to-cart" data-id="2" data-name="Smart Watch Pro" data-price="299.99">Add to Cart</button>+ </div>++ <div class="product-card" id="product-3">+ <h3>Portable Charger 20000mAh</h3>+ <p class="price">$49.99</p>+ <p class="description">Fast-charging portable battery pack with USB-C and dual USB-A ports.</p>+ <p class="stock in-stock">In Stock (56 available)</p>+ <button class="add-to-cart" data-id="3" data-name="Portable Charger" data-price="49.99">Add to Cart</button>+ </div>++ <div class="product-card" id="product-4">+ <h3>Mechanical Keyboard</h3>+ <p class="price">$129.99</p>+ <p class="description">RGB backlit mechanical keyboard with Cherry MX switches.</p>+ <p class="stock out-of-stock">Out of Stock</p>+ <button class="add-to-cart" data-id="4" data-name="Mechanical Keyboard" data-price="129.99" disabled>Out of Stock</button>+ </div>+ </section>++ <section id="pagination-section">+ <button id="load-more-btn">Load More Products</button>+ <div id="more-products" style="display: none;">+ <div class="product-card" id="product-5">+ <h3>USB-C Cable (3 pack)</h3>+ <p class="price">$19.99</p>+ <p class="description">High-quality USB-C cables with fast charging capability.</p>+ <p class="stock in-stock">In Stock (100 available)</p>+ <button class="add-to-cart" data-id="5" data-name="USB-C Cable" data-price="19.99">Add to Cart</button>+ <span>ADDITIONAL_PRODUCTS_LOADED</span>+ </div>+ <div class="product-card" id="product-6">+ <h3>Screen Protector (2 pack)</h3>+ <p class="price">$14.99</p>+ <p class="description">Tempered glass screen protectors for smartphones.</p>+ <p class="stock in-stock">In Stock (75 available)</p>+ <button class="add-to-cart" data-id="6" data-name="Screen Protector" data-price="14.99">Add to Cart</button>+ </div>+ </div>+ </section>++ <section id="cart-section" style="display: none;">+ <h2>Shopping Cart</h2>+ <div id="cart-items"></div>+ <div id="cart-total">+ <strong>Total: $<span id="total-amount">0.00</span></strong>+ </div>+ <button id="checkout-btn">Proceed to Checkout</button>+ </section>++ <section id="checkout-section" style="display: none;">+ <h2>Checkout Complete!</h2>+ <p class="verification-text">VERIFY_CHECKOUT_SUCCESS_ORDER</p>+ <div id="order-summary"></div>+ </section>+ </main>++ <script>+ let cart = [];++ function attachAddToCartListeners() {+ document.querySelectorAll('.add-to-cart').forEach(btn => {+ btn.removeEventListener('click', addToCartHandler);+ btn.addEventListener('click', addToCartHandler);+ });+ }++ function addToCartHandler() {+ if (this.disabled) return;+ const item = {+ id: this.dataset.id,+ name: this.dataset.name,+ price: parseFloat(this.dataset.price)+ };+ cart.push(item);+ updateCart();+ }++ function updateCart() {+ document.getElementById('cart-count').textContent = cart.length;+ if (cart.length > 0) {+ document.getElementById('cart-section').style.display = 'block';+ const hasLazyItem = cart.some(item => parseInt(item.id) >= 5);+ const items = cart.map((item, i) => `+ <div class="cart-item" id="cart-item-${i}">+ <span>${item.name}</span>+ <span>$${item.price.toFixed(2)}</span>+ <span>CART_ITEM_${item.name.replace(/\s/g, '_').toUpperCase()}</span>+ </div>+ `).join('');+ document.getElementById('cart-items').innerHTML = items ++ (hasLazyItem ? '<p>CART_UPDATED_WITH_LAZY_PRODUCT</p>' : '');+ const total = cart.reduce((sum, item) => sum + item.price, 0);+ document.getElementById('total-amount').textContent = total.toFixed(2);+ }+ }++ document.getElementById('load-more-btn').addEventListener('click', function() {+ document.getElementById('more-products').style.display = 'block';+ this.style.display = 'none';+ attachAddToCartListeners();+ document.querySelector('#more-products .add-to-cart').addEventListener('click', addToCartHandler);+ });++ document.getElementById('checkout-btn').addEventListener('click', function() {+ const total = cart.reduce((sum, item) => sum + item.price, 0);+ document.getElementById('cart-section').style.display = 'none';+ document.getElementById('checkout-section').style.display = 'block';+ document.getElementById('order-summary').innerHTML = `+ <p>Order Total: $${total.toFixed(2)}</p>+ <p>Items: ${cart.length}</p>+ <p>ORDER_TOTAL_${total.toFixed(2).replace('.', '_')}</p>+ `;+ });++ // Attach listeners on load+ attachAddToCartListeners();+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/form.html b/tests/benchmark/fixtures/form.htmlnew file mode 100644index 00000000..e49a53c0--- /dev/null+++ b/tests/benchmark/fixtures/form.html@@ -0,0 +1,152 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Form - PinchTab Benchmark</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/form.html">Form</a></nav>+ </header>+ <main>+ <h1>Contact Form — VERIFY_FORM_PAGE_22222</h1>++ <form id="contact-form">+ <div class="form-group">+ <label for="fullname">Full Name:</label>+ <input type="text" id="fullname" name="fullname" required>+ </div>++ <div class="form-group">+ <label for="email">Email Address:</label>+ <input type="email" id="email" name="email" required>+ </div>++ <div class="form-group">+ <label for="phone">Phone Number:</label>+ <input type="tel" id="phone" name="phone">+ </div>++ <div class="form-group">+ <label for="country">Country:</label>+ <select id="country" name="country">+ <option value="">Select a country</option>+ <option value="us">United States</option>+ <option value="uk">United Kingdom</option>+ <option value="de">Germany</option>+ <option value="fr">France</option>+ <option value="it">Italy</option>+ <option value="jp">Japan</option>+ </select>+ </div>++ <div class="form-group">+ <label for="subject">Subject:</label>+ <select id="subject" name="subject">+ <option value="">Choose a subject</option>+ <option value="general">General Inquiry</option>+ <option value="support">Technical Support</option>+ <option value="sales">Sales Question</option>+ <option value="feedback">Feedback</option>+ </select>+ </div>++ <div class="form-group">+ <label for="message">Message:</label>+ <textarea id="message" name="message" rows="5"></textarea>+ </div>++ <div class="form-group">+ <label>+ <input type="checkbox" id="newsletter" name="newsletter">+ Subscribe to newsletter+ </label>+ </div>++ <div class="form-group">+ <label>Priority:</label>+ <label><input type="radio" name="priority" value="low"> Low</label>+ <label><input type="radio" name="priority" value="medium" checked> Medium</label>+ <label><input type="radio" name="priority" value="high"> High</label>+ </div>++ <div class="form-actions">+ <button type="submit" id="submit-btn">Submit Form</button>+ <button type="reset" id="reset-btn">Reset</button>+ </div>+ </form>++ <div id="form-errors" style="display: none; color: red; margin-bottom: 20px; border: 1px solid red; padding: 10px;">+ <h3>Validation Errors:</h3>+ <ul id="error-list"></ul>+ </div>++ <div id="form-result" style="display: none;">+ <h2>Form Submitted Successfully!</h2>+ <p class="verification-text">VERIFY_FORM_SUBMITTED_SUCCESS</p>+ <div id="submitted-data"></div>+ </div>+ </main>++ <script>+ document.getElementById('contact-form').addEventListener('submit', function(e) {+ e.preventDefault();+ const form = e.target;+ const errors = [];++ // Validation+ if (!form.fullname.value.trim()) {+ errors.push('Full Name is required');+ }+ if (!form.email.value.trim()) {+ errors.push('Email is required');+ } else if (!form.email.value.includes('@')) {+ errors.push('Email must be valid');+ }+ if (!form.country.value) {+ errors.push('Country is required');+ }+ if (!form.subject.value) {+ errors.push('Subject is required');+ }++ if (errors.length > 0) {+ // Show errors+ const errorList = document.getElementById('error-list');+ errorList.innerHTML = errors.map(e => `<li>${e}</li>`).join('');+ document.getElementById('form-errors').style.display = 'block';+ return;+ }++ // Hide errors if form is valid+ document.getElementById('form-errors').style.display = 'none';++ const data = {+ fullname: form.fullname.value,+ email: form.email.value,+ phone: form.phone.value,+ country: form.country.value,+ subject: form.subject.value,+ message: form.message.value,+ newsletter: form.newsletter.checked,+ priority: form.priority.value+ };++ document.getElementById('form-result').style.display = 'block';+ document.getElementById('submitted-data').innerHTML = `+ <ul>+ <li>Name: ${data.fullname.toUpperCase()}</li>+ <li>Email: ${data.email}</li>+ <li>Country: ${data.country}</li>+ <li>Subject: ${data.subject}</li>+ </ul>+ <p>SUBMISSION_DATA_NAME_${data.fullname.replace(/\s/g, '_').toUpperCase()}</p>+ <p>FORM_VALIDATION_THEN_SUCCESS</p>+ ${!data.phone ? '<p>OPTIONAL_FIELD_SKIPPED_SUCCESS</p>' : ''}+ `;+ form.style.display = 'none';+ });+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/index.html b/tests/benchmark/fixtures/index.htmlnew file mode 100644index 00000000..d81080de--- /dev/null+++ b/tests/benchmark/fixtures/index.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>PinchTab Benchmark - Home</title>+</head>+<body>+ <header>+ <h1>PinchTab Benchmark Suite</h1>+ <nav>+ <a href="/articles.html" id="nav-articles">Articles</a>+ <a href="/search.html" id="nav-search">Search</a>+ <a href="/form.html" id="nav-form">Form</a>+ <a href="/dashboard.html" id="nav-dashboard">Dashboard</a>+ <a href="/ecommerce.html" id="nav-shop">Shop</a>+ </nav>+ </header>+ <main>+ <section id="hero">+ <h2>Welcome to the Benchmark Test Suite</h2>+ <p>This site contains controlled test pages for verifying browser automation accuracy. VERIFY_HOME_LOADED_12345</p>+ </section>+ <section id="quick-links">+ <h3>Test Categories</h3>+ <ul>+ <li><a href="/articles.html">Article Reading</a> - Long-form content extraction</li>+ <li><a href="/search.html">Search Flow</a> - Query input and results</li>+ <li><a href="/form.html">Form Interaction</a> - Input, select, checkbox, submit</li>+ <li><a href="/dashboard.html">Dashboard</a> - Dynamic data, tables, charts</li>+ <li><a href="/ecommerce.html">E-commerce</a> - Product listing, cart, checkout</li>+ </ul>+ </section>+ </main>+ <footer>+ <p>Benchmark Fixtures v1.0 | <span id="timestamp"></span></p>+ </footer>+ <script>+ document.getElementById('timestamp').textContent = new Date().toISOString();+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/login.html b/tests/benchmark/fixtures/login.htmlnew file mode 100644index 00000000..eefc52f7--- /dev/null+++ b/tests/benchmark/fixtures/login.html@@ -0,0 +1,61 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Login — PinchTab Benchmark</title>+</head>+<body>+ <main id="login-page">+ <h1>Sign In — VERIFY_LOGIN_PAGE_77777</h1>+ <form id="login-form">+ <div>+ <label for="username">Username</label>+ <input type="text" id="username" name="username" autocomplete="username">+ </div>+ <div>+ <label for="password">Password</label>+ <input type="password" id="password" name="password" autocomplete="current-password">+ </div>+ <div>+ <label><input type="checkbox" id="remember-me"> Remember me</label>+ </div>+ <button type="submit" id="login-btn">Sign In</button>+ <p id="login-error" style="display:none;color:red">INVALID_CREDENTIALS_ERROR</p>+ </form>+ </main>++ <main id="dashboard-page" style="display:none">+ <h1>Welcome back — VERIFY_LOGIN_SUCCESS_DASHBOARD</h1>+ <p>Logged in as: <strong id="logged-user"></strong></p>+ <p>SESSION_TOKEN_ACTIVE_TRUE SESSION_RENEWED</p>+ <nav>+ <a href="/wiki.html">Encyclopedia</a>+ <a href="/spa.html">Task Manager</a>+ <a href="/dashboard.html">Analytics</a>+ </nav>+ <button id="logout-btn">Sign Out</button>+ </main>++ <script>+ const VALID = { 'admin': 'password123', 'benchmark': 'test456', 'luigi': 'secret789' };++ document.getElementById('login-form').addEventListener('submit', function(e) {+ e.preventDefault();+ const user = document.getElementById('username').value;+ const pass = document.getElementById('password').value;+ if (VALID[user] && VALID[user] === pass) {+ document.getElementById('login-page').style.display = 'none';+ document.getElementById('dashboard-page').style.display = 'block';+ document.getElementById('logged-user').textContent = user;+ } else {+ document.getElementById('login-error').style.display = 'block';+ }+ });++ document.getElementById('logout-btn').addEventListener('click', function() {+ document.getElementById('dashboard-page').style.display = 'none';+ document.getElementById('login-page').style.display = 'block';+ });+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/search.html b/tests/benchmark/fixtures/search.htmlnew file mode 100644index 00000000..123958ae--- /dev/null+++ b/tests/benchmark/fixtures/search.html@@ -0,0 +1,80 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Search - PinchTab Benchmark</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/search.html">Search</a></nav>+ </header>+ <main>+ <h1>Search — VERIFY_SEARCH_PAGE_11111</h1>++ <div id="search-box">+ <input type="text" id="search-input" placeholder="Search articles..." autocomplete="off">+ <button id="search-btn">Search</button>+ </div>++ <div id="results" style="display: none;">+ <h2>Search Results for: <span id="query-display"></span></h2>+ <div id="results-list"></div>+ </div>++ <div id="no-results" style="display: none;">+ <p>No results found for "<span id="no-results-query"></span>"</p>+ </div>+ </main>++ <script>+ const articles = [+ { title: "The Future of Artificial Intelligence", category: "Technology", keywords: ["ai", "artificial", "intelligence", "machine", "learning"] },+ { title: "Climate Action in 2026", category: "Environment", keywords: ["climate", "environment", "carbon", "renewable"] },+ { title: "Mars Colony: First Steps", category: "Space", keywords: ["mars", "space", "colony", "planet"] },+ { title: "Quantum Computing Breakthrough", category: "Technology", keywords: ["quantum", "computing", "technology"] },+ { title: "Ocean Conservation Efforts", category: "Environment", keywords: ["ocean", "marine", "conservation"] }+ ];++ function search(query) {+ query = query.toLowerCase();+ return articles.filter(a =>+ a.title.toLowerCase().includes(query) ||+ a.keywords.some(k => k.includes(query))+ );+ }++ document.getElementById('search-btn').addEventListener('click', performSearch);+ document.getElementById('search-input').addEventListener('keypress', function(e) {+ if (e.key === 'Enter') performSearch();+ });++ function performSearch() {+ const query = document.getElementById('search-input').value.trim();+ if (!query) return;++ const results = search(query);+ const resultsDiv = document.getElementById('results');+ const noResultsDiv = document.getElementById('no-results');+ const resultsList = document.getElementById('results-list');++ if (results.length > 0) {+ resultsDiv.style.display = 'block';+ noResultsDiv.style.display = 'none';+ document.getElementById('query-display').textContent = query;+ resultsList.innerHTML = results.map((r, i) => `+ <div class="result-item" id="result-${i+1}">+ <h3>${r.title}</h3>+ <span class="category">${r.category}</span>+ <p class="verification">RESULT_FOUND_${r.title.replace(/\s/g, '_').toUpperCase()}</p>+ </div>+ `).join('');+ } else {+ resultsDiv.style.display = 'none';+ noResultsDiv.style.display = 'block';+ document.getElementById('no-results-query').textContent = query;+ }+ }+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/spa.html b/tests/benchmark/fixtures/spa.htmlnew file mode 100644index 00000000..e226c07f--- /dev/null+++ b/tests/benchmark/fixtures/spa.html@@ -0,0 +1,147 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Task Manager — PinchTab Benchmark</title>+</head>+<body>+ <header>+ <h1>Task Manager — VERIFY_SPA_PAGE_99999</h1>+ <nav>+ <button id="tab-all" class="tab active" onclick="showTab('all')">All Tasks</button>+ <button id="tab-active" class="tab" onclick="showTab('active')">Active</button>+ <button id="tab-done" class="tab" onclick="showTab('done')">Completed</button>+ </nav>+ </header>+ <main>+ <section id="add-task-section">+ <input type="text" id="new-task-input" placeholder="Add a new task...">+ <select id="priority-select">+ <option value="low">Low Priority</option>+ <option value="medium" selected>Medium Priority</option>+ <option value="high">High Priority</option>+ </select>+ <button id="add-task-btn">Add Task</button>+ </section>++ <section id="task-list">+ <div id="tab-all-content">+ <h2>All Tasks (<span id="total-count">3</span>)</h2>+ <ul id="tasks">+ <li class="task-item" id="task-1" data-status="active" data-priority="high">+ <input type="checkbox" class="task-check">+ <span class="task-title">Write benchmark tests</span>+ <span class="task-priority">HIGH</span>+ <button class="delete-task" data-id="1">✕</button>+ </li>+ <li class="task-item" id="task-2" data-status="done" data-priority="medium">+ <input type="checkbox" class="task-check" checked>+ <span class="task-title">Set up Docker environment</span>+ <span class="task-priority">MEDIUM</span>+ <button class="delete-task" data-id="2">✕</button>+ </li>+ <li class="task-item" id="task-3" data-status="active" data-priority="low">+ <input type="checkbox" class="task-check">+ <span class="task-title">Review pull request</span>+ <span class="task-priority">LOW</span>+ <button class="delete-task" data-id="3">✕</button>+ </li>+ </ul>+ <p id="task-stats">TASK_STATS_TOTAL_3_ACTIVE_2_DONE_1</p>+ </div>+ </section>+ </main>+ <script>+ let taskCount = 3;+ let tasks = [];++ // Load tasks from localStorage on page load+ function loadTasks() {+ const saved = localStorage.getItem('tasks');+ if (saved) {+ tasks = JSON.parse(saved);+ taskCount = tasks.length;+ renderTasks();+ } else {+ // Initialize default tasks+ tasks = [+ { id: 1, title: 'Write benchmark tests', status: 'active', priority: 'high' },+ { id: 2, title: 'Set up Docker environment', status: 'done', priority: 'medium' },+ { id: 3, title: 'Review pull request', status: 'active', priority: 'low' }+ ];+ saveTasks();+ renderTasks();+ }+ }++ function saveTasks() {+ localStorage.setItem('tasks', JSON.stringify(tasks));+ }++ function renderTasks() {+ const tasksList = document.getElementById('tasks');+ tasksList.innerHTML = '';+ let activeCount = 0;+ let doneCount = 0;++ tasks.forEach(task => {+ if (task.status === 'active') activeCount++;+ if (task.status === 'done') doneCount++;++ const li = document.createElement('li');+ li.className = 'task-item';+ li.id = `task-${task.id}`;+ li.dataset.status = task.status;+ li.dataset.priority = task.priority;+ li.innerHTML = `+ <input type="checkbox" class="task-check" ${task.status === 'done' ? 'checked' : ''}>+ <span class="task-title">${task.title}</span>+ <span class="task-priority">${task.priority.toUpperCase()}</span>+ <button class="delete-task" data-id="${task.id}">✕</button>+ ${task.title.includes('Persistent') ? '<span>TASK_PERSISTENT_TEST_FOUND_AFTER_RELOAD</span>' : ''}+ `;+ tasksList.appendChild(li);+ });++ document.getElementById('total-count').textContent = tasks.length;+ document.getElementById('task-stats').textContent = `TASK_STATS_TOTAL_${tasks.length}_ACTIVE_${activeCount}_DONE_${doneCount}`;+ }++ document.getElementById('add-task-btn').addEventListener('click', function() {+ const title = document.getElementById('new-task-input').value.trim();+ const priority = document.getElementById('priority-select').value;+ if (!title) return;+ taskCount++;+ const newTask = { id: taskCount, title: title, status: 'active', priority: priority };+ tasks.push(newTask);+ saveTasks();+ renderTasks();+ document.getElementById('new-task-input').value = '';+ // Show verification span+ const taskEl = document.getElementById(`task-${taskCount}`);+ if (taskEl) {+ const span = document.createElement('span');+ span.textContent = `TASK_ADDED_${title.replace(/\s/g,'_').toUpperCase()}_PRIORITY_${priority.toUpperCase()}`;+ taskEl.appendChild(span);+ }+ });++ document.getElementById('tasks').addEventListener('click', function(e) {+ if (e.target.classList.contains('delete-task')) {+ const id = parseInt(e.target.dataset.id);+ tasks = tasks.filter(t => t.id !== id);+ saveTasks();+ renderTasks();+ }+ });++ function showTab(tab) {+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));+ document.getElementById(`tab-${tab}`).classList.add('active');+ }++ // Load tasks on page load+ loadTasks();+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/wiki-go.html b/tests/benchmark/fixtures/wiki-go.htmlnew file mode 100644index 00000000..7cc24f16--- /dev/null+++ b/tests/benchmark/fixtures/wiki-go.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Go Language — Encyclopedia</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/wiki.html">Encyclopedia</a> | Go Language</nav>+ </header>+ <main>+ <h1>Go (programming language) — VERIFY_WIKI_GO_LANG_88888</h1>++ <div id="infobox">+ <table>+ <tr><th>Paradigm</th><td id="paradigm">Compiled, concurrent, imperative, structured</td></tr>+ <tr><th>Designed by</th><td id="designers">Robert Griesemer, Rob Pike, Ken Thompson</td></tr>+ <tr><th>Developer</th><td id="developer">Google LLC</td></tr>+ <tr><th>First appeared</th><td id="first-appeared">2009</td></tr>+ <tr><th>Stable release</th><td id="stable-release">1.22 / February 2024</td></tr>+ <tr><th>Typing discipline</th><td id="typing">Static, strong, inferred, structural</td></tr>+ <tr><th>License</th><td id="license">BSD-style</td></tr>+ <tr><th>Website</th><td><a href="#" id="website-link">go.dev</a></td></tr>+ </table>+ </div>++ <section id="overview">+ <h2>Overview</h2>+ <p>Go is a statically typed, compiled high-level general-purpose programming language. It was designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson, and is open source.</p>+ <p>Go is syntactically similar to C, but also has memory safety, garbage collection, structural typing, and CSP-style concurrency. The language is often referred to as Golang because of its former domain name <strong>golang.org</strong>, but its proper name is Go.</p>+ </section>++ <section id="features">+ <h2>Key Features</h2>+ <ul id="feature-list">+ <li id="feature-1">Fast compilation</li>+ <li id="feature-2">Garbage collection</li>+ <li id="feature-3">Built-in concurrency (goroutines and channels)</li>+ <li id="feature-4">Static typing with type inference</li>+ <li id="feature-5">Single binary output</li>+ <li id="feature-6">Standard library</li>+ </ul>+ <p>FEATURE_COUNT_6</p>+ </section>++ <section id="usage">+ <h2>Common Use Cases</h2>+ <ul>+ <li>Cloud infrastructure (Docker, Kubernetes)</li>+ <li>Web services and APIs</li>+ <li>Command-line tools</li>+ <li>Network programming</li>+ </ul>+ </section>++ <section id="comments">+ <h2>Discussion</h2>+ <form id="comment-form">+ <textarea id="comment-text" placeholder="Add your comment..."></textarea>+ <select id="comment-rating">+ <option value="">Rate this article</option>+ <option value="5">★★★★★ Excellent</option>+ <option value="4">★★★★ Good</option>+ <option value="3">★★★ Average</option>+ <option value="2">★★ Poor</option>+ <option value="1">★ Terrible</option>+ </select>+ <button type="submit" id="submit-comment">Post Comment</button>+ </form>+ <div id="comment-result"></div>+ </section>+ </main>+ <script>+ document.getElementById('comment-form').addEventListener('submit', function(e) {+ e.preventDefault();+ const text = document.getElementById('comment-text').value;+ const rating = document.getElementById('comment-rating').value;+ document.getElementById('comment-result').innerHTML =+ `<p>COMMENT_POSTED_RATING_${rating}_TEXT_RECEIVED</p>`;+ });+ </script>+</body>+</html>diff --git a/tests/benchmark/fixtures/wiki-python.html b/tests/benchmark/fixtures/wiki-python.htmlnew file mode 100644index 00000000..085b855a--- /dev/null+++ b/tests/benchmark/fixtures/wiki-python.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Python — Encyclopedia</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/wiki.html">Encyclopedia</a> | Python</nav>+ </header>+ <main>+ <h1>Python (programming language) — VERIFY_WIKI_PYTHON_LANG</h1>++ <div id="infobox">+ <table>+ <tr><th>Paradigm</th><td id="paradigm">Multi-paradigm: object-oriented, procedural, functional</td></tr>+ <tr><th>Designed by</th><td id="designers">Guido van Rossum</td></tr>+ <tr><th>Developer</th><td id="developer">Python Software Foundation</td></tr>+ <tr><th>First appeared</th><td id="first-appeared">1991</td></tr>+ <tr><th>Stable release</th><td id="stable-release">3.12 / October 2023</td></tr>+ <tr><th>Typing discipline</th><td id="typing">Dynamic, strong, duck typing</td></tr>+ <tr><th>License</th><td id="license">PSF License</td></tr>+ <tr><th>Website</th><td><a href="#" id="website-link">python.org</a></td></tr>+ </table>+ </div>++ <section id="features">+ <h2>Key Features</h2>+ <ul id="feature-list">+ <li id="feature-1">Interpreted (not compiled)</li>+ <li id="feature-2">Garbage collection</li>+ <li id="feature-3">Dynamic typing</li>+ <li id="feature-4">Large standard library</li>+ <li id="feature-5">Extensive third-party packages (PyPI)</li>+ <li id="feature-6">Interactive REPL</li>+ <li id="feature-7">Cross-platform</li>+ </ul>+ <p>FEATURE_COUNT_7 COMPARISON_TABLE_BUILT</p>+ </section>++ <section id="usage">+ <h2>Common Use Cases</h2>+ <ul>+ <li>Data science and machine learning</li>+ <li>Web development (Django, Flask)</li>+ <li>Scripting and automation</li>+ <li>Scientific computing</li>+ </ul>+ </section>+ </main>+</body>+</html>diff --git a/tests/benchmark/fixtures/wiki-rust.html b/tests/benchmark/fixtures/wiki-rust.htmlnew file mode 100644index 00000000..43e98bed--- /dev/null+++ b/tests/benchmark/fixtures/wiki-rust.html@@ -0,0 +1,50 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Rust — Encyclopedia</title>+</head>+<body>+ <header>+ <nav><a href="/">Home</a> | <a href="/wiki.html">Encyclopedia</a> | Rust</nav>+ </header>+ <main>+ <h1>Rust (programming language) — VERIFY_WIKI_RUST_LANG</h1>++ <div id="infobox">+ <table>+ <tr><th>Paradigm</th><td id="paradigm">Multi-paradigm: concurrent, functional, imperative, structured</td></tr>+ <tr><th>Designed by</th><td id="designers">Graydon Hoare</td></tr>+ <tr><th>Developer</th><td id="developer">The Rust Foundation</td></tr>+ <tr><th>First appeared</th><td id="first-appeared">2010</td></tr>+ <tr><th>Stable release</th><td id="stable-release">1.75 / December 2023</td></tr>+ <tr><th>Typing discipline</th><td id="typing">Static, strong, inferred, linear (ownership)</td></tr>+ <tr><th>License</th><td id="license">MIT / Apache 2.0</td></tr>+ <tr><th>Website</th><td><a href="#" id="website-link">rust-lang.org</a></td></tr>+ </table>+ </div>++ <section id="features">+ <h2>Key Features</h2>+ <ul id="feature-list">+ <li id="feature-1">Memory safety without garbage collection</li>+ <li id="feature-2">Ownership system (borrow checker)</li>+ <li id="feature-3">Zero-cost abstractions</li>+ <li id="feature-4">Concurrency without data races</li>+ <li id="feature-5">Pattern matching</li>+ </ul>+ <p>FEATURE_COUNT_5</p>+ </section>++ <section id="usage">+ <h2>Common Use Cases</h2>+ <ul>+ <li>Systems programming</li>+ <li>WebAssembly</li>+ <li>Embedded systems</li>+ <li>Game engines</li>+ </ul>+ </section>+ </main>+</body>+</html>diff --git a/tests/benchmark/fixtures/wiki.html b/tests/benchmark/fixtures/wiki.htmlnew file mode 100644index 00000000..f791a2ec--- /dev/null+++ b/tests/benchmark/fixtures/wiki.html@@ -0,0 +1,68 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Encyclopedia — PinchTab Benchmark</title>+</head>+<body>+ <header>+ <nav>+ <a href="/">Home</a> |+ <a href="/wiki.html">Encyclopedia</a> |+ <a href="/wiki-go.html">Go Language</a> |+ <a href="/wiki-http.html">HTTP Protocol</a>+ </nav>+ <form id="wiki-search">+ <input type="text" id="wiki-search-input" placeholder="Search encyclopedia...">+ <button type="submit" id="wiki-search-btn">Search</button>+ </form>+ </header>+ <main>+ <h1>Encyclopedia — VERIFY_WIKI_INDEX_55555</h1>+ <p>A reference collection covering technology, science, and engineering.</p>++ <section id="featured">+ <h2>Featured Articles</h2>+ <ul>+ <li><a href="/wiki-go.html" id="link-go">Go (programming language)</a> — Compiled, statically typed, garbage-collected language from Google</li>+ <li><a href="/wiki-http.html" id="link-http">HTTP/2</a> — Binary protocol for web communication</li>+ <li><a href="/wiki-browser.html" id="link-browser">Browser Automation</a> — Techniques for programmatic browser control</li>+ </ul>+ </section>++ <section id="categories">+ <h2>Categories</h2>+ <div class="category" id="cat-languages">+ <h3>Programming Languages</h3>+ <p>COUNT_LANGUAGES_12 articles</p>+ <p class="data-marker">COMPARISON_DATA_FOUND</p>+ <a href="/wiki-go.html" id="link-go-lang">Go</a>, <a href="/wiki-python.html" id="link-python">Python</a>, <a href="/wiki-rust.html" id="link-rust">Rust</a>, TypeScript, Java, C+++ </div>+ <div class="category" id="cat-protocols">+ <h3>Network Protocols</h3>+ <p>COUNT_PROTOCOLS_8 articles</p>+ <a href="/wiki-http.html">HTTP</a>, WebSocket, gRPC, QUIC+ </div>+ <div class="category" id="cat-tools">+ <h3>Developer Tools</h3>+ <p>COUNT_TOOLS_15 articles</p>+ Browser automation, CI/CD, Package managers+ </div>+ </section>+ </main>+ <script>+ document.getElementById('wiki-search').addEventListener('submit', function(e) {+ e.preventDefault();+ const q = document.getElementById('wiki-search-input').value.toLowerCase();+ if (q.includes('go') || q.includes('golang')) {+ window.location.href = '/wiki-go.html';+ } else if (q.includes('http')) {+ window.location.href = '/wiki-http.html';+ } else {+ document.querySelector('main').insertAdjacentHTML('beforeend',+ `<p id="search-no-result">No results found for "${q}". SEARCH_MISS_RESULT</p>`);+ }+ });+ </script>+</body>+</html>diff --git a/tests/benchmark/scripts/record-agent-step.sh b/tests/benchmark/scripts/record-agent-step.shnew file mode 100755index 00000000..34def848--- /dev/null+++ b/tests/benchmark/scripts/record-agent-step.sh@@ -0,0 +1,100 @@+#!/bin/bash+#+# Record a benchmark step result+#+# Usage:+# ./record-step.sh <group> <step> <pass|fail|skip> <input_tokens> <output_tokens> [notes]+#+# Example:+# ./record-step.sh 1 1 pass 150 45 "Navigation completed"+# ./record-step.sh 2 3 fail 200 80 "Element not found"++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+RESULTS_DIR="${SCRIPT_DIR}/../results"++# Find most recent report file+REPORT_FILE=$(ls -t "${RESULTS_DIR}"/agent_benchmark_*.json 2>/dev/null | head -1)++if [[ -z "${REPORT_FILE}" ]]; then+ echo "ERROR: No benchmark report found. Run ./run-benchmark.sh first."+ exit 1+fi++if [[ $# -lt 5 ]]; then+ echo "Usage: $0 <group> <step> <pass|fail|skip> <input_tokens> <output_tokens> [notes]"+ exit 1+fi++GROUP="$1"+STEP="$2"+STATUS="$3"+INPUT_TOKENS="$4"+OUTPUT_TOKENS="$5"+NOTES="${6:-}"+TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)+TOTAL_TOKENS=$((INPUT_TOKENS + OUTPUT_TOKENS))++# Calculate cost based on model (from report)+MODEL=$(jq -r '.benchmark.model' "${REPORT_FILE}")+PROVIDER=$(jq -r '.benchmark.provider' "${REPORT_FILE}")++# Cost per 1M tokens+case "${MODEL}" in+ *haiku*) INPUT_RATE=0.25; OUTPUT_RATE=1.25 ;;+ *sonnet*) INPUT_RATE=3.0; OUTPUT_RATE=15.0 ;;+ *opus*) INPUT_RATE=15.0; OUTPUT_RATE=75.0 ;;+ *gpt-4o-mini*) INPUT_RATE=0.15; OUTPUT_RATE=0.60 ;;+ *gpt-4o*) INPUT_RATE=2.50; OUTPUT_RATE=10.0 ;;+ *gpt-4*) INPUT_RATE=10.0; OUTPUT_RATE=30.0 ;;+ *gemini*flash*) INPUT_RATE=0.075; OUTPUT_RATE=0.30 ;;+ *gemini*pro*) INPUT_RATE=1.25; OUTPUT_RATE=5.0 ;;+ *) INPUT_RATE=1.0; OUTPUT_RATE=3.0 ;;+esac++# Calculate cost (using bc for floating point)+COST=$(echo "scale=6; (${INPUT_TOKENS} / 1000000 * ${INPUT_RATE}) + (${OUTPUT_TOKENS} / 1000000 * ${OUTPUT_RATE})" | bc)++# Create step entry+STEP_JSON=$(cat << EOF+{+ "group": ${GROUP},+ "step": ${STEP},+ "id": "${GROUP}.${STEP}",+ "status": "${STATUS}",+ "input_tokens": ${INPUT_TOKENS},+ "output_tokens": ${OUTPUT_TOKENS},+ "total_tokens": ${TOTAL_TOKENS},+ "cost_usd": ${COST},+ "notes": "${NOTES}",+ "timestamp": "${TIMESTAMP}"+}+EOF+)++# Append to report+TMP_FILE=$(mktemp)+jq --argjson step "${STEP_JSON}" '.steps += [$step]' "${REPORT_FILE}" > "${TMP_FILE}"++# Update totals+jq --argjson in "${INPUT_TOKENS}" --argjson out "${OUTPUT_TOKENS}" --argjson cost "${COST}" \+ --arg status "${STATUS}" \+ '.totals.input_tokens += $in |+ .totals.output_tokens += $out |+ .totals.total_tokens += ($in + $out) |+ .totals.estimated_cost_usd += $cost |+ if $status == "pass" then .totals.steps_passed += 1+ elif $status == "fail" then .totals.steps_failed += 1+ else .totals.steps_skipped += 1 end' \+ "${TMP_FILE}" > "${REPORT_FILE}"++rm -f "${TMP_FILE}"++# If failed, also log to error log with details+if [[ "${STATUS}" == "fail" ]]; then+ ERROR_LOG="${RESULTS_DIR}/errors.log"+ echo "[${TIMESTAMP}] Step ${GROUP}.${STEP} FAILED: ${NOTES}" >> "${ERROR_LOG}"+fi++echo "Recorded: Step ${GROUP}.${STEP} = ${STATUS} (${TOTAL_TOKENS} tokens, \$${COST})"diff --git a/tests/benchmark/scripts/record-step.sh b/tests/benchmark/scripts/record-step.shnew file mode 100755index 00000000..4702da88--- /dev/null+++ b/tests/benchmark/scripts/record-step.sh@@ -0,0 +1,100 @@+#!/bin/bash+#+# Record a benchmark step result+#+# Usage:+# ./record-step.sh <group> <step> <pass|fail|skip> <input_tokens> <output_tokens> [notes]+#+# Example:+# ./record-step.sh 1 1 pass 150 45 "Navigation completed"+# ./record-step.sh 2 3 fail 200 80 "Element not found"++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+RESULTS_DIR="${SCRIPT_DIR}/../results"++# Find most recent report file+REPORT_FILE=$(ls -t "${RESULTS_DIR}"/baseline_*.json "${RESULTS_DIR}"/benchmark_*.json 2>/dev/null | head -1)++if [[ -z "${REPORT_FILE}" ]]; then+ echo "ERROR: No benchmark report found. Run ./run-benchmark.sh first."+ exit 1+fi++if [[ $# -lt 5 ]]; then+ echo "Usage: $0 <group> <step> <pass|fail|skip> <input_tokens> <output_tokens> [notes]"+ exit 1+fi++GROUP="$1"+STEP="$2"+STATUS="$3"+INPUT_TOKENS="$4"+OUTPUT_TOKENS="$5"+NOTES="${6:-}"+TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)+TOTAL_TOKENS=$((INPUT_TOKENS + OUTPUT_TOKENS))++# Calculate cost based on model (from report)+MODEL=$(jq -r '.benchmark.model' "${REPORT_FILE}")+PROVIDER=$(jq -r '.benchmark.provider' "${REPORT_FILE}")++# Cost per 1M tokens+case "${MODEL}" in+ *haiku*) INPUT_RATE=0.25; OUTPUT_RATE=1.25 ;;+ *sonnet*) INPUT_RATE=3.0; OUTPUT_RATE=15.0 ;;+ *opus*) INPUT_RATE=15.0; OUTPUT_RATE=75.0 ;;+ *gpt-4o-mini*) INPUT_RATE=0.15; OUTPUT_RATE=0.60 ;;+ *gpt-4o*) INPUT_RATE=2.50; OUTPUT_RATE=10.0 ;;+ *gpt-4*) INPUT_RATE=10.0; OUTPUT_RATE=30.0 ;;+ *gemini*flash*) INPUT_RATE=0.075; OUTPUT_RATE=0.30 ;;+ *gemini*pro*) INPUT_RATE=1.25; OUTPUT_RATE=5.0 ;;+ *) INPUT_RATE=1.0; OUTPUT_RATE=3.0 ;;+esac++# Calculate cost (using bc for floating point)+COST=$(echo "scale=6; (${INPUT_TOKENS} / 1000000 * ${INPUT_RATE}) + (${OUTPUT_TOKENS} / 1000000 * ${OUTPUT_RATE})" | bc)++# Create step entry+STEP_JSON=$(cat << EOF+{+ "group": ${GROUP},+ "step": ${STEP},+ "id": "${GROUP}.${STEP}",+ "status": "${STATUS}",+ "input_tokens": ${INPUT_TOKENS},+ "output_tokens": ${OUTPUT_TOKENS},+ "total_tokens": ${TOTAL_TOKENS},+ "cost_usd": ${COST},+ "notes": "${NOTES}",+ "timestamp": "${TIMESTAMP}"+}+EOF+)++# Append to report+TMP_FILE=$(mktemp)+jq --argjson step "${STEP_JSON}" '.steps += [$step]' "${REPORT_FILE}" > "${TMP_FILE}"++# Update totals+jq --argjson in "${INPUT_TOKENS}" --argjson out "${OUTPUT_TOKENS}" --argjson cost "${COST}" \+ --arg status "${STATUS}" \+ '.totals.input_tokens += $in |+ .totals.output_tokens += $out |+ .totals.total_tokens += ($in + $out) |+ .totals.estimated_cost_usd += $cost |+ if $status == "pass" then .totals.steps_passed += 1+ elif $status == "fail" then .totals.steps_failed += 1+ else .totals.steps_skipped += 1 end' \+ "${TMP_FILE}" > "${REPORT_FILE}"++rm -f "${TMP_FILE}"++# If failed, also log to error log with details+if [[ "${STATUS}" == "fail" ]]; then+ ERROR_LOG="${RESULTS_DIR}/errors.log"+ echo "[${TIMESTAMP}] Step ${GROUP}.${STEP} FAILED: ${NOTES}" >> "${ERROR_LOG}"+fi++echo "Recorded: Step ${GROUP}.${STEP} = ${STATUS} (${TOTAL_TOKENS} tokens, \$${COST})"diff --git a/tests/benchmark/scripts/run-optimization.sh b/tests/benchmark/scripts/run-optimization.shnew file mode 100755index 00000000..f96e0dcd--- /dev/null+++ b/tests/benchmark/scripts/run-optimization.sh@@ -0,0 +1,99 @@+#!/bin/bash+#+# PinchTab Benchmark Optimization Loop+# Runs both benchmarks, analyzes differences, proposes improvements+#++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+RESULTS_DIR="${SCRIPT_DIR}/results"+LOG_FILE="${RESULTS_DIR}/optimization_log.md"+TIMESTAMP=$(date +%Y%m%d_%H%M%S)+RUN_NUMBER=$(grep -c "^## Run #" "${LOG_FILE}" 2>/dev/null || echo 0)+RUN_NUMBER=$((RUN_NUMBER + 1))++echo "=== PinchTab Optimization Run #${RUN_NUMBER} ==="+echo "Timestamp: ${TIMESTAMP}"++# Ensure we're on feat/benchmark branch+cd ~/dev/pinchtab+CURRENT_BRANCH=$(git branch --show-current)+if [[ "${CURRENT_BRANCH}" != "feat/benchmark" ]]; then+ echo "Switching to feat/benchmark branch..."+ git checkout feat/benchmark+fi+git pull --rebase origin feat/benchmark 2>/dev/null || true++# Ensure Docker is running+cd "${SCRIPT_DIR}"+if ! docker compose ps 2>/dev/null | grep -q "running"; then+ echo "Starting Docker..."+ docker compose up -d --build+ sleep 15+fi++# Verify PinchTab is healthy+if ! curl -sf -H "Authorization: Bearer benchmark-token" http://localhost:9867/health > /dev/null; then+ echo "ERROR: PinchTab not responding, restarting..."+ docker compose down+ docker compose up -d --build+ sleep 15+fi++# Initialize reports+BASELINE_REPORT="${RESULTS_DIR}/baseline_${TIMESTAMP}.json"+AGENT_REPORT="${RESULTS_DIR}/agent_benchmark_${TIMESTAMP}.json"++cat > "${BASELINE_REPORT}" << EOF+{+ "benchmark": {+ "type": "baseline",+ "run_number": ${RUN_NUMBER},+ "timestamp": "${TIMESTAMP}",+ "model": "claude-haiku-4-5"+ },+ "totals": {+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "estimated_cost_usd": 0,+ "steps_passed": 0,+ "steps_failed": 0,+ "steps_skipped": 0+ },+ "steps": []+}+EOF++cat > "${AGENT_REPORT}" << EOF+{+ "benchmark": {+ "type": "agent",+ "run_number": ${RUN_NUMBER},+ "timestamp": "${TIMESTAMP}",+ "model": "claude-haiku-4-5"+ },+ "totals": {+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "estimated_cost_usd": 0,+ "steps_passed": 0,+ "steps_failed": 0,+ "steps_skipped": 0+ },+ "steps": []+}+EOF++# Clear previous agent commands log+rm -f "${RESULTS_DIR}/agent_commands.log"++echo "Reports initialized:"+echo " Baseline: ${BASELINE_REPORT}"+echo " Agent: ${AGENT_REPORT}"+echo ""+echo "Ready for benchmark execution."+echo "Timestamp for this run: ${TIMESTAMP}"+echo "Run number: ${RUN_NUMBER}"