# madarX OS

A **local-first** Next.js + React agent product. SQLite-backed runtime, background cron daemon, durable heartbeat worker, approval-gated local tools, and a Main Agent chat for orchestrating named workers. The whole stack runs on your machine.

> Status: actively developed. HAIL Phases 1–6 are implemented and validated. See [STATUS.md](./STATUS.md) for the current milestone, [project-update.md](./project-update.md) for the detailed running handoff, and [CHANGELOG.md](./CHANGELOG.md) for shipped work.

## Prerequisites

- **Node.js ≥ 22.5** — required for the built-in `node:sqlite` module.
- macOS or Linux. Windows is not currently tested.

## Quick start

Install the `madarx` command, then run everything with one command:

```bash
curl -fsSL https://raw.githubusercontent.com/kareemodev777/madarx-os/main/scripts/install.sh | bash
# or: npm install -g madarx

madarx setup     # master key, folder permissions, API keys, WhatsApp, auto-update
madarx           # boots web + cron + heartbeat + WhatsApp, opens the dashboard
```

`madarx` boots the web dashboard, the cron scheduler, the durable heartbeat worker, and the WhatsApp bridge (idle until you pair a number), then opens <http://127.0.0.1:8787/>. Your data lives in `~/.madarx/`, so upgrades never touch it. Update anytime with `madarx update`. See the [npm guide](./docs/npm-guide.md) for how install/usage/updates work, or [`docs/install.md`](./docs/install.md) for the command reference.

Prerequisite: **Node.js ≥ 22.5** (for the built-in `node:sqlite` module).

### Develop from source

```bash
git clone https://github.com/kareemodev777/madarx-os.git
cd madarx-os
npm install
npm run dev        # http://127.0.0.1:8787/
```

For a production-style build: `npm run build && npm start`.

## Background daemons

When you run `madarx`, the cron scheduler, heartbeat worker, and WhatsApp bridge are started for you. In a from-source / separate-process deployment you can run them individually:

```bash
npm run daemon            # cron daemon — queues due schedules into heartbeat_tasks
npm run heartbeat:worker  # durable worker — claims tasks, retries, recovers stale leases
```

One-shot variants for testing:

```bash
npm run daemon:once
npm run heartbeat:once
```

The cron daemon writes due work into the SQLite `heartbeat_tasks` table. The heartbeat worker claims it with leases, runs it, retries transient failures with backoff, and pauses approval-required tasks.

Optional WhatsApp gateway (pair a **dedicated** number, not your personal one — Baileys is unofficial and the paired number can be banned):

```bash
npm run whatsapp:bridge
```

## Voice (Jarvis)

A polished voice console for the Main Agent — open it from the chat panel's microphone button. Every lane is opt-in and bring-your-own-key; nothing reaches an external provider until a credential lands in the secrets vault. See `docs/voice/jarvis.md` for the full operator guide.

| Lane | What it needs | Notes |
|------|---------------|-------|
| **Realtime** (primary) | `OPENAI_API_KEY` | Server mints a 60-second ephemeral session; browser opens WebRTC directly to OpenAI. The long-lived key never crosses to the browser. |
| **TTS-only** (fallback) | `ANTHROPIC_API_KEY` + (`OPENAI_API_KEY` or `ELEVENLABS_API_KEY`) | Existing typed chat handles the LLM; `POST /api/voice/tts` speaks the final reply. |
| **Local** (open-source slots) | `MADARX_LOCAL_STT_URL`, `MADARX_LOCAL_TTS_URL` | URL slots for Whisper.cpp / FasterWhisper / Piper / Coqui. |
| **Off** | – | Default when no providers are configured. |

The voice agent is given the durable Madarx context on every session mint: today's date, active project, open tasks, recent artifact titles, pending approvals, brand voice, and non-`local_only` memory rows. It can call a curated tool set (`create_artifact`, `update_artifact`, `delete_artifact`, `find_artifacts`, `get_state`, `web_search`, `web_fetch`, `voice_speak`); every call routes through `executeRegistryTool` / `executeTool`, so trust-mode, approval gates, allowlists, rate limits, and audit are identical to typed chat. Voice **never** bypasses the `irreversible_external` approval gate (e.g. `gh_pr_merge`, `email_send`, `supabase_sql`).

Brand: Onyx surface, Bone/Graphite text, Mars Red reserved for active speech peaks + approval banners.

## Open Design corpus

