manus-talk-to-my-lawyer Development Patterns
Auto-generated skill from repository analysis
Overview
This skill teaches development patterns for manus-talk-to-my-lawyer, a TypeScript/Vite-based legal technology platform. The codebase follows a phase-based development approach with comprehensive testing, structured database migrations, and integrated payment processing. The application appears to be a full-stack platform supporting multiple user roles (subscribers, employees, attorneys, admins) with email notifications, Stripe payments, and tRPC API architecture.
Coding Conventions
File Naming
- Use camelCase for all file names
- Test files follow pattern:
*.test.* - Phase-based test files:
phase*.test.ts - Database migrations:
drizzle/####_*.sql
Import/Export Style
// Use alias imports
import { something } from '@/shared/types'
import { db } from '@/server/db'
// Mixed export style - both named and default exports
export const namedFunction = () => {}
export default ComponentName
Commit Messages
- Average length: ~271 characters
- Common prefixes:
checkpoint,docs - Phase commits:
Phase X:orCheckpoint: Phase X: - Freeform descriptive style
Workflows
Phase Checkpoint Commit
Trigger: When finishing a major feature or improvement phase
Command: /complete-phase
- Implement feature changes across multiple implementation files
- Add comprehensive test coverage in
server/phase*.test.ts - Run tests and validate all pass (document XXX/XXX tests passing)
- Confirm 0 TypeScript errors with
tsc --noEmit - Create checkpoint commit with descriptive message:
Checkpoint: Phase X: [Feature description and testing summary] - Implemented [specific changes] - Added tests covering [test scenarios] - XXX/XXX tests passing - 0 TypeScript errors - Update
todo.mdwith completed phase progress
Database Schema Migration
Trigger: When adding new database fields or tables
Command: /add-db-column
- Update
drizzle/schema.tswith new schema definitions:export const newTable = pgTable('new_table', { id: serial('id').primaryKey(), newColumn: text('new_column').notNull(), createdAt: timestamp('created_at').defaultNow(), }); - Generate migration SQL file:
drizzle/####_description.sql - Update migration metadata in
drizzle/meta/*.json - Update
drizzle/meta/_journal.jsonwith new migration entry - Apply migration to Supabase database (via MCP or direct SQL execution)
- Update
server/db.tswith new query functions if needed:export const getNewTableData = async (id: number) => { return await db.select().from(newTable).where(eq(newTable.id, id)); };
Email Template Integration
Trigger: When adding new email notifications to the system
Command: /add-email-template
- Add email template function to
server/email.ts:export const sendNewNotificationEmail = async ( to: string, data: { name: string; details: string } ) => { // Branded email template implementation }; - Wire email sending into relevant tRPC procedures in
server/routers.ts:.mutation(async ({ input, ctx }) => { const result = await someDbOperation(input); // Fire-and-forget email sending sendNewNotificationEmail(input.email, result).catch(console.error); return result; }) - Add email template tests in
server/phase*.test.ts - Update
todo.mdwith email integration status - Ensure fire-and-forget error handling (errors caught and logged, don't block main flow)
Frontend Page Updates
Trigger: When implementing frontend features that span multiple pages
Command: /update-frontend-pages
- Update relevant page components in
client/src/pages/:// Ensure proper role-based rendering if (user?.role === 'attorney') { return <AttorneyView />; } - Modify shared components if needed in
client/src/components/ - Update routing in
client/src/App.tsxif adding new routes - Ensure responsive design and mobile compatibility
- Test across all user roles: subscriber, employee, attorney, admin
- Verify navigation and permissions work correctly
Stripe Payment Integration
Trigger: When adding new payment flows or modifying pricing
Command: /update-stripe-integration
- Update
server/stripe.tswith new checkout logic:export const createCheckoutSession = async (priceId: string) => { return stripe.checkout.sessions.create({ // Checkout configuration }); }; - Modify
server/stripeWebhook.tsfor webhook handling:case 'checkout.session.completed': await handleCheckoutCompleted(event.data.object); break; - Update
shared/pricing.tswith new pricing constants - Update frontend payment pages (
Pricing.tsx,Billing.tsx, etc.) - Add commission tracking in
server/db.tsif needed - Test payment flows end-to-end in Stripe test mode
Documentation Update
Trigger: When documenting architecture, features, or development processes
Command: /update-docs
- Create or update markdown files in
docs/or root directory - Update
README.mdwith project overview and setup instructions - Document system architecture in
ARCHITECTURE.md - Update
todo.mdwith current progress and next steps - Ensure documentation reflects current codebase state and deployment process
- Include code examples and configuration details
tRPC Procedure Addition
Trigger: When adding new API endpoints for frontend consumption
Command: /add-trpc-procedure
- Add procedure definition to
server/routers.tsor modular router files:newProcedure: publicProcedure .input(z.object({ field: z.string(), })) .query(async ({ input, ctx }) => { return await getSomeData(input.field); }), - Add input validation with Zod schemas for type safety
- Implement database queries in
server/db.tsif needed - Add comprehensive tests in
server/phase*.test.ts:test('newProcedure returns expected data', async () => { const result = await caller.newProcedure({ field: 'test' }); expect(result).toMatchObject({ /* expected shape */ }); }); - Wire frontend calls to new procedures using tRPC hooks
- Ensure proper role-based access control with middleware
Project TODO Tracker
Last Updated: 2026-03-04 Purpose: Shared TODO list across all coding agents (Claude, GitHub Copilot, Codex, etc.) Usage: Mark items as
[x]when completed. All agents should continue from the last completed item.
Phase 1: Foundation
- Database schema (users roles, letter_requests, letter_versions, review_actions, workflow_jobs, research_runs, attachments, notifications)
- Status machine enum and transition validation (submitted → researching → drafting → pending_review → under_review → approved/rejected/needs_changes, NO draft state)
- Global design system (color palette, typography, theme)
Phase 2: Auth & Navigation
- Role-based user system (subscriber, employee, admin)
- Role-based routing and navigation
- DashboardLayout with sidebar for each role (AppLayout component)
- Login/auth flow with role detection and auto-redirect
Phase 3: Subscriber Portal
- Multi-step letter intake form (jurisdiction, matter type, parties, facts, desired outcome)
- File upload for attachments (S3 integration)
- My Letters list page with status badges
- Letter detail page (status timeline, intake summary, final approved letter only)
- Secure data isolation — subscribers never see AI drafts or research
Phase 4: Employee/Attorney Review Center
- Review queue with filtering (pending_review, under_review, needs_changes)
- Review detail page with intake panel, AI draft editor, research panel
- Claim/assign letter for review
- Save attorney edit version
- Approve/reject/request changes actions
- Review actions audit trail
Phase 5: Admin Dashboard
- Failed jobs monitor
- Retry failed pipeline jobs
- System health overview (queue counts, status distribution)
- User management (role assignment)
Phase 6: AI Pipeline
- Stage 1: Perplexity API research (jurisdiction rules, statutes, case law)
- Research packet validation gate
- Stage 2: OpenAI drafting from validated research
- Draft parser/validator
- Pipeline orchestration (status transitions, job logging)
- Failure handling and retry logic
Phase 6b: High-Priority Additions
- Deterministic research packet validator (validateResearchPacket)
- Deterministic draft JSON parser/validator (parseAndValidateDraftLlmOutput)
- Subscriber-safe detail endpoint (never returns ai_draft/attorney edits/internal research)
- Notification system via Resend email (subscriber: needs_changes/approved/rejected; attorney/admin: pending_review/failed jobs)
- Transactional email templates: status change, approval, rejection, needs_changes, new_review_needed
- Resend API key configuration (via webdev_request_secrets)
- Claim/assignment locking in attorney review queue
- Retry failed job controls for admins
- Idempotency protections for duplicate submissions/retries
- Note visibility (internal vs user_visible) in review actions
- Final approved version generation on approval (freeze version + current_final_version_id)
- PDF export / downloadable output for final letters (future enhancement)
Phase 7: Testing & Delivery
- Vitest unit tests for critical paths (29 tests passing)
- End-to-end verification (TypeScript clean, server healthy)
- Save checkpoint and deliver
Future Enhancements
- PDF export for final approved letters
- n8n workflow integration for letter generation
- Stripe payment integration for subscriptions
- Mobile PWA optimization
Phase 8: E2E Workflow Audit & Fix
- Audit intake form fields → pipeline input mapping
- Add 3rd AI stage: Claude/Anthropic final letter assembly (combines research + draft into professional letter)
- Ensure pipeline status transitions fire correctly: submitted → researching → drafting → pending_review
- Ensure review center claim/approve/reject correctly updates status and creates final version
- Ensure approved letter appears in subscriber My Letters with full content
- Ensure subscriber detail page shows final approved letter (not AI drafts/research)
Phase 9: Stripe Payment Integration
- Add Stripe feature via webdev_add_feature
- Subscription plans: per-letter ($299), monthly ($200/mo unlimited), annual ($2000/yr 48 letters)
- Checkout session creation with metadata
- Webhook handler for checkout.session.completed
- Atomic subscription activation (prevent race conditions)
- Commission tracking (5% employee referral)
- Employee coupon system (20% discount on per-letter)
- Pricing page UI
- Credit/letter allowance enforcement before letter submission
Phase 10: Spec Compliance Patches (from pasted_content_4)
- Add buildNormalizedPromptInput helper (trim strings, safe defaults, filter empty rows)
- Strengthen validateResearchPacket: require sourceUrl+sourceTitle per rule, prefer >= 3 rules
- Add subscriber updateForChanges mutation (re-submit after needs_changes)
- Add admin forceStatusTransition mutation (audited)
- Add frontend polling/revalidation for researching/drafting/pending_review statuses
- Add status timeline component in subscriber LetterDetail
- Add subscriber update form when status is needs_changes
- Verify success path E2E (submit → research → draft → assembly → pending_review → claim → approve → subscriber sees final)
- Verify failure path (invalid research stops pipeline, invalid draft stops pipeline)
- Verify security (subscriber cannot access ai_draft/research/internal notes)
Phase 12: Stripe Payment Integration
- Fix TypeScript error in AdminLetterDetail page
- Add Stripe scaffold via webdev_add_feature
- Configure STRIPE_SECRET_KEY and STRIPE_PUBLISHABLE_KEY
- Create subscriptions and payments tables in database
- Create Stripe products/prices: per-letter ($29), monthly ($79/mo), annual ($599/yr)
- Build checkout session endpoint (tRPC)
- Build Stripe webhook handler (subscription events, payment events)
- Build subscription status checker middleware
- Build billing portal redirect endpoint
- Build Pricing page with 3 plans
- Build Subscription status component in subscriber dashboard
- Gate letter submission behind active subscription or available credits
- Show upgrade prompt when subscriber has no active plan
- Admin: view subscriber subscription status
- Run tests and save checkpoint (29/29 passing, 0 TS errors)
Phase 11: n8n Workflow Integration & Frontend Polish
- Get n8n workflow webhook URL for the best legal letter workflow
- Activate the n8n workflow so webhook is live
- Update pipeline.ts to call n8n webhook as primary, with in-app AI fallback
- Add N8N_WEBHOOK_URL as environment variable
- Build admin letter detail page with force status transition dialog
- Add polling/revalidation to employee ReviewDetail for in-progress statuses
- Verify TypeScript compiles cleanly
- Run all tests
Phase 13: Dashboard Enhancement — Letters History & Payment Receipts
- Audit current subscriber dashboard, MyLetters, and Billing pages
- Add backend: letters list with search/filter/sort/pagination (tRPC)
- Add backend: payment receipts list from Stripe invoices (tRPC)
- Rebuild MyLetters page as full Letters History with search, filter by status/type/date, sort, pagination
- Build Payment Receipts page with Stripe invoice history, amounts, dates, downloadable receipt links
- Enhance subscriber Dashboard with summary stats (total letters, active subscription, credits used, pending reviews)
- Add recent activity feed on dashboard (last 5 letters with status)
- Add quick action cards on dashboard (Submit Letter, View Letters, Billing)
- Run tests, verify, save checkpoint
Phase 14: Paywall Flow Revision + Dashboard Enhancements
- Add generated_locked status to schema enum and status machine
- Update DB migration to include generated_locked status
- Add payToUnlock mutation: create per-letter checkout, on success advance to pending_review
- Build LetterPaywall component: blurred AI draft preview + Pay Now button
- Update LetterDetail to show LetterPaywall when status = generated_locked
- Update pipeline to set status = generated_locked after AI assembly (instead of pending_review)
- Update Stripe webhook to handle letter unlock (generated_locked → pending_review)
- Update MyLetters list: generated_locked highlighted amber with "Unlock for $29" badge
- Update StatusTimeline: generated_locked step with amber lock icon
- Update StatusBadge: generated_locked shows "Ready to Unlock" in yellow
- Tests: 31/31 passing, 0 TypeScript errors
- Build Payment Receipts page with invoice history, amounts, dates, receipt links (future)
- Enhance subscriber Dashboard: subscription status widget, activity feed, quick action cards (future)
- Add date range filter to Letters History (future)
Phase 15: Post-Submission Email Notifications
- Add sendLetterSubmissionEmail: branded confirmation email sent immediately after letter submission
- Add sendLetterReadyEmail: "your draft is ready" email sent when AI pipeline sets generated_locked
- Add sendLetterUnlockedEmail: payment confirmation email sent after Stripe unlock webhook
- Wire sendLetterSubmissionEmail into letters.submit mutation (routers.ts)
- Wire sendLetterReadyEmail into pipeline.ts Stage 3 completion (in-app pipeline path)
- Wire sendLetterReadyEmail into n8nCallback.ts completion (n8n pipeline path)
- Wire sendLetterUnlockedEmail into stripeWebhook.ts letter unlock handler
- Tests: 35/35 passing, 0 TypeScript errors
Phase 16: Dev Email Preview Endpoint
- Build server/emailPreview.ts: dev-only Express route at GET /api/dev/email-preview
- Index page: lists all 9 templates with HTML and plain-text preview links
- Per-template rendering: ?type=submission|letter_ready|unlocked|approved|rejected|needs_changes|new_review|job_failed|status_update
- Query param support: ?name=&subject=&letterId=&state=&letterType=&mode= for realistic preview data
- Guard: only active in NODE_ENV !== production (verified in tests)
- Dev toolbar overlay showing template name and subject line in browser
- Register route in server/_core/index.ts
- Vitest tests: route export, dev registration, production guard (3 new tests)
- Tests: 38/38 passing, 0 TypeScript errors
Note: This TODO list is synchronized across all documentation files. When completing items, update this section in all files to maintain consistency.
Testing Patterns
- Tests are organized by development phases:
phase*.test.ts - Comprehensive test coverage expected for each phase
- Test results documented in commit messages (XXX/XXX tests passing)
- TypeScript compilation must pass (0 errors) before commits
- Tests cover tRPC procedures, database operations, and email functionality
Commands
| Command | Purpose |
|---|---|
/complete-phase | Complete a development phase with comprehensive testing and checkpoint commit |
/add-db-column | Add new database schema with proper Drizzle migration |
/add-email-template | Integrate new branded email notifications with fire-and-forget sending |
/update-frontend-pages | Update multiple frontend pages with role-based considerations |
/update-stripe-integration | Modify payment flows and webhook handling |
/update-docs | Create or update project documentation |
/add-trpc-procedure | Add new API endpoints with validation and testing |