Imported from Vahagn113/GLYPHAI (
.agents/AGENTS.md). Install upstream withnpx skills add Vahagn113/GLYPHAI --skill .agents. Copyright stays with the author.
GLYPH AI Project Rules & Guidelines
This document outlines the architecture, patterns, directory structure, security, styling, and rules for working on the GLYPH AI OCR, CV Optimization, Voice Processing, and Document Intelligence platform.
1. Technology Stack & Architecture
- Framework: Next.js 15+ (App Router)
- Runtime & Language: React 19, TypeScript (Strict mode)
- Styling: Tailwind CSS v4 (configured via
@tailwindcss/postcssand PostCSS), with@tailwindcss/typographyandtw-animate-css - AI SDK:
@google/genai(v2.4.0) — Never use legacy@google/generative-ai - Database & Auth: Supabase (
@supabase/supabase-js,@supabase/ssr) with Cookie-based auth in Next.js middleware and SSR - Animations: Motion / Framer Motion (
motion/reactormotion) - Icons:
lucide-react - PDF & Document Processing:
pdf-lib,pdf-parse - Validation:
zodand@hookform/resolvers - Analytics:
@vercel/analytics
2. Directory Structure & Key Modules
GLYPHAI/
├── app/
│ ├── (auth)/ # Authentication routes (sign-in, sign-up, forgot-password, reset-password)
│ ├── about/ # About & company information page
│ ├── account/ # User dashboard (history, privacy, profile, usage)
│ ├── admin/ # Admin management (dashboard, audit-logs, feedback, history-cleanup, settings, usage, users)
│ ├── api/ # Server-side API endpoints
│ │ ├── account/ # User account operations
│ │ ├── admin/ # Admin CRUD and operational endpoints
│ │ ├── auth/ # Auth callback / verification
│ │ ├── chat/ # Document chat API
│ │ ├── cron/ # Scheduled cleanup and maintenance tasks
│ │ ├── cv-builder/ # CV optimization and parsing API
│ │ ├── extract/ # Primary OCR & multi-mode extraction API
│ │ ├── feedback/ # User feedback submission
│ │ ├── magic-chat/ # Assistant and smart contextual querying
│ │ ├── storage/ # Cloud file storage endpoints
│ │ └── transcribe-voice/ # Audio/voice transcription endpoint
│ ├── auth/ # OAuth/auth callback handlers
│ ├── privacy/ # Privacy policy page
│ ├── use-cases/ # Industry solutions and use-case pages
│ ├── globals.css # Global styles, Tailwind v4 imports, custom themes
│ ├── layout.tsx # Root layout with providers & metadata
│ ├── page.tsx # Main interactive OCR & document intelligence studio
│ ├── robots.ts & sitemap.ts # SEO configuration
│ └── icon.png
├── components/
│ ├── account/ # User profile & account components
│ ├── auth/ # Sign-in, sign-up modal / form components
│ ├── chat/ # Document chat widget & drawer
│ ├── common/ # Reusable buttons, badges, modals, spinners
│ ├── cv/ # CV Optimizer & CV Result viewer components
│ ├── extraction/ # Confidence badges, mode selector, settings, result viewer
│ ├── home/ # Landing page sections, hero, features
│ ├── layout/ # Navbar, footer, navigation shells
│ ├── providers/ # React context & theme providers
│ └── ui/ # Primitives (dialogs, tabs, dropdowns, tooltips)
├── lib/
│ ├── armenianTranscriptNormalization.ts # Armenian orthography & spelling corrections
│ ├── armenianTransliteration.ts # Armenian Latin-to-Armenian script transliteration engine
│ ├── cv-templates.ts # CV markdown formatting & theme templates
│ ├── documentHighlights.ts # Text coordinate highlighting and search helpers
│ ├── env.ts # Environment variable validation & getters
│ ├── exportUtils.ts # Client-side file exporter (TXT, MD, JSON, PDF)
│ ├── extractionModes/ # Structured schemas & extraction definitions
│ │ ├── contractAnalyzer.ts
│ │ ├── generalOcr.ts
│ │ ├── index.ts
│ │ ├── invoiceExtractor.ts
│ │ ├── receiptExtractor.ts
│ │ ├── resumeParser.ts
│ │ ├── tableExtractor.ts
│ │ └── types.ts
│ ├── fileValidation.ts # Client-side file type & size validation
│ ├── formatters.ts # Currency, date, confidence, and text formatters
│ ├── localHistory.ts # Guest/local storage history fallback
│ ├── prompts.ts # System prompts for OCR & reasoning
│ ├── security/ # Error sanitize helpers & upload validations
│ ├── services/ # Usage quotas, audit logging, history, app settings
│ ├── supabase/ # Client, Server, and Admin Supabase instances & types
│ ├── translations.ts # Multi-language dictionary (EN, RU, AM/HY)
│ ├── types.ts # Core UI & extraction data models
│ └── utils.ts # Tailwind merge & className utility (cn)
├── middleware.ts # Supabase session cookie refresher
└── supabase/ # Database migrations, schema, and seed SQL
3. Gemini API Integration Rules
- Client Initialization: Always initialize
GoogleGenAIfrom@google/genai. - User-Agent Header: Every client instance MUST include the
"User-Agent": "aistudio-build"header in its HTTP options:const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY, httpOptions: { headers: { "User-Agent": "aistudio-build", }, }, }); - Fallback Models & Retries: Production API routes should fall back gracefully across models (e.g.,
gemini-3.1-flash-lite,gemini-3.5-flash,gemini-flash-latest) with automatic retries and timeouts (withTimeout). - Temperature Configuration:
- OCR, Structured Extraction, Armenian Transliteration: Low temperature (
0.1-0.2) for maximum factual accuracy and structure fidelity. - CV Improvement, Creative Summaries: Moderate temperature (
0.4-0.7).
- OCR, Structured Extraction, Armenian Transliteration: Low temperature (
4. Structured Extraction & Extraction Modes
- All custom structured extraction models reside in
lib/extractionModes/. - Every custom mode must implement
ExtractionModeConfigfromlib/extractionModes/types.ts. - Confidence Scoring: Each field in a structured schema must output a confidence score along with the value using the
buildConfidenceFieldSchema(description, valType)helper:properties: { someFieldName: buildConfidenceFieldSchema("Description of this field"), } - Registry: When adding or modifying modes, update both
CUSTOM_EXTRACTION_MODES_MAPandCUSTOM_EXTRACTION_MODES_LISTinlib/extractionModes/index.ts. - Supported core extraction modes:
- General OCR & Markdown: High-fidelity text, handwriting, and layout extraction.
- Invoice Extractor: Vendor, billing info, itemized line items, taxes, totals.
- Receipt Extractor: Merchant, transaction time, taxes, payment methods.
- Contract Analyzer: Parties, effective dates, obligations, liability clauses, risks.
- Resume / CV Parser: Personal info, education, skills, work history.
- Table / Spreadsheet Extractor: Matrix grid parsing into markdown and JSON arrays.
5. Localization & Multi-language Support
- GLYPH AI natively supports English (
en), Russian (ru), and Armenian (am/hy). - Centralized Translations: All user-facing UI labels must be declared in
lib/translations.tsunder thetranslationsdictionary acrossen,ru, andam. - Language Boundaries:
- UI labels strictly follow the selected UI locale.
- Document extraction output preserves or targets the document's native language or user-specified target translation without corrupting key formats.
- Armenian Language Specialization:
lib/armenianTransliteration.ts: Armenian Latin-script to Armenian character phonetic mapper.lib/armenianTranscriptNormalization.ts: Orthographic spelling and punctuation normalization.
6. Authentication, Quotas & Security
- Authentication Tiers:
- Guest / Unauthenticated: Local-only storage history fallback (
lib/localHistory.ts), strict file size limits (guest_max_file_size_mb), and daily action limits (guest_total_actions). - Registered Users: Supabase Auth, cloud history syncing, larger payload sizes (
registered_max_file_size_mb), daily quota tracking vialib/services/usage.ts. - Admin / Staff Roles: Controlled via
app_role(admin,moderator,support,owner) with full access to/admintelemetry, user restrictions, and audit logs.
- Guest / Unauthenticated: Local-only storage history fallback (
- Stateless & Secure Processing:
- File buffers and base64 payloads must be validated with
validateBase64Uploadinlib/security/uploadValidation.ts. - Sensitive server errors must be redacted before sending to clients via
safeErrorResponseinlib/security/errors.ts.
- File buffers and base64 payloads must be validated with
7. UI/UX & Styling Guidelines
- Tailwind CSS v4: Modern CSS theme tokens defined in
app/globals.css. Ensure all utility classes are compatible with Tailwind v4. - Aesthetics & Theme:
- Sleek dark/light UI palette with accent glow highlights, modern typography, glassmorphism badges, and responsive layouts.
- Support for custom dynamic CV template themes (Modern, Minimal, Tech, Executive, Creative).
- Animations & Micro-interactions:
- Use Framer Motion (
motioncomponents) for tab switches, drag-and-drop dropzones, extraction progress steps, and accordion details.
- Use Framer Motion (
- Responsive Design: All screens (Studio, Document Chat, History Viewer, Admin, Account) must be fully responsive across mobile, tablet, and widescreen viewports.
8. Development & Verification Workflow
- Local Dev Server: Run
npm run devto start the Next.js development server (runs onhttp://localhost:3000). - Linting: Run
npm run lintbefore committing code. - Builds: Run
npm run buildwhen validating server/client boundaries, type contracts, routing, or deployment bundles. Usenpm run cleanif Next.js cache needs flushing.