Imported from pavan53732/pmegp (
AGENTS.md). Install upstream withnpx skills add pavan53732/pmegp. Copyright stays with the author.
AGENTS.md — PMEGP AI Guider
Project Status
This is a design-phase project. No package.json or source code exists yet. The canonical architecture document is DPR-GUIDE-BLUEPRINT.md (1892 lines). All implementation must conform to it.
Non-Negotiable Architecture Rules
- Blueprint is law.
DPR-GUIDE-BLUEPRINT.mdis the single source of truth. If you detect any code violating it, stop and flag the violation. - Clean Architecture dependency direction: Presentation → Application → Engines → Domain. Infrastructure implements contracts from
application/contracts/orshared/contracts/. Application NEVER imports Infrastructure. - Engine execution order is hardcoded. Engine 21 → 22 → 23 is a strict sequence. Engine 22 must always execute before Engine 23. The WorkflowOrchestrator enforces this.
- ComputedResults write partition (Build Rule 3):
- Engine 22 EXCLUSIVELY writes: annualRevenue, annualExpenses, grossProfit, netProfit, netCashFlow, debtEquityRatio, interestCoverageRatio, roiPercent, breakEvenMonths, paybackPeriodMonths.
- Engine 23 EXCLUSIVELY writes: totalProjectCost, capitalExpenditure, workingCapital, meansOfFinance, meansOfFinanceValidation, subsidyRate, expectedSubsidyAmount, emi, dscr.
- No engine may write to a field owned by the other.
- Engine 23 is the sole computation point for
capitalExpenditure + workingCapital = totalProjectCost. The only exception is Engine 25's defensive re-validation as an export guard. - No hardcoded PMEGP values outside the Rule Engine or Datasets.
- All exports originate from DPRReport.
DPRReportis transient;ProjectFileis persistent. They have a two-creation lifecycle (see blueprint §8).
Tech Stack (v1 target)
- Runtime: Node.js 24+, npm 11, Electron 38+
- Frontend: Next.js 16, React 19, TypeScript 5.x, Tailwind CSS 4, shadcn/ui, Lucide Icons
- State: Zustand, React Hook Form, Zod
- Database: SQLite via better-sqlite3 (requires electron-rebuild), SQLite FTS5
- Testing: Vitest (unit), Playwright (e2e)
- Export: ExcelJS (Excel), webContents.printToPDF() (PDF)
- AI: OpenAI-compatible API via streaming SSE
Repository Structure
src/
application/ # Use cases, orchestration, contracts (ports/interfaces)
domain/ # Canonical entities, schemas, rules, calculations, validations
engines/ # The 00-29 pipeline
infrastructure/ # External I/O: ai, database, filesystem, exports, logging, providers
presentation/ # UI layer (Next.js/React)
shared/ # Types, utilities, shared contracts
tests/
dist/
Engine Pipeline (30 engines, 4 phases)
| Phase | Engines | Purpose |
|---|---|---|
| Phase 0: Initialization | 00–01 | AI runtime setup, guided onboarding |
| Phase 1: Pre-DPR (The Guide) | 02–21 | Business discovery, eligibility, scoring, loan structuring |
| Phase 2: DPR Pipeline (The Generator) | 22–25 | Financial modeling, PMEGP rules, narrative generation, DPR assembly |
| Phase 3: Post-DPR (The Assistant) | 26–29 | Bank interview coach, export, tracking, scheme sync |
Critical sequence: Engine 22 (Financial Modeling) → Engine 23 (PMEGP Rule Engine) → Engine 24 (Narratives) → Engine 25 (DPR Assembly). Engine 22 and 23 have strict field ownership — never cross-write.
DPRReport Two-Creation Lifecycle
This is the most misunderstood part of the architecture:
- Creation #1 (DRAFT SEED): Engine 25 assembles a transient
DPRReport, then WRITES its narratives INTOProjectFile.narratives(the persisted DRAFT copy). Direction:DPRReport → ProjectFile. - Creation #2 (EXPORT SNAPSHOT): Engine 27 READS the frozen
ProjectFile.narratives(the APPROVED copy after lock) and ASSEMBLES a fresh transientDPRReportfor export. Direction:ProjectFile → DPRReport.
DPRReport is never persisted. ProjectFile is the persistent state. ProjectFile.narratives is the canonical approved narrative — ai.narrativeInfo is raw AI output and NOT the freeze target.
IPC Boundary (Renderer ↔ Main)
Only four cross-cutting services bridge the IPC boundary. No other IPC channel is permitted:
CommandService— execute commandsSearchService— global searchNotificationService— system notificationsWorkspaceService— open/close projects
Renderer security: contextIsolation: true, nodeIntegration: false, sandbox: true. API key never enters Renderer — all AI calls go through Main via IPC.
Key Conventions
- Dates: ISO-8601 UTC (
YYYY-MM-DDTHH:mm:ss.sssZ) - Currency: Absolute INR integers (e.g.,
500000= ₹5 Lakh). Never fractional. - Percentages: 0–100 decimal scale (e.g.,
10.5= 10.5%) - Scores/Confidence: 0.0–1.0 decimal scale. All domain scores use the
Scorebranded type. - Branded types are mandatory for domain primitives:
Percent,Score,Ratio,INR,PositiveInteger,NICCode,UUID,PhoneNumber. Factory functions (makeUUID,makeNICCode) must validate before minting. - Zero
anyallowed. Useunknownwhere type is genuinely unknown. - Database: better-sqlite3 is synchronous. All writes serialized through a single Main-process connection. Schema uses
snake_case. - File extension: Project files use
.pmegpdpr(not.json). Registered for OS double-click open.
State Machine & Locking
- ProjectFile.revision is the single source of truth for versioning.
DPRLock.versionandDPRSnapshot.versionare derived views. - Locking: Once
DPRLock.locked = true, all data sections are frozen. Unlocking triggers aDomainEvent, incrementsProjectFile.revision, and re-runs the engine pipeline. - Cost Reconciliation: Post-lock, Engine 27 MUST source
portalCostSubmissionfromProjectFile.approvedProjectCost— never recompute from live AI inferences. - Unlock Recalculation: When unlocked, the project retains its original
schemeVersionUsedto prevent historical subsidy mutation. User must explicitly opt-in to upgrade via Engine 29.
Portal Cost Mapping (Engine 25)
Engine 25 maps fields to portal layout. Critical mappings:
Capital Expenditure←ComputedResults.capitalExpenditure(Engine 23's value; do NOT recompute)Working Capital←ComputedResults.workingCapital(Engine 23's value; do NOT recompute)Total Project Cost← Capital Expenditure + Working Capital
Defensive guard: Engine 25 re-validates CapEx + WC = Total as a final export safety check. This is the only permitted exception to Build Rule 3.
Narrative Portal Export (Engine 25)
13 DPRNarrativeSections map to 3 portal fields:
summary←projectSummaryentrepreneurBackground←entrepreneurBackgroundmarketIndustryAnalysis←industryOverview + targetMarket + competitiveAnalysis + futureGrowthStrategy(joined with double-newline)
Unmapped sections are discarded during portal export. Max 500 words per field.
AI Provider Contract
- OpenAI-compatible HTTPS API, SSE streaming
- Retry: max 3 with exponential backoff (1s/2s/4s)
- Circuit-breaker: after 3rd consecutive failure across ANY engine, block until manual retest
- API key: Main receives via IPC, immediately
safeStorage.encryptString, stores ciphertext reference only. Never log plaintext.
Crash Recovery
- Clean-shutdown marker at
%APPDATA%/PMEGP-AI-GUIDER/.clean-shutdown - Written via atomic rename on graceful exit
- On crash:
RecoveryService.hasAutosave()prompts user per project before workspace opens RecoveryService.restoreFromAutosaveruns insideBEGIN IMMEDIATEtransaction
Scheme Sync (Engine 29)
- Configurable endpoint URL in
ApplicationSettings.pmegpSchemeSync.endpointUrl - Versioned JSON bundle with SHA-256 checksum verification
- Manual trigger only (no background polling) — this is the sole external network integration beyond AI
- Mid-draft projects keep their
schemeVersionUseduntil user opts in
Subagent Personas
When spawning subagents, use these roles (defined in CLAUDE.md):
| Role | Responsibility |
|---|---|
| PMEGP Architect Agent | Enforce blueprint compliance, reject violations |
| Financial Engine Engineer | Implement engines 21, 22, 23 math (EMI, DSCR, subsidy, margin money) |
| SQLite Database Admin | Schema, migrations, IPC-DB interface. snake_case only |
| UI/Electron Specialist | React frontend, Tailwind, Shadcn, glassmorphism, micro-animations |
Common Mistakes to Avoid
- Writing formulas in
engines/instead ofdomain/calculations/ - Importing
infrastructure/fromapplication/(Clean Architecture violation) - Engine 22 and 23 writing to each other's fields
- Treating
DPRReportas persistent (it's transient;ProjectFileis the persistent state) - Forgetting
ProjectFile.revisionis the single source of truth for versioning - Using
ai.narrativeInfoas the approved narrative (it's raw AI output;ProjectFile.narrativesis the canonical copy) - Using
workingCapitalRequirement(deleted; Engine 23 ownsworkingCapitalexclusively) - Using
.jsonextension for project files (use.pmegpdpr) - Hardcoding PMEGP values outside the Rule Engine or Datasets
- Bypassing the WorkflowOrchestrator to run engines directly