A pinned, read-only mirror of [`nexu-io/open-design`](https://github.com/nexu-io/open-design) lives under [`workspace/skills/open-design/`](./workspace/skills/open-design/). It ships craft notes, ~130 design skills, ~140 design systems, and prompt + design templates. Apache-2.0 — see the bundled `NOTICE.md`.

Claude-Code-backed agents see the tree natively via `--add-dir workspace`. Non-Claude-Code engines get an injected catalog from `lib/agent-open-design-skills.js`. Read it programmatically via `lib/open-design.js` or `GET /api/marketplace/open-design`.

Refresh against a newer upstream commit:

```bash
# 1. Edit scripts/vendor-open-design.config.json to bump `commit`
# 2. Clone open-design at that commit somewhere local (default: /tmp/open-design)
# 3. Re-vendor (idempotent — clean re-runs produce no diff):
npm run vendor:open-design
```

## Documentation

- [`docs/npm-guide.md`](./docs/npm-guide.md) — how the `madarx` npm package installs, what it installs, how to use it, and how updates work.
- [`docs/install.md`](./docs/install.md) — install / run / commands quick reference.
- [`CLAUDE.md`](./CLAUDE.md) — canonical architecture, commands, API surface, and key constraints. Start here if you are reading the code.
- [`STATUS.md`](./STATUS.md) — concise current project status, validation results, and remaining roadmap.
- [`project-update.md`](./project-update.md) — current state of the product.
- [`CHANGELOG.md`](./CHANGELOG.md) — what shipped, newest first.
- [`CONTRIBUTING.md`](./CONTRIBUTING.md) — how to contribute.
- [`SECURITY.md`](./SECURITY.md) — vulnerability reporting.
- [`specs/`](./specs/) — implementation plans, requirements, and QA notes.

## What this product includes

- Next.js 15 App Router dashboard at `/`.
- Admin console under `/projects`, `/agents`, `/tasks`, `/approvals`, `/disk`, `/missions`, `/audit`, `/schedules`, `/activity`, `/reports`, `/marketplace`, `/help`, `/settings`. Diagnostics at `/runtime`.
- SQLite database at `data/madarx.sqlite`.
- API routes backed by the same runtime database (see [`CLAUDE.md`](./CLAUDE.md#api-surface) for the full list).
- Background cron daemon (`scripts/cron-daemon.mjs`) and heartbeat worker (`scripts/heartbeat-worker.mjs`) backed by durable SQLite tables.
- Per-agent engine routing across Anthropic API, Claude Code CLI, Ollama, Hermes, and Codex.
- Safe local-machine tool marketplace (files / terminal / processes / web / Supabase / Vercel / GitHub / Resend / voice) with allowlists, sliding-window rate limits, and a four-tier risk model.
- Vendored design corpus from `nexu-io/open-design` at `workspace/skills/open-design/` — see the [Open Design corpus](#open-design-corpus) section.
- Generic one-time approval requests in `approval_requests` exposed via `/api/approvals`.
- Generated agent files under `workspace/agents/<agent-id>/`.

## Secrets

Integration credentials (Anthropic, GitHub token, Resend, Supabase, etc.) live in an **AES-256-GCM encrypted vault** inside the SQLite database, not in `.env.local`.

On first run, if no master key is set, one is generated and written to `.env.local` along with a warning. To set one explicitly:

```bash
# Generate a key
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"

# Export it (or add to ~/.zshrc / ~/.bashrc to persist)
export MADARX_MASTER_KEY=<paste key here>
```

**Add credentials** through the dashboard at Tools → Secrets, or import existing `.env.local` keys with:

```bash
node scripts/migrate-env-to-secrets.mjs
```

After migration, remove the imported keys from `.env.local`. Non-credential config (`MADARX_ALLOWED_ROOTS`, `CRON_DAEMON_INTERVAL_MS`, etc.) stays in `.env.local` — see [`.env.example`](./.env.example).

Never commit `.env.local`, the SQLite database, the `workspace/` directory, or the `data/whatsapp/session/` directory.

## Testing and checks

```bash
npm test          # full test suite (Node built-in test runner)
npm run build     # Next.js production build
npm run check     # canonical pre-ship gate: syntax checks + tests + build
npm run smoke:routes  # ping every admin route against a running dev server, assert 200
```

CI runs `npm run check` on every pull request and push to `main` via [`.github/workflows/check.yml`](./.github/workflows/check.yml).

## Local tool safety and approvals

Default local tool roots are the repo root and `workspace/`. Add extra roots with `MADARX_ALLOWED_ROOTS`.

Read-only file tools can run automatically inside allowed roots. File writes, patches, risky terminal commands, package-manager mutation, process kills, deploys, git commits, and git pushes create durable approval requests first. Approvals are single-use.

**Blocked by default:** `.env*`, `.ssh`, `/etc`, `/var`, `/private`, `/System`, `/Library`, `sudo`, `rm -rf`, `git reset --hard`. Tool output previews are capped and redacted before audit logging.

A fourth risk tier — **`irreversible_external`** — always requires human approval regardless of trust mode. This covers `gh_pr_merge`, `stripe_refund`, `email_send`, `supabase_rest_delete`, raw destructive SQL, and similar actions.

If heartbeat work gets stuck, run `npm run heartbeat:once`; stale leased/running tasks are recovered when their lease expires. Inspect `heartbeat_tasks`, `heartbeat_task_events`, pending approvals, and `local_tool_audit` from `/api/state` or the dashboard runtime panels.

## Deployment

madarX OS is local-first. Self-host on any Node 22+ environment — your laptop, a VPS, a container, or a platform like Vercel, Fly, or Render. No platform-specific glue is required. The cron daemon, heartbeat worker, and (optional) WhatsApp bridge each need a long-running process slot.

For a single-machine self-host, run `npm run build && npm start` for the web tier and start the daemons under a process manager of your choice (systemd, pm2, tmux, supervisord — pick what your host gives you).

## License

[MIT](./LICENSE) © 2026 Abdul Kareem.
