# Contributing to Assuremind

This guide covers how to build, test, and publish the package from source.

---

## Prerequisites

| Tool | Version |
|------|---------|
| Node.js | >= 18 |
| npm | >= 9 |
| Git | any recent |

---

## Clone and Install

```bash
git clone https://github.com/your-org/assuremind.git
cd assuremind
npm install
```

Install the UI dependencies separately:

```bash
cd ui && npm install && cd ..
```

---

## Project Structure

```
assuremind/
├── src/
│   ├── cli/          # CLI entry point and commands (init, run, generate, …)
│   ├── engine/       # Test runner, executor, self-healing, Allure reporter, recorder
│   ├── ai/           # Smart router, provider adapters, prompts, code cache
│   ├── mcp/          # Playwright MCP integration (accessibility snapshots, action mapper)
│   ├── rag/          # RAG memory — TF-IDF embedder, vector store, code/healing/error corpora
│   ├── storage/      # File-based JSON stores (suites, cases, results, healing)
│   ├── server/       # Fastify API server + WebSocket
│   ├── types/        # Zod schemas and TypeScript types
│   └── utils/        # Shared utilities (errors, logger, hash, sanitize, env)
├── ui/               # React 18 + Vite + TailwindCSS Studio front-end
│   └── src/
│       ├── api/      # Typed API client
│       ├── components/
│       ├── hooks/
│       └── pages/    # Dashboard, TestEditor, Reports, Healing, …
├── templates/        # Files copied into user projects on `init`
├── tests/
│   ├── unit/         # Pure unit tests (no I/O, fast)
│   └── integration/  # CLI and server integration tests
├── tsup.config.ts    # Library bundler config
└── vitest.config.ts  # Test runner config
```

---

## Build Commands

### Build everything (library + UI)

```bash
npm run build
```

This runs two steps in order:

**1. Build the TypeScript library:**

```bash
npm run build:lib
```

Uses `tsup` to compile `src/` → `dist/`. Outputs:
- `dist/index.js` / `dist/index.mjs` — CJS + ESM entry points
- `dist/index.d.ts` — TypeScript declarations
- `dist/cli/index.js` — CLI binary (referenced by `bin.assuremind` in package.json)

**2. Build the React UI:**

```bash
npm run build:ui
```

Runs `vite build` inside `ui/`. Output goes to `ui/dist/`. The Fastify server serves this at runtime via `@fastify/static`.

---

## Development Mode

Watch for TypeScript changes and recompile the library:

```bash
npm run dev
```

Watch and hot-reload the Studio UI (requires `npm run dev` running in parallel):

```bash
npm run dev:ui
```

---

## Testing

Run the full test suite:

```bash
npm test
```

Run with coverage report:

```bash
npm run test:coverage
```

Run in watch mode during development:

```bash
npm run test:watch
```

### Test organisation

| Directory | Purpose | Speed |
|-----------|---------|-------|
| `tests/unit/` | Individual functions and classes | ~5 ms/test |
| `tests/integration/` | CLI commands, server HTTP routes | ~50–300 ms/test |

**Coverage target:** > 80% statements.

Engine files (`src/engine/`) and AI provider adapters (`src/ai/providers/`) are excluded from coverage thresholds because they require live Playwright browsers and API keys respectively.

---

## Linting and Formatting

```bash
npm run lint          # ESLint (TypeScript-aware)
npm run lint:fix      # Auto-fix lint issues
npm run format        # Prettier
npm run typecheck     # tsc --noEmit (no output, just type errors)
```

---

## Adding a New AI Provider

1. Create `src/ai/providers/<name>.ts` implementing the `AIProvider` interface from `src/types/ai.ts`.
2. Register it in `src/ai/router.ts` → `createProvider()` switch.
3. Add the required env vars to `templates/env.example`.
4. Add validation in `src/utils/env.ts` → `PROVIDER_ENV` map.
5. Update `docs/GETTING-STARTED.md` with the new provider block.

---

## Releasing a New Version

This package is distributed via private GitHub repository (not npm registry).

### Steps to release

```bash
# 1. Update version in package.json
#    e.g., "version": "1.1.0"

# 2. Build and verify
npm run build
npm test

# 3. Commit and tag
git add -A
git commit -m "release: v1.1.0"
git tag v1.1.0

# 4. Push
git push origin main
git push origin v1.1.0
```

### Versioning

Follow [Semantic Versioning](https://semver.org):

| Change | Version bump | Example |
|--------|-------------|---------|
| Bug fixes | Patch | `1.0.0` → `1.0.1` |
| New features (backwards compatible) | Minor | `1.0.0` → `1.1.0` |
| Breaking changes | Major | `1.0.0` → `2.0.0` |

### Consumer installation

```bash
npm install git+https://github.com/<org>/assuremind.git#v1.1.0
```

---

## Architecture Notes

### Storage model

Everything is stored as plain JSON files in the user's project directory — no database required. Structure after `init`:

```
<project>/
├── tests/
│   └── <suite-slug>/
│       ├── suite.json
│       └── <case-slug>.test.json
├── variables/
│   ├── global.json
│   ├── dev.env.json
│   ├── staging.env.json
│   └── prod.env.json
├── results/
│   ├── runs/
│   │   └── <runId>.json
│   ├── screenshots/
│   ├── videos/
│   ├── traces/
│   ├── reports/
│   ├── healing/
│   └── .rag/              # RAG semantic memory (auto-generated)
│       ├── idf-vocab.json
│       ├── code-corpus.json
│       ├── healing-corpus.json
│       └── error-catalog.json
└── autotest.config.json   # written by writeConfig()
```

Suite and case file names are derived from the `name` field via `toSlug()` (lowercased, alphanumeric + hyphens). This means **the directory/file name is the URL parameter** used in Studio API routes — not the UUID stored inside the JSON.

### Self-healing cascade

When a test step fails, the engine tries up to 5 healing levels in order:

| Level | Strategy |
|-------|---------|
| 1 | Smart Retry — wait + retry with backoff |
| 2 | AI Regeneration — AI rewrites Playwright code |
| 3 | Multi-Selector — try alternate selectors (ID, text, role, aria) |
| 4 | Visual/SoM — screenshot + AI visual analysis |
| 5 | Decompose — break step into smaller sub-actions |

Healed steps are saved as `pending` events in `results/healing/pending.json` for human review via `npx assuremind apply-healing` or the Studio Healing page.

### AI cost optimisation

1. **Template engine** — recognises common patterns (navigate, click, fill, etc.) and uses zero-cost templates.
2. **Code cache** — SHA-based cache keyed on `(normalised instruction, url pattern)`. Cache persists to `results/code-cache.json`.
3. **RAG memory** — semantic retrieval from past runs. Code Corpus matches >= 0.90 are used directly as fuzzy cache hits ($0). Lower matches (0.65-0.90) enrich the AI prompt. Healing Corpus injects proven past fixes into self-healing prompts. Error Catalog warns the AI about known-bad patterns.
4. **MCP enrichment** — when enabled, the SmartRouter takes a live accessibility snapshot and feeds real page elements to the AI, boosting selector accuracy to ~90-95%.
5. **Complexity classifier** — routes simple steps to cheap/fast models (tiered mode) and complex steps to capable models.
6. **Batch generation** — multiple empty steps sent in one API call.
7. **Test Recorder** — deterministic code from browser interactions, zero AI calls. Uses Playwright's accessibility tree to resolve locators with 6 strategies, verified with `count() === 1`.
