# 🧾 Zero to NanoBooks: Master Self-Study Curriculum & Engineering Blueprint
### *The Definitive 24-Stage Engineering Journey on Google Antigravity (AGY)*

> **Target Audience**: Full-Stack Engineers & Autonomous Agent Collaborators  
> **Scope**: Monorepo Architecture, Multi-Tenant PostgreSQL RLS, Fastify, Next.js, GST/Accounting, DevOps & Antigravity Agent Fleet  
> **Stages**: 00 → 23 (Capstone) + Autonomous Agent Ecosystem  
> **Repository**: [`/Users/vijaygurukumar/infinite-erp`](file:///Users/vijaygurukumar/infinite-erp)

---

## 🧭 Architectural Overview & How to Use This Curriculum

This curriculum is arranged in **strict dependency order** — each stage builds directly on the conceptual and technical foundation of the previous ones. Every stage provides:
1. **Core Topics**: The foundational principles you need to master.
2. **Curated Free Resources**: High-signal documentation, interactive sandboxes, and guides.
3. **Repository Pointers ("See it in NanoBooks")**: Exact files and implementations in your own codebase with clickable links.
4. **Self-Verifiable Checkpoints**: Concrete, zero-grade exercises to validate your understanding experimentally.

```mermaid
flowchart TD
    subgraph Foundations ["Core Foundations (Stages 0–5)"]
        S0["00: Terminal & CLI"] --> S1["01: Git & GitHub"]
        S1 --> S2["02: Modern JavaScript"]
        S2 --> S3["03: Strict TypeScript"]
        S3 --> S4["04: Relational SQL"]
        S4 --> S5["05: PostgreSQL Engine"]
    end

    subgraph BackendCore ["Backend & Security Core (Stages 6–11)"]
        S5 --> S6["06: 🛡️ Multi-Tenancy RLS (UNAVOIDABLE)"]
        S6 --> S7["07: HTTP & REST Protocols"]
        S7 --> S8["08: Fastify Framework"]
        S8 --> S9["09: 🔐 Auth & Request Lifecycle (UNAVOIDABLE)"]
        S9 --> S10["10: Zod Validation Shields"]
        S10 --> S11["11: node:test & Local Feedback (<4s)"]
    end

    subgraph FrontendSuite ["Modern Web & Frontend (Stages 12–16)"]
        S11 --> S12["12: HTML & CSS Semantics"]
        S12 --> S13["13: React & State Primitives"]
        S13 --> S14["14: Next.js App Router"]
        S14 --> S15["15: Tailwind Design System"]
        S15 --> S16["16: Web Patterns (apiFetch, i18n, PWA, Offline)"]
    end

    subgraph DomainDevOps ["Domain Knowledge & DevOps (Stages 17–22)"]
        S16 --> S17["17: 🏛️ Indian GST Engine (REVIEW GATE)"]
        S17 --> S18["18: 📚 Double-Entry Accounting (REVIEW GATE)"]
        S18 --> S19["19: Docker Multi-Stage Builds"]
        S19 --> S20["20: GCP Serverless Stack"]
        S20 --> S21["21: CI/CD & GitHub Actions"]
        S21 --> S22["22: 🚀 Deployment & Staging Gate (UNAVOIDABLE)"]
    end

    subgraph Graduation ["Capstone & Agent Symphony (Stage 23+)"]
        S22 --> S23["23: 🎓 Capstone: Ship Solo Feature"]
        S23 --> AG["🤖 Antigravity Multi-Agent Orchestration"]
    end

    style S6 fill:#fde8e8,stroke:#e02424,stroke-width:2px;
    style S9 fill:#fde8e8,stroke:#e02424,stroke-width:2px;
    style S17 fill:#fef08a,stroke:#ca8a04,stroke-width:2px;
    style S18 fill:#fef08a,stroke:#ca8a04,stroke-width:2px;
    style S22 fill:#fde8e8,stroke:#e02424,stroke-width:2px;
    style S23 fill:#dcfce7,stroke:#16a34a,stroke-width:3px;
    style AG fill:#e0e7ff,stroke:#4f46e5,stroke-width:2px;
```

---

## 00. Terminal Foundations & Modern Development Environment

Get comfortable with the foundational tools — Unix filesystem, terminal navigation, environment variables, and modern editors.

* **Key Topics**:
  - Filesystem hierarchy, absolute vs. relative paths, symlinks, file permissions.
  - Shell commands: `cd`, `ls -la`, `mkdir -p`, `pwd`, `grep`, `find`, `cat`, piping (`|`).
  - Environment variables (`PATH`, `NODE_ENV`, `.env` injection).
  - Modern IDE setup (VS Code / Antigravity workspace layout).
* **Curated Resources**:
  - [MDN Command Line Crash Course](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line)
  - [freeCodeCamp: Learn the Linux Command Line](https://www.freecodecamp.org/news/the-linux-command-line-handbook/)
* **See it in NanoBooks**:
  - Review repository structure: [`/apps/api`](file:///Users/vijaygurukumar/infinite-erp/apps/api), [`/apps/web`](file:///Users/vijaygurukumar/infinite-erp/apps/web), [`/packages/db`](file:///Users/vijaygurukumar/infinite-erp/packages/db), [`/scripts`](file:///Users/vijaygurukumar/infinite-erp/scripts).
  - Inspect project documentation: [`AGENTS.md`](file:///Users/vijaygurukumar/infinite-erp/AGENTS.md).
* **Checkpoint**:
  ```bash
  cd /Users/vijaygurukumar/infinite-erp
  ls -la apps/api/src/routes
  ```
  Navigate across apps, list route files, and inspect package configurations without errors.

---

## 01. Git, GitHub & Branch Discipline

Version control fundamentals and the discipline of clean git commits, branch isolation, and pull requests.

* **Key Topics**:
  - Commits, SHAs, staged vs. working tree changes (`git status`, `git diff`, `git add -p`).
  - Trunk-based branching (`main` vs. `feature/*`), merge vs. rebase.
  - Remote synchronization (`clone`, `fetch`, `pull --rebase`, `push`).
  - Why production promotion requires a clean committed SHA (`git rev-parse HEAD`).
* **Curated Resources**:
  - [Learn Git Branching (Interactive Sandbox)](https://learngitbranching.js.org/)
  - [Pro Git Book (Chapters 1–3)](https://git-scm.com/book/en/v2)
* **See it in NanoBooks**:
  - Walkthrough: [`docs/first-pr-walkthrough.md`](file:///Users/vijaygurukumar/infinite-erp/docs/first-pr-walkthrough.md).
  - Pre-promotion gate logic: [`scripts/staging-agent.py`](file:///Users/vijaygurukumar/infinite-erp/scripts/staging-agent.py).
* **Checkpoint**:
  Create a test branch, edit a markdown file, run `git status`, commit with a structured semantic message, and verify `git log -n 1`.

---

## 02. Modern JavaScript (ESNext & Async Primitives)

Master modern JavaScript language features, functional primitives, and asynchronous event-loop mechanics.

* **Key Topics**:
  - Scope, block bindings (`const`/`let`), closures, and immutability.
  - Array functional transformations: `.map()`, `.filter()`, `.reduce()`, `.find()`, `.some()`.
  - Object manipulation: destructuring, rest/spread operators, optional chaining (`?.`), nullish coalescing (`??`).
  - Async runtime: Microtasks, Event Loop, Promises, `async`/`await`, `Promise.all()`, error handling via `try/catch`.
* **Curated Resources**:
  - [Eloquent JavaScript (Free 4th Edition)](https://eloquentjavascript.net/)
  - [MDN JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
* **See it in NanoBooks**:
  - Pure calculation engine: [`apps/api/src/lib/gst.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/gst.ts).
  - Money & paise precision utilities: [`apps/api/src/lib/money.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/money.ts).
* **Checkpoint**:
  Write a standalone Node.js script using `Array.prototype.reduce` and `async/await` to process an invoice line array, calculate totals with discounts, and format output into JSON.

---

## 03. Strict TypeScript & Type Systems

TypeScript type systems in strict mode across backend APIs, shared DB packages, and frontend clients.

* **Key Topics**:
  - Types vs. Interfaces, utility types (`Partial`, `Pick`, `Omit`, `Record`).
  - Type narrowing, Discriminated Unions, type guards (`is`).
  - Generics and generic constraints (`<T extends Record<string, unknown>>`).
  - Module declaration & ambient type augmentations (`declare module 'fastify'`).
  - `strict: true`, `noImplicitAny`, and `exactOptionalPropertyTypes`.
* **Curated Resources**:
  - [TypeScript Official Handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
  - [TypeScript Playground](https://www.typescriptlang.org/play)
* **See it in NanoBooks**:
  - Fastify request type augmentation: [`apps/api/src/plugins/tenant.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/tenant.ts).
  - Type-safe fetch client: [`apps/web/src/lib/api.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/lib/api.ts).
* **Checkpoint**:
  Run the project TypeScript verification:
  ```bash
  python3 scripts/dev-agent.py typecheck
  ```
  Ensure all apps compile with zero type errors.

---

## 04. Relational Database & SQL Core

Relational data modeling, ACID properties, indexing, and join algorithms independent of vendor specifics.

* **Key Topics**:
  - Relational algebra: Entities, attributes, composite primary keys, foreign keys.
  - DML operations: `SELECT`, `INSERT ... RETURNING`, `UPDATE`, `DELETE`, `UPSERT` (`ON CONFLICT`).
  - Joins: `INNER JOIN`, `LEFT JOIN`, `CROSS JOIN LATERAL`.
  - Aggregations: `GROUP BY`, `HAVING`, `SUM()`, `COUNT()`, Window functions (`ROW_NUMBER() OVER (...)`).
  - Database Normalization (1NF, 2NF, 3NF, BCNF) vs. Pragmatic Denormalization.
* **Curated Resources**:
  - [SQLBolt: Interactive SQL Lessons](https://sqlbolt.com/)
  - [PostgreSQL Tutorial: SQL Language](https://www.postgresql.org/docs/current/tutorial-sql.html)
* **See it in NanoBooks**:
  - Clean relational table migration: [`packages/db/migrations/004_create_customers.sql`](file:///Users/vijaygurukumar/infinite-erp/packages/db/migrations/004_create_customers.sql).
* **Checkpoint**:
  Write and execute a SQL query joining `invoices` with `invoice_items` and `customers`, grouping by customer ID and calculating total revenue.

---

## 05. PostgreSQL Engine & Migration Architecture

Deep dive into PostgreSQL types, connection management, MVCC, and schema migrations.

* **Key Topics**:
  - PostgreSQL specialized types: `UUID`, `TIMESTAMPTZ`, `JSONB`, `NUMERIC(15,2)`, `TEXT`.
  - Transactions: `BEGIN`, `COMMIT`, `ROLLBACK`, Savepoints, Transaction isolation levels (`READ COMMITTED`, `SERIALIZABLE`).
  - Indexing strategies: B-Tree, GIN on JSONB, Composite indexes `(tenant_id, created_at)`.
  - Migration lifecycles: Numeric versioning, deterministic up/down migrations.
* **Curated Resources**:
  - [PGExercises: Interactive Postgres Queries](https://pgexercises.com/)
  - [PostgreSQL Documentation: Data Definition](https://www.postgresql.org/docs/current/ddl.html)
* **See it in NanoBooks**:
  - Local database orchestration: [`docs/local-setup.md`](file:///Users/vijaygurukumar/infinite-erp/docs/local-setup.md).
  - Schema migrations directory: [`packages/db/migrations/`](file:///Users/vijaygurukumar/infinite-erp/packages/db/migrations/).
  - Migration linter:
    ```bash
    python3 scripts/dev-agent.py audit-migrations
    ```
* **Checkpoint**:
  Inspect migration files, verify ordering, and run the automated migration audit tool.

---

## 06. 🛡️ Multi-Tenancy Invariant & Row-Level Security (RLS)
> [!CAUTION]
> **CRITICAL ARCHITECTURAL BOUNDARY (UNAVOIDABLE)**:
> Multi-tenancy in NanoBooks is enforced mathematically at the PostgreSQL layer, **NEVER** solely by application `WHERE` clauses.

* **Key Topics**:
  - The shared-database, shared-schema multi-tenant architecture.
  - PostgreSQL Row-Level Security: `ALTER TABLE ... ENABLE ROW LEVEL SECURITY;` and `FORCE ROW LEVEL SECURITY;`.
  - Transaction-local tenant context: `set_config('app.current_tenant', tenant_id, true)` (the 3rd argument `is_local = true` binds it strictly to the current transaction).
  - Composite foreign keys: `FOREIGN KEY (tenant_id, customer_id) REFERENCES customers(tenant_id, id)`.
  - Role separation: Application queries execute as unprivileged `nanobooks_app` (cannot bypass RLS), never as superuser.
* **Curated Resources**:
  - [PostgreSQL Documentation: Row Security Policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html)
  - [Supabase RLS Deep Dive](https://supabase.com/docs/guides/database/postgres/row-level-security)
* **See it in NanoBooks**:
  - Multi-tenancy rules: [`.agents/rules/development-standards.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/rules/development-standards.md).
  - Tenant context transaction wrapper: [`apps/api/src/plugins/tenant.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/tenant.ts) (`withTenant()`).
  - Mathematical isolation proof script: [`scripts/compliance-agent.py`](file:///Users/vijaygurukumar/infinite-erp/scripts/compliance-agent.py).
* **Checkpoint**:
  Run the RLS isolation audit tool:
  ```bash
  python3 scripts/compliance-agent.py audit-rls
  ```
  Confirm 100% tenant isolation across all tables.

---

## 07. HTTP Protocols & RESTful Architecture

The transport layer connecting browsers, mobile POS clients, external payment webhooks, and Fastify.

* **Key Topics**:
  - HTTP/1.1 & HTTP/2 frame semantics, TCP handshakes, TLS termination.
  - HTTP Methods: `GET` (idempotent/safe), `POST` (create), `PATCH` (partial update), `DELETE`.
  - HTTP Status Codes: `200 OK`, `201 Created`, `400 Bad Request`, `401 Unauthorized`, `403 Forbidden`, `409 Conflict`, `422 Unprocessable Entity`.
  - Headers: `Authorization: Bearer <token>`, `Content-Type`, `Idempotency-Key`, `X-Request-Id`, `Cache-Control`.
* **Curated Resources**:
  - [MDN: Overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview)
  - [RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110.html)
* **See it in NanoBooks**:
  - API Client error handling & token attachment: [`apps/web/src/lib/api.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/lib/api.ts).
* **Checkpoint**:
  Use `curl -v` or an automated test script to probe an API endpoint and inspect response headers and status codes.

---

## 08. Fastify Framework Architecture

The high-throughput Node.js backend framework powering NanoBooks API.

* **Key Topics**:
  - Fastify core: Router, Request, Reply, Context lifecycle.
  - Plugin encapsulation tree & `fastify-plugin` (`fp`).
  - Lifecycle hooks: `onRequest`, `preParsing`, `preValidation`, `preHandler`, `preSerialization`, `onSend`, `onResponse`.
  - Server decorations: `app.decorate('db', ...)`, `app.decorateRequest('tenantId', ...)`.
* **Curated Resources**:
  - [Fastify Documentation: Lifecycle](https://fastify.dev/docs/latest/Reference/Lifecycle/)
  - [Fastify Documentation: Plugins](https://fastify.dev/docs/latest/Reference/Plugins/)
* **See it in NanoBooks**:
  - Server entry point & plugin registration: [`apps/api/src/server.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/server.ts).
  - Plugin decorators: [`apps/api/src/plugins/tenant.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/tenant.ts).
* **Checkpoint**:
  Inspect how `apps/api/src/server.ts` registers routes and verify plugin encapsulation boundaries.

---

## 09. 🔐 API Request Lifecycle, Auth & Middleware Chain
> [!CAUTION]
> **UNAVOIDABLE AUTHENTICATION GATE**:
> NanoBooks processes 3 distinct JWT credential archetypes. Verification must strictly inspect the token header algorithm.

* **Key Topics**:
  - Dual JWT verification system:
    1. **Store Owners**: Supabase Auth tokens (`ES256` asymmetric signature).
    2. **Staff Members**: NanoBooks Staff tokens (`HS256` symmetric HMAC).
    3. **Storefront Customers**: Public Storefront tokens (`HS256`).
  - Algorithm-based token dispatch: Reading `alg` safely from unverified header, then dispatching to the matching cryptographic verifier.
  - Live database authorization: Roles and permissions are re-evaluated against Postgres on every request, never blindly trusted from JWT payload claims.
  - The 5-stage mutating route middleware chain:
    1. `requireAuth` (JWT verification & user identity).
    2. `withTenant` (sets session RLS context).
    3. `requirePermission` (RBAC authorization).
    4. `enforcePlanLimits` (SaaS tier quota checks).
    5. `withTenantAudit` (structured audit trail with `actor_user_id`).
* **Curated Resources**:
  - [JWT.io: Introduction to JSON Web Tokens](https://jwt.io/introduction)
  - [RFC 7519: JSON Web Token Specification](https://www.rfc-editor.org/rfc/rfc7519)
* **See it in NanoBooks**:
  - Auth dispatch engine: [`apps/api/src/plugins/tenant.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/tenant.ts).
  - RBAC permission guards: [`apps/api/src/plugins/permissions.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/permissions.ts).
  - Plan quota enforcement: [`apps/api/src/plugins/plan-enforcement.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/plan-enforcement.ts).
  - Audit logging plugin: [`apps/api/src/plugins/audit.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/plugins/audit.ts).
* **Checkpoint**:
  Trace a request through [`apps/api/src/routes/invoices.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/routes/invoices.ts) from initial HTTP parse to final audit trail insert.

---

## 10. Zod Runtime Validation & Serialization Shields

Enforcing strict boundary typing on every incoming HTTP payload, query parameter, and outgoing JSON response.

* **Key Topics**:
  - Why compile-time TypeScript types vanish at runtime.
  - Schema construction: `z.object()`, `z.string().uuid()`, `z.number().positive()`, `z.enum()`.
  - Semantic field conventions:
    - `.optional()`: Field may be omitted (leaves existing DB value untouched).
    - `.nullable()`: Field may be `null` (explicitly clears the DB value).
  - Request parsing: `schema.safeParse()`, handling Zod errors with standardized 400 responses.
  - Type inference: `type CreateInvoiceInput = z.infer<typeof CreateInvoiceSchema>;`.
* **Curated Resources**:
  - [Zod Official Documentation](https://zod.dev/)
* **See it in NanoBooks**:
  - Customer input schema: [`apps/api/src/routes/customers.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/routes/customers.ts).
  - Invoice input schema: [`apps/api/src/routes/invoices.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/routes/invoices.ts).
* **Checkpoint**:
  Write a Zod schema validating a complex object with nested arrays and test `.safeParse()` against valid and invalid payloads.

---

## 11. Backend Testing & The Lightning Fast Local Feedback Loop

Zero-dependency automated testing using Node.js native test runner (`node:test` / `tsx --test`).

* **Key Topics**:
  - Testing pyramid: Pure unit tests (<5ms) vs. In-process integration tests (<100ms).
  - In-process HTTP testing via `app.inject()` (Fastify light-my-request) without binding physical TCP ports.
  - Clean tenant isolation in tests: Dynamic shop provisioning helper (`createShop()`) generating disposable isolated tenants.
  - Bidirectional test assertions (positive 200 OK vs. negative 401/403/422).
  - Lightning-fast local feedback loop (<4s full check).
* **Curated Resources**:
  - [Node.js Test Runner Documentation](https://nodejs.org/api/test.html)
* **See it in NanoBooks**:
  - Integration test suite: [`apps/api/src/routes/invoices.itest.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/routes/invoices.itest.ts).
  - Local verification script:
    ```bash
    python3 scripts/dev-agent.py verify-local
    ```
  - Single-file targeted test runner:
    ```bash
    python3 scripts/dev-agent.py test --file invoices.itest.ts
    ```
* **Checkpoint**:
  Run `python3 scripts/dev-agent.py verify-local` and achieve 100% test pass in <4 seconds.

---

## 12. Semantic HTML & Responsive CSS

Building resilient, accessible UI foundations for shop owners operating on low-end mobile devices and desktop monitors alike.

* **Key Topics**:
  - Semantic HTML5 structure (`<main>`, `<section>`, `<article>`, `<header>`, `<table>`, `<form>`).
  - CSS Box Model, specificity, CSS custom properties (variables).
  - Flexbox & CSS Grid layouts for complex responsive data tables.
  - Accessibility (a11y): ARIA roles, focus management, minimum tap targets (48x48px).
* **Curated Resources**:
  - [MDN: Learn Web Development](https://developer.mozilla.org/en-US/docs/Learn)
  - [web.dev: Responsive Web Design Basics](https://web.dev/responsive-web-design-basics/)
* **See it in NanoBooks**:
  - Dashboard component templates: [`apps/web/src/components/`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/components/).
* **Checkpoint**:
  Audit a dashboard page for responsive behavior across mobile (375px) and desktop (1440px) viewports.

---

## 13. React Core & State Primitives

Declarative UI development using modern React functional components and hooks.

* **Key Topics**:
  - Component composition, JSX syntax, unidirectional data flow.
  - React Hooks: `useState` (local state), `useEffect` (side-effects & cleanup), `useCallback`, `useMemo`, `useRef`.
  - Controlled inputs, form handling, error boundaries.
  - Optimistic UI updates and state synchronization.
* **Curated Resources**:
  - [React Documentation: Describing the UI](https://react.dev/learn/describing-the-ui)
  - [React Documentation: Managing State](https://react.dev/learn/managing-state)
* **See it in NanoBooks**:
  - Reusable UI components: [`apps/web/src/components/`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/components/).
* **Checkpoint**:
  Inspect a stateful component in `apps/web/src/components/` and trace its state re-render lifecycle.

---

## 14. Next.js App Router Architecture

File-system based routing, Server Components, and client boundary isolation.

* **Key Topics**:
  - Next.js App Router directory structure: `layout.tsx`, `page.tsx`, `loading.tsx`, `error.tsx`, `not-found.tsx`.
  - Route Groups: `(auth)`, `(dashboard)`, `(marketing)` for logical organization without URL pollution.
  - Server Components (default) vs. Client Components (`'use client'`).
  - Dynamic route parameters: `[tenantId]`, `[invoiceId]`.
* **Curated Resources**:
  - [Next.js App Router Documentation](https://nextjs.org/docs/app)
* **See it in NanoBooks**:
  - Web routing tree: [`apps/web/src/app/`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/app/).
  - Dashboard layout: [`apps/web/src/app/(dashboard)/layout.tsx`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/app/(dashboard)/layout.tsx).
* **Checkpoint**:
  Explore the route group structure in `apps/web/src/app/` and locate all public vs. authenticated pages.

---

## 15. Tailwind CSS Design System

Utility-first CSS architecture, design tokens, and theme customization.

* **Key Topics**:
  - Utility-first principles, JIT compiler.
  - Responsive design prefixes (`sm:`, `md:`, `lg:`, `xl:`).
  - Pseudo-class variants (`hover:`, `focus:`, `disabled:`, `dark:`).
  - Custom design tokens in `tailwind.config.js`.
* **Curated Resources**:
  - [Tailwind CSS Documentation](https://tailwindcss.com/docs)
* **See it in NanoBooks**:
  - Tailwind configuration: [`apps/web/tailwind.config.js`](file:///Users/vijaygurukumar/infinite-erp/apps/web/tailwind.config.js).
  - Component styling: [`apps/web/src/app/(dashboard)/dashboard/invoices/page.tsx`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/app/(dashboard)/dashboard/invoices/page.tsx).
* **Checkpoint**:
  Inspect the styling classes used in the invoices dashboard table.

---

## 16. NanoBooks Web Patterns (apiFetch, i18n, PWA, Offline & Local AI Engine)

Specialized frontend patterns designed for Indian retail MSMEs and private on-device intelligence.

* **Key Topics**:
  - `apiFetch<T>()`: Custom fetch wrapper with automatic JWT injection, base URL resolution, and 401 redirect interceptors.
  - Type-safe internationalization (English & Tamil): `satisfies Dict` pattern ensuring 100% key parity at compile time.
  - Progressive Web App (PWA): Service worker caching (`sw.js`) with `__BUILD_ID__` cache-busting.
  - Offline POS & Invoice queue: Client-side IndexedDB persistence using `idb` with client-generated idempotency keys.
  - On-Device Local AI & Remote MCP: 4-state direct Ollama probe (`11434`), zero-cost local inference (`Llama 3.2`, `Qwen 2.5 Coder`), and remote Model Context Protocol SSE stream.
* **Curated Resources**:
  - [MDN: Progressive Web Apps](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)
  - [Model Context Protocol Specification](https://modelcontextprotocol.io)
  - [Ollama Model Library & API](https://ollama.com)
* **See it in NanoBooks**:
  - API Client: [`apps/web/src/lib/api.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/lib/api.ts).
  - AI Copilot Settings: [`apps/web/src/app/(dashboard)/dashboard/settings/ai-copilot/page.tsx`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/app/(dashboard)/dashboard/settings/ai-copilot/page.tsx).
  - AI Chat Route: [`apps/api/src/routes/ai-chat.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/routes/ai-chat.ts).
  - Localization dictionaries & tests: [`apps/web/src/lib/i18n/en.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/lib/i18n/en.ts), [`ta.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/lib/i18n/ta.ts), [`i18n.test.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/web/src/lib/i18n/i18n.test.ts).
  - Service Worker: [`apps/web/public/sw.js`](file:///Users/vijaygurukumar/infinite-erp/apps/web/public/sw.js).
* **Checkpoint**:
  Run the test suite and inspect AI Copilot settings:
  ```bash
  cd apps/web && pnpm test
  ```
  Confirm all tests pass and inspect the 4-state Ollama probe in the UI.

---

## 17. 🏛️ Domain Mastery: Indian GST Architecture
> [!WARNING]
> **REVIEW GATE MODULE**:
> Changes to tax calculation logic must preserve documented statutory references and integer paise precision.

* **Key Topics**:
  - Goods & Services Tax (GST) principles in India.
  - Tax split mechanics:
    - **Intra-state** (Supplier State == Customer State): Split equally into **CGST (50%) + SGST (50%)**.
    - **Inter-state** (Supplier State != Customer State): Full **IGST (100%)**.
  - GSTIN 15-digit structure: First 2 digits indicate State Code (e.g., `33` = Tamil Nadu, `29` = Karnataka).
  - Place of Supply rules (IGST Act Section 10).
  - Rounding & precision rules: Converting all calculations to integer paise in [`lib/money.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/money.ts) to avoid IEEE-754 floating-point drift.
* **Curated Resources**:
  - [GST Portal Official Taxpayer Guides](https://www.gst.gov.in/)
  - [ClearTax GST Structure Guide](https://cleartax.in/s/gst-tax-rates)
* **See it in NanoBooks**:
  - GST calculation engine: [`apps/api/src/lib/gst.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/gst.ts).
  - Integer paise precision library: [`apps/api/src/lib/money.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/money.ts).
  - Statutory documentation: [`docs/gst.md`](file:///Users/vijaygurukumar/infinite-erp/docs/gst.md).
* **Checkpoint**:
  Run compliance audit:
  ```bash
  python3 scripts/compliance-agent.py audit-gst
  ```
  Validate GST calculation accuracy and tax splits.

---

## 18. 📚 Domain Mastery: Double-Entry Bookkeeping & General Ledger
> [!WARNING]
> **REVIEW GATE MODULE**:
> General ledger mutations must strictly maintain the fundamental accounting equation: `Assets = Liabilities + Equity`.

* **Key Topics**:
  - The fundamental accounting equation: `Assets = Liabilities + Equity`.
  - Chart of Accounts (COA): 5 primary classifications (Asset, Liability, Equity, Revenue, Expense).
  - Double-entry invariants: Every Journal Entry must have `Total Debits == Total Credits`.
  - Auto-journal posting: Sales invoices automatically trigger journal entries (Debit Cash/AR, Credit Revenue, Credit GST Payable).
* **Curated Resources**:
  - [AccountingCoach: Debits and Credits](https://www.accountingcoach.com/debits-and-credits/explanation)
  - [AccountingCoach: Accounting Equation](https://www.accountingcoach.com/accounting-equation/explanation)
* **See it in NanoBooks**:
  - Default Chart of Accounts: [`apps/api/src/lib/accounting.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/accounting.ts).
  - Auto-journal hooks: [`apps/api/src/lib/accounting-hooks.ts`](file:///Users/vijaygurukumar/infinite-erp/apps/api/src/lib/accounting-hooks.ts).
  - Mini-ERP Roadmap: [`docs/mini-erp-tracker.md`](file:///Users/vijaygurukumar/infinite-erp/docs/mini-erp-tracker.md).
* **Checkpoint**:
  Verify the default chart of accounts and journal balance validation logic in `apps/api/src/lib/accounting.ts`.

---

## 19. Docker & Containerization

Packaging the Fastify API and Next.js Web applications into secure, lightweight container images.

* **Key Topics**:
  - Containerization vs. Virtualization.
  - Multi-stage Dockerfiles: Builder stage (compiling TS, bundling Next.js) vs. Production runner stage (minimal alpine node image).
  - Docker Compose for multi-container local development.
  - Image size optimization, layer caching, non-root user execution (`USER node`).
* **Curated Resources**:
  - [Docker Documentation: Multi-stage builds](https://docs.docker.com/build/building/multi-stage/)
* **See it in NanoBooks**:
  - Multi-stage API Dockerfile: [`apps/api/Dockerfile`](file:///Users/vijaygurukumar/infinite-erp/apps/api/Dockerfile).
  - Multi-stage Web Dockerfile: [`apps/web/Dockerfile`](file:///Users/vijaygurukumar/infinite-erp/apps/web/Dockerfile).
  - Local container composition: [`docker-compose.yml`](file:///Users/vijaygurukumar/infinite-erp/docker-compose.yml).
* **Checkpoint**:
  Inspect `apps/api/Dockerfile` and trace the builder-to-runner layer copying.

---

## 20. Google Cloud Platform (GCP) Serverless Architecture

Production infrastructure powering NanoBooks on Google Cloud.

* **Key Topics**:
  - **Cloud Run**: Serverless container execution with auto-scaling and zero-downtime revision traffic shifting.
  - **Cloud SQL**: Managed PostgreSQL with high-availability, automated backups, and private VPC peering.
  - **Secret Manager**: Secure runtime injection of database credentials and JWT secrets.
  - **Cloud Tasks**: Asynchronous reliable task queue execution for notifications and WhatsApp dispatch.
  - **Artifact Registry**: Docker container image repository.
* **Curated Resources**:
  - [Google Cloud Run Documentation](https://cloud.google.com/run/docs)
  - [Google Cloud SQL for PostgreSQL](https://cloud.google.com/sql/docs/postgres)
* **See it in NanoBooks**:
  - GCP Architecture Reference: [`docs/deployment-gcp.md`](file:///Users/vijaygurukumar/infinite-erp/docs/deployment-gcp.md).
  - Ops Agent tools: [`scripts/ops-agent.py`](file:///Users/vijaygurukumar/infinite-erp/scripts/ops-agent.py).
* **Checkpoint**:
  Review GCP deployment architecture in `docs/deployment-gcp.md`.

---

## 21. CI/CD Pipelines & GitHub Actions

Automated build, test, and gated release pipelines.

* **Key Topics**:
  - Continuous Integration (CI): Running lint, typecheck, unit tests on pull requests.
  - Continuous Delivery (CD): Automated deployment to Staging on merge to `main`.
  - Gated Release: Manual `workflow_dispatch` trigger for Production releases.
  - Secret management in GitHub Actions (`GCP_SA_KEY`, `DATABASE_URL`).
* **Curated Resources**:
  - [GitHub Actions Documentation](https://docs.github.com/en/actions)
* **See it in NanoBooks**:
  - GitHub Actions workflow: [`.github/workflows/deploy.yml`](file:///Users/vijaygurukumar/infinite-erp/.github/workflows/deploy.yml).
* **Checkpoint**:
  Inspect `.github/workflows/deploy.yml` and identify the differences between staging and production deploy triggers.

---

## 22. 🚀 Deployment Pipeline & Staging-First Quality Lifecycle
> [!CAUTION]
> **STRICT RULE 1 & 2 (UNAVOIDABLE)**:
> Direct deployment to Production without Staging verification is strictly forbidden. Every promotion requires a clean git commit.

* **Key Topics**:
  - The 4-step deployment pipeline:
    1. `dev-agent verify-local` (<4s).
    2. `staging-agent deploy` (~60s concurrent rollout).
    3. `staging-e2e-tester` (46+ autonomous scenarios in <2s).
    4. `staging-agent promote` (gated promotion to `nanobooks.in`).
  - Separation of database migrations: Migrations are deliberate and verified before rollout.
  - Yellow `🟡 STAGING ENVIRONMENT` banner isolation in staging UI.
* **Curated Resources**:
  - Multi-tenancy & Staging standards: [`.agents/rules/staging-workflow.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/rules/staging-workflow.md).
  - Verification pitfalls: [`.agents/rules/verification-and-known-pitfalls.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/rules/verification-and-known-pitfalls.md).
* **See it in NanoBooks**:
  - Deployment tool: [`scripts/deploy.py`](file:///Users/vijaygurukumar/infinite-erp/scripts/deploy.py).
  - Staging Agent: [`scripts/staging-agent.py`](file:///Users/vijaygurukumar/infinite-erp/scripts/staging-agent.py).
  - E2E Staging Tester: [`scripts/staging-e2e-tester.py`](file:///Users/vijaygurukumar/infinite-erp/scripts/staging-e2e-tester.py).
* **Checkpoint**:
  Run the automated E2E test suite against staging:
  ```bash
  python3 scripts/staging-e2e-tester.py
  ```
  Verify all scenarios pass with a 100% score.

---

## 23. 🎓 Capstone: Ship One Production Feature Solo

The ultimate proof of mastery: Ship a complete, real feature across the full stack with zero AI assistance.

* **Requirements**:
  1. **Database Migration**: Schema change in `packages/db/migrations/` with composite key `(tenant_id, id)`, `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY`, and policy.
  2. **Fastify API Route**: Zod schema validation, `requireAuth`, `withTenant`/`withTenantAudit`, structured response.
  3. **Integration Test**: Node.js test in `apps/api/src/routes/*.itest.ts` using `createShop()` and `app.inject()`.
  4. **Frontend UI**: Next.js App Router component in `apps/web` utilizing `apiFetch<T>()`.
  5. **Bilingual i18n**: Add keys to both `en.ts` and `ta.ts`, verify `i18n.test.ts` passes.
  6. **Quality Gate**: Run full verification:
     ```bash
     python3 scripts/dev-agent.py verify-local
     ```
  7. **Pull Request**: Commit with clean SHA and open a Pull Request.

---

## ⚡ Skip / Skim Guidance Matrix

| Stage | Name | Priority | Guidance & Rationale |
| :--- | :--- | :--- | :--- |
| **00–03** | Terminal, Git, JS, TypeScript | 🔴 **Never Skip** | Foundation of the entire monorepo. |
| **04–05** | SQL & PostgreSQL | 🔴 **Never Skip** | Prerequisite for multi-tenant database operations. |
| **06** | **Multi-Tenancy & RLS** | 🚨 **CRITICAL** | Mistakes cause catastrophic cross-tenant data leaks. |
| **07–08** | HTTP & Fastify | 🟡 Skimmable | Review before modifying backend route handlers. |
| **09** | **Auth & Request Lifecycle** | 🚨 **CRITICAL** | Flaws cause authentication bypasses. |
| **10** | Zod Validation | 🟢 Quick Read | Straightforward schema patterns. |
| **11** | Backend Testing | 🔴 **Must Know** | Safety net against regressions in billing/tax. |
| **12–15** | HTML, CSS, React, Next.js | 🟡 Skimmable | Skip only if exclusively working on backend. |
| **16** | Frontend Patterns (apiFetch/i18n) | 🟡 Skimmable | Essential before modifying web UI. |
| **17** | **Indian GST Architecture** | ⚠️ **REVIEW GATE** | Mandatory before touching any invoice or tax code. |
| **18** | **Double-Entry Bookkeeping** | ⚠️ **REVIEW GATE** | Mandatory before touching ledger or journal entries. |
| **19–21** | Docker, GCP, CI/CD | 🟡 Skimmable | Helpful for understanding release workflows. |
| **22** | **Deployment Pipeline** | 🚨 **CRITICAL** | Mandatory before running any staging or prod release. |
| **23** | **Capstone Solo Feature** | 🎓 **Graduation** | The definitive proof of engineering readiness. |

---

## 🤖 The Antigravity Autonomous Agent Fleet

Once Stages 00–23 are mastered, leverage the specialized Antigravity agent pool for high-speed development, automated auditing, and deployment orchestration.

```mermaid
flowchart TD
    Master["👑 agy-master-orchestrator\n(Supreme Multi-Agent Triage & Lifecycle)"]

    Master --> Dev["🛠️ development-agent\n(Code, RLS, Zod, Tests, verify-local)"]
    Master --> Stg["🚀 staging-agent\n(High-speed build, rollout, promote)"]
    Master --> QA["🧪 staging-test-agent\n(Zero-wait E2E test matrix)"]
    Master --> Chrome["🌐 chrome-staging-qa-agent\n(DevTools QA & Test Data Seeding)"]
    Master --> ERP["📊 erp-agent\n(5-Pillar Mini-ERP implementation)"]
    Master --> Comp["⚖️ compliance-agent\n(GST Tax Sanitizer & RLS Proofs)"]
    Master --> Ops["⚙️ ops-agent\n(Cost optimization, DR drills, SRE)"]
    Master --> Onb["🤝 onboarding-agent\n(Archetype kits & activation)"]
    Master --> Gro["📈 growth-agent\n(Subscriptions, milestones, dunning)"]
    Master --> Fire["🚒 firefighter-agent\n(Incident response & instant rollback)"]

    style Master fill:#4f46e5,color:#fff,stroke:#3730a3,stroke-width:3px;
    style Dev fill:#0284c7,color:#fff;
    style Stg fill:#059669,color:#fff;
    style QA fill:#16a34a,color:#fff;
    style Chrome fill:#0d9488,color:#fff;
    style ERP fill:#7c3aed,color:#fff;
    style Comp fill:#d97706,color:#fff;
    style Ops fill:#475569,color:#fff;
    style Onb fill:#ea580c,color:#fff;
    style Gro fill:#db2777,color:#fff;
    style Fire fill:#dc2626,color:#fff;
```

### 📋 Agent Command Reference

| Agent | Skill File | Primary Command | Purpose |
| :--- | :--- | :--- | :--- |
| **Master Orchestrator** | [`.agents/skills/agy-master-orchestrator/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/agy-master-orchestrator/SKILL.md) | Antigravity Triage | Autonomous end-to-end task coordination |
| **Development** | [`.agents/skills/development-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/development-agent/SKILL.md) | `python3 scripts/dev-agent.py verify-local` | <4s fast validation & architectural review |
| **Staging** | [`.agents/skills/staging-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/staging-agent/SKILL.md) | `python3 scripts/staging-agent.py deploy` | High-speed concurrent staging deployment |
| **Testing** | [`.agents/skills/staging-test-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/staging-test-agent/SKILL.md) | `python3 scripts/staging-e2e-tester.py` | Zero-wait autonomous E2E testing |
| **Chrome Staging QA** | [`.agents/skills/chrome-staging-qa-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/chrome-staging-qa-agent/SKILL.md) | `python3 scripts/chrome-staging-qa-agent.py plan` | Chrome DevTools test plans & data seeding |
| **ERP Implementation** | [`.agents/skills/erp-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/erp-agent/SKILL.md) | `python3 scripts/erp-agent.py status` | Track & build 5 Mini-ERP pillars |
| **Compliance** | [`.agents/skills/compliance-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/compliance-agent/SKILL.md) | `python3 scripts/compliance-agent.py audit-gst` | GST tax sanitizer & mathematical RLS proof |
| **Ops & SRE** | [`.agents/skills/ops-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/ops-agent/SKILL.md) | `python3 scripts/ops-agent.py sleep staging` | Cloud SQL cost sleeping & DR drill checks |
| **Onboarding** | [`.agents/skills/onboarding-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/onboarding-agent/SKILL.md) | `python3 scripts/onboarding-agent.py audit-activation` | Business archetype kit staging & TTFI metrics |
| **Growth & Dunning** | [`.agents/skills/growth-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/growth-agent/SKILL.md) | `python3 scripts/growth-agent.py audit-subscriptions` | Razorpay subscription lifecycle & milestones |
| **Firefighter** | [`.agents/skills/firefighter-agent/SKILL.md`](file:///Users/vijaygurukumar/infinite-erp/.agents/skills/firefighter-agent/SKILL.md) | `python3 scripts/firefighter-agent.py rollback <service>` | Instant Cloud Run rollback & live diagnostics |
