Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

chore: cleaning up scripts

Luigi Agosti899d6ab33b61
diff --git a/scripts/API_COMMENT_FORMAT.md b/scripts/API_COMMENT_FORMAT.md
deleted file mode 100644
index a4c27adc..00000000
--- a/scripts/API_COMMENT_FORMAT.md
+++ /dev/null
@@ -1,159 +0,0 @@
-# API Documentation Comment Format
-
-This guide shows how to add documentation to handler functions that will be auto-extracted.
-
-## Format
-
-Add structured comments above handler functions using this format:
-
-```go
-// HandleSnapshot returns the accessibility tree of the current tab.
-//
-// @Endpoint GET /snapshot
-// @Description Returns the page structure with clickable elements
-//
-// @Param tabId string query The tab ID (required)
-// @Param filter string query Filter: "interactive" or "all" (optional, default: "all")
-// @Param interactive bool query Show only interactive elements (optional)
-//
-// @Response 200 application/json Returns accessibility tree
-//
-// @Example curl:
-// curl "http://localhost:9867/snapshot?tabId=abc123&filter=interactive"
-//
-// @Example cli:
-// pinchtab snap -i -c
-//
-// @Example python:
-// import requests
-// response = requests.get("http://localhost:9867/snapshot", params={"tabId": "abc123"})
-func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
-```
-
-## Tags
-
-| Tag | Description | Example |
-|-----|-------------|---------|
-| `@Endpoint` | HTTP method and path | `@Endpoint GET /snapshot` |
-| `@Description` | Brief description | `@Description Returns page structure` |
-| `@Param` | Query/body parameter | `@Param tabId string query Tab ID (required)` |
-| `@Response` | Response format | `@Response 200 application/json Returns data` |
-| `@Example curl:` | cURL example | `curl "http://localhost:9867/snapshot?..."` |
-| `@Example cli:` | CLI example | `pinchtab snap -i` |
-| `@Example python:` | Python example | `import requests; ...` |
-| `@Example javascript:` | JavaScript example | `fetch("http://...").then(...)` |
-
-## Parameter Format
-
-```
-@Param {name} {type} {location} {description}
-```
-
-- `name`: Parameter name
-- `type`: Data type (string, int, bool, json, etc.)
-- `location`: Where parameter comes from (query, body, path)
-- `description`: Human-readable description + (required/optional, default value)
-
-## Example: Full Handler
-
-```go
-// HandleAction performs an action on the current tab (click, type, etc).
-//
-// @Endpoint POST /action
-// @Description Click, type, fill, press, or other actions on page elements
-//
-// @Param tabId string query The tab ID (required)
-// @Param kind string body Action type: "click", "type", "fill", "press", "hover", "focus", "scroll", "select" (required)
-// @Param ref string body Element reference from snapshot (e.g., "e5") (required)
-// @Param text string body Text to type or fill (for "type"/"fill" actions)
-// @Param value string body Value for "select" action
-//
-// @Response 200 application/json Returns result
-// @Response 400 application/json Invalid parameters
-//
-// @Example curl click:
-// curl -X POST http://localhost:9867/action?tabId=abc123 \
-// -H "Content-Type: application/json" \
-// -d '{"kind":"click","ref":"e5"}'
-//
-// @Example curl type:
-// curl -X POST http://localhost:9867/action?tabId=abc123 \
-// -H "Content-Type: application/json" \
-// -d '{"kind":"type","ref":"e3","text":"[email protected]"}'
-//
-// @Example cli click:
-// pinchtab click e5
-//
-// @Example cli type:
-// pinchtab type e3 "[email protected]"
-func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
-```
-
-## How It Works
-
-The doc generator will:
-1. Parse Go files looking for handler functions
-2. Extract comments using `@` tags
-3. Generate complete API documentation with:
- - Parameters and defaults
- - Examples in multiple formats (curl, CLI, Python, JavaScript)
- - Response types
- - Error codes
-
-## Benefits
-
-- ✅ Documentation lives in code (single source of truth)
-- ✅ Easy to update when API changes
-- ✅ Auto-generates curl examples
-- ✅ Auto-generates CLI examples
-- ✅ Shows default values
-- ✅ Marks required vs optional
-- ✅ Multiple language examples
-
-## Starting Points
-
-For now, add comments to these high-value endpoints first:
-
-```
-Priority 1 (core operations):
-- HandleNavigate (POST /navigate)
-- HandleSnapshot (GET /snapshot)
-- HandleAction (POST /action)
-- HandleText (GET /text)
-
-Priority 2 (instance/profile management):
-- handleList (GET /instances, GET /profiles)
-- handleLaunchByName (POST /instances/launch)
-- handleCreate (POST /profiles/create)
-
-Priority 3 (everything else)
-```
-
-## Example: How to Add to HandleNavigate
-
-```go
-// HandleNavigate navigates a tab to a URL.
-//
-// @Endpoint POST /navigate
-// @Description Navigate to a URL in a tab or create new tab
-//
-// @Param tabId string query Tab ID (optional - creates new tab if omitted)
-// @Param url string query URL to navigate to (required)
-// @Param blockAds bool query Block ads (optional, default: false)
-// @Param blockImages bool query Block images (optional, default: false)
-// @Param blockMedia bool query Block media (optional, default: false)
-//
-// @Response 200 application/json Returns {tabId, url, title}
-//
-// @Example curl navigate existing:
-// curl -X POST "http://localhost:9867/navigate?tabId=abc123&url=https://example.com"
-//
-// @Example curl navigate new:
-// curl -X POST "http://localhost:9867/navigate?url=https://example.com"
-//
-// @Example cli:
-// pinchtab nav https://example.com
-func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
-```
-
-This way, all documentation is version-controlled in the code itself.
diff --git a/scripts/API_DOCS_GENERATION.md b/scripts/API_DOCS_GENERATION.md
deleted file mode 100644
index 7200bcc5..00000000
--- a/scripts/API_DOCS_GENERATION.md
+++ /dev/null
@@ -1,120 +0,0 @@
-# Generating API Documentation
-
-This guide explains how to automatically generate API reference documentation from Go code.
-
-## Overview
-
-We have two tools to help generate API documentation:
-
-1. **Go tool** (`scripts/gen-api-docs/main.go`) — More reliable, parses Go AST
-2. **Bash script** (`scripts/generate-api-docs.sh`) — Simple pattern matching
-
-## Using the Go Tool (Recommended)
-
-### Generate Endpoint Summary
-
-```bash
-# Run from repo root
-go run scripts/gen-api-docs/main.go
-```
-
-**Output:**
-- Endpoint summary table (Method, Path, Handler)
-- Detailed endpoint list
-- Handler names
-
-### Redirect to File
-
-```bash
-go run scripts/gen-api-docs/main.go > docs/references/endpoints-auto.md
-```
-
-### What It Extracts
-
-- HTTP method (GET, POST, PUT, DELETE, PATCH)
-- Path pattern (e.g., `/snapshot`, `/action`)
-- Handler function name (e.g., `HandleSnapshot`)
-- Sorts by method, then path
-
-## How It Works
-
-The Go tool:
-
-1. **Parses** `internal/handlers/handlers.go`
-2. **Uses Go AST** to find `RegisterRoutes()` function
-3. **Extracts** all `mux.HandleFunc()` and `mux.Handle()` calls
-4. **Parses** route strings with pattern: `"METHOD /path"`
-5. **Generates** markdown documentation
-
-### Limitations
-
-Currently extracts:
-- ✅ HTTP method and path
-- ✅ Handler function name
-- ❌ Query parameters (would need to parse handler functions)
-- ❌ Request body structure (would need struct tag analysis)
-- ❌ Response types (would need return type analysis)
-
-## Enhancing the Tool
-
-To add more features, extend `scripts/gen-api-docs/main.go`:
-
-### Extract Query Parameters
-
-```go
-// Look for r.URL.Query().Get("paramName") in handler code
-// Parse parameters from handler functions
-```
-
-### Extract Request Body Structure
-
-```go
-// Look for json.Unmarshal patterns
-// Parse request struct definitions
-// Extract field names and types
-```
-
-### Extract Response Types
-
-```go
-// Analyze handler return types
-// Look for json.Marshal patterns
-// Extract response struct definitions
-```
-
-## Current Usage
-
-The manually-written `docs/references/endpoints.md` is the source of truth because it includes:
-- Full request/response examples
-- Query parameters and defaults
-- Error responses
-- Usage examples
-
-**Auto-generation tool is useful for:**
-- Verifying endpoints are documented
-- Creating a quick reference table
-- Tracking which endpoints exist in code
-- Finding undocumented endpoints
-
-## Next Steps
-
-To make this fully automated:
-
-1. Add structured comments above handler functions:
- ```go
- // HandleSnapshot returns the accessibility tree
- // Query params: tabId, filter, interactive
- func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
- ```
-
-2. Use the `go/parser` with structured comments to extract documentation
-
-3. Parse request/response types using `go/types` for full type information
-
-4. Generate complete API docs automatically (with parameter docs, types, examples)
-
-## Related Files
-
-- `internal/handlers/handlers.go` — Route definitions
-- `internal/handlers/*.go` — Handler implementations
-- `docs/references/endpoints.md` — Manually-written API docs (source of truth)
diff --git a/scripts/ENDPOINT_METADATA.md b/scripts/ENDPOINT_METADATA.md
deleted file mode 100644
index d61bc469..00000000
--- a/scripts/ENDPOINT_METADATA.md
+++ /dev/null
@@ -1,107 +0,0 @@
-# Endpoint Metadata Format
-
-Add rich metadata to endpoints using structured comments.
-
-## Format
-
-Add comments above handler functions with metadata:
-
-```go
-// HandleNavigate navigates a tab to a URL or creates a new tab.
-// @Description Navigate to a URL in an existing tab or create a new tab
-// @Implemented true
-// @Param tabId string body optional Tab ID (creates new if omitted)
-// @Param url string body required URL to navigate to
-// @Param newTab bool body optional Force create new tab (default: false)
-// @Param timeout float64 body optional Timeout in ms (default: 30000)
-// @Curl curl -X POST http://localhost:9867/navigate -H "Content-Type: application/json" -d '{"url":"https://example.com"}'
-// @CLI pinchtab nav https://example.com
-// @Example {"tabId":"tab-123","url":"https://example.com","timeout":30000}
-func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
-```
-
-## Tags
-
-| Tag | Format | Example | Purpose |
-|-----|--------|---------|---------|
-| `@Description` | Text | `@Description Navigate to URL or create new tab` | Brief endpoint description |
-| `@Implemented` | true/false | `@Implemented true` | Is this endpoint fully implemented? |
-| `@Param` | name type location required/optional description | `@Param url string body required URL to navigate` | Parameter definition |
-| `@Curl` | Full curl command | `@Curl curl -X POST http://localhost:9867/...` | Example curl command |
-| `@CLI` | CLI command | `@CLI pinchtab nav https://example.com` | Example CLI command |
-| `@Example` | JSON | `@Example {"url":"https://example.com"}` | Example request payload |
-
-## Example: Full Handler Documentation
-
-```go
-// HandleAction performs a single action on a tab.
-// @Description Click, type, fill, hover, focus, scroll, select on page elements
-// @Implemented true
-// @Param tabId string body required Tab ID
-// @Param kind string body required Action: "click", "type", "fill", "press", "hover", "focus", "scroll", "select"
-// @Param ref string body required Element ref from snapshot (e.g., "e5")
-// @Param text string body optional Text to type or fill
-// @Param key string body optional Key for "press" (e.g., "Enter", "Tab")
-// @Curl curl -X POST http://localhost:9867/action -H "Content-Type: application/json" -d '{"tabId":"abc","kind":"click","ref":"e5"}'
-// @CLI pinchtab click e5
-// @Example {"tabId":"abc123","kind":"click","ref":"e5"}
-func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
-```
-
-## Parameter Format
-
-```
-@Param {name} {type} {location} {required|optional} {description}
-```
-
-**Types:** `string`, `int`, `bool`, `float64`, `json`
-**Location:** `query`, `body`, `path`
-**Requirement:** `required` or `optional (with defaults)`
-
-## Examples (By Endpoint Type)
-
-### Query Parameters (GET)
-
-```go
-// @Param tabId string query required Tab ID
-// @Param filter string query optional Filter: "interactive" or "all" (default: "all")
-// @Param compact bool query optional Compact output (default: false)
-```
-
-### Body Parameters (POST)
-
-```go
-// @Param tabId string body required Tab ID
-// @Param url string body required URL to navigate to
-// @Param timeout float64 body optional Timeout in ms (default: 30000)
-```
-
-### Path Parameters
-
-```go
-// @Param id string path required Instance ID
-// @Param name string path required Profile name
-```
-
-## Priority Endpoints to Document
-
-Phase 1 (Core):
-- `HandleNavigate` (POST /navigate)
-- `HandleSnapshot` (GET /snapshot)
-- `HandleAction` (POST /action)
-- `HandleText` (GET /text)
-
-Phase 2 (Instance Management):
-- `handleList` in orchestrator (GET /instances)
-- `handleLaunchByName` in orchestrator (POST /instances/launch)
-
-Phase 3 (Profile Management):
-- `handleCreate` in profiles (POST /profiles/create)
-- `handleImport` in profiles (POST /profiles/import)
-
-## Current Implementation Status
-
-Check `docs/references/api-reference.json` for the full list. Mark endpoints as:
-- `@Implemented true` — Fully working
-- `@Implemented false` — Planned/WIP
-- (No tag) — Unknown status
diff --git a/scripts/README.md b/scripts/README.md
index b916f92d..de90edb7 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -1,174 +1,41 @@
-# Scripts & Tools
+# Scripts
-Utility scripts for PinchTab development, testing, and documentation.
+Development and CI scripts for PinchTab.
-## API Documentation Generation
+## Build & Run
-### Overview
+| Script | Purpose |
+|--------|---------|
+| `build-dashboard.sh` | Generate TS types (tygo) + build React dashboard + copy to Go embed |
+| `dev.sh` | Full build (dashboard + Go) and run |
-Keep the API reference in sync with code changes **without losing user metadata**.
+## CI Scripts
-### Quick Start
+Used by GitHub Actions workflows:
-```bash
-# Check what changed (dry-run)
-go run scripts/update-api-reference.go --dry-run
+| Script | Workflow | Purpose |
+|--------|----------|---------|
+| `build-dashboard.sh` | `go-verify.yml` | Build dashboard before lint |
-# Apply changes (adds new endpoints, removes old ones, keeps metadata)
-go run scripts/update-api-reference.go
+## Quality
-# Query the result
-jq '.endpoints | map(select(.cli == true)) | length' docs/references/api-reference.json
-jq '.endpoints[] | select(.method == "POST") | .path' docs/references/api-reference.json
-```
+| Script | Purpose |
+|--------|---------|
+| `check-docs-json.sh` | `docs-verify.yml` | Validate docs/index.json |
+| `check.sh` | Local pre-push checks (mirrors CI: gofmt, vet, build, test, lint, integration) |
+| `check-gosec.sh` | Security scan with gosec just to reproduce CI|
+| `pre-commit` | Pre-commit hook (format, lint) |
+| `doctor.sh` | Check requirements |
-### Tools
+## Hooks
-#### `update-api-reference.go` (Main Tool - USE THIS)
+| Script | Purpose |
+|--------|---------|
+| `install-hooks.sh` | Install git hooks |
-**Smart merge tool** that updates the API reference without overwriting user-added metadata.
+## Scripts / Testing
-**Features:**
-- ✅ Scans code for current endpoints
-- ✅ Reads existing `api-reference.json`
-- ✅ **Merges intelligently:**
- - Keeps all user-added fields (description, examples, params, implementation status)
- - Adds new endpoints found in code
- - Removes endpoints no longer in code
- - Updates only method/path/handler
-- ✅ Shows what changed (added/removed)
-- ✅ Preserves all manual metadata
-
-**Usage:**
-```bash
-# Dry-run first (show changes, no write)
-go run scripts/update-api-reference.go --dry-run
-
-# Apply changes
-go run scripts/update-api-reference.go
-```
-
-**Example Output:**
-```
-Found 66 endpoints in code
-Found 66 endpoints in existing file
-Merged to 66 endpoints
-✓ No changes needed
-
-Wrote docs/references/api-reference.json
-```
-
-#### `gen-api-docs/main.go` (Reference)
-
-Go-based tool using AST parsing. Use this **only** if you want to regenerate from scratch.
-
-**Output:**
-```json
-{
- "version": "1.0",
- "generated": "auto-generated from Go code",
- "count": 66,
- "endpoints": [
- {
- "method": "GET",
- "path": "/snapshot",
- "handler": "HandleSnapshot"
- }
- ]
-}
-```
-
-### Workflow: Keep API Reference in Sync
-
-**Scenario 1: New endpoint added to code**
-```bash
-go run scripts/update-api-reference.go --dry-run
-# Output:
-# ✨ New endpoints:
-# + POST /new-endpoint
-
-go run scripts/update-api-reference.go
-# Adds /new-endpoint with basic fields, preserves all existing metadata
-```
-
-**Scenario 2: Endpoint removed from code**
-```bash
-go run scripts/update-api-reference.go --dry-run
-# Output:
-# ❌ Removed endpoints:
-# - DELETE /old-endpoint
-
-go run scripts/update-api-reference.go
-# Removes /old-endpoint, preserves all other data
-```
-
-**Scenario 3: User adds metadata manually**
-Edit `docs/references/api-reference.json` to add:
-```json
-{
- "method": "GET",
- "path": "/snapshot",
- "handler": "HandleSnapshot",
- "description": "Get accessibility tree",
- "cli": true,
- "curl": true,
- "examples": {
- "curl": "curl http://localhost:9867/snapshot?tabId=abc"
- }
-}
-```
-
-Then run:
-```bash
-go run scripts/update-api-reference.go
-# Preserves all your edits, updates code-derived fields only
-```
-
-### JSON File Structure
-
-**Location:** `docs/references/api-reference.json`
-
-**Fields per endpoint:**
-- `method` — HTTP method (GET, POST, PUT, DELETE, PATCH)
-- `path` — URL path pattern (e.g., `/snapshot`, `/instances/{id}/action`)
-- `handler` — Go handler function name
-- `description` (optional) — What this endpoint does
-- `cli` (optional) — CLI support flag
-- `curl` (optional) — Curl support flag
-- `params` (optional) — Parameter list with types/descriptions
-- `examples` (optional) — curl/cli/payload examples
-- `implemented` (optional) — Implementation status
-
-### Query Examples
-
-```bash
-# List all endpoints with CLI support
-jq '.endpoints[] | select(.cli == true) | {method, path}' docs/references/api-reference.json
-
-# Count endpoints by method
-jq '.endpoints | group_by(.method) | map({method: .[0].method, count: length})' docs/references/api-reference.json
-
-# Find endpoints with documented examples
-jq '.endpoints[] | select(.examples.curl != null) | .path' docs/references/api-reference.json
-
-# Validate total count
-TOTAL=$(jq '.count' docs/references/api-reference.json)
-ACTUAL=$(jq '.endpoints | length' docs/references/api-reference.json)
-[ "$TOTAL" = "$ACTUAL" ] && echo "✓ Count matches" || echo "✗ Mismatch"
-```
-
-### Why This Approach?
-
-- ✅ **Automatic sync** — Code changes reflected without manual updates
-- ✅ **User data preserved** — Descriptions, examples, status stay intact
-- ✅ **Conflict-free** — Smart merge avoids overwriting metadata
-- ✅ **Auditable** — Shows what changed with dry-run
-- ✅ **Git-friendly** — Only changed endpoints in commits
-
----
-
-## Other Scripts
-
-- `gen-api-docs/main.go` — Generate endpoints from scratch
-- `generate-api-docs.sh` — Bash alternative (legacy)
-- `ENDPOINT_METADATA.md` — Guide for adding structured endpoint docs
+| Script | Purpose |
+|--------|---------|
+| `simulate-memory-load.sh` | Memory load testing |
+| `simulate-ratelimit-leak.sh` | Rate limit leak testing |
diff --git a/scripts/run-gosec.sh b/scripts/check-gosec.sh
similarity index 100%
rename from scripts/run-gosec.sh
rename to scripts/check-gosec.sh
diff --git a/scripts/dev.sh b/scripts/dev.sh
index 8015161a..bb5a813f 100755
--- a/scripts/dev.sh
+++ b/scripts/dev.sh
@@ -12,5 +12,4 @@ echo "🔨 Building Go..."
go build -o pinchtab ./cmd/pinchtab
# Run
-echo "🦀 Starting PinchTab..."
exec ./pinchtab "$@"
diff --git a/doctor.sh b/scripts/doctor.sh
similarity index 100%
rename from doctor.sh
rename to scripts/doctor.sh
diff --git a/scripts/gen-api-docs/main.go b/scripts/gen-api-docs/main.go
deleted file mode 100644
index 8fbdfad1..00000000
--- a/scripts/gen-api-docs/main.go
+++ /dev/null
@@ -1,328 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "log"
- "os"
- "regexp"
- "sort"
- "strings"
-)
-
-type Endpoint struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Handler string `json:"handler"`
- Description string `json:"description,omitempty"`
- Implemented *bool `json:"implemented,omitempty"`
- Params []Parameter `json:"params,omitempty"`
- Examples ExampleGroup `json:"examples,omitempty"`
-}
-
-type Parameter struct {
- Name string `json:"name"`
- Type string `json:"type"`
- Location string `json:"location"` // query, body, path
- Required bool `json:"required"`
- Description string `json:"description"`
-}
-
-type ExampleGroup struct {
- Curl string `json:"curl,omitempty"`
- CLI string `json:"cli,omitempty"`
- Payload string `json:"payload,omitempty"` // Example JSON payload
-}
-
-type APIReference struct {
- Version string `json:"version"`
- Generated string `json:"generated"`
- Count int `json:"count"`
- Endpoints []Endpoint `json:"endpoints"`
-}
-
-func main() {
- // Parse all relevant files for routes
- var endpoints []Endpoint
-
- // Main handlers
- endpoints = append(endpoints, extractEndpoints("internal/handlers/handlers.go")...)
-
- // Dashboard handlers
- endpoints = append(endpoints, extractEndpoints("internal/dashboard/dashboard.go")...)
-
- // Profiles service
- profiles, err := findProfilesFile()
- if err == nil {
- endpoints = append(endpoints, extractEndpoints(profiles)...)
- }
-
- // Orchestrator service
- orchestrator, err := findOrchestratorFile()
- if err == nil {
- endpoints = append(endpoints, extractEndpoints(orchestrator)...)
- }
-
- // Remove duplicates
- endpointMap := make(map[string]Endpoint)
- for _, ep := range endpoints {
- key := ep.Method + " " + ep.Path
- if _, exists := endpointMap[key]; !exists {
- endpointMap[key] = ep
- }
- }
-
- endpoints = make([]Endpoint, 0, len(endpointMap))
- for _, ep := range endpointMap {
- endpoints = append(endpoints, ep)
- }
-
- // Sort by method then path
- sort.Slice(endpoints, func(i, j int) bool {
- if endpoints[i].Method != endpoints[j].Method {
- return endpoints[i].Method < endpoints[j].Method
- }
- return endpoints[i].Path < endpoints[j].Path
- })
-
- // Build API reference
- ref := APIReference{
- Version: "1.0",
- Generated: "auto-generated from Go code",
- Count: len(endpoints),
- Endpoints: endpoints,
- }
-
- // Output as JSON
- encoder := json.NewEncoder(os.Stdout)
- encoder.SetIndent("", " ")
- if err := encoder.Encode(ref); err != nil {
- log.Fatalf("Error encoding JSON: %v", err)
- }
-}
-
-func findProfilesFile() (string, error) {
- // Look for profiles service implementation
- matches := []string{
- "internal/profiles/handlers.go",
- "internal/profiles/profiles.go",
- "internal/handler/profiles.go",
- "internal/bridge/profiles.go",
- }
- for _, path := range matches {
- if _, err := os.Stat(path); err == nil {
- return path, nil
- }
- }
- return "", fmt.Errorf("profiles file not found")
-}
-
-func findOrchestratorFile() (string, error) {
- // Look for orchestrator service implementation
- matches := []string{
- "internal/orchestrator/handlers.go",
- "internal/orchestrator/orchestrator.go",
- "internal/bridge/orchestrator.go",
- }
- for _, path := range matches {
- if _, err := os.Stat(path); err == nil {
- return path, nil
- }
- }
- return "", fmt.Errorf("orchestrator file not found")
-}
-
-func extractEndpoints(filePath string) []Endpoint {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
- if err != nil {
- log.Fatalf("Error parsing file: %v", err)
- }
-
- var endpoints []Endpoint
- handlerMetadata := make(map[string]Endpoint)
-
- // First, extract metadata from all handler functions
- for _, decl := range file.Decls {
- funcDecl, ok := decl.(*ast.FuncDecl)
- if !ok {
- continue
- }
-
- // Look for handler functions and extract their metadata
- if strings.Contains(funcDecl.Name.Name, "Handle") || strings.Contains(funcDecl.Name.Name, "handle") {
- if funcDecl.Doc != nil {
- commentText := ""
- for _, comment := range funcDecl.Doc.List {
- commentText += strings.TrimPrefix(comment.Text, "// ") + "\n"
- }
- metadata := extractMetadata(commentText)
- if metadata.Description != "" || len(metadata.Params) > 0 || metadata.Examples.Curl != "" {
- handlerMetadata[funcDecl.Name.Name] = metadata
- }
- }
- }
- }
-
- // Then, extract routes from RegisterHandlers/RegisterRoutes
- for _, decl := range file.Decls {
- funcDecl, ok := decl.(*ast.FuncDecl)
- if !ok {
- continue
- }
-
- // Look for RegisterHandlers or RegisterRoutes
- if funcDecl.Name.Name == "RegisterHandlers" || funcDecl.Name.Name == "RegisterRoutes" {
- // Extract HandleFunc calls
- routeEndpoints := extractHandleFuncCalls(funcDecl.Body)
-
- // Merge with metadata
- for _, ep := range routeEndpoints {
- if meta, ok := handlerMetadata[ep.Handler]; ok {
- ep.Description = meta.Description
- ep.Implemented = meta.Implemented
- ep.Params = meta.Params
- ep.Examples = meta.Examples
- }
- endpoints = append(endpoints, ep)
- }
- }
- }
-
- return endpoints
-}
-
-func extractMetadata(commentText string) Endpoint {
- ep := Endpoint{}
- lines := strings.Split(commentText, "\n")
-
- for _, line := range lines {
- // Remove "// " prefix if present, then trim
- line = strings.TrimPrefix(line, "// ")
- line = strings.TrimSpace(line)
-
- if line == "" || !strings.HasPrefix(line, "@") {
- continue
- }
-
- // Split on first space after the tag
- parts := strings.SplitN(line, " ", 2)
- if len(parts) < 2 {
- continue
- }
-
- tag := parts[0]
- value := strings.TrimSpace(parts[1])
-
- switch tag {
- case "@Description":
- ep.Description = value
- case "@Implemented":
- implemented := value == "true"
- ep.Implemented = &implemented
- case "@Param":
- param := parseParam(value)
- ep.Params = append(ep.Params, param)
- case "@Curl":
- ep.Examples.Curl = value
- case "@CLI":
- ep.Examples.CLI = value
- case "@Example":
- ep.Examples.Payload = value
- }
- }
-
- return ep
-}
-
-func parseParam(paramStr string) Parameter {
- // Format: name type location required/optional description
- // Example: url string body required URL to navigate to
- parts := strings.SplitN(paramStr, " ", 5)
-
- p := Parameter{}
- if len(parts) >= 1 {
- p.Name = parts[0]
- }
- if len(parts) >= 2 {
- p.Type = parts[1]
- }
- if len(parts) >= 3 {
- p.Location = parts[2]
- }
- if len(parts) >= 4 {
- p.Required = parts[3] == "required"
- }
- if len(parts) >= 5 {
- p.Description = parts[4]
- }
-
- return p
-}
-
-func extractHandleFuncCalls(body *ast.BlockStmt) []Endpoint {
- var endpoints []Endpoint
-
- routePattern := regexp.MustCompile(`^(GET|POST|PUT|DELETE|PATCH)\s+(/[^\s]*)`)
-
- for _, stmt := range body.List {
- exprStmt, ok := stmt.(*ast.ExprStmt)
- if !ok {
- continue
- }
-
- callExpr, ok := exprStmt.X.(*ast.CallExpr)
- if !ok {
- continue
- }
-
- // Check if this is mux.HandleFunc or mux.Handle
- selector, ok := callExpr.Fun.(*ast.SelectorExpr)
- if !ok {
- continue
- }
-
- if selector.Sel.Name != "HandleFunc" && selector.Sel.Name != "Handle" {
- continue
- }
-
- // Extract route pattern (first argument)
- if len(callExpr.Args) < 1 {
- continue
- }
-
- basicLit, ok := callExpr.Args[0].(*ast.BasicLit)
- if !ok {
- continue
- }
-
- // Parse route string
- route := strings.Trim(basicLit.Value, "\"")
- matches := routePattern.FindStringSubmatch(route)
- if len(matches) < 3 {
- continue
- }
-
- method := matches[1]
- path := matches[2]
-
- // Extract handler name (second argument)
- var handler string
- if len(callExpr.Args) >= 2 {
- if selectorExpr, ok := callExpr.Args[1].(*ast.SelectorExpr); ok {
- handler = selectorExpr.Sel.Name
- }
- }
-
- endpoints = append(endpoints, Endpoint{
- Method: method,
- Path: path,
- Handler: handler,
- })
- }
-
- return endpoints
-}
diff --git a/scripts/generate-api-docs.sh b/scripts/generate-api-docs.sh
deleted file mode 100755
index ca27ebb6..00000000
--- a/scripts/generate-api-docs.sh
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/bin/bash
-# Generate API reference documentation from Go handler definitions
-# Usage: ./scripts/generate-api-docs.sh > docs/references/endpoints-generated.md
-
-set -e
-
-cd "$(dirname "$0")/.."
-
-echo "# API Reference (Auto-Generated)"
-echo ""
-echo "This documentation is generated from Go code."
-echo "Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
-echo ""
-echo "---"
-echo ""
-
-echo "## Endpoints Summary"
-echo ""
-echo "| Method | Path | Handler |"
-echo "|--------|------|---------|"
-
-# Extract routes from handlers.go
-grep -E 'mux\.Handle(Func)?\(' internal/handlers/handlers.go | \
- sed -E 's/.*mux\.HandleFunc?\("([A-Z]+) ([^"]+)".*h\.([A-Za-z]+).*/| \1 | \2 | \3 |/' | \
- sort
-
-echo ""
-echo "---"
-echo ""
-echo "## Detailed Endpoints"
-echo ""
-
-# Extract each route and try to find documentation
-while IFS= read -r line; do
- if [[ $line =~ mux\.HandleFunc\(\"([A-Z]+)[[:space:]]+([^\"]+)\".*h\.([A-Za-z0-9]+) ]]; then
- METHOD="${BASH_REMATCH[1]}"
- PATH="${BASH_REMATCH[2]}"
- HANDLER="${BASH_REMATCH[3]}"
-
- # Find the handler in the codebase
- HANDLER_FILE=$(grep -l "func.*($HANDLER" internal/handlers/*.go 2>/dev/null | head -1)
-
- if [ -n "$HANDLER_FILE" ]; then
- # Extract comments before the handler
- COMMENT=$(grep -B 5 "func.*($HANDLER" "$HANDLER_FILE" | grep "^[[:space:]]*\/\/" | head -1 | sed 's/^[[:space:]]*\/\/[[:space:]]*//')
-
- echo "### $METHOD $PATH"
- echo ""
- if [ -n "$COMMENT" ]; then
- echo "$COMMENT"
- echo ""
- fi
- echo "\`\`\`"
- echo "$METHOD $PATH"
- echo "\`\`\`"
- echo ""
- fi
- fi
-done < <(grep 'mux\.HandleFunc' internal/handlers/handlers.go | head -20)
-
-echo "---"
-echo ""
-echo "## Notes"
-echo ""
-echo "- This documentation is auto-generated from Go code"
-echo "- For full details, see inline comments in \`internal/handlers/*.go\`"
-echo "- Query parameters and request bodies vary by endpoint"
-echo ""
diff --git a/scripts/generate-types.sh b/scripts/generate-types.sh
deleted file mode 100755
index 8efa2012..00000000
--- a/scripts/generate-types.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-# Generate TypeScript types from Go structs using tygo
-set -e
-
-cd "$(dirname "$0")/.."
-
-# Ensure tygo is installed
-if ! command -v tygo &> /dev/null; then
- echo "Installing tygo..."
- go install github.com/gzuidhof/tygo@latest
-fi
-
-# Generate types
-echo "Generating TypeScript types..."
-tygo generate
-
-echo "✓ Types generated: dashboard/src/generated/types.ts"
diff --git a/scripts/install-autostart.sh b/scripts/install-autostart.sh
deleted file mode 100755
index 5e7ee8ac..00000000
--- a/scripts/install-autostart.sh
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/bin/bash
-set -e
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-PINCHTAB_BIN="$(cd "$SCRIPT_DIR/.." && pwd)/pinchtab"
-
-echo "🦀 Pinchtab Auto-Start Installer"
-echo "================================"
-
-if [[ "$OSTYPE" == "darwin"* ]]; then
- echo "Detected macOS - using launchd"
- if [ ! -f "$PINCHTAB_BIN" ]; then
- echo "Building pinchtab..."
- (cd "$SCRIPT_DIR/.." && go build -o pinchtab ./cmd/pinchtab)
- fi
- echo "Installing pinchtab to /usr/local/bin..."
- sudo cp "$PINCHTAB_BIN" /usr/local/bin/pinchtab
- PLIST_SRC="$SCRIPT_DIR/launchd/com.pinchtab.bridge.plist"
- PLIST_DST="$HOME/Library/LaunchAgents/com.pinchtab.bridge.plist"
- mkdir -p "$HOME/Library/LaunchAgents"
- cp "$PLIST_SRC" "$PLIST_DST"
- echo "Loading LaunchAgent..."
- launchctl load -w "$PLIST_DST" 2>/dev/null || true
-
- echo ""
- echo "✅ Pinchtab installed and set to auto-start!"
- echo ""
- echo "Commands:"
- echo " Start: launchctl start com.pinchtab.bridge"
- echo " Stop: launchctl stop com.pinchtab.bridge"
- echo " Status: launchctl list | grep pinchtab"
- echo " Logs: tail -f /tmp/pinchtab.*.log"
- echo " Disable: launchctl unload ~/Library/LaunchAgents/com.pinchtab.bridge.plist"
-
-elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
- echo "Detected Linux - using systemd"
- if [ ! -f "$PINCHTAB_BIN" ]; then
- echo "Building pinchtab..."
- (cd "$SCRIPT_DIR/.." && go build -o pinchtab ./cmd/pinchtab)
- fi
- echo "Installing pinchtab to /usr/local/bin..."
- sudo cp "$PINCHTAB_BIN" /usr/local/bin/pinchtab
- SERVICE_SRC="$SCRIPT_DIR/systemd/pinchtab.service"
- SERVICE_DST="/etc/systemd/system/[email protected]"
- sudo cp "$SERVICE_SRC" "$SERVICE_DST"
- echo "Enabling service for user $USER..."
- sudo systemctl daemon-reload
- sudo systemctl enable "pinchtab@$USER.service"
- sudo systemctl start "pinchtab@$USER.service"
-
- echo ""
- echo "✅ Pinchtab installed and set to auto-start!"
- echo ""
- echo "Commands:"
- echo " Start: sudo systemctl start pinchtab@$USER"
- echo " Stop: sudo systemctl stop pinchtab@$USER"
- echo " Status: sudo systemctl status pinchtab@$USER"
- echo " Logs: sudo journalctl -u pinchtab@$USER -f"
- echo " Disable: sudo systemctl disable pinchtab@$USER"
-
-else
- echo "❌ Unsupported OS: $OSTYPE"
- echo "Please manually configure auto-start for your system."
- exit 1
-fi
-
-echo ""
-echo "Test with: curl http://localhost:9867/health"
diff --git a/scripts/launchd/com.pinchtab.bridge.plist b/scripts/launchd/com.pinchtab.bridge.plist
deleted file mode 100644
index 4342d925..00000000
--- a/scripts/launchd/com.pinchtab.bridge.plist
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>Label</key>
- <string>com.pinchtab.bridge</string>
-
- <key>ProgramArguments</key>
- <array>
- <string>/usr/local/bin/pinchtab</string>
- </array>
-
- <key>EnvironmentVariables</key>
- <dict>
- <key>PINCHTAB_PORT</key>
- <string>9867</string>
- <key>PINCHTAB_HEADLESS</key>
- <string>true</string>
- <key>PINCHTAB_PROFILE_DIR</key>
- <string>~/.pinchtab/chrome-profile</string>
- </dict>
-
- <key>RunAtLoad</key>
- <true/>
-
- <key>KeepAlive</key>
- <true/>
-
- <key>StandardOutPath</key>
- <string>/tmp/pinchtab.out.log</string>
-
- <key>StandardErrorPath</key>
- <string>/tmp/pinchtab.err.log</string>
-
- <key>ProcessType</key>
- <string>Interactive</string>
-</dict>
-</plist>
\ No newline at end of file
diff --git a/scripts/run_pinchtab.sh b/scripts/run_pinchtab.sh
deleted file mode 100755
index c00c4dd5..00000000
--- a/scripts/run_pinchtab.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
-BIN_DIR="$ROOT_DIR/bin"
-BIN_PATH="$BIN_DIR/pinchtab"
-
-mkdir -p "$BIN_DIR"
-cd "$ROOT_DIR"
-
-go build -o "$BIN_PATH" ./cmd/pinchtab
-
-if [ "$#" -eq 0 ]; then
- set -- dashboard
-fi
-
-exec "$BIN_PATH" "$@"
diff --git a/scripts/setup-hooks.sh b/scripts/setup-hooks.sh
deleted file mode 100755
index f1026166..00000000
--- a/scripts/setup-hooks.sh
+++ /dev/null
@@ -1,42 +0,0 @@
-#!/bin/bash
-# Setup git hooks for Pinchtab development
-
-YELLOW='\033[1;33m'
-GREEN='\033[0;32m'
-RED='\033[0;31m'
-NC='\033[0m' # No Color
-
-echo -e "${YELLOW}🦀 Pinchtab Git Hooks Setup${NC}"
-echo ""
-
-# Check if we're in the right directory
-if [ ! -d ".githooks" ]; then
- echo -e "${RED}✗ Error: .githooks directory not found${NC}"
- echo " Please run this script from the Pinchtab root directory"
- exit 1
-fi
-
-# Check current hooks path
-CURRENT_PATH=$(git config core.hooksPath)
-
-if [ "$CURRENT_PATH" = ".githooks" ]; then
- echo -e "${GREEN}✓ Git hooks already configured correctly${NC}"
- echo " Pre-commit checks will run automatically"
-else
- echo "Setting up git hooks..."
- git config core.hooksPath .githooks
-
- if [ $? -eq 0 ]; then
- echo -e "${GREEN}✓ Git hooks configured successfully${NC}"
- echo ""
- echo "Pre-commit hook will now check:"
- echo " • gofmt formatting"
- echo " • go vet"
- echo " • go test"
- echo ""
- echo -e "${GREEN}Ready to commit with confidence! 🚀${NC}"
- else
- echo -e "${RED}✗ Failed to configure git hooks${NC}"
- exit 1
- fi
-fi
\ No newline at end of file
diff --git a/scripts/systemd/pinchtab.service b/scripts/systemd/pinchtab.service
deleted file mode 100644
index f4ff366e..00000000
--- a/scripts/systemd/pinchtab.service
+++ /dev/null
@@ -1,28 +0,0 @@
-[Unit]
-Description=Pinchtab Browser Automation Bridge
-Documentation=https://github.com/pinchtab/pinchtab
-After=network.target
-
-[Service]
-Type=simple
-User=%i
-ExecStart=/usr/local/bin/pinchtab
-Restart=always
-RestartSec=5
-
-# Environment
-Environment="PINCHTAB_PORT=9867"
-Environment="PINCHTAB_HEADLESS=true"
-Environment="PINCHTAB_PROFILE_DIR=%h/.pinchtab/chrome-profile"
-Environment="DISPLAY=:0"
-
-# Logging
-StandardOutput=journal
-StandardError=journal
-
-# Security
-NoNewPrivileges=true
-PrivateTmp=true
-
-[Install]
-WantedBy=default.target
\ No newline at end of file
diff --git a/scripts/simulate-memory-load.sh b/scripts/testing/simulate-memory-load.sh
similarity index 100%
rename from scripts/simulate-memory-load.sh
rename to scripts/testing/simulate-memory-load.sh
diff --git a/scripts/simulate-ratelimit-leak.sh b/scripts/testing/simulate-ratelimit-leak.sh
similarity index 100%
rename from scripts/simulate-ratelimit-leak.sh
rename to scripts/testing/simulate-ratelimit-leak.sh
diff --git a/scripts/uninstall-autostart.sh b/scripts/uninstall-autostart.sh
deleted file mode 100755
index 3e2fea8a..00000000
--- a/scripts/uninstall-autostart.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash
-set -e
-
-echo "🦀 Pinchtab Auto-Start Uninstaller"
-echo "==================================="
-
-if [[ "$OSTYPE" == "darwin"* ]]; then
- echo "Detected macOS - removing launchd configuration"
-
- PLIST="$HOME/Library/LaunchAgents/com.pinchtab.bridge.plist"
-
- echo "Stopping Pinchtab..."
- launchctl unload "$PLIST" 2>/dev/null || true
-
- if [ -f "$PLIST" ]; then
- echo "Removing LaunchAgent..."
- rm "$PLIST"
- fi
-
- read -p "Remove /usr/local/bin/pinchtab? (y/N): " -n 1 -r
- echo
- if [[ $REPLY =~ ^[Yy]$ ]]; then
- sudo rm -f /usr/local/bin/pinchtab
- fi
-
-elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
- echo "Detected Linux - removing systemd configuration"
-
- echo "Stopping Pinchtab..."
- sudo systemctl stop "pinchtab@$USER" 2>/dev/null || true
- sudo systemctl disable "pinchtab@$USER" 2>/dev/null || true
-
- if [ -f "/etc/systemd/system/[email protected]" ]; then
- echo "Removing systemd service..."
- sudo rm "/etc/systemd/system/[email protected]"
- sudo systemctl daemon-reload
- fi
-
- read -p "Remove /usr/local/bin/pinchtab? (y/N): " -n 1 -r
- echo
- if [[ $REPLY =~ ^[Yy]$ ]]; then
- sudo rm -f /usr/local/bin/pinchtab
- fi
-
-else
- echo "❌ Unsupported OS: $OSTYPE"
- exit 1
-fi
-
-echo ""
-echo "✅ Pinchtab auto-start has been removed!"
diff --git a/scripts/update-api-reference.go b/scripts/update-api-reference.go
deleted file mode 100644
index 64e996b3..00000000
--- a/scripts/update-api-reference.go
+++ /dev/null
@@ -1,363 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "flag"
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "log"
- "os"
- "regexp"
- "sort"
- "strings"
-)
-
-type Endpoint struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Handler string `json:"handler"`
- Description string `json:"description,omitempty"`
- Implemented *bool `json:"implemented,omitempty"`
- CLI bool `json:"cli,omitempty"`
- Curl bool `json:"curl,omitempty"`
- Params []Parameter `json:"params,omitempty"`
- Examples ExampleGroup `json:"examples,omitempty"`
-}
-
-type Parameter struct {
- Name string `json:"name"`
- Type string `json:"type"`
- Location string `json:"location"`
- Required bool `json:"required"`
- Description string `json:"description"`
-}
-
-type ExampleGroup struct {
- Curl string `json:"curl,omitempty"`
- CLI string `json:"cli,omitempty"`
- Payload string `json:"payload,omitempty"`
-}
-
-type APIReference struct {
- Version string `json:"version"`
- Generated string `json:"generated"`
- Count int `json:"count"`
- Endpoints []Endpoint `json:"endpoints"`
-}
-
-func main() {
- dryRun := flag.Bool("dry-run", false, "Show changes without writing")
- flag.Parse()
-
- // Generate current endpoints from code
- currentEndpoints := generateEndpoints()
- fmt.Printf("Found %d endpoints in code\n", len(currentEndpoints))
-
- // Read existing API reference
- existingData := readExistingReference()
- fmt.Printf("Found %d endpoints in existing file\n", len(existingData.Endpoints))
-
- // Merge endpoints
- mergedEndpoints := mergeEndpoints(existingData.Endpoints, currentEndpoints)
- fmt.Printf("Merged to %d endpoints\n", len(mergedEndpoints))
-
- // Sort by method then path
- sort.Slice(mergedEndpoints, func(i, j int) bool {
- if mergedEndpoints[i].Method != mergedEndpoints[j].Method {
- return mergedEndpoints[i].Method < mergedEndpoints[j].Method
- }
- return mergedEndpoints[i].Path < mergedEndpoints[j].Path
- })
-
- // Build final reference
- result := APIReference{
- Version: "2.0",
- Generated: "auto-merged from code + user metadata",
- Count: len(mergedEndpoints),
- Endpoints: mergedEndpoints,
- }
-
- // Show changes
- showChanges(existingData.Endpoints, mergedEndpoints)
-
- if !*dryRun {
- // Write to file
- outputPath := "docs/references/api-reference.json"
- data, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- log.Fatalf("Error marshaling JSON: %v", err)
- }
-
- err = os.WriteFile(outputPath, append(data, '\n'), 0644)
- if err != nil {
- log.Fatalf("Error writing file: %v", err)
- }
- fmt.Printf("\nWrote %s\n", outputPath)
- } else {
- fmt.Println("\n(dry-run mode - no changes written)")
- }
-}
-
-func generateEndpoints() []Endpoint {
- var endpoints []Endpoint
-
- // Parse all handler files
- endpoints = append(endpoints, extractEndpoints("internal/handlers/handlers.go")...)
- endpoints = append(endpoints, extractEndpoints("internal/dashboard/dashboard.go")...)
-
- profiles, err := findProfilesFile()
- if err == nil {
- endpoints = append(endpoints, extractEndpoints(profiles)...)
- }
-
- orchestrator, err := findOrchestratorFile()
- if err == nil {
- endpoints = append(endpoints, extractEndpoints(orchestrator)...)
- }
-
- // Remove duplicates
- endpointMap := make(map[string]Endpoint)
- for _, ep := range endpoints {
- key := ep.Method + " " + ep.Path
- if _, exists := endpointMap[key]; !exists {
- endpointMap[key] = ep
- }
- }
-
- endpoints = make([]Endpoint, 0, len(endpointMap))
- for _, ep := range endpointMap {
- endpoints = append(endpoints, ep)
- }
-
- return endpoints
-}
-
-func readExistingReference() APIReference {
- path := "docs/references/api-reference.json"
- data, err := os.ReadFile(path)
- if err != nil {
- fmt.Printf("Could not read existing file (%v), starting fresh\n", err)
- return APIReference{
- Version: "2.0",
- Generated: "auto-merged from code + user metadata",
- Endpoints: []Endpoint{},
- }
- }
-
- var ref APIReference
- err = json.Unmarshal(data, &ref)
- if err != nil {
- fmt.Printf("Error parsing existing file (%v), starting fresh\n", err)
- return APIReference{
- Version: "2.0",
- Generated: "auto-merged from code + user metadata",
- Endpoints: []Endpoint{},
- }
- }
-
- return ref
-}
-
-func mergeEndpoints(existing, current []Endpoint) []Endpoint {
- // Index existing endpoints by key
- existingMap := make(map[string]Endpoint)
- for _, ep := range existing {
- key := ep.Method + " " + ep.Path
- existingMap[key] = ep
- }
-
- // Index current endpoints by key
- currentMap := make(map[string]Endpoint)
- for _, ep := range current {
- key := ep.Method + " " + ep.Path
- currentMap[key] = ep
- }
-
- // Merge: keep existing fields, update method/path/handler
- merged := []Endpoint{}
- for _, current := range current {
- key := current.Method + " " + current.Path
-
- if existing, ok := existingMap[key]; ok {
- // Endpoint exists: keep all user metadata, update only code-derived fields
- merged = append(merged, Endpoint{
- Method: current.Method,
- Path: current.Path,
- Handler: current.Handler,
- Description: existing.Description, // Keep existing
- Implemented: existing.Implemented, // Keep existing
- CLI: existing.CLI, // Keep existing
- Curl: existing.Curl, // Keep existing
- Params: existing.Params, // Keep existing
- Examples: existing.Examples, // Keep existing
- })
- } else {
- // New endpoint: add with basic fields
- merged = append(merged, Endpoint{
- Method: current.Method,
- Path: current.Path,
- Handler: current.Handler,
- CLI: false,
- Curl: true,
- })
- }
- }
-
- return merged
-}
-
-func showChanges(existing, merged []Endpoint) {
- existingMap := make(map[string]bool)
- for _, ep := range existing {
- key := ep.Method + " " + ep.Path
- existingMap[key] = true
- }
-
- mergedMap := make(map[string]bool)
- added := []string{}
- removed := []string{}
-
- for _, ep := range merged {
- key := ep.Method + " " + ep.Path
- mergedMap[key] = true
-
- if !existingMap[key] {
- added = append(added, fmt.Sprintf("%s %s", ep.Method, ep.Path))
- }
- }
-
- for _, ep := range existing {
- key := ep.Method + " " + ep.Path
- if !mergedMap[key] {
- removed = append(removed, fmt.Sprintf("%s %s", ep.Method, ep.Path))
- }
- }
-
- if len(added) > 0 {
- fmt.Println("\n✨ New endpoints:")
- for _, ep := range added {
- fmt.Printf(" + %s\n", ep)
- }
- }
-
- if len(removed) > 0 {
- fmt.Println("\n❌ Removed endpoints:")
- for _, ep := range removed {
- fmt.Printf(" - %s\n", ep)
- }
- }
-
- if len(added) == 0 && len(removed) == 0 {
- fmt.Println("✓ No changes needed")
- }
-}
-
-func extractEndpoints(filePath string) []Endpoint {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
- if err != nil {
- return []Endpoint{}
- }
-
- var endpoints []Endpoint
-
- for _, decl := range file.Decls {
- funcDecl, ok := decl.(*ast.FuncDecl)
- if !ok {
- continue
- }
-
- if funcDecl.Name.Name == "RegisterHandlers" || funcDecl.Name.Name == "RegisterRoutes" {
- endpoints = append(endpoints, extractHandleFuncCalls(funcDecl.Body)...)
- }
- }
-
- return endpoints
-}
-
-func extractHandleFuncCalls(body *ast.BlockStmt) []Endpoint {
- var endpoints []Endpoint
- routePattern := regexp.MustCompile(`^(GET|POST|PUT|DELETE|PATCH)\s+(/[^\s]*)`)
-
- for _, stmt := range body.List {
- exprStmt, ok := stmt.(*ast.ExprStmt)
- if !ok {
- continue
- }
-
- callExpr, ok := exprStmt.X.(*ast.CallExpr)
- if !ok {
- continue
- }
-
- selector, ok := callExpr.Fun.(*ast.SelectorExpr)
- if !ok {
- continue
- }
-
- if selector.Sel.Name != "HandleFunc" && selector.Sel.Name != "Handle" {
- continue
- }
-
- if len(callExpr.Args) < 1 {
- continue
- }
-
- basicLit, ok := callExpr.Args[0].(*ast.BasicLit)
- if !ok {
- continue
- }
-
- route := strings.Trim(basicLit.Value, "\"")
- matches := routePattern.FindStringSubmatch(route)
- if len(matches) < 3 {
- continue
- }
-
- method := matches[1]
- path := matches[2]
-
- var handler string
- if len(callExpr.Args) >= 2 {
- if selectorExpr, ok := callExpr.Args[1].(*ast.SelectorExpr); ok {
- handler = selectorExpr.Sel.Name
- }
- }
-
- endpoints = append(endpoints, Endpoint{
- Method: method,
- Path: path,
- Handler: handler,
- })
- }
-
- return endpoints
-}
-
-func findProfilesFile() (string, error) {
- matches := []string{
- "internal/profiles/handlers.go",
- "internal/profiles/profiles.go",
- }
- for _, path := range matches {
- if _, err := os.Stat(path); err == nil {
- return path, nil
- }
- }
- return "", fmt.Errorf("profiles file not found")
-}
-
-func findOrchestratorFile() (string, error) {
- matches := []string{
- "internal/orchestrator/handlers.go",
- "internal/orchestrator/orchestrator.go",
- }
- for _, path := range matches {
- if _, err := os.Stat(path); err == nil {
- return path, nil
- }
- }
- return "", fmt.Errorf("orchestrator file not found")
-}
diff --git a/scripts/verify-release.sh b/scripts/verify-release.sh
deleted file mode 100755
index 6df1d7bd..00000000
--- a/scripts/verify-release.sh
+++ /dev/null
@@ -1,93 +0,0 @@
-#!/bin/bash
-# verify-release.sh - Validate that a release has all expected binary permutations
-#
-# Usage:
-# ./scripts/verify-release.sh [TAG] # Verify specific tag (default: latest)
-# ./scripts/verify-release.sh v0.7.6
-#
-# This script ensures:
-# 1. All 6 binary permutations are present
-# 2. checksums.txt exists
-# 3. Checksums are valid (optional, requires local binaries)
-
-set -e
-
-REPO="${REPO:-pinchtab/pinchtab}"
-TAG="${1:-}" # Empty = latest
-
-# Expected binary names (must match .goreleaser.yml)
-EXPECTED_BINARIES=(
- "pinchtab-linux-amd64"
- "pinchtab-linux-arm64"
- "pinchtab-darwin-amd64"
- "pinchtab-darwin-arm64"
- "pinchtab-windows-amd64.exe"
- "pinchtab-windows-arm64.exe"
-)
-
-echo "=== Release Binary Verification ==="
-echo ""
-
-# Get release info
-if [ -z "$TAG" ]; then
- echo "📦 Fetching latest release..."
- RELEASE=$(gh release view --repo "$REPO" --json assets,tagName)
-else
- echo "📦 Fetching release: $TAG"
- RELEASE=$(gh release view "$TAG" --repo "$REPO" --json assets,tagName 2>/dev/null) || {
- echo "❌ Release not found: $TAG"
- exit 1
- }
-fi
-
-TAG_NAME=$(echo "$RELEASE" | jq -r '.tagName')
-echo " Tag: $TAG_NAME"
-echo ""
-
-# Extract asset names
-ASSETS=$(echo "$RELEASE" | jq -r '.assets[].name')
-
-# Check for each expected binary
-FOUND=0
-MISSING=()
-
-echo "Checking binaries:"
-for BINARY in "${EXPECTED_BINARIES[@]}"; do
- if echo "$ASSETS" | grep -q "^${BINARY}$"; then
- echo " ✓ $BINARY"
- ((FOUND++))
- else
- echo " ✗ $BINARY (MISSING)"
- MISSING+=("$BINARY")
- fi
-done
-
-EXPECTED_COUNT=${#EXPECTED_BINARIES[@]}
-
-echo ""
-echo "Summary:"
-echo " Expected: $EXPECTED_COUNT"
-echo " Found: $FOUND"
-
-# Check for checksums
-if echo "$ASSETS" | grep -q "^checksums.txt$"; then
- echo " ✓ checksums.txt present"
-else
- echo " ✗ checksums.txt missing"
-fi
-
-echo ""
-
-# Status
-if [ $FOUND -eq $EXPECTED_COUNT ] && echo "$ASSETS" | grep -q "^checksums.txt$"; then
- echo "✅ All binaries present ($FOUND/$EXPECTED_COUNT)"
- exit 0
-else
- if [ ${#MISSING[@]} -gt 0 ]; then
- echo "❌ Missing binaries:"
- for BIN in "${MISSING[@]}"; do
- echo " - $BIN"
- done
- fi
- exit 1
-fi