# ADbotix — PROJECT INSTRUCTIONS (read this first, every session)

This is the root build-rules file for the ADbotix platform. Claude Code MUST read this
file at the start of every session before writing or changing any code. The full
business logic and numbers live in `ADbotix_Development_Specification.md` — this file is
the *engineering contract* for HOW we build, not WHAT the numbers are.

---

## 1. What we are building

An investment platform with three income engines (Stacking, Holding, Global Auto Pool)
plus 30-level team income, ranks, capping, wallet, and withdrawals. Money is handled, so
correctness and auditability beat cleverness everywhere.

Phase-1 payments: **MetaMask deposit + manual admin verification (tx-hash) + manual
weekly payout.** No live payment gateway, no auto-payout in phase 1.

---

## 2. Tech stack (do not deviate without asking)

- PHP 8.x, Yii2 **Advanced** template (frontend / backend / common / console).
- MySQL 8.x, InnoDB. **All schema changes via migrations only** (`console/migrations/`).
- Frontend views: HTML + **Tailwind CSS**. One compiled CSS file for the public+panel
  frontend, one for backend admin.
- No heavy JS framework. Plain JS / Alpine.js only if genuinely needed.
- **Visual design is governed by `DESIGN_SYSTEM.md` — read it before building any view.**
  It is the single source of truth for colors, typography, spacing, and components, and
  follows Anthropic's frontend-design discipline (one cohesive direction, shared tokens,
  distinctive non-Inter typography). Design tokens live once in `tailwind.tokens.js` and feed
  both Tailwind builds; shared UI partials live in `common/views/components/` and every page
  is composed from them (never inline a styled element a partial already covers — §8).

---

## 3. Repository structure (authoritative)

```
adbotix/
├── common/
│   ├── models/            # ActiveRecord models (shared)
│   ├── services/          # ALL business logic lives here (see rule 5)
│   ├── views/components/  # shared design-system UI partials (see DESIGN_SYSTEM.md)
│   └── helpers/
├── console/
│   ├── controllers/       # cron jobs (M12) as console commands
│   └── migrations/        # every table + change, nothing manual
├── frontend/
│   ├── modules/site/      # public website (5 pages, anonymous)
│   ├── modules/panel/     # investor / leader dashboard (auth-gated)
│   └── web/media/         # ALL images live here
├── backend/               # admin panel (M11), auth-gated, admin RBAC
├── ADbotix_Development_Specification.md   # the business spec (numbers + logic)
├── DESIGN_SYSTEM.md                      # visual design contract (read before any view)
├── PROJECT_INSTRUCTIONS.md               # this file
└── PROGRESS.md                           # running build log (update every feature)
```

- Public website and panel are BOTH in `frontend` but separated by module
  (`site` vs `panel`) with separate asset bundles. Marketing site stays light;
  panel is always behind login.
- One `media/` folder at `frontend/web/media/`. No images scattered elsewhere.

---

## 4. The golden rule: thin controllers, fat services

**All business logic goes in `common/services/` as plain service classes.** Controllers
(frontend, backend) and cron jobs (console) only validate input and CALL services. They
never compute income, mutate wallets, or place pool positions directly.

Why: the same logic is triggered from three places (panel actions, admin actions, cron).
Duplicating it guarantees drift and money bugs. One service = one source of truth = testable.

Example services we will build:
`InvestmentService`, `WalletService`, `StackingService`, `HoldingService`,
`PoolService`, `ReferralService`, `RoyaltyService`, `RebirthService`,
`LevelIncomeService`, `RankService`, `CappingService`, `WithdrawalService`.

---

## 5. Money & wallet rules (non-negotiable)

1. Every balance change goes through `WalletService` and writes ONE `wallet_ledger` row.
   No model ever edits `wallets.balance` directly.
2. Every wallet mutation runs inside a DB transaction. On any error, roll back fully.
3. `wallet.balance` must ALWAYS equal the sum of its ledger rows. Add a test that asserts this.
4. Every ledger row is tagged with a `source` enum (stacking, holding, level, rank,
   referral, royalty, matrix, rebirth, transfer_in, transfer_out, withdrawal, fee).
5. Cap checks (M9) happen at credit time, inside the crediting service.
6. Money stored as DECIMAL(18,2) — never float. Percentages as DECIMAL too.
7. Cron jobs are idempotent: a `job_runs` table keys each run by (job, period). Re-running
   the same period must never double-credit.

---

## 6. Security baseline (every feature)

- All panel/admin routes behind auth; admin uses RBAC roles.
- CSRF on all forms (Yii2 default — keep enabled).
- Use ActiveRecord / parameter binding only. Never string-concatenate SQL.
- Validate and whitelist every input in model rules; never trust client values
  (especially amounts, plan ids, usernames, tx-hashes).
- Passwords via Yii2 `Yii::$app->security` hashing only.
- Withdrawals and transfers: server recomputes fees and balances; never trust amounts
  sent from the client.
- Admin actions and config changes write to an immutable `audit_log`.
- Rate-limit login and withdrawal-request endpoints.

---

## 7. Database rules

- Every table created/changed via a migration. Name migrations clearly
  (`m250101_000001_create_wallets_table`).
- Keep schema normalized but simple. Index foreign keys and any column used in WHERE/JOIN
  by the cron jobs (user_id, sponsor_id, date, month, status).
- Use a `tree_closure` table for genealogy (ancestor, descendant, depth) so level-income
  and 60:40 queries stay fast.
- Every table: `id`, `created_at`, `updated_at` unless there is a reason not to.
- Use foreign keys with sensible ON DELETE behaviour (mostly RESTRICT for money tables).

---

## 8. Code style

- Clean, simple, readable. No premature abstraction, no clever one-liners.
- Reusable: shared logic in services/helpers, shared views as partials.
- One responsibility per class/method. Methods short.
- Comment the WHY for any non-obvious money/percentage rule, citing the spec section
  (e.g. `// M6.3.4: first cycle deducts 58%, rebirths deduct 23%`).
- No dead code, no commented-out blocks left behind.

---

## 9. How we work: ONE feature at a time, end to end

We build in the dependency order in `EXECUTION_PLAN.md`. For EACH feature, complete this
full loop before starting the next:

1. **Migration** — create/alter tables for this feature.
2. **Model(s)** — ActiveRecord with validation rules.
3. **Service** — business logic in `common/services/`.
4. **Controller + views** — thin controller, Tailwind views.
5. **Wiring** — menu links, routes, asset bundle.
6. **Test** — unit test the service (esp. money math) + manual run-through against the
   feature's Acceptance Criteria in the spec.
7. **Update `PROGRESS.md`** — what was built, any decisions, what's next.

Do not start a new feature until the current one passes its Acceptance Criteria.

---

## 10. Definition of done (per feature)

- Migration runs clean up AND down (`migrate/up`, `migrate/down`).
- Service has tests covering the spec's worked examples and edge cases.
- Acceptance Criteria from the spec section all pass.
- No direct balance edits; ledger reconciles.
- Code reviewed against this file's rules.
- `PROGRESS.md` updated.

---

## 11. What to ask before assuming

If a number or rule is not in `ADbotix_Development_Specification.md`, STOP and ask — do not
invent percentages, caps, or fees. The five open items in spec §14 are explicitly unsettled;
use a config value with a clearly-marked default and flag it, do not hardcode a guess.
