CodeDocs Vault

Entry Points & Execution Flow

Application Entry Points

1. NestJS API (apps/api/src/main.ts)

The API server is the central nervous system. All authentication, authorization, and business logic flows through here.

Bootstrap sequence (lines 18-187):

1. Create NestJS app (bodyParser: false for better-auth)
2. Configure CORS with dynamic origin validation
3. Apply Helmet security headers
4. Set up origin validation middleware (CSRF for mutations)
5. Apply admin auth rate limiter (/api/auth/admin/*)
6. Configure body parser (150MB limit, skip /api/auth paths)
7. Enable global ValidationPipe (whitelist + transform)
8. Enable URI versioning (default: v1)
9. Set up Swagger at /api/docs
10. Start listening on PORT (default: 3333)
11. Register SIGTERM/SIGINT handlers

Key middleware stack:

Request → CORS → Helmet → Origin validation → Rate limiting → 
Body parsing → Validation → Route → Guards → Interceptors → Handler

2. Next.js Main App (apps/app/)

Request lifecycle:

Browser request
    │
    ▼
proxy.ts (middleware)
    │ Check session cookie existence
    │ Redirect to /auth if missing
    │ Allow: /invite/*, /unsubscribe/*
    │
    ▼
Root layout.tsx
    │ Fetch session via auth.api.getSession()
    │ Initialize providers (QueryClient, Theme, Analytics)
    │
    ▼
(app)/layout.tsx
    │ Enforce session check
    │ Handle pending invitations
    │
    ▼
[orgId]/layout.tsx
    │ Validate org membership
    │ Sync activeOrganizationId
    │ Resolve permissions (built-in + custom roles)
    │ Check canAccessApp()
    │ Fetch feature flags (PostHog)
    │ Load org logos from S3
    │
    ▼
Page component
    │ Server component: fetch via serverApi
    │ Pass fallbackData to client
    │
    ▼
Client component
    │ useSWR() with apiClient
    │ Render UI

3. Portal App (apps/portal/)

Browser request
    │
    ▼
Root layout.tsx
    │ NuqsAdapter, Toaster, PostHog analytics
    │
    ▼
(app)/layout.tsx
    │ Session auth check
    │ Redirect to /auth if missing
    │
    ▼
(home)/page.tsx
    │ Fetch memberships
    │ Single org → redirect to org page
    │ Multiple orgs → show org picker

4. Framework Editor (apps/framework-editor/)

Internal-only tool
    │ Requires user.role === 'admin'
    │ Requires @trycompai.ai email
    │
    ▼
Framework/requirement/template CRUD

5. Trigger.dev Workers

Two projects with independent entry points:

API project (apps/api/trigger.config.ts):

{
  project: "proj_zhioyrusqertqgafqgpj",
  runtime: "node",
  machine: "medium-2x",
  maxDuration: 300,  // 5 min default
  retries: { maxAttempts: 3, factor: 2, minTimeoutInMs: 1000, maxTimeoutInMs: 10000 }
}

App project (apps/app/trigger.config.ts):

{
  project: "proj_lhxjliiqgcdyqbgtucda",
  runtime: "node",
  maxDuration: 300,
  // Includes puppeteer extension for browser automation
}

6. Device Agent (packages/device-agent/)

Electron app
    │
    ├── Main process
    │   ├── IPC handlers (auth, checks, remediation)
    │   ├── Platform-specific check runners
    │   └── API communication
    │
    └── Renderer process
        ├── Auth UI (login/logout)
        ├── Check results display
        └── Remediation guidance

Key Code Paths

Path 1: User Login

Browser → /auth page
    │
    ├── Email/Password
    │   └── authClient.signIn.email() → API /api/auth/sign-in/email
    │
    ├── Magic Link
    │   └── authClient.signIn.magicLink() → API /api/auth/magic-link
    │       └── Email sent via Resend → click link → session created
    │
    ├── Email OTP
    │   └── authClient.signIn.emailOTP() → API /api/auth/email-otp
    │       └── 6-digit code sent → verify → session created
    │
    └── Social (Google/GitHub/Microsoft)
        └── Redirect to OAuth provider → callback → session created
        
Session created:
    │ httpOnly cookie set on .trycomp.ai
    │ activeOrganizationId set to first org
    │
    ▼
Redirect to /{orgId}/overview
    │ Layout resolves permissions
    │ Dashboard loads

Path 2: Cloud Security Scan

User clicks "Run Scan" on integrations page
    │
    ▼
POST /v1/cloud-security/scan
    │ HybridAuthGuard → PermissionGuard (cloud-security:update)
    │ Triggers Trigger.dev task
    │
    ▼
Trigger.dev: run-cloud-security-scan (15 min timeout)
    │
    ├── Get credentials (handle OAuth refresh)
    ├── Detect enabled services (Cost Explorer / Service Usage API)
    │
    ├── For each service:
    │   ├── Create provider-specific adapter (50+ AWS adapters)
    │   ├── Execute compliance checks
    │   ├── Record pass/fail with evidence
    │   └── Map to framework task templates
    │
    ▼
Results saved to cloud_security_finding table
    │ Integration results with severity, remediation
    │
    ▼
User sees findings in UI
    │
    ├── Click "Preview Remediation"
    │   └── Trigger.dev: remediate-preview
    │       └── Phase 1: AI generates fix plan (Claude Opus, temp 0)
    │       └── Phase 2: Execute read steps → refine with real state
    │
    ├── Click "Apply Fix"
    │   └── Trigger.dev: remediate-single
    │       └── Execute fix steps via AWS SDK
    │       └── Track: executing → success/failed/needs_permissions
    │
    └── Click "Batch Remediate"
        └── Trigger.dev: remediate-batch
            └── Sequential execution with rollback capability

Path 3: Questionnaire Processing

User uploads questionnaire (Excel/PDF/Word)
    │
    ▼
POST /v1/questionnaires/upload
    │ File saved to S3 (questionnaire bucket)
    │ Questionnaire record created (status: parsing)
    │
    ▼
Trigger.dev: process-knowledge-base-document
    │
    ├── Extract content
    │   ├── .xlsx → exceljs parser (rich text XML)
    │   ├── .docx → mammoth library
    │   ├── .pdf → Claude Sonnet (native PDF support)
    │   ├── .csv → plain text split
    │   └── images → GPT-4o vision
    │
    ├── Parse questions
    │   ├── Try: Groq (fast, 25K char chunks)
    │   ├── Fallback: Claude Sonnet (200K context)
    │   └── Fallback: OpenAI GPT-4o-mini
    │   └── De-duplicate by normalized text
    │
    ├── For each question:
    │   ├── Generate embedding (text-embedding-3-small)
    │   ├── Vector similarity search (pgvector)
    │   │   Sources: policies, context docs, manual answers
    │   ├── Build RAG prompt with top-k context
    │   └── Generate answer (gpt-4o-mini)
    │       └── Guardrail: "N/A" if insufficient context
    │
    ▼
Save answers (status: generated)
Update questionnaire (status: completed, counts)
    │
    ▼
User reviews in UI
    │ Can edit answers (status → manual)
    │ Can mark as N/A
    │ Can export to original format

Path 4: Policy Lifecycle

New organization onboarding
    │
    ▼
Trigger.dev: generate-full-policies
    │ For each framework template policy:
    │   ├── Fetch template (FrameworkEditorPolicyTemplate)
    │   ├── Merge with company context (industry, size, tech stack)
    │   ├── Call gpt-5-mini for TipTap JSON generation
    │   ├── Sanitize output
    │   └── Save as draft policy
    │
    ▼
Admin reviews policies in editor
    │
    ├── Manual editing (TipTap rich text editor)
    │
    ├── AI chat assistant
    │   └── POST /api/policies/[id]/chat
    │       └── Claude Sonnet streaming with tools
    │       └── Can fetch vendors, other policies, evidence
    │       └── Proposes edits as TipTap JSON
    │
    ├── AI section editor
    │   └── POST /api/policies/[id]/edit-section
    │       └── Claude Sonnet single-turn edit
    │
    ▼
Admin publishes policy (status: published)
    │ PolicyVersion created
    │ Published content locked
    │ Email notification to relevant members
    │
    ▼
Employees see policy in portal
    │ Must acknowledge/sign
    │ Tracked per-member

Path 5: Integration Check Execution

Integration connected (e.g., AWS, GitHub)
    │
    ▼
Trigger.dev: run-connection-checks
    │
    ├── Lookup manifest from registry
    ├── Validate required variables
    ├── Create CheckContext with:
    │   ├── Auto-authenticated HTTP helpers
    │   ├── Pagination helpers (cursor, offset, Link header)
    │   ├── State management
    │   └── Result recording (pass/fail + evidence)
    │
    ├── Execute checks:
    │   ├── Code-based checks (run function in manifest)
    │   │   └── ctx.pass() or ctx.fail() for each resource
    │   └── DSL-based checks (JSON definition → interpreter)
    │       └── Steps: fetch → forEach → branch → emit
    │
    ├── Map results to framework tasks
    │   └── Passing checks auto-complete linked tasks
    │
    ▼
Save IntegrationResults
    │ Severity: info, low, medium, high, critical
    │ Remediation steps included
    │
    ▼
Scheduled re-runs via run-integration-checks-schedule

State Transitions

Task Status Flow

                 ┌──────────┐
                 │   todo    │
                 └─────┬────┘
                       │ start
                 ┌─────▼────┐
                 │in_progress│
                 └─────┬────┘
                       │ submit for review
                 ┌─────▼────┐         ┌───────────┐
                 │ in_review ├────────►│not_relevant│
                 └─────┬────┘ reject   └───────────┘
                       │ approve
                 ┌─────▼────┐
                 │   done    │
                 └──────────┘
                 
                 ┌──────────┐
                 │  failed   │ (automation failure)
                 └──────────┘

Policy Status Flow

┌───────┐    publish    ┌───────────┐   review needed   ┌─────────────┐
│ draft ├──────────────►│ published ├──────────────────►│ needs_review│
└───┬───┘               └───────────┘                   └──────┬──────┘
    │                                                          │
    └──────────────────────────────────────────────────────────┘
                        edit → new draft version

Finding Status Flow

┌──────┐   submit    ┌────────────────┐   close   ┌────────┐
│ open ├────────────►│ready_for_review├──────────►│ closed │
└──────┘             └───────┬────────┘           └────────┘
                             │ needs work
                     ┌───────▼────────┐
                     │needs_revision  ├──► back to ready_for_review
                     └────────────────┘

Questionnaire Processing Flow

┌─────────┐   upload   ┌─────────┐   AI processing   ┌───────────┐
│ (none)  ├───────────►│ parsing ├───────────────────►│ completed │
└─────────┘            └────┬────┘                    └───────────┘
                            │ error
                       ┌────▼────┐
                       │ failed  │
                       └─────────┘

Trust Access Request Flow

┌──────────────┐   review   ┌──────────┐
│ under_review ├───────────►│ approved │──► TrustAccessGrant created
└──────┬───────┘            └──────────┘
       │                    ┌──────────┐
       ├───────────────────►│  denied  │
       │                    └──────────┘
       │                    ┌──────────┐
       └───────────────────►│ canceled │
                            └──────────┘

Cloud Remediation Flow

Finding detected
    │
    ▼
Preview requested → AI generates plan
    │
    ▼
User acknowledges → Execute fix steps
    │
    ├── executing → success (finding resolved)
    ├── executing → failed (rollback available)
    └── executing → needs_permissions (suggests IAM fix)