YAS/yetanothersuite_implementation_plan.md
YetAnotherSuite Dev 262fbf48e2 feat: Phase 1 foundation — monorepo, auth, DB schema, API, shared packages
Phase 1.1: Monorepo Setup & Design System
- Turborepo + pnpm workspaces monorepo structure
- Shared packages: @yetanother/types, @yetanother/utils, @yetanother/hooks, @yetanother/ui, @yetanother/db
- Radix UI primitives with custom shadcn/ui-style components (Button, Dialog, Toast, Tooltip, Tabs, Label)
- Tailwind CSS v4 with design tokens (light theme)
- TypeScript strict mode with composite project references

Phase 1.2: Authentication & User Management
- Fastify server setup with JWT auth (register, login, me endpoints)
- @fastify/jwt with cookie support
- User and workspace models with Prisma ORM

Phase 1.3: Database Schema & Migrations
- Full Prisma schema: User, Workspace, Node, NodeLink, Tag,
  Folder, Reminder, Embedding, Activity, Attachment,
  WorkspaceMember, SyncCheckpoint
- pgvector extension for embeddings (vector(1536))
- Seed script for dev data
- Comprehensive indexes (GIN, BRIN, B-tree)

Phase 1.4: API Foundation & Middleware
- Fastify REST API with versioned routes (/api/v1)
- Zod request validation on all endpoints
- CORS, Helmet security headers, rate limiting
- Structured logging with pino-pretty
- Swagger/OpenAPI docs at /docs
- WebSocket support (collaboration ready)
- CRUD routes: nodes, workspaces, search, auth

Tooling:
- ESLint 9 flat config with TypeScript parser
- Prettier with consistent formatting rules
- Turbo v2 task orchestration
- GitHub Actions CI workflow
- Husky + lint-staged pre-commit hooks
2026-07-20 21:58:17 +02:00

954 lines
44 KiB
Markdown

# YetAnotherSuite — Implementation Plan
> **The Unified Productivity Ecosystem — Todo, Calendar, and Notes, Connected by AI**
>
> Platform: Web (PWA), Desktop (Electron/Tauri), Mobile (React Native) | Phases: 6 | Timeline: 24-28 weeks
---
## 1. Vision & Core Concept
### Vision
A unified workspace where tasks, events, and knowledge naturally interconnect. No more context switching between apps — your todos appear in your calendar, your notes link to your tasks, and AI surfaces the right information at the right time.
### Problem Statement
Current productivity stacks are fragmented: todos in one app, calendar in another, notes in a third. Users lose context, duplicate effort, and miss connections between their work. YetAnotherSuite eliminates fragmentation by treating tasks, events, and notes as interconnected nodes in a personal knowledge and action graph.
### Key Differentiators
- Unified data model — tasks, events, and notes share a single graph structure
- AI-powered cross-modal linking (e.g., 'this note relates to this meeting and these tasks')
- Contextual workspace switching — calendar view shows relevant notes, task view shows upcoming deadlines
- Natural language input across all modules ('Schedule meeting with Sarah next Tuesday and create prep notes')
- Local-first with seamless cloud sync — works offline, syncs when connected
- Time-blocking integration — drag tasks directly onto calendar as time blocks
- Bi-directional references — tasks reference notes, notes reference events, events link to tasks
### Competitive Positioning
Notion (notes) + Todoist (tasks) + Google Calendar (events) = 3 apps, 3 contexts, 3 syncs. YetAnotherSuite = 1 app, 1 context, 1 sync, with AI connecting everything.
### Target Users
- Knowledge workers managing complex projects
- Executives and managers coordinating teams
- Researchers and academics with time-bound deliverables
- Freelancers juggling multiple clients and deadlines
- Students managing coursework and research
---
## 2. System Architecture
### Frontend Stack
- **Framework**: React 18+ with TypeScript (strict mode)
- **State Management**: Zustand (global) + TanStack Query (server state) + Jotai (local UI)
- **Editor Engine**: TipTap / ProseMirror (block-based, extensible)
- **Calendar Engine**: Custom React components + date-fns + rrule for recurrence
- **Styling**: Tailwind CSS + Radix UI primitives + shadcn/ui components
- **Realtime Collaboration**: Yjs (CRDT) for all modules
- **Build Tool**: Vite + Turborepo (monorepo)
- **Desktop Wrapper**: Tauri (Rust-based, lightweight, secure)
- **Mobile**: React Native (shared business logic via React Native Web)
- **Testing**: Vitest + React Testing Library + Playwright + MSW (API mocking)
### Backend Stack
- **Api Gateway**: Node.js + Fastify (or Go + Gin for performance-critical paths)
- **Database**: PostgreSQL 15+ (primary) with JSONB for flexible content
- **Caching**: Redis (sessions, hot data, rate limiting)
- **Search**: Meilisearch (instant) + pgvector (semantic) — hybrid search
- **Realtime**: WebSocket server (Socket.io or native WS with Redis adapter)
- **Queue**: BullMQ (Redis-based) for background jobs (AI processing, sync, exports)
- **Ai Services**: OpenAI/Anthropic API + local fallback (Ollama) + self-hosted embeddings
- **File Storage**: S3-compatible (MinIO for self-hosting) + CDN for assets
- **Vector Database**: pgvector (PostgreSQL extension) for semantic search and recommendations
- **Sync Engine**: Custom sync protocol (based on CRDTs + operational transforms) for offline-first
### Infrastructure
- **Containerization**: Docker + Docker Compose (dev) + Kubernetes (production)
- **Orchestration**: Helm charts for K8s deployment
- **Ci Cd**: GitHub Actions with matrix builds (Web, Desktop, Mobile)
- **Monitoring**: Prometheus + Grafana (metrics) + Sentry (errors) + LogRocket (session replay)
- **Deployment**: Railway/Render (MVP) → AWS/GCP (scale) with Terraform
- **Cdn**: Cloudflare (global edge caching)
- **Backup**: Automated PostgreSQL backups + S3 versioning
---
## 3. Unified Data Model
### Philosophy
All entities (tasks, events, notes) are 'Nodes' in a unified graph. They share common properties (title, content, timestamps, metadata) but have type-specific extensions. Relationships are first-class citizens.
### Core Entities
#### User
- **Fields**: id (UUID PK), email (unique, indexed), display_name, avatar_url, preferences (JSONB: theme, timezone, notification_settings, default_views), encryption_key (for E2E encrypted notes), created_at, updated_at, last_active_at
- **Relations**: Workspaces (many-to-many via WorkspaceMember), Nodes (one-to-many, owned), SharedNodes (many-to-many via NodeShare), Activities (one-to-many)
#### Workspace
- **Fields**: id (UUID PK), name, slug (unique per user), description, settings (JSONB: default_view, color_scheme, ai_enabled, retention_policy), owner_id (FK → User), created_at, updated_at
- **Relations**: Members (many-to-many via WorkspaceMember), Nodes (one-to-many), Tags (one-to-many, workspace-scoped), Folders (one-to-many, workspace-scoped), Integrations (one-to-many)
#### Node (Polymorphic Base)
- **Fields**: id (UUID PK), type (ENUM: 'task', 'event', 'note', 'project', 'goal'), workspace_id (FK → Workspace), owner_id (FK → User), parent_id (FK → Node, self-referencing for hierarchy), title, content (JSONB: ProseMirror doc for notes, structured data for tasks/events), plain_text (generated, for search), status (ENUM: 'active', 'archived', 'deleted'), priority (INTEGER: 1-5, nullable), start_time (TIMESTAMPTZ, for events and task deadlines), end_time (TIMESTAMPTZ, for events and task durations), duration_minutes (INTEGER, computed or explicit), recurrence_rule (TEXT, iCal RRULE format), completion_rate (DECIMAL, for projects/goals), metadata (JSONB: type-specific data), version (INTEGER, for optimistic locking), is_encrypted (BOOLEAN, for E2E notes), created_at, updated_at, completed_at, archived_at
- **Relations**: Parent (self-referencing), Children (self-referencing), Tags (many-to-many via NodeTag), Links (many-to-many via NodeLink, self-referencing), Backlinks (many-to-many via NodeLink, inverse), Embeddings (one-to-many), Activities (one-to-many), Reminders (one-to-many), Attachments (one-to-many)
- **Indexes**: GIN on content (JSONB), GIN on metadata (JSONB), B-tree on type, status, workspace_id, owner_id, BRIN on created_at (time-series optimization), GIST on tsvector (full-text search)
#### NodeLink (Relationship Graph)
- **Fields**: id (UUID PK), source_id (FK → Node), target_id (FK → Node), link_type (ENUM: 'references', 'blocks', 'relates_to', 'parent_of', 'child_of', 'scheduled_as', 'prepared_for'), strength (DECIMAL: 0-1, AI-computed relevance), is_auto (BOOLEAN, AI-generated vs user-created), context (TEXT, why they're related), created_at
- **Constraints**: UNIQUE(source_id, target_id, link_type), CHECK(source_id != target_id)
- **Indexes**: B-tree on source_id, target_id, B-tree on link_type, is_auto
#### Tag
- **Fields**: id (UUID PK), name, color (HEX), workspace_id (FK → Workspace), is_system (BOOLEAN, e.g., 'urgent', 'meeting'), created_at
- **Relations**: Nodes (many-to-many via NodeTag), Workspace (many-to-one)
#### Folder
- **Fields**: id (UUID PK), name, workspace_id (FK → Workspace), parent_id (FK → Folder, self-referencing), view_type (ENUM: 'list', 'board', 'calendar', 'gallery'), filter_config (JSONB: saved filters), sort_config (JSONB: default sort), order_index (INTEGER), created_at
- **Relations**: Nodes (many-to-many via NodeFolder), Parent (self-referencing), Children (self-referencing)
#### Reminder
- **Fields**: id (UUID PK), node_id (FK → Node), user_id (FK → User), remind_at (TIMESTAMPTZ), notification_type (ENUM: 'push', 'email', 'sms', 'in_app'), status (ENUM: 'pending', 'sent', 'dismissed', 'snoozed'), snooze_until (TIMESTAMPTZ), created_at
#### Embedding
- **Fields**: id (UUID PK), node_id (FK → Node), chunk_index (INTEGER, for long content), chunk_text (TEXT, the text segment), vector (VECTOR(1536), pgvector), model_version (TEXT, e.g., 'text-embedding-3-large-v1'), created_at
- **Indexes**: HNSW index on vector (for fast similarity search)
#### Activity
- **Fields**: id (UUID PK), user_id (FK → User), node_id (FK → Node, nullable), workspace_id (FK → Workspace), action_type (ENUM: 'created', 'updated', 'deleted', 'viewed', 'shared', 'linked', 'completed', 'ai_assisted'), metadata (JSONB: before/after snapshots, AI prompt used, etc.), session_id (TEXT, for grouping), created_at
- **Indexes**: BRIN on created_at, B-tree on user_id, workspace_id, action_type
#### Attachment
- **Fields**: id (UUID PK), node_id (FK → Node), filename, mime_type, size_bytes, storage_key (S3 path), thumbnail_key (S3 path, for images), uploaded_by (FK → User), created_at
#### WorkspaceMember
- **Fields**: id (UUID PK), workspace_id (FK → Workspace), user_id (FK → User), role (ENUM: 'owner', 'admin', 'editor', 'viewer'), permissions (JSONB: granular overrides), joined_at, last_accessed_at
#### SyncCheckpoint
- **Fields**: id (UUID PK), user_id (FK → User), device_id (TEXT), last_sync_at (TIMESTAMPTZ), sync_token (TEXT, for delta sync), device_info (JSONB: os, app_version, screen_size), updated_at
---
## 4. Module Specifications
### Tasks Module
- **Description**: Full-featured task management with projects, subtasks, and time estimates
**Core Views**:
- **Inbox**: Uncategorized tasks, quick capture
- **Today**: Tasks due today + scheduled events
- **Upcoming**: Calendar-integrated task timeline
- **Projects**: Hierarchical project boards with progress
- **Anytime**: Tasks without specific deadlines
- **Completed**: Archive with search and restore
**Features**:
- Quick capture with natural language ('Buy milk tomorrow morning')
- Subtasks and checklists within tasks
- Priority levels (P1-P4) with visual urgency indicators
- Time estimates and actual time tracking
- Recurring tasks with flexible patterns
- Drag-and-drop reordering and nesting
- Batch operations (complete, reschedule, tag, assign)
- Focus mode (Pomodoro integration with task context)
### Calendar Module
- **Description**: Time-blocking calendar with task integration and smart scheduling
**Core Views**:
- **Day**: Hour-by-hour with task slots
- **Week**: Standard work week view
- **Month**: Overview with density indicators
- **Year**: Long-term planning with goals
- **Schedule**: List view of upcoming events
- **Availability**: Shareable free/busy slots
**Features**:
- Drag tasks from todo list onto calendar as time blocks
- Smart scheduling suggestions ('You have 2 hours free Thursday afternoon')
- Recurring events with complex patterns (bi-weekly, nth weekday)
- Multiple calendar layers (work, personal, shared)
- External calendar sync (Google, Outlook, Apple iCal)
- Meeting prep auto-linking (find relevant notes for upcoming meetings)
- Travel time buffers and location-based reminders
- Focus time protection (auto-block deep work sessions)
### Notes Module
- **Description**: AI-native note-taking with bidirectional linking and knowledge graph
**Core Views**:
- **All Notes**: Chronological list with search
- **Graph**: Visual knowledge graph of all notes
- **Daily Notes**: Date-stamped journal entries
- **Templates**: Reusable note structures
- **Trash**: Soft-deleted notes with recovery
**Features**:
- Block-based editor with slash commands and markdown
- Bidirectional linking with auto-suggestion ('[[Meeting Notes]]')
- Daily notes with automatic date headings
- Templates with dynamic fields and placeholders
- Web clipper for saving articles and annotating
- AI-powered summarization and expansion
- Semantic search across all notes
- Export to Markdown, PDF, HTML, Notion
---
## 5. Development Phases & Features
### Phase 1 Foundation
**Timeline**: Weeks 1-4 | **Theme**: Foundation & Core Infrastructure
#### Monorepo Setup & Design System
- **Description**: Turborepo with shared packages (ui, utils, types, hooks). shadcn/ui base components. Theme system (light/dark/auto).
- **Complexity**: Medium
- **Tech Stack**: Turborepo, pnpm, Tailwind, Radix UI, shadcn/ui
- **Dependencies**: None
- **Acceptance Criteria**:
- Shared packages build independently
- Design tokens (colors, spacing, typography) centralized
- Storybook running with all base components
- Dark mode toggle working globally
#### Authentication & User Management
- **Description**: JWT-based auth with refresh tokens, OAuth (Google, GitHub, Microsoft), magic links, password reset, profile management.
- **Complexity**: Medium
- **Tech Stack**: Fastify, Passport.js, PostgreSQL, Redis, JWT
- **Dependencies**: Monorepo Setup
- **Acceptance Criteria**:
- All auth flows working end-to-end
- Session management with Redis
- Rate limiting on auth endpoints
- Email verification and password reset
#### Database Schema & Migrations
- **Description**: Implement full unified schema with migrations, seed data, and test fixtures. Set up pgvector extension.
- **Complexity**: High
- **Tech Stack**: PostgreSQL, pgvector, Prisma ORM, Docker
- **Dependencies**: Monorepo Setup
- **Acceptance Criteria**:
- All entities created with proper constraints
- Migration system reversible
- Seed data for development
- pgvector extension enabled and indexed
#### API Foundation & Middleware
- **Description**: REST API structure, error handling, validation (Zod), logging, rate limiting, CORS, API versioning.
- **Complexity**: Medium
- **Tech Stack**: Fastify, Zod, Pino, Helmet
- **Dependencies**: Database Schema, Authentication
- **Acceptance Criteria**:
- Consistent API response format
- Request validation on all endpoints
- Structured logging with correlation IDs
- Rate limiting per user/IP
#### Offline-First Sync Engine
- **Description**: CRDT-based sync protocol with IndexedDB local storage, background sync, conflict resolution UI.
- **Complexity**: High
- **Tech Stack**: Yjs, IndexedDB, Service Workers, Background Sync API
- **Dependencies**: API Foundation
- **Acceptance Criteria**:
- Create/edit/delete notes offline, sync on reconnect
- Conflict resolution UI for simultaneous edits
- Sync status indicator in UI
- Data integrity verified across devices
### Phase 2 Notes Mvp
**Timeline**: Weeks 5-8 | **Theme**: Notes Module MVP
#### Block-Based Editor
- **Description**: Notion-like editor with slash commands, markdown shortcuts, rich embeds, drag-and-drop blocks.
- **Complexity**: High
- **Tech Stack**: TipTap, ProseMirror, React, tippy.js
- **Dependencies**: Monorepo Setup, Offline-First Sync
- **Acceptance Criteria**:
- All basic block types (paragraph, heading, list, code, quote, divider)
- Slash menu with 15+ commands
- Markdown shortcuts (## for H2, - for list)
- Drag-and-drop reordering of blocks
#### Note CRUD & Organization
- **Description**: Create, read, update, delete notes. Folders, tags, favorites, trash. Note list with sorting and filtering.
- **Complexity**: Medium
- **Tech Stack**: PostgreSQL, Prisma, Zustand, TanStack Query
- **Dependencies**: Database Schema, Block-Based Editor
- **Acceptance Criteria**:
- Full CRUD with optimistic UI updates
- Folder hierarchy with drag-and-drop
- Tag management with color coding
- Trash with 30-day retention and restore
#### Full-Text Search
- **Description**: Instant search across all notes with highlighting, filters (date, type, tag), and search history.
- **Complexity**: Medium
- **Tech Stack**: Meilisearch, PostgreSQL tsvector, React
- **Dependencies**: Note CRUD
- **Acceptance Criteria**:
- Search results in <100ms for 10k notes
- Highlighting of matched terms
- Filter by date range, tags, folders
- Recent searches and suggestions
#### Bidirectional Linking
- **Description**: [[Wiki-style links]] with auto-completion, backlink panels, and unlinked references suggestions.
- **Complexity**: High
- **Tech Stack**: TipTap plugin, PostgreSQL, React
- **Dependencies**: Block-Based Editor, Note CRUD
- **Acceptance Criteria**:
- Type [[ to trigger note autocomplete
- Backlink panel showing all references to current note
- Unlinked mentions detection (text matching note titles)
- Broken link detection and repair suggestions
### Phase 3 Todo Calendar
**Timeline**: Weeks 9-14 | **Theme**: Tasks & Calendar Integration
#### Task Management Core
- **Description**: Full task CRUD with priorities, due dates, subtasks, projects, sections. Inbox, Today, Upcoming views.
- **Complexity**: High
- **Tech Stack**: React, DnD Kit, date-fns, PostgreSQL
- **Dependencies**: Note CRUD, API Foundation
- **Acceptance Criteria**:
- Task creation with natural language parsing
- Subtask nesting (3 levels deep)
- Priority colors and urgency sorting
- Bulk operations (complete, reschedule, move)
#### Calendar Engine
- **Description**: Full calendar with day/week/month/year views. Event CRUD, recurring events, all-day events, time zones.
- **Complexity**: High
- **Tech Stack**: React, date-fns, rrule, luxon
- **Dependencies**: Task Management Core
- **Acceptance Criteria**:
- All calendar views rendering correctly
- Recurring events with complex patterns
- Timezone handling (user + event timezones)
- All-day and multi-day events
#### Task-Calendar Integration
- **Description**: Drag tasks onto calendar as time blocks. Tasks shown in calendar views. Calendar events linked to tasks.
- **Complexity**: High
- **Tech Stack**: DnD Kit, React, PostgreSQL, NodeLink
- **Dependencies**: Task Management Core, Calendar Engine
- **Acceptance Criteria**:
- Drag task from list to calendar slot
- Task appears as time block in calendar
- Calendar event can be converted to task
- Bidirectional updates (reschedule in calendar updates task)
#### Natural Language Input
- **Description**: Parse natural language for tasks and events ('Meeting with Sarah next Tuesday at 3pm for 1 hour').
- **Complexity**: High
- **Tech Stack**: OpenAI API, compromise.js, chrono-node, custom NLP
- **Dependencies**: Task Management Core, Calendar Engine
- **Acceptance Criteria**:
- Parse 90%+ of common date/time expressions
- Extract duration, participants, location
- Handle relative dates (tomorrow, next week)
- Fallback to manual input when parsing fails
#### Reminders & Notifications
- **Description**: Push, email, and in-app notifications for tasks and events. Smart reminders (travel time, prep time).
- **Complexity**: Medium
- **Tech Stack**: Web Push API, BullMQ, Redis, Firebase Cloud Messaging
- **Dependencies**: Task Management Core, Calendar Engine
- **Acceptance Criteria**:
- Push notifications delivered reliably
- Email reminders with note context
- Smart reminders (15min before, travel time)
- Notification preferences per workspace
#### External Calendar Sync
- **Description**: Sync with Google Calendar, Outlook, Apple iCal. Two-way or one-way sync options.
- **Complexity**: High
- **Tech Stack**: Google Calendar API, Microsoft Graph API, iCal parser, BullMQ
- **Dependencies**: Calendar Engine
- **Acceptance Criteria**:
- Import events from external calendars
- Export Suite events to external calendars
- Conflict detection and resolution
- Sync frequency configurable (real-time, hourly, daily)
### Phase 4 Ai Intelligence
**Timeline**: Weeks 15-18 | **Theme**: AI-Powered Intelligence Layer
#### Semantic Search & Embeddings
- **Description**: Vector-based semantic search across all content. Find notes/tasks/events by meaning, not just keywords.
- **Complexity**: High
- **Tech Stack**: OpenAI text-embedding-3-large, pgvector, HNSW index, React
- **Dependencies**: Full-Text Search, Note CRUD, Task Management Core
- **Acceptance Criteria**:
- Semantic search results relevant to query intent
- Hybrid search (keyword + semantic) ranking
- Embeddings updated within 5s of content change
- Search across all modules (notes, tasks, events)
#### AI Writing Assistant
- **Description**: Inline AI for expanding, summarizing, rewriting, translating, and answering questions about content.
- **Complexity**: High
- **Tech Stack**: OpenAI GPT-4o, SSE streaming, TipTap plugin, React
- **Dependencies**: Block-Based Editor
- **Acceptance Criteria**:
- AI suggestions appear inline with streaming
- Accept/reject/dismiss UI for suggestions
- Context-aware (uses surrounding paragraphs + linked notes)
- Works offline with local model fallback
#### Smart Linking & Knowledge Graph
- **Description**: AI auto-discovers relationships between all nodes. Visual graph explorer with filtering and clustering.
- **Complexity**: High
- **Tech Stack**: D3.js, OpenAI API, pgvector, Graph algorithms, React
- **Dependencies**: Semantic Search, Bidirectional Linking, Task-Calendar Integration
- **Acceptance Criteria**:
- Auto-suggest 3-5 related items for any node
- Graph view with 100+ nodes rendering at 60fps
- Clustering by workspace, time, or topic
- User can confirm/reject AI-suggested links
#### Smart Scheduling Assistant
- **Description**: AI suggests optimal times for tasks based on calendar, priorities, energy levels, and deadlines.
- **Complexity**: High
- **Tech Stack**: OpenAI/Anthropic API, Constraint solver, Calendar Engine, React
- **Dependencies**: Task-Calendar Integration, Calendar Engine
- **Acceptance Criteria**:
- Suggest time blocks for unscheduled tasks
- Respect user preferences (morning focus, afternoon meetings)
- Consider task dependencies and deadlines
- One-click accept or modify suggestion
#### Meeting Prep & Action Extraction
- **Description**: Before meetings, auto-surface relevant notes. After meetings, extract action items and create tasks.
- **Complexity**: High
- **Tech Stack**: OpenAI GPT-4o, NodeLink, Task Management Core, BullMQ
- **Dependencies**: Smart Linking, Task Management Core
- **Acceptance Criteria**:
- Auto-collect notes linked to meeting participants/topic
- Generate meeting prep summary 15min before
- Extract action items from meeting notes
- Create linked tasks with assignees and deadlines
### Phase 5 Collaboration
**Timeline**: Weeks 19-22 | **Theme**: Collaboration & Team Features
#### Real-time Collaboration
- **Description**: Multi-user editing on notes, shared task lists, shared calendars. Presence awareness, cursors, comments.
- **Complexity**: High
- **Tech Stack**: Yjs, WebSocket, Redis adapter, React
- **Dependencies**: Offline-First Sync, Notes MVP, Task Management Core
- **Acceptance Criteria**:
- 3+ users editing same note simultaneously
- Cursor positions and selections visible
- Comments and suggestions on specific blocks
- Conflict-free merging with CRDTs
#### Workspace & Team Management
- **Description**: Workspaces with members, roles (Owner/Admin/Editor/Viewer), permissions, and activity feeds.
- **Complexity**: Medium
- **Tech Stack**: PostgreSQL RLS, CASL, React, Zustand
- **Dependencies**: Authentication, Real-time Collaboration
- **Acceptance Criteria**:
- Role-based access control enforced at API level
- Workspace switching with isolated data
- Member invitation via email/link
- Activity feed showing team actions
#### Sharing & Permissions
- **Description**: Share individual nodes or folders with granular permissions. Public links with optional passwords.
- **Complexity**: Medium
- **Tech Stack**: PostgreSQL, CASL, React, UUID tokens
- **Dependencies**: Workspace & Team Management
- **Acceptance Criteria**:
- Share via link with view/edit permissions
- Password-protected public links
- Revoke sharing instantly
- Audit log of all share actions
#### Templates & Automation
- **Description**: Customizable templates for notes, tasks, events. Automation rules (when X, do Y).
- **Complexity**: High
- **Tech Stack**: JSON Schema, Workflow engine, BullMQ, React
- **Dependencies**: Notes MVP, Task Management Core, Calendar Engine
- **Acceptance Criteria**:
- Template gallery with 20+ built-in templates
- User-created templates with dynamic fields
- Automation: 'When task created with tag X, add to project Y'
- Webhook triggers for external integrations
### Phase 6 Platform Scale
**Timeline**: Weeks 23-28 | **Theme**: Platform, Extensibility & Enterprise
#### Public API & Webhooks
- **Description**: REST and GraphQL APIs with comprehensive documentation. Webhook events for all mutations.
- **Complexity**: Medium
- **Tech Stack**: Fastify, GraphQL (Mercurius), OpenAPI, Webhook delivery
- **Dependencies**: Workspace & Team Management
- **Acceptance Criteria**:
- REST API covering all CRUD operations
- GraphQL with subscriptions for real-time
- Webhook retry logic with exponential backoff
- API rate limits and usage dashboards
#### Plugin System
- **Description**: Third-party extensions with sandboxed execution. Plugin marketplace.
- **Complexity**: High
- **Tech Stack**: iframe sandbox, Plugin API, Manifest schema, CodeSandbox API
- **Dependencies**: Public API
- **Acceptance Criteria**:
- Plugin manifest validation and installation
- Sandboxed execution with limited permissions
- Plugin settings UI integration
- Marketplace with ratings and reviews
#### Desktop & Mobile Apps
- **Description**: Native desktop (Tauri) and mobile (React Native) with full feature parity and offline support.
- **Complexity**: High
- **Tech Stack**: Tauri, React Native, Expo, SQLite (local), Capacitor
- **Dependencies**: Offline-First Sync, All core modules
- **Acceptance Criteria**:
- Desktop app <50MB installer
- Mobile app on iOS and Android
- Full offline functionality on all platforms
- Native notifications and system integrations
#### SSO & Enterprise Compliance
- **Description**: SAML 2.0, OIDC, SCIM provisioning. Audit logs, data retention, GDPR tools, SOC 2 readiness.
- **Complexity**: Medium
- **Tech Stack**: Passport.js, SAML, SCIM, Audit trail, Encryption
- **Dependencies**: Workspace & Team Management
- **Acceptance Criteria**:
- SAML integration with major IdPs (Okta, Azure AD)
- SCIM user provisioning and deprovisioning
- Complete audit trail exportable as CSV/JSON
- GDPR data export and deletion within 24h
#### Self-Hosting & On-Premise
- **Description**: Docker-based deployment with license management. Single-tenant option for enterprise.
- **Complexity**: Medium
- **Tech Stack**: Docker Compose, Kubernetes, License API, Terraform
- **Dependencies**: All core modules
- **Acceptance Criteria**:
- One-command Docker deployment
- License validation and renewal
- Automated backups and restore
- Health checks and monitoring endpoints
#### Advanced Analytics Dashboard
- **Description**: Personal and team productivity insights. Time tracking, completion rates, focus metrics.
- **Complexity**: Medium
- **Tech Stack**: ClickHouse, Metabase, D3.js, React
- **Dependencies**: Activity tracking, Workspace & Team Management
- **Acceptance Criteria**:
- Personal productivity score and trends
- Team workload distribution view
- Time spent by project/category
- Exportable reports (PDF, CSV)
---
## 6. API Design
### REST Endpoints
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/nodes` | List all nodes with filtering by type, workspace, date, status, tags |
| POST | `/api/v1/nodes` | Create new node (task, event, note, project, goal) |
| GET | `/api/v1/nodes/:id` | Get node by ID with links, backlinks, and related content |
| PATCH | `/api/v1/nodes/:id` | Update node (partial, optimistic locking) |
| DELETE | `/api/v1/nodes/:id` | Soft delete node (move to trash) |
| POST | `/api/v1/nodes/:id/restore` | Restore node from trash |
| GET | `/api/v1/nodes/:id/links` | Get all outgoing and incoming links for a node |
| POST | `/api/v1/nodes/:id/links` | Create link between nodes |
| GET | `/api/v1/nodes/:id/related` | AI-suggested related nodes (semantic + graph) |
| POST | `/api/v1/nodes/:id/ai` | AI operations: summarize, expand, rewrite, extract actions, suggest links |
| GET | `/api/v1/search` | Hybrid search (full-text + semantic) across all nodes |
| GET | `/api/v1/workspaces/:id/graph` | Knowledge graph data for visualization (nodes + links) |
| GET | `/api/v1/workspaces/:id/calendar` | Calendar events for a workspace with date range |
| GET | `/api/v1/workspaces/:id/tasks` | Tasks for a workspace with filters and sorting |
| GET | `/api/v1/workspaces/:id/notes` | Notes for a workspace with folder hierarchy |
| GET | `/api/v1/workspaces/:id/activity` | Activity feed for workspace |
| POST | `/api/v1/natural-language` | Parse natural language input into structured node data |
| POST | `/api/v1/sync` | Delta sync endpoint for offline-first clients |
| GET | `/ws/collab/:nodeId` | WebSocket for real-time collaboration on a node |
| GET | `/api/v1/user/me` | Current user profile, preferences, and workspaces |
| PATCH | `/api/v1/user/me` | Update user preferences and settings |
| GET | `/api/v1/user/me/notifications` | User notification feed |
| GET | `/api/v1/integrations/calendars` | List connected external calendars |
| POST | `/api/v1/integrations/calendars/:provider/connect` | Connect external calendar (Google, Outlook, Apple) |
### GraphQL Schema
```
Core Types: User, Workspace, Node, NodeLink, Tag, Folder, Reminder, Activity, Attachment, WorkspaceMember
Queries:
- nodes(filter: NodeFilter, pagination: Pagination): NodeConnection
- node(id: UUID!): Node
- search(query: String!, type: SearchType, filters: SearchFilters): SearchResultConnection
- relatedNodes(id: UUID!, limit: Int): [NodeLink]
- graph(workspaceId: UUID!, depth: Int): GraphData
- calendar(workspaceId: UUID!, range: DateRange): [Node]
- tasks(workspaceId: UUID!, filters: TaskFilters): [Node]
- notes(workspaceId: UUID!, folderId: UUID): [Node]
- activity(workspaceId: UUID!, limit: Int): [Activity]
Mutations:
- createNode(input: CreateNodeInput!): Node
- updateNode(id: UUID!, input: UpdateNodeInput!): Node
- deleteNode(id: UUID!): Boolean
- createLink(input: CreateLinkInput!): NodeLink
- deleteLink(id: UUID!): Boolean
- aiAssist(id: UUID!, operation: AIOperation!, context: String): AIResult
- naturalLanguage(input: String!): ParsedNodeData
Subscriptions:
- nodeUpdated(id: UUID!): Node
- userPresence(workspaceId: UUID!): [UserPresence]
- notificationReceived(userId: UUID!): Notification
```
---
## 7. AI Integration Strategy
### Model Selection
- **OpenAI** `gpt-4o` (Primary): Writing assistant, summarization, action extraction, natural language parsing
- **Anthropic** `claude-3-5-sonnet` (Fallback): Long-context analysis, complex reasoning, meeting prep
- **Local** `llama3.1/phi4 via Ollama` (Offline fallback): Privacy-sensitive operations, offline mode, cost reduction
- **OpenAI** `text-embedding-3-large` (Primary): Node embeddings for semantic search and recommendations
- **Local** `nomic-embed-text via Ollama` (Offline fallback): Offline embeddings for local-only content
### Key Prompts
**Summarize**:
```
Summarize the following content in 3-5 bullet points, preserving key insights, action items, and decisions:
{content}
```
**Expand**:
```
Expand on the following outline/idea with detailed explanations, examples, and connections to related concepts. Maintain the original tone and style:
{content}
```
**Rewrite**:
```
Rewrite the following text to be {style} (e.g., more concise, more formal, simpler). Preserve all key information:
{content}
```
**Link Suggestions**:
```
Given this node:
{current_node}
And these candidate nodes:
{candidates}
Identify which nodes are semantically related and explain why. Consider content similarity, shared topics, temporal proximity, and participant overlap. Return as JSON array of {{node_id, relevance_score, reason, link_type}}.
```
**Tag Generation**:
```
Generate 3-5 relevant tags for this content. Be specific and use domain-appropriate terminology. Consider existing tags: {existing_tags}:
{content}
```
**Natural Language Parse**:
```
Parse the following natural language input into structured data. Extract: type (task/event/note), title, description, due_date, duration, priority, participants, location, tags, related_notes. Return as JSON. Input: '{input}'
```
**Action Extraction**:
```
Extract all action items from the following meeting notes or text. For each action item, identify: task description, assignee (if mentioned), deadline (if mentioned), priority. Return as JSON array.
{content}
```
**Meeting Prep**:
```
The user has a meeting titled '{meeting_title}' with {participants} at {time}. Based on their notes and previous meetings, summarize relevant context, open questions, and suggested talking points.
Relevant notes:
{related_notes}
```
**Smart Schedule**:
```
Given these unscheduled tasks with priorities and deadlines:
{tasks}
And this calendar availability:
{availability}
Suggest optimal time blocks for each task. Consider: task priority, deadline proximity, estimated duration, user energy patterns (morning/evening preference), and meeting prep time. Return as JSON array of {{task_id, suggested_start, suggested_end, reasoning}}.
```
### Embedding Pipeline
1. Chunk node content into semantic segments (paragraphs, sections, task descriptions)
2. Generate embeddings for each chunk + full node summary
3. Store in pgvector with metadata (node_id, chunk_index, type, workspace_id)
4. Build HNSW index for fast approximate nearest neighbor search
5. Update embeddings asynchronously on node modification (BullMQ queue)
6. Cache popular embeddings in Redis
7. Re-embed all content monthly with latest model version
### AI Features
- Inline writing assistant (expand, summarize, rewrite, translate)
- Smart linking suggestions across all modules
- Auto-tagging based on content analysis
- Natural language task/event creation
- Meeting prep auto-collection
- Action item extraction from notes
- Smart scheduling with calendar optimization
- Daily/weekly digest generation
- Duplicate detection and merge suggestions
- Content similarity warnings (avoid redundant notes)
---
## 8. Security & Compliance
### Authentication
- JWT with refresh token rotation (7-day access, 30-day refresh)
- OAuth 2.0 (Google, GitHub, Microsoft, Apple)
- Magic links (passwordless option)
- WebAuthn/FIDO2 for hardware key support
- SAML 2.0 and OIDC for enterprise SSO
- TOTP-based 2FA (optional for personal, required for teams)
### Authorization
- RBAC with predefined roles: Owner, Admin, Editor, Viewer
- Resource-level permissions (share individual nodes with custom access)
- Workspace-level access controls with inheritance
- Field-level encryption for sensitive notes (E2E optional)
- Row-level security (RLS) in PostgreSQL
- API-level permission checks (CASL/Ability)
- Audit logging for all permission changes
### Data Protection
- AES-256 encryption at rest (PostgreSQL TDE)
- TLS 1.3 in transit (HSTS enforced)
- E2E encryption option for sensitive workspaces (keys held by user)
- GDPR data export (complete user data dump in 24h)
- GDPR right to erasure (complete deletion within 30 days)
- Data retention policies configurable per workspace
- Automated backup encryption (AES-256-GCM)
- SOC 2 Type II compliance target (Phase 6)
- Penetration testing quarterly (external firm)
---
## 9. Performance Targets
| Metric | Target | Measurement |
|--------|--------|-------------|
| Time to First Contentful Paint | < 1.0s | Lighthouse |
| Time to Interactive | < 2.5s | Lighthouse |
| Editor interaction latency | < 30ms | Chrome DevTools |
| Search response time (full-text) | < 50ms | API response time |
| Search response time (semantic) | < 200ms | API response time |
| AI suggestion latency (first token) | < 500ms | SSE stream start |
| Calendar render (month view, 100 events) | < 100ms | React profiler |
| Task list render (1000 tasks) | < 150ms | React profiler |
| Sync reconciliation (100 changes) | < 2s | Offline simulation |
| Concurrent users per API node | > 2000 | Load testing |
| WebSocket message latency | < 50ms | Ping/pong |
| Database query P99 | < 100ms | PostgreSQL logs |
### Optimization Strategies
- Virtualized rendering for long lists (react-window/react-virtuoso)
- Lazy loading of note content and embeddings (intersection observer)
- CDN for static assets, avatars, and thumbnails (Cloudflare)
- Database connection pooling (PgBouncer, 100 connections)
- Redis caching for hot data (search results, user sessions, workspace configs)
- Query result caching with stale-while-revalidate
- WebSocket connection multiplexing (single connection per user)
- Debounced auto-save (1.5s) with optimistic UI updates
- Service Worker for asset caching and offline support
- Image optimization (WebP/AVIF, responsive sizes)
- Code splitting by module (todo, calendar, notes loaded on demand)
- Tree shaking and dead code elimination
- Database query optimization (composite indexes, query plan analysis)
- Read replicas for search and analytics queries
- GraphQL query complexity analysis and depth limiting
---
## 10. Development Workflow
### Version Control & Quality
- ESLint + Prettier (strict config, no warnings allowed)
- TypeScript strict mode with noImplicitAny
- Husky pre-commit hooks (lint, type-check, test affected)
- Conventional commits (feat:, fix:, docs:, refactor:, test:, chore:)
- Branch naming: feature/xxx, fix/xxx, refactor/xxx, docs/xxx
### Testing Strategy
- **Unit Tests**: Vitest for logic, React Testing Library for components, 80% coverage minimum
- **Integration Tests**: API endpoint testing with supertest + test database, 60% coverage
- **E2E Tests**: Playwright for critical user flows (auth, create note, search, calendar drag, sync)
- **Visual Regression**: Chromatic/Storybook for UI component snapshots
- **Performance Tests**: Lighthouse CI + custom benchmarks for editor and calendar
- **Contract Tests**: Pact for API consumer-provider contracts
### Deployment Pipeline
1. Developer pushes feature branch triggers CI (lint, type-check, unit tests, build)
2. PR created automated review (CodeRabbit/PR-Agent) + human review required
3. CI passes preview deployment generated (Vercel/Railway preview URL)
4. E2E tests run against preview environment
5. Merge to main auto-deploy to staging environment
6. Staging smoke tests (automated + manual QA checklist)
7. Manual promotion to production with feature flags
8. Production deployment with blue-green strategy (zero downtime)
9. Post-deploy monitoring (error rates, performance metrics) for 30 minutes
10. Automatic rollback if error rate > 0.1% or P95 latency > 2x baseline
---
## 11. Monetization Strategy
### Free — $0
- Unlimited personal notes, tasks, and events
- 1 workspace
- Basic AI (20 requests/day)
- 7-day version history
- Local sync only (no cloud)
- Web and mobile access
- Community support
### Pro — $10/month or $96/year
- Everything in Free
- Unlimited AI requests
- Unlimited workspaces
- Cloud sync across devices
- 30-day version history
- Advanced search (semantic + full-text)
- Knowledge graph view
- External calendar sync
- Web clipper
- Priority email support
### Team — $18/user/month or $180/user/year
- Everything in Pro
- Real-time collaboration
- Team workspaces with RBAC
- Shared templates and automation
- Admin dashboard and analytics
- SSO (Google Workspace, Microsoft 365)
- 90-day version history
- Shared team calendar
- API access (10k requests/month)
- Priority support (24h response)
### Enterprise — Custom pricing
- Everything in Team
- SAML/OIDC SSO (Okta, Azure AD, custom)
- SCIM user provisioning
- Self-hosting option
- Unlimited version history
- Audit logs and compliance reports
- Custom AI model training
- Dedicated account manager
- SLA (99.9% uptime, 4h response)
- Onboarding and training
- White-label option
---
## 12. Risk Mitigation
### Technical Risks
- **CRDT conflicts in complex multi-module editing**: Extensive Yjs testing across all node types, dedicated conflict resolution UI, automated conflict simulation tests
- **AI API latency and cost at scale**: Aggressive caching of AI responses, local model fallback (Ollama), rate limiting per user, usage quotas with graceful degradation
- **Search performance with millions of nodes**: Meilisearch sharding, pgvector HNSW indexing, read replicas, query result caching, eventual consistency for embeddings
- **Offline sync data corruption or loss**: Checksums on all sync operations, sync conflict resolution UI, automated backup before sync, integrity verification on reconnect
- **Calendar recurrence complexity (DST, timezone, leap years)**: Comprehensive test suite with edge cases, use battle-tested rrule library, UTC storage with timezone display, automated regression tests
- **Cross-platform feature parity gaps**: Shared business logic layer (React Native Web), feature flags per platform, automated cross-platform E2E tests, platform-specific UI adapters
### Business Risks
- **Market saturation (Notion, Todoist, Google Calendar, Obsidian)**: Differentiate on unified experience + AI-native features, target power users who feel fragmentation pain, freemium to reduce switching cost
- **AI dependency and vendor lock-in**: Local model support from day one, transparent AI usage, user control over AI features, multiple provider support (OpenAI, Anthropic, local)
- **Self-hosting cannibalizing cloud revenue**: Self-hosting only at Enterprise tier, cloud-first features (collaboration, AI), managed hosting option for teams
- **Team productivity app adoption challenges**: Individual-first design (works great solo), gradual team features, import from competitors, migration assistance for Enterprise
---
## 13. Success Metrics
### Engagement
- DAU/MAU ratio > 35%
- Average session duration > 20 minutes
- Nodes created per user per week > 15 (tasks + events + notes)
- Cross-module usage (users who use 2+ modules daily) > 60%
- AI feature usage (at least 1 AI interaction per week) > 40%
### Retention
- Week-1 retention > 65%
- Week-4 retention > 45%
- Month-3 retention > 30%
- Month-12 retention > 20%
- NPS score > 55
### Performance
- P99 API latency < 200ms
- Uptime > 99.95%
- Zero unplanned data loss incidents
- Sync conflict resolution rate > 95% automatic
- AI suggestion acceptance rate > 30%
### Business
- Free-to-Pro conversion rate > 5%
- Team upgrade rate (Pro users upgrading to Team) > 15%
- Average revenue per user (ARPU) > $12/month
- Customer acquisition cost (CAC) < $50
- Net revenue retention (NRR) > 110%
---
## 14. Agent Development Guidelines
### Execution Principles
Phase-by-phase execution: Complete each phase fully before moving to the next. No skipping MVP features.
Module-by-module delivery: Finish Notes MVP before starting Tasks, finish Tasks before Calendar integration.
Test-driven development: Write tests before implementation. Maintain >80% coverage for critical paths.
Documentation-first: Update API docs, component stories, and data model diagrams before coding.
Incremental AI integration: Start with simple prompts, gradually add embeddings, knowledge graphs, and smart scheduling.
Performance budgeting: Profile after every major feature. No regressions on existing metrics.
Security hardening: Implement auth from day one. Never commit secrets. Use environment configs.
Collaboration protocol: Use Yjs for real-time features. Test with 3+ concurrent users minimum.
Deployment readiness: Every merged PR must be deployable. Feature flags for incomplete work.
Cross-platform consistency: Shared logic layer, platform-specific UI adapters, consistent behavior.
### Agent Checkpoints
- After Phase 1: Validate monorepo builds, auth flows work, database migrations reversible, offline sync functional
- After Phase 2: Validate block editor has all basic blocks, notes CRUD complete, search <100ms, bidirectional linking works
- After Phase 3: Validate task-calendar drag integration, natural language parsing 90%+ accuracy, external calendar sync working
- After Phase 4: Validate semantic search relevance, AI suggestions accepted >30%, knowledge graph renders 100+ nodes at 60fps
- After Phase 5: Validate real-time collaboration with 3+ users, RBAC enforced at API level, sharing permissions granular
- After Phase 6: Validate REST + GraphQL APIs, plugin sandbox secure, desktop <50MB, mobile on both platforms
### Code Generation Rules
- Generate TypeScript with strict types no any types except in test mocks
- Use functional components with hooks no class components
- Prefer composition over inheritance use HOCs and render props sparingly
- Separate business logic from UI custom hooks for data operations
- Use Zod for all runtime validation never trust client input
- Implement optimistic UI updates rollback on error with toast notification
- Add loading and error states to every async operation no silent failures
- Use React.memo and useMemo judiciously profile before optimizing
- Write accessible components ARIA labels, keyboard navigation, focus management
- Internationalize from day one i18n keys for all user-facing strings
---
*Plan generated for YetAnotherSuite — Unified Productivity Ecosystem*
*30 Features | 6 Phases | 24-28 Weeks | 12 Core Entities | 5 AI Models | 24 API Endpoints*