Skip to content

02. Engineering Handbook: Code Standards & Protocols

Status: Active / Golden Version: 1.0 (Consolidated Jan 2026)

"How we write code at Singular Dream. Non-negotiable rules for stability and maintainability."


1. Code Organization

Naming Conventions

Type Convention Example
Components PascalCase PropertyTable.tsx
Hooks camelCase (suffix) useAuth.ts
Utilities kebab-case date-utils.ts
Routes kebab-case page.tsx, layout.tsx

Monorepo Structure

  • apps/platform/: The Composition Root (UI).
  • packages/modules/*: Domain Logic (The Brains).
  • packages/foundation/*: Infrastructure (The Plumbing).

2. Standard Technology Stack (The Arsenal)

The following technologies are the Canonical Choices. Alternatives are forbidden without an ADR.

Core Platform

Capability Technology Details
Framework Next.js 14 + TypeScript App Router, Server Actions, Strict Mode.
Monorepo TurboRepo + pnpm High-performance build caching and package management.
Runtime Node.js 18+ (Alpine) Serverless-compatible execution environment.

UI & UX Fabric

Capability Technology Details
Primitives Radix UI Headless accessible components (Dialog, Popover, Tabs).
Styling Tailwind CSS Utility-first styling with tailwind-merge and clsx.
Animation Framer Motion Physics-based transitions and micro-interactions.
Icons Lucide React Consistent SVG icon set.
Charts Recharts Composable data visualization.
Feedback Sonner Toast notifications.

Domain Capabilities

Capability Technology Details
Forms React Hook Form + Zod Controlled state with schema validation ("Parse, don't validate").
Editor/CMS MDX Editor WYSIWYG Markdown editing (@mdxeditor/editor).
Realtime LiveKit WebRTC video/audio streaming (Board Meetings).
Payment Stripe (Planned) Payment processing.
Communications Twilio / Resend Multi-channel messaging (Voice, SMS, WhatsApp, Email).

Syncfusion Essential Studio

Syncfusion provides enterprise-grade UI components and document processing capabilities. All licenses configured in Doppler.

Component License Variable Purpose
UI Controls SYNCFUSION_LICENSE_KEY 1,800+ UI components (Grids, Charts, Calendars, Diagrams, Rich Text Editor).
Document SDK SYNCFUSION_DOCUMENT_SDK_LICENSE Create/edit/convert PDF, Word (DOCX), Excel, PowerPoint without Office dependencies.
PDF Viewer SYNCFUSION_PDF_VIEWER_LICENSE View, annotate, fill forms, apply digital signatures to PDFs.
DOCX Editor Covered by Document SDK Word-like editing with formatting, tables, images, track changes, collaboration.
Spreadsheet Editor SYNCFUSION_SPREADSHEET_EDITOR_LICENSE Excel-like editing with formulas, charts, formatting, data validation.
Public Components NEXT_PUBLIC_SYNCFUSION_LICENSE_KEY Client-side UI component license.

Key Capabilities: - Data Grids: DataGrid, Pivot Table, Tree Grid with filtering, sorting, grouping, master-detail views - Visualization: 50+ chart types (Bar, Line, Pie, 3D, Sankey, Stock, Gauges, Heatmaps) - Scheduling: Scheduler, Gantt Chart, Calendar, DatePicker, DateRangePicker - Rich Editors: Rich Text Editor, Block Editor with slash commands, inline content - Diagrams: Flowcharts, org charts, mind maps with drag/drop, containers, customization - Document Processing: - PDF: Create, edit, merge, split, compress, extract text, form filling, digital signatures - Word: Full DOCX editing, mail merge, find/replace, conversion to PDF/HTML/RTF - Excel: Read/write/modify, formulas (400+), charts, conditional formatting, data validation - PowerPoint: Create/edit presentations, convert to PDF/images - PDF Viewer: Annotations, form filling, digital signatures, redaction, page manipulation, AI-powered search - Collaboration: Track changes, comments, threaded reviews, real-time co-authoring

License Validation: Run doppler run -- node scripts/test-syncfusion-license.js to verify all keys.

Infrastructure & Backend

Capability Technology Details
Database Firestore (NoSQL) Scalable document store.
Functions Node.js (Next.js) Server Actions and API Routes.
Push Firebase (FCM) Mobile and Web push notifications.
Secrets Doppler Secret management and environment injection. See ADR: Secrets Management.

2. Communications Infrastructure

The platform uses a unified Communications Cabinet registry to provide access to pre-configured communication providers.

The Cabinet Pattern

Providers are accessed via the CommunicationsCabinet static class in @sd/foundation-communications.

import { CommunicationsCabinet } from '@sd/foundation-communications';

// Send an SMS
await CommunicationsCabinet.sms.sendSMS(to, body);

// Send an Email
await CommunicationsCabinet.email.sendEmail(to, subject, body);

// Send a Push Notification
await CommunicationsCabinet.push.sendMulticast(tokens, title, body);

Provider Matrix

Service Provider Status Secrets Required
SMS/MMS Twilio Active TWILIO_ACCOUNT_SID, TWILIO_API_KEY_SID, TWILIO_API_KEY_SECRET
Voice Twilio Active TWILIO_ACCOUNT_SID, TWILIO_FROM_NUMBER
WhatsApp Twilio Active TWILIO_ACCOUNT_SID, TWILIO_FROM_NUMBER
Email Resend Active RESEND_API_KEY
Push Firebase Active FIREBASE_SERVICE_ACCOUNT_JSON
RTC LiveKit Active LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL
Fax Twilio Discontinued Not available (Twilio Fax API retired 2021).
Auth Firebase Auth Identity provider (Email, Google, Phone).
Storage Google Cloud Storage (GCS) Blob storage for Deeds/Evidence.
AI/ML Vertex AI (Gemini 2.0) Multimodal reasoning and extraction.
Email Resend Transactional email infrastructure.

Forensics & Parsing

Capability Technology Details
PDF Vision Puppeteer Headless Chrome for rasterizing compromised PDFs.
OCR Tesseract.js Client/Server optical character recognition.
Extraction pdf-parse Raw text layer extraction (Fast path).

Quality & Tooling

Capability Technology Details
Unit Test Vitest Fast component/logic testing.
E2E Test Playwright Full browser automation testing.
Linting ESLint + Prettier Code quality and formatting.
Analysis Dependency Cruiser Circular dependency detection (imports:cruise).

3. Platform Standards (The Golden Rules)

The following standards govern the core architecture and user experience.

Standard Name Description
STND-60 Tri-Pane Shell The forensic workbench layout. Left: Register, Center: Workspace, Right: Metadata/Detail Drawer.
STND-63 Hub-and-Spoke Global navigation model. Top-level modules are Hubs; features are Spokes. Module visibility is decoupled from context.
STND-64 Unified Header Utility Cluster Consolidation of identity (Avatar) and persona (Context Switcher) in the top-right header for clear hierarchy.
STND-70 Unified Telemetry Multi-range, polymorphic signal ingestion and visualization standard for Building Pulse.
STND-78 Registry-Driven Authz Capabilities are defined in the central CAPABILITY_REGISTRY and infused into session snapshots based on the Persona Graph.
STND-79 Cinematic Stacking Mandatory z-index layering for marketing pages via LandingSection to ensure background/atmosphere/content integrity.
STND-82 High-Fidelity Identity Capture Standards for user avatar management using hybrid (Live Camera + Upload) capture methods.
STND-90 Unified Auth Terminal Side-by-side modal authentication architecture (Branding vs. Login) with unified identifier/verification flow.
STND-95 Commit Protocol Standardized protocol for atomic commits, ghost branching, and pre-flight verification.
STND-96 Hosted Verification Mandatory verification against persistent hosted environments (-dev) before production promotion.
STND-97 Test Traceability Mandatory @cap, @persona, and @env metadata tagging for all verification artifacts.
STND-98 Tooling Taxonomy Strict file naming (.test.ts, .spec.ts, .verify.ts) to ensure correct runner execution.
STND-99 Aesthetic Persistence Automated visual regression/screenshot comparison for Gold Workbenches and Landing pages.
STND-100 Resident Accessibility Automated WCAG audits as a "Hard Gate" for sprint certification.
STND-101 Telemetry-Driven Verification Cross-pillar verification that links UI actions to backend forensic signals.
STND-102 Requirement-to-Test The "Verification Blueprint" requirement during the architectural planning phase.
STND-103 Data Seeding Taxonomy Organized 'DataSeeder' family for DEV, TEST, and PROD environments.
STND-104 Persistence-Aware Seeding Mandatory idempotency and 'Resident-Ready' logical loading for hosted environments.
STND-105 Procedural Workflow Formal procedure for creating new verification and provisioning scripts.
STND-112 Module Specification The mandatory Specification Template incorporating flat hierarchy and "What Good Looks Like" checklists.
STND-112.R Evergreen Stewardship The mandatory protocol for reconciling "As-Built" reality from walkthrough.md back into core specifications (The Perpetual Loop).


3. The API Boundary: Server Actions

CRITICAL: Server Actions (apps/platform/src/actions/*) are the only bridge between UI and Backend. Actions MUST be protected by the verifyContext guard or the registry-backed capability check.

Authorization (Standard 78)

Never hardcode role checks (e.g., if (role === 'admin')). Use the Capability Registry: - Client: can(capId) or useHasCapability(capId). - Server: verifyCapability(capId) or verifyContext(requirements). * ❌ import { service } from '@sd/com-community'; * ✅ const { service } = await import('@sd/com-community');

The Universal Envelope (RULE-43.4)

All actions must return data wrapped in ActionResponse<T>.

type ActionResponse<T> = {
    success: boolean;
    data?: T;
    error?: string; // AppError code
    validationErrors?: Record<string, string[]>;
}

Usage:

export async function myAction(props: any) {
    return safeAction(async () => {
        const { service } = await import('@sd/mod-knowledge'); // Lazy Load
        const data = await service.doWork();
        return serialize(data); // Strip Classes/Dates
    });
}


3. Data & Typing

The DTO Boundary

Services must not return raw Database objects (which might contain secrets). * Pattern: Use Zod PublicSchema.parse(data) to strip internal fields before returning.

Multi-Language Data

Fields requiring translation use the Localized Object Pattern.

type Localized<T = string> = { en?: T; es?: T };
interface Article {
    title: Localized; // { en: "Hello", es: "Hola" }
}


4. Error Handling

We use the Throwing Pattern with AppError. * Services: Throw new AppError(code, meta). * Actions: The safeAction wrapper automatically catches these and converts them to { success: false, error: code }.

Never throw raw Javascript Errors for business logic failures.


5. Internationalization (i18n)

  • Component: const t = useTranslations('Namespace'); <h1>{t('key')}</h1>
  • JSON: apps/platform/messages/en.json must always match es.json.
  • Linting: The build will fail if you leave hardcoded strings.
  • Dev Shield (Fast-Iteration): To mitigate memory spikes during i18n hot-reloads (Hazard 774.C), use pnpm dev:fast. This flags SUSPEND_I18N=true, bypassing message bundles and returning only raw keys to the UI.

6. Stability & Sanitation Protocols

The Ghostbuster Protocol

Lingering zombie processes (Next.js, Firebase, Playwright) can lock ports and corrupt environment state. - Trigger: Run pnpm ghostbuster before starting dev:turbo. - Action: Aggressively kills PIDs on known ports and purges stale JS artifacts from src.

Memory Hardening

Next.js dev servers with extensive i18n and modular foundations require increased heap limits. - Rule: NODE_OPTIONS="--max-old-space-size=4096" is mandatory for all development scripts.


6. The AI Development Protocol

In an AI-driven workflow, the human role shifts from Writer to Architect & Auditor.

A. The "3-Step" Review Verification

We do not review code line-by-line for syntax (TypeScript does that). We review for Intent and Safety.

Phase What to Review The "Human-in-the-Loop" Question
1. Plan implementation_plan.md "Does this approach actually solve the business problem?"
2. Diff git diff (Files Changed) "Did the AI hallucinate a dependency or bypass security?"
3. Proof walkthrough.md "Do I see evidence (Screenshots/Logs) that it works?"

B. The "Junior Dev" Heuristic

Treat AI Agents as Brilliant but Literal Junior Engineers. * They generate valid code faster than you. (Don't nitpick style). * They lack context. (Check for architectural violations). * They are eager to please. (Check for "Happy Path" bias; ask "What if this fails?").

C. Timing

  • Small Tasks: Review the diff before allowing the git commit tool.
  • Features: Require a walkthrough.md before merging to main.
  • Architectural Deliverables: High-fidelity reviews for GOLDEN documents should be conducted via Typora to ensure visual alignment and formatting integrity.

D. The Typora Review Protocol

For major architectural synchronization or plan reviews: 1. Open: Execute open -a Typora [FILE_PATH]. 2. Audit: Review for narrative flow, standard adherence, and visual clarity. 3. Sign-off: Provide feedback or approval within the chat interface.

D. The Automated Steward (Deep Checks)

Humans are bad at finding dead code or subtle security holes. We delegate this to "The Steward" (CI/CD).

Type When? Tool Who Fixes It?
Dead Code On PR knip (or ts-prune) The AI (Author) must remove unused exports before merge.
Security On PR npm audit + snyk The AI must upgrade packages immediately.
Complexity Weekly complexity-report The Architect (Human) schedules a refactor sprint for "Hotspots".
Efficiency Monthly lighthouse / Load Test The Architect reviews performance budgets.

The Rule: "If a machine can check it, a human shouldn't review it." * Don't comment "unused variable". Let the Linter block the merge. * Don't comment "circular dependency". Let depcruise fail the build.

E. Evergreen Stewardship (Standard 112.R)

To prevent architectural drift, every implementation cycle must close the loop between the Code and the Specification.

  1. The Loop: Findings from the walkthrough.md (Implementation Realizations) must be funneled back into the relevant DESIGN_SPECS/*.md file.
  2. Persistence: Stewardship is not "Optional Documentation." It is a terminal condition for marking a task as Completed.
  3. Thinking Stash: Use architecture/THINKING/ to seed logic during development, but reconcile it to GOLDEN/ before handover.

7. Development Excellence: The Commit Protocol

To ensure high-fidelity deliverables and a "No-Mess" history, all developers must adhere to Standard 95.

A. Atomic Commit Philosophy

  • One Change, One Commit: Never bundle unrelated features into a single commit.
  • Message Format: feat(domain): description (STND-XX).
  • Citations: Always cite the Standard (STND) or Hazard (HAZ) being addressed.

B. Ghost Branching (Autonomous Isolation)

Use short-lived Ghost Branches for all non-trivial tasks: 1. Spawn: git checkout -b ghost/[TASK_ID]-[slug] 2. Verify: The Platform Verification GitHub Action automatically runs on ghost/* pushes. 3. Collapse: Once verified and approved, merge via --no-ff into development. 4. Purge: Delete the ghost branch immediately after integration.

C. The "Pre-Flight" Check

The build pipeline is the final arbiter of truth. A branch is not considered "Done" until the CI suite results in a Green Checkmark. - Mandatory Checks: Linting, Type-Check (TSC), and Unit Tests (Vitest).


8. The "No-Bad-Habits" Guardrails

For junior developers or those new to the stack: - Lint Enforcement: Commit hooks and CI will block any "sloppy" code (unused vars, shadowed types). - Type Guard: strict mode is mandatory. Raw any is forbidden unless explicitly documented as a Forensic Bypass.


9. The 'AutoTester' Family (Standard 98)

Verification is organized by operational phase and environment capability.

Protocol Phase Env Tool Purpose
AutoTester-Dev DEV Emulator Vitest Fast local logic/component verification.
AutoTester-Overnight DEV/TEST Mixed Playwright/TSX Self-healing deep-scan and bridge testing.
AutoTester-Sprint TEST Hosted Playwright Formal milestone certification (Hosted).
AutoTester-Sanctuary PROD Production Playwright Non-destructive health check (Live).

10. The Art of Excellence: Advanced Verification

Standard 97: Comprehensive Traceability

All verification artifacts (scripts, tests) MUST include the following metadata in their header: - @cap: Capability ID (from Book 06). - @persona: Actor ID (from Persona Book). - @env: Target state (local, hosted, sanctuary). - @tool: The primary runner (vitest, playwright, tsx).

Standard 99: Aesthetic Persistence (Visual Regression)

To guard the high-density aesthetics of the platform: - Use Playwright toHaveScreenshot() for all "Gold Workbench" modules. - Maintain a baseline of "Resident-Facing" landing sections.

Standard 100: Accessibility Hard-Gate

  • No Pull Request to main shall be accepted if automated accessibility audits (Axe) reveal Critical violations.

Standard 101: The Forensic Loop

  • Integration tests must verify that the corresponding Telemetric Signal was recorded in Firestore (ops_telemetry_tests).

Standard 102: The Verification Blueprint

  • Every Feature Specification MUST include a "Verification Blueprint" section defining the Persona, Success State, and Boundary Hazards before implementation begins.

11. The 'DataSeeder' Family (Standard 103)

Seeding is organized by environmental capability and target data fidelity.

Protocol Phase Env Purpose
DataSeeder-Local DEV Emulator Nuke & Reload. Rapid seeding for local dev iteration.
DataSeeder-Gold TEST Hosted Resident-Ready. Reconstituting the canonical Golden Graph.
DataSeeder-Chaos TEST Hosted Stress Testing. Injecting edge-case "Chaos" data.
DataSeeder-Demo TEST/PROD Hosted Pre-Production. Preparing "The Full Show" for stakeholders.
DataSeeder-Sanctuary PROD Production Protected. Controlled restoration of reference data.

12. Persistence-Aware Data (Standard 104)

Shifting from "Destructive Injection" to "Resident Reconciliation" in persistent environments.

Standard 104.1: The Purge Protocol

  • Scripts targeting hosted environments MUST support targeted purging by namespace or tag to avoid total database wipes.

Standard 104.2: Resident-Ready Idempotency

  • Rule: Hosted seeders MUST use UPSERT logic.
  • Verify existence via primary key (UID, Slug, or Email) before creation to prevent duplicate records.
  • If a script is interrupted and re-run, it must reach the same end-state without error.