Skip to content

Instantly share code, notes, and snippets.

@shamshirz
Last active April 24, 2025 03:19
Show Gist options
  • Save shamshirz/eb1dac86bc7238f228ed58d1fac5fba2 to your computer and use it in GitHub Desktop.
Save shamshirz/eb1dac86bc7238f228ed58d1fac5fba2 to your computer and use it in GitHub Desktop.
This is a template for a Claude Code custom command for starting projects. `.claude/commands/plan.md` and run within CC, `> /project/plan Details about the project`

Project Guide

Project Overview

  • Elixir/Phoenix application
  • Event sourcing architecture with Commanded and EventStore
  • Integrates with {fill this out}
  • Phoenix LiveView for real-time interfaces
  • Oban for background jobs

Business Context

… Enter what your business does, and how your app contributes to that business …

Development Workflow

bin/verify Usage

  • Always run bin/verify before submitting changes
  • Pay attention to all warnings as they indicate potential issues
  • Fix each issue before proceeding to ensure code quality
  • This runs all of our deterministic checks so you don't have to run them individually

Specific Dev change info you build up over time

eg. when doing destructive migrations, remove the code in 1 PR, then remove the columns in a 2nd PR

LiveView Real-time Updates

  • Use standard pattern: subscribe in mount, handle_info for PubSub messages
  • Consider extracting complex component logic into reusable view functions
  • Query data for display at the LiveView level, not in components
  • For remote data (like Notion guides), fetch in the LiveView and pass to components

Git Guidelines

  • Squash merge commits
  • Each commit in main = complete feature
  • Reference similar previous commits when implementing new features

Architecture

Event Sourcing

… your arch here …

Component Patterns

  • Never perform database queries within function components
  • Components receive data structures; LiveViews fetch data
  • Create dedicated structs for component inputs
  • Extract shared view code into reusable component modules
  • Transform raw DB entities into presentable data structures in LiveView
  • Prefer parameters with defaults over duplicate functions

LiveView Organization

  • Functions order: render → mount → callbacks → private helpers
  • Derive UI state from data models, not UI-only state
  • Use PubSub for real-time updates
  • Keep data access in projection modules, not LiveViews
  • Split complex UIs into logical sections with separate component functions
  • Handle different states of data (pending/completed) in mount by filtering data appropriately
  • Use consistent PubSub message handling for real-time UI updates

Templates & UI

Template Best Practices

  • Use function components over embedded content
  • Prefer :if and :for over <%= %> syntax
  • Account pages: gradient header + card pattern with negative transform
  • Toast notifications instead of traditional flash messages
  • Separate completed vs. pending items with distinct visual treatments
  • Use consistent color schemes: Forest green for active items, gray for completed items
  • Display completed items in condensed format with completion status indicators

File & Audio Handling

  • LiveView uploads with allow_upload/3 and PubSub notifications
  • Store in CloudFlare R2 with presigned URLs
  • Audio: RecordRTC.js with MP3 format and LiveView hooks
  • Use specialized functions for specific file operations (e.g., delete_audio_file vs generic delete_file)
  • Handle file operations through dedicated notifiers to keep LiveViews focused on UI concerns

Code Style

  • Pattern matching over case statements
  • Boolean functions end with question mark
  • Sort aliases alphabetically
  • Prefer simple functions over complex abstractions
  • Derived values over redundant storage (timestamps vs booleans)
  • Pass sort direction as parameter with default rather than duplicate functions

Testing

Strategies

  • Prefer async tests with unique module names
  • No Mox - use Adapter pattern or nothing
  • LiveView: use Phoenix.LiveViewTest, has_element?, render_click/submit
  • Events: use Cove.DataCase, sequence events with consistent metadata
  • For schema changes: MIX_ENV=test mix ecto.drop instead of migrations/rollbacks

Component Testing

  • Test components with meaningful HTML elements/IDs, not "data-testid"
  • Test toast messages with Phoenix.Flash.get(conn.assigns.flash, :info)
  • Handle PubSub by manually sending test messages to LiveView process

Features

… existing stuff you have in your app, ask Claude to catalogue it …

Development Phases and Planning

Multi-Phase Approach

  • Break large features into multiple logical phases
  • Create a detailed PLAN.md or thinking.md document before implementation
  • Document each phase with clear milestones and checklists
  • Mark completed items with a checkmark (✅) to track progress
  • Include implementation details and code snippets in planning documents
  • Plan for future phases while implementing current phase

Phase Structure

  1. Problem Description: Context, Problem Statement, Target Outcome
  2. Implementation Options: Compare approaches with pros/cons
  3. Recommendation: Select and justify the chosen approach
  4. Milestones: Break work into logical chunks with checklists
  5. Implementation Details: Code structures, patterns, and examples
  6. Testing Strategy: How to verify the implementation works correctly
  7. Future Enhancements: Ideas for subsequent phases

We are beginning a new project, take extra steps to decide on how we want to implement the solution. Create a PLAN.md file that will contain all of the information about this project. Read relevant parts of our repo, and give me 3 implementation options for how we can accomplish the outcome we want with the pros and cons of each, which you would recommend, and why. You will build a quality PRD to guide our work, there is some guidance on what makes a good PRD below. Here is the problem context: $ARGUMENTS

PLAN.md Template guidance

This defines the outline of the problem we are going to solve, along with the initial plan for what we want to do and what we need the outcome to be. Your job is to review the project information and convert the PLAN.md from a rough PRD docuement into a thorough plan list that starts with a strong problem description, context on what is going on, and the target outcome. Then it breaks down the work into milestones that each have their own markdown checklist of tasks to accomplish and ending with an item for the automated test that will be created to assert that the milestone is meeting the outcome we need.

PLAN.md Example

Client Progress Tracking and Communication Feature

Problem Description

Context: FitFlow provides personalized fitness coaching services through scheduled video sessions, customized workout plans, and nutritional guidance. Our platform currently handles user registration, integrations with services (Stripe, Calendly, MailChimp), and coordinates between these services to manage scheduling and automated communications. We're built on Elixir/Phoenix with Fly.io hosting, Postgres database, and LiveView for the UI, using an event sourcing architecture.

Problem: During their fitness journey, clients need a way to share progress updates, challenges, and workout completion details between scheduled coaching sessions. Currently, clients book sessions but have no structured way to communicate their progress until they meet with their coach. This limits the coach's ability to make timely adjustments to training plans and reduces the effectiveness of the coaching relationship. Additionally, clients can't easily track their own progress or receive feedback between sessions.

Target Outcome: We need an MVP for a two-way asynchronous communication system that allows clients to:

  1. Submit text and photo/video updates about their progress
  2. Receive structured feedback and plan adjustments
  3. Access a timeline of their fitness journey

This will enable coaches to monitor client progress continuously and provide more targeted guidance, while giving clients visibility into their fitness journey through a structured timeline.

Implementation Approach

After analyzing our codebase and considering our event sourcing architecture, I recommend Option 1: Extending the Story Aggregate as the implementation approach. This leverages our existing patterns and infrastructure while allowing for the specific needs of fitness journey tracking.

Implementation Options

Option 1: Extend the Story Aggregate (Recommended)

Description: Leverage the existing Story aggregate and projection, extending it to support progress updates and coach responses.

Pros:

  • Reuses existing patterns in our codebase (Story aggregate, events, projections)
  • Maintains consistency with our current approach to media sharing
  • We already have photo/video functionality in the Progress Story feature
  • Minimal new infrastructure needed

Cons:

  • May require refactoring existing Story code to handle new fitness-specific scenarios
  • Could create complexity if fitness journeys diverge significantly from current story submission flow

Option 2: Create a Dedicated FitnessJourney Aggregate

Description: Build a completely new aggregate and associated projections specific to fitness progress communications.

Pros:

  • Clean separation between fitness communications and other features
  • Purpose-built for fitness-specific workflows and states
  • Could better accommodate future fitness-specific enhancements

Cons:

  • Duplicates functionality that exists in Story aggregate
  • More initial work to implement the full stack of commands, events, projections
  • Introduces another distinct pattern/concept to maintain

Option 3: Generic Conversation Redesign

Description: Create a more generic messaging system that could be used across multiple use cases.

Pros:

  • More flexible for future applications beyond fitness tracking
  • Could potentially replace other communication features over time
  • Single consistent pattern for all communications

Cons:

  • More abstract design required
  • Larger scope and more complexity
  • May not address specific fitness workflow needs without additional abstractions

Recommendation

Extend the Story aggregate (Option 1) because:

  1. It aligns with our existing patterns and domain model
  2. Reuses our media submission capabilities
  3. Can leverage existing UI components with targeted modifications
  4. Has the fastest path to MVP
  5. Can evolve toward Option 2 if fitness journeys prove to need significant specialization

Milestones

1. Architecture and Data Model Updates

  • Define the fitness journey story schema extensions (progress_metrics, workout_status, coach_assigned, etc.)
  • Design the projection changes needed to support fitness journey timelines
  • Create sequence diagrams for the progress communication flow
  • Determine needed changes to the Story aggregate state
  • Define PubSub channels for progress updates
  • Automated test that asserts backend can store and retrieve fitness journey data

2. Commands and Events

  • Create RecordProgressUpdate command with fields for update_text, update_type, and media_ids
  • Create ProgressUpdateRecorded event to log client-provided updates
  • Create AssignCoachToClient command and CoachAssignedToClient event
  • Create UpdateWorkoutStatus command and WorkoutStatusUpdated event
  • Create ProvideCoachFeedback command and CoachFeedbackProvided event
  • Update Story aggregate to handle new fitness-related commands
  • Create tests for all new commands and events
  • Implement validations for fitness-specific business rules
  • Automated test that verifies command handling and event emission

3. Projection Updates

  • Update StoryProjector to handle fitness-related events
  • Add workout_status, progress_metrics, and coach_id to Story schema
  • Implement FitnessTimelineEntry projection for tracking journey milestones
  • Create migration for schema changes
  • Update queries in context modules to support new fitness fields
  • Implement PubSub broadcasts for real-time progress updates
  • Automated test for projection building after fitness events

4. Notifiers and Integrations

  • Create ProgressUpdateNotifier to send coach notifications
  • Implement integration with MailChimp for milestone celebrations
  • Update SMS notifications for workout reminders
  • Create Oban jobs for scheduled check-ins
  • Implement achievement milestone notifications
  • Automated tests for notifiers and integrations

5. UI Component Updates

  • Create fitness_timeline component for displaying journey progress
  • Implement progress_update_form component for client updates
  • Create coach_feedback_form component for coach responses
  • Update client_home_live to show fitness status
  • Create progress_detail_live for detailed journey view
  • Implement role-based access controls for coach vs client views
  • Add progress indicators and toast notifications
  • Add photo/video upload for progress updates
  • Implement workout log attachments
  • Automated tests for all new LiveView and component functionality

6. Helper Scripts for Manual Operations

  • Create script to manually update progress metrics
  • Implement script for client data export for coach review
  • Create script for bulk program updates
  • Add fitness journey statistics to admin dashboard
  • Automated tests for helper scripts

Implementation Notes

  • The initial MVP focuses on the functional flow, not polished UX
  • We'll leverage existing photo/video upload functionality
  • Progress tracking will be manual at first, with automation planned for future phases
  • We'll use existing authentication and membership models without modification
  • Progress communications will be structured as sequential entries in a timeline rather than threaded conversations

Future Enhancements (Out of Scope for MVP)

  • AI-assisted workout plan adjustments
  • Automated progress milestone detection
  • Integration with fitness tracking devices
  • Advanced analytics for progress trends
  • Mobile push notifications for workout reminders
  • Coach capacity management and load balancing
  • Real-time chat with coaches during workout sessions

Iteration Workflow

You will implement each step by analyzing what needs to be done, understanding the existing code base and patterns, and then leveraging the language and existing tools to help verify your success.

  • bin/verify
    • This script contains all the checks you need to ensure code quality
    • Including, compilation, formating, testing, recommendations
#!/usr/bin/env bash
# verify - Script for verifying Cove codebase changes
# Runs various checks with emoji status indicators
# Don't exit immediately on error so we can handle errors in run_step
# and provide meaningful output
set +e
function run_step() {
local cmd="$1"
local description="$2"
echo -n "Running $description... "
# Capture output and exit status
output=$(eval "$cmd" 2>&1)
exit_code=$?
if [ $exit_code -ne 0 ]; then
echo ""
echo ""
echo "$output"
return $exit_code
fi
echo ""
return 0
}
# Main execution
echo "Code verification"
echo "======================"
# Basic checks
run_step "mix compile --warnings-as-errors" "compiler checks" || exit 1
run_step "mix format" "code formatting" || exit 1
run_step "mix test" "test suite" || exit 1
run_step "mix hex.audit" "dependency security audit" || exit 1
run_step "mix assets.build" "JavaScript asset build" || exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